ATLAS Offline Software
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | List of all members
python.pydraw.Draw_Cmd Class Reference
Inheritance diagram for python.pydraw.Draw_Cmd:
Collaboration diagram for python.pydraw.Draw_Cmd:

Public Member Functions

def __init__ (self, s)
 

Public Attributes

 errstr
 
 excstr
 
 histspec
 
 tuple_o
 
 stmts
 
 sel
 
 exprs
 
 tuple
 
 lo
 
 hi
 

Private Member Functions

def _tupleparse (self, s)
 
def _parserange (self, tuple)
 
def _mung_id (self, id)
 
def _mung_index (self, s1, s2)
 
def _mung_n (self, s1, s2)
 
def _mung_loop (self, s1, s2)
 
def _mung_expr_dollar (self, s)
 
def _mung_expr_ids (self, s)
 
def _mung_expr (self, s)
 
def _make_func (self, payload, extargs='')
 

Private Attributes

 _iddict
 
 _limdict
 
 _loopdict
 

Detailed Description

Holds information used to implement a draw/scan/loop command.

Pass the draw string to the constructor.  See the file-level comments
for details on the syntax of this.  This will define the
following attributes:

  errstr -   If set to a string, there was an error.
             Should be None if everything's ok.
  tuple -    The name of the tuple object.
  tuple_o -  Tuple object.
  lo -       The lower bound for row iteration.
  hi -       The upper bound for row iteration.
  stmts -    List of additional statements.
  exprs -    List of draw expressions.
  sel -      Selection expression or None.
  sel_orig - Untransformed selection expression or None.
  expr_orig- Untransformed plotting expression.
  histspec - The text following `;', split into space-separated words.

Other attributes:
  _iddict -  Map from loop identifiers (`foo' in `foo$i')
             to temp variables used to reference
             them in the loop function.
  _limdict - Map from loop identifiers (`foo' in `foo$2')
             to the largest explicit index seen.
  _loopdict - Map of loop dummy variable names to _Loopvar instances.

Definition at line 609 of file pydraw.py.

Constructor & Destructor Documentation

◆ __init__()

def python.pydraw.Draw_Cmd.__init__ (   self,
  s 
)
Initialize from a draw string.  See above for more details.

Definition at line 638 of file pydraw.py.

638  def __init__ (self, s):
639  """Initialize from a draw string. See above for more details."""
640 
641  # Assume no error.
642  self.errstr = None
643 
644  self._iddict = {}
645  self._limdict = {}
646  self._loopdict = {}
647 
648  try:
649  self._tupleparse (s)
650  except Exception as e:
651  import traceback
652  self.errstr = str(e)
653  self.excstr = traceback.format_exc()
654  return
655 
656 
657 

Member Function Documentation

◆ _make_func()

def python.pydraw.Draw_Cmd._make_func (   self,
  payload,
  extargs = '' 
)
private
Create the text for the function to process this query.

PAYLOAD is the payload expression to plug in.
EXTARGS is an additional string to add to the end of the
function's argument list (to set default values, for example).
Returns the function definition as a string.

Definition at line 939 of file pydraw.py.

939  def _make_func (self, payload, extargs = ''):
940  """Create the text for the function to process this query.
941 
942  PAYLOAD is the payload expression to plug in.
943  EXTARGS is an additional string to add to the end of the
944  function's argument list (to set default values, for example).
945  Returns the function definition as a string.
946  """
947 
948  sel = self.sel
949  if self._limdict:
950  limsel = ' and '.join (["len(%s)>=%d" % (self._iddict[p[0]], p[1])
951  for p in self._limdict.items()])
952  if not sel:
953  sel = limsel
954  else:
955  sel = limsel + " and (" + sel + ")"
956 
957  ftext = "def _loopfunc(_i, %s%s):\n" % (_evtvar, extargs)
958  for (id1, id2) in sorted(self._iddict.items()):
959  ftext += " %s = %s.%s\n" % (id2, _evtvar, id1)
960  indent = 2
961 
962  for (i,l) in sorted(self._loopdict.items()):
963  ids = sorted(l.get_ids())
964  assert (not not ids)
965  if len(ids) == 1:
966  vars = l.itname (ids[0])
967  lists = self._iddict[ids[0]]
968  else:
969  vars = "(" + ','.join([l.itname (id) for id in ids]) + ")"
970  lists = ("zip(" + ','.join([self._iddict[id] for id in ids])
971  + ")")
972  if l.explicit:
973  vars = "(%s,%s)" % (l.dumname(), vars)
974  lists = "enumerate(%s)" % lists
975  ftext += ' '*indent + "for %s in %s:\n" % (vars, lists)
976  indent += 2
977 
978  for s in self.stmts:
979  ftext += ' '*indent + s + '\n'
980 
981  if sel and sel != '1':
982  ftext += ' '*indent + "if (%s):\n" % sel
983  indent += 2
984 
985  ftext += ' '*indent + "%s\n" % payload
986 
987  if _debug:
988  print (ftext)
989 
990  return ftext
991 
992 

◆ _mung_expr()

def python.pydraw.Draw_Cmd._mung_expr (   self,
  s 
)
private
Process $ constructions and id substitution in string S.

Returns the modified string.

Definition at line 930 of file pydraw.py.

930  def _mung_expr (self, s):
931  """Process $ constructions and id substitution in string S.
932 
933  Returns the modified string.
934  """
935  s = self._mung_expr_dollar (s)
936  return self._mung_expr_ids (s)
937 
938 

◆ _mung_expr_dollar()

def python.pydraw.Draw_Cmd._mung_expr_dollar (   self,
  s 
)
private
Process $ constructions in string S.

Returns the modified string.

Definition at line 868 of file pydraw.py.

868  def _mung_expr_dollar (self, s):
869  """Process $ constructions in string S.
870 
871  Returns the modified string.
872  """
873  if not s:
874  return s
875  pos = 0
876  while 1:
877  (s1, s2) = _find_outer (s[pos:], '$', True)
878  if s2 is None:
879  break
880  snew = None
881  if len(s2) > 0:
882  if s2[0] in string.digits:
883  snew = self._mung_index (s1, s2)
884  elif (s2[0] == 'n' and
885  (not (len(s1) > 0 and s1[-1] in _idchars) or
886  s1.endswith (' and') or
887  s1.endswith (' or') or
888  s1.endswith ('not'))):
889  snew = self._mung_n (s1, s2)
890  elif s2[0] in string.ascii_letters:
891  snew = self._mung_loop (s1, s2)
892  s = s[:pos]
893  if snew is None:
894  snew = s1 + '$' + s2
895  pos = pos + len(s1)+1
896  s = s + snew
897  return s
898 
899 

◆ _mung_expr_ids()

def python.pydraw.Draw_Cmd._mung_expr_ids (   self,
  s 
)
private
Perform id substitution in S.

For identifiers in S that are attributes of our tuple,
replace them with references to the tuple attribute
(using _mung_id).

Returns the modified string.

Definition at line 900 of file pydraw.py.

900  def _mung_expr_ids (self, s):
901  """Perform id substitution in S.
902 
903  For identifiers in S that are attributes of our tuple,
904  replace them with references to the tuple attribute
905  (using _mung_id).
906 
907  Returns the modified string.
908  """
909  if not s:
910  return s
911 
912  tlist = tokenize.generate_tokens (StringIO(s).readline)
913  out = []
914  afterDot = False
915  for tnum, val, a, b, c in tlist:
916  if tnum == token.NAME and not afterDot:
917  if hasattr (self.tuple_o, val):
918  val = self._mung_id (val)
919  #val = _evtvar + '.' + val
920  out.append ((tnum, val))
921  # Don't mung names after a period. We may have attributes
922  # with the same names as variables in the tuple.
923  if tnum == token.OP and val == '.':
924  afterDot = True
925  else:
926  afterDot = False
927  return _untokenize (out)
928 
929 

◆ _mung_id()

def python.pydraw.Draw_Cmd._mung_id (   self,
  id 
)
private
Given a loop identifier (`foo' in `foo$i'), return the identifier
used to reference it in loop functions.

Definition at line 770 of file pydraw.py.

770  def _mung_id (self, id):
771  """Given a loop identifier (`foo' in `foo$i'), return the identifier
772  used to reference it in loop functions.
773  """
774  out = self._iddict.get (id)
775  if not out:
776  out = '_e_' + id
777  self._iddict[id] = out
778  return out
779 
780 

◆ _mung_index()

def python.pydraw.Draw_Cmd._mung_index (   self,
  s1,
  s2 
)
private
Handle an explicit index reference; i.e., `foo$2'.

S1 and S2 are pieces of the string before and after the `$'.
Returns the modified string.

Definition at line 781 of file pydraw.py.

781  def _mung_index (self, s1, s2):
782  """Handle an explicit index reference; i.e., `foo$2'.
783 
784  S1 and S2 are pieces of the string before and after the `$'.
785  Returns the modified string.
786  """
787  pos2 = 0
788  while pos2 < len(s2) and s2[pos2] in string.digits:
789  pos2 += 1
790  if pos2 == 0:
791  self.errstr = "Bad index"
792  return ''
793  i = int (s2[:pos2])
794  if i < 1:
795  self.errstr = "Bad index"
796  return ''
797  s = ("[%d]" % (i-1)) + s2[pos2:]
798  pos2 = len(s1)-1
799  while pos2 >= 0 and s1[pos2] in _idchars:
800  pos2 -= 1
801  pos2 += 1
802  if pos2 == len(s1):
803  self.errstr = "Bad index"
804  return ''
805  id = s1[pos2:]
806  s = s1[:pos2] + self._mung_id (id) + s
807  self._limdict[id] = max (i, self._limdict.get(id, 0))
808  return s
809 
810 

◆ _mung_loop()

def python.pydraw.Draw_Cmd._mung_loop (   self,
  s1,
  s2 
)
private
Handle use of a dummy loop variable, such as foo$i.

S1 and S2 are pieces of the string before and after the `$'.
Returns the modified string.

Definition at line 825 of file pydraw.py.

825  def _mung_loop (self, s1, s2):
826  """Handle use of a dummy loop variable, such as foo$i.
827 
828  S1 and S2 are pieces of the string before and after the `$'.
829  Returns the modified string.
830  """
831 
832  # Scan after the $ to find the dummy variable.
833  pos2 = 0
834  while pos2 < len(s2) and s2[pos2] in _idchars:
835  pos2 += 1
836  if pos2 == 0:
837  self.errstr = "Bad loop var"
838  return ''
839  loopvar = s2[:pos2]
840 
841  # Look it up. Make a new _Loopvar object if it's not in the map.
842  ll = self._loopdict.get (loopvar)
843  if not ll:
844  ll = _Loopvar(loopvar)
845  self._loopdict[loopvar] = ll
846 
847  # Is the $ after an identifier?
848  if len(s1) > 0 and s1[-1] in _idchars:
849  # Yes --- find the identifier.
850  pos3 = len(s1)-1
851  while pos3 >= 0 and s1[pos3] in _idchars:
852  pos3 -= 1
853  pos3 += 1
854  assert (len(s1) - pos3 >= 1)
855  id = s1[pos3:]
856 
857  # Replace with the iterator.
858  s = s1[:pos3] + ll.add_id(id) + s2[pos2:]
859  self._mung_id (id)
860  else:
861  # Explicit use of the dummy.
862  # Replace with the dummy name and note that it was used explicitly.
863  s = s1 + ("%s" % ll.dumname()) + s2[pos2:]
864  ll.explicit = 1
865  return s
866 
867 

◆ _mung_n()

def python.pydraw.Draw_Cmd._mung_n (   self,
  s1,
  s2 
)
private
Handle a length reference; i.e., `$nfoo'.

S1 and S2 are pieces of the string before and after the `$'.
Returns the modified string.

Definition at line 811 of file pydraw.py.

811  def _mung_n (self, s1, s2):
812  """Handle a length reference; i.e., `$nfoo'.
813 
814  S1 and S2 are pieces of the string before and after the `$'.
815  Returns the modified string.
816  """
817  pos2 = 1
818  while pos2 < len(s2) and s2[pos2] in _idchars:
819  pos2 += 1
820  id = s2[1:pos2]
821  s = s1 + (" len(%s)" % self._mung_id(id)) + s2[pos2:]
822  return s
823 
824 

◆ _parserange()

def python.pydraw.Draw_Cmd._parserange (   self,
  tuple 
)
private
Parse the range part of a draw string.

See above for more details.
Fills self.tuple, self.lo, self.hi.

Definition at line 733 of file pydraw.py.

733  def _parserange (self, tuple):
734  """Parse the range part of a draw string.
735 
736  See above for more details.
737  Fills self.tuple, self.lo, self.hi.
738  """
739  lo = 0
740  hi = sys.maxsize
741  (tuple, tail) = _find_outer (tuple, '[')
742  if tail:
743  g = copy.copy (_globals)
744 
745  pos = tail.find (':')
746  pos2 = tail.find (']')
747  if pos2 < 0:
748  pos2 = len (tail) #pragma: NO COVER
749  if pos < 0:
750  slo = tail[:pos2].strip()
751  if len (slo) > 0:
752  lo = int (eval (slo, g))
753  hi = lo + 1
754  else:
755  slo = tail[:pos].strip()
756  if len (slo) > 0:
757  lo = int (eval (slo, g))
758  shi = tail[pos+1:pos2].strip()
759  if len (shi) > 0:
760  hi = int (eval (shi, g))
761 
762  if tuple[0] == '(' and tuple[-1] == ')':
763  tuple = tuple[1:-1].strip()
764  self.tuple = tuple
765  self.lo = lo
766  self.hi = hi
767  return
768 
769 

◆ _tupleparse()

def python.pydraw.Draw_Cmd._tupleparse (   self,
  s 
)
private
Parse a draw string.  See above for more details.

Definition at line 658 of file pydraw.py.

658  def _tupleparse (self, s):
659  """Parse a draw string. See above for more details."""
660 
661  # Split off the histspec.
662  (s, self.histspec) = _find_outer (s, ';')
663 
664  # ??? Don't split at spaces in delimiters.
665  # _find_outer doesn't really work for this since it operates
666  # on the tokenized string, in which whitespace doesn't appear.
667  if self.histspec is None:
668  self.histspec = []
669  else:
670  self.histspec = self.histspec.split ()
671 
672  # Gotta have something.
673  s = s.strip()
674  if not s:
675  self.errstr = "Empty draw string."
676  return
677 
678  # Split off the tuple part --- before the first period.
679  (tuple, s) = _find_outer (s, '.')
680  if not s:
681  self.errstr = "Missing period in tuple specification."
682  return
683 
684  # Handle a range specification on the sample.
685  self._parserange (tuple)
686 
687  # Try to find the sample.
688  try:
689  self.tuple_o = eval (self.tuple, _globals)
690  except NameError:
691  self.tuple_o = None
692  if not self.tuple_o:
693  self.errstr = "Can't find sample " + self.tuple
694  return
695 
696  # Look for additional statements.
697  self.stmts = _split_outer (s, '@')
698  s = self.stmts[-1]
699  del self.stmts[-1]
700  self.stmts = [self._mung_expr(x) for x in self.stmts]
701 
702  # Split off the selection.
703  (self.expr_orig, self.sel_orig) = _find_outer (s, "if")
704  self.sel = self._mung_expr (self.sel_orig)
705 
706  self.exprs = [self._mung_expr(x) for x in
707  _split_outer (self.expr_orig, ':')]
708 
709  # Check the interface of the sample. If it doesn't have
710  # the loop interface but has the root tree interface,
711  # use a wrapper.
712  if hasattr (self.tuple_o, 'loop'):
713  # Ok --- has the loop interface.
714  pass
715  elif (hasattr (self.tuple_o, 'GetEntry') and
716  hasattr (self.tuple_o, 'GetEntries')):
717  # Has the TTree interface. Use a wrapper.
718  self.tuple_o = TreeLoopWrapper (self.tuple_o)
719  elif (hasattr (self.tuple_o, 'size') and
720  hasattr (self.tuple_o, 'seekEvent')): #pragma: NO COVER
721  # Has the appmgr interface. Use a wrapper.
722  self.tuple_o = AthenaLoopWrapper (self.tuple_o) #pragma: NO COVER
723  else:
724  # An error --- complain.
725  self.errstr = ("Sample " + self.tuple +
726  " doesn't have a correct interface.")
727  return
728 
729  return
730 
731 
732 

Member Data Documentation

◆ _iddict

python.pydraw.Draw_Cmd._iddict
private

Definition at line 644 of file pydraw.py.

◆ _limdict

python.pydraw.Draw_Cmd._limdict
private

Definition at line 645 of file pydraw.py.

◆ _loopdict

python.pydraw.Draw_Cmd._loopdict
private

Definition at line 646 of file pydraw.py.

◆ errstr

python.pydraw.Draw_Cmd.errstr

Definition at line 642 of file pydraw.py.

◆ excstr

python.pydraw.Draw_Cmd.excstr

Definition at line 653 of file pydraw.py.

◆ exprs

python.pydraw.Draw_Cmd.exprs

Definition at line 706 of file pydraw.py.

◆ hi

python.pydraw.Draw_Cmd.hi

Definition at line 766 of file pydraw.py.

◆ histspec

python.pydraw.Draw_Cmd.histspec

Definition at line 668 of file pydraw.py.

◆ lo

python.pydraw.Draw_Cmd.lo

Definition at line 765 of file pydraw.py.

◆ sel

python.pydraw.Draw_Cmd.sel

Definition at line 704 of file pydraw.py.

◆ stmts

python.pydraw.Draw_Cmd.stmts

Definition at line 697 of file pydraw.py.

◆ tuple

python.pydraw.Draw_Cmd.tuple

Definition at line 764 of file pydraw.py.

◆ tuple_o

python.pydraw.Draw_Cmd.tuple_o

Definition at line 689 of file pydraw.py.


The documentation for this class was generated from the following file:
DerivationFramework::TriggerMatchingUtils::sorted
std::vector< typename R::value_type > sorted(const R &r, PROJ proj={})
Helper function to create a sorted vector from an unsorted range.
python.processes.powheg.ZZj_MiNNLO.ZZj_MiNNLO.__init__
def __init__(self, base_directory, **kwargs)
Constructor: all process options are set here.
Definition: ZZj_MiNNLO.py:18
TCS::join
std::string join(const std::vector< std::string > &v, const char c=',')
Definition: Trigger/TrigT1/L1Topo/L1TopoCommon/Root/StringUtils.cxx:10
TrigJetMonitorAlgorithm.items
items
Definition: TrigJetMonitorAlgorithm.py:71
get
T * get(TKey *tobj)
get a TObject* from a TKey* (why can't a TObject be a TKey?)
Definition: hcg.cxx:127
str
Definition: BTagTrackIpAccessor.cxx:11