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 601 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 630 of file pydraw.py.

630  def __init__ (self, s):
631  """Initialize from a draw string. See above for more details."""
632 
633  # Assume no error.
634  self.errstr = None
635 
636  self._iddict = {}
637  self._limdict = {}
638  self._loopdict = {}
639 
640  try:
641  self._tupleparse (s)
642  except Exception as e:
643  import traceback
644  self.errstr = str(e)
645  self.excstr = traceback.format_exc()
646  return
647 
648 
649 

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 931 of file pydraw.py.

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

◆ _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 922 of file pydraw.py.

922  def _mung_expr (self, s):
923  """Process $ constructions and id substitution in string S.
924 
925  Returns the modified string.
926  """
927  s = self._mung_expr_dollar (s)
928  return self._mung_expr_ids (s)
929 
930 

◆ _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 860 of file pydraw.py.

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

◆ _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 892 of file pydraw.py.

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

◆ _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 762 of file pydraw.py.

762  def _mung_id (self, id):
763  """Given a loop identifier (`foo' in `foo$i'), return the identifier
764  used to reference it in loop functions.
765  """
766  out = self._iddict.get (id)
767  if not out:
768  out = '_e_' + id
769  self._iddict[id] = out
770  return out
771 
772 

◆ _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 773 of file pydraw.py.

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

◆ _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 817 of file pydraw.py.

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

◆ _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 803 of file pydraw.py.

803  def _mung_n (self, s1, s2):
804  """Handle a length reference; i.e., `$nfoo'.
805 
806  S1 and S2 are pieces of the string before and after the `$'.
807  Returns the modified string.
808  """
809  pos2 = 1
810  while pos2 < len(s2) and s2[pos2] in _idchars:
811  pos2 += 1
812  id = s2[1:pos2]
813  s = s1 + (" len(%s)" % self._mung_id(id)) + s2[pos2:]
814  return s
815 
816 

◆ _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 725 of file pydraw.py.

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

◆ _tupleparse()

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

Definition at line 650 of file pydraw.py.

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

Member Data Documentation

◆ _iddict

python.pydraw.Draw_Cmd._iddict
private

Definition at line 636 of file pydraw.py.

◆ _limdict

python.pydraw.Draw_Cmd._limdict
private

Definition at line 637 of file pydraw.py.

◆ _loopdict

python.pydraw.Draw_Cmd._loopdict
private

Definition at line 638 of file pydraw.py.

◆ errstr

python.pydraw.Draw_Cmd.errstr

Definition at line 634 of file pydraw.py.

◆ excstr

python.pydraw.Draw_Cmd.excstr

Definition at line 645 of file pydraw.py.

◆ exprs

python.pydraw.Draw_Cmd.exprs

Definition at line 698 of file pydraw.py.

◆ hi

python.pydraw.Draw_Cmd.hi

Definition at line 758 of file pydraw.py.

◆ histspec

python.pydraw.Draw_Cmd.histspec

Definition at line 660 of file pydraw.py.

◆ lo

python.pydraw.Draw_Cmd.lo

Definition at line 757 of file pydraw.py.

◆ sel

python.pydraw.Draw_Cmd.sel

Definition at line 696 of file pydraw.py.

◆ stmts

python.pydraw.Draw_Cmd.stmts

Definition at line 689 of file pydraw.py.

◆ tuple

python.pydraw.Draw_Cmd.tuple

Definition at line 756 of file pydraw.py.

◆ tuple_o

python.pydraw.Draw_Cmd.tuple_o

Definition at line 681 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