Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_forward_star(self, node): if node not in self._node_attributes: raise ValueError("No such node exists.") return self._forward_star[node].copy()
[ "Given a node, get a copy of that node's forward star.\n\n :param node: node to retrieve the forward-star of.\n :returns: set -- set of hyperedge_ids for the hyperedges\n in the node's forward star.\n :raises: ValueError -- No such node exists.\n\n " ]
Please provide a description of the function:def get_backward_star(self, node): if node not in self._node_attributes: raise ValueError("No such node exists.") return self._backward_star[node].copy()
[ "Given a node, get a copy of that node's backward star.\n\n :param node: node to retrieve the backward-star of.\n :returns: set -- set of hyperedge_ids for the hyperedges\n in the node's backward star.\n :raises: ValueError -- No such node exists.\n\n " ]
Please provide a description of the function:def get_successors(self, tail): frozen_tail = frozenset(tail) # If this node set isn't any tail in the hypergraph, then it has # no successors; thus, return an empty list if frozen_tail not in self._successors: return set(...
[ "Given a tail set of nodes, get a list of edges of which the node\n set is the tail of each edge.\n\n :param tail: set of nodes that correspond to the tails of some\n (possibly empty) set of edges.\n :returns: set -- hyperedge_ids of the hyperedges that have tail\n ...
Please provide a description of the function:def get_predecessors(self, head): frozen_head = frozenset(head) # If this node set isn't any head in the hypergraph, then it has # no predecessors; thus, return an empty list if frozen_head not in self._predecessors: retur...
[ "Given a head set of nodes, get a list of edges of which the node set\n is the head of each edge.\n\n :param head: set of nodes that correspond to the heads of some\n (possibly empty) set of edges.\n :returns: set -- hyperedge_ids of the hyperedges that have head\n ...
Please provide a description of the function:def is_B_hypergraph(self): for hyperedge_id in self._hyperedge_attributes: head = self.get_hyperedge_head(hyperedge_id) if len(head) > 1: return False return True
[ "Indicates whether the hypergraph is a B-hypergraph.\n In a B-hypergraph, all hyperedges are B-hyperedges -- that is, every\n hyperedge has exactly one node in the head.\n\n :returns: bool -- True iff the hypergraph is a B-hypergraph.\n\n " ]
Please provide a description of the function:def is_F_hypergraph(self): for hyperedge_id in self._hyperedge_attributes: tail = self.get_hyperedge_tail(hyperedge_id) if len(tail) > 1: return False return True
[ "Indicates whether the hypergraph is an F-hypergraph.\n In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every\n hyperedge has exactly one node in the tail.\n\n :returns: bool -- True iff the hypergraph is an F-hypergraph.\n\n " ]
Please provide a description of the function:def is_BF_hypergraph(self): for hyperedge_id in self._hyperedge_attributes: tail = self.get_hyperedge_tail(hyperedge_id) head = self.get_hyperedge_head(hyperedge_id) if len(tail) > 1 and len(head) > 1: retu...
[ "Indicates whether the hypergraph is a BF-hypergraph.\n A BF-hypergraph consists of only B-hyperedges and F-hyperedges.\n See \"is_B_hypergraph\" or \"is_F_hypergraph\" for more details.\n\n :returns: bool -- True iff the hypergraph is an F-hypergraph.\n\n " ]
Please provide a description of the function:def get_symmetric_image(self): new_H = self.copy() # No change to _node_attributes necessary, as nodes remain the same # Reverse the tail and head (and __frozen_tail and __frozen_head) for # every hyperedge for hyperedge_id ...
[ "Creates a new DirectedHypergraph object that is the symmetric\n image of this hypergraph (i.e., identical hypergraph with all\n edge directions reversed).\n Copies of each of the nodes' and hyperedges' attributes are stored\n and used in the new hypergraph.\n\n :returns: Directed...
Please provide a description of the function:def get_induced_subhypergraph(self, nodes): sub_H = self.copy() sub_H.remove_nodes(sub_H.get_node_set() - set(nodes)) return sub_H
[ "Gives a new hypergraph that is the subhypergraph of the current\n hypergraph induced by the provided set of nodes. That is, the induced\n subhypergraph's node set corresponds precisely to the nodes provided,\n and the coressponding hyperedges in the subhypergraph are only those\n from t...
Please provide a description of the function:def read(self, file_name, delim=',', sep='\t'): in_file = open(file_name, 'r') # Skip the header line in_file.readline() line_number = 2 for line in in_file.readlines(): line = line.strip() # Skip emp...
[ "Read a directed hypergraph from a file, where nodes are\n represented as strings.\n Each column is separated by \"sep\", and the individual\n tail nodes and head nodes are delimited by \"delim\".\n The header line is currently ignored, but columns should be of\n the format:\n ...
Please provide a description of the function:def write(self, file_name, delim=',', sep='\t'): out_file = open(file_name, 'w') # write first header line out_file.write("tail" + sep + "head" + sep + "weight\n") for hyperedge_id in self.get_hyperedge_id_set(): line = ...
[ "Write a directed hypergraph to a file, where nodes are\n represented as strings.\n Each column is separated by \"sep\", and the individual\n tail nodes and head nodes are delimited by \"delim\".\n The header line is currently ignored, but columns should be of\n the format:\n ...
Please provide a description of the function:def _check_hyperedge_attributes_consistency(self): # required_attrs are attributes that every hyperedge must have. required_attrs = ['weight', 'tail', 'head', '__frozen_tail', '__frozen_head'] # Get list of hyperedg...
[ "Consistency Check 1: consider all hyperedge IDs listed in\n _hyperedge_attributes\n\n :raises: ValueError -- detected inconsistency among dictionaries\n\n " ]
Please provide a description of the function:def _check_node_attributes_consistency(self): # Get list of nodes from the node attributes dict nodes_from_attributes = set(self._node_attributes.keys()) # Perform consistency checks on each node. for node in nodes_from_attributes: ...
[ "Consistency Check 2: consider all nodes listed in\n _node_attributes\n\n :raises: ValueError -- detected inconsistency among dictionaries\n\n " ]
Please provide a description of the function:def _check_predecessor_successor_consistency(self): # Check 3.1: ensure that predecessors has the same headsets # that successors has predecessor_heads = set(self._predecessors.keys()) successor_heads = set() for key, value in...
[ "Consistency Check 3: predecessor/successor symmetry\n\n :raises: ValueError -- detected inconsistency among dictionaries\n\n " ]
Please provide a description of the function:def _check_hyperedge_id_consistency(self): # Get list of hyperedge_ids from the hyperedge attributes dict hyperedge_ids_from_attributes = set(self._hyperedge_attributes.keys()) # get hyperedge ids in the forward star forward_star_hyp...
[ "Consistency Check 4: check for misplaced hyperedge ids\n\n :raises: ValueError -- detected inconsistency among dictionaries\n\n " ]
Please provide a description of the function:def _check_node_consistency(self): # Get list of nodes from the node attributes dict nodes_from_attributes = set(self._node_attributes.keys()) # Get list of hyperedge_ids from the hyperedge attributes dict hyperedge_ids_from_attribut...
[ "Consistency Check 5: check for misplaced nodes\n\n :raises: ValueError -- detected inconsistency among dictionaries\n\n " ]
Please provide a description of the function:def _check_consistency(self): # TODO: is ValueError the proper exception to raise? Should # we make a new exception ("ConsistencyException")? # TODO: many of these for loops can be replaced by list # comprehension; however the errors...
[ "Compares the contents of the six dictionaries and ensures\n that they are consistent with each other, raising a ValueError\n if there is any inconsistency among the dictionaries. This\n function is used in testing when modifying hypergraphs. The\n consistency checks are divided into the...
Please provide a description of the function:def getall(self, key, default=_marker): identity = self._title(key) res = [v for i, k, v in self._impl._items if i == identity] if res: return res if not res and default is not _marker: return default r...
[ "Return a list of all values matching the key." ]
Please provide a description of the function:def extend(self, *args, **kwargs): self._extend(args, kwargs, 'extend', self._extend_items)
[ "Extend current MultiDict with more values.\n\n This method must be used instead of update.\n " ]
Please provide a description of the function:def setdefault(self, key, default=None): identity = self._title(key) for i, k, v in self._impl._items: if i == identity: return v self.add(key, default) return default
[ "Return value for key, set value to default if key is not present." ]
Please provide a description of the function:def popone(self, key, default=_marker): identity = self._title(key) for i in range(len(self._impl._items)): if self._impl._items[i][0] == identity: value = self._impl._items[i][2] del self._impl._items[i] ...
[ "Remove specified key and return the corresponding value.\n\n If key is not found, d is returned if given, otherwise\n KeyError is raised.\n\n " ]
Please provide a description of the function:def popall(self, key, default=_marker): found = False identity = self._title(key) ret = [] for i in range(len(self._impl._items)-1, -1, -1): item = self._impl._items[i] if item[0] == identity: r...
[ "Remove all occurrences of key and return the list of corresponding\n values.\n\n If key is not found, default is returned if given, otherwise\n KeyError is raised.\n\n " ]
Please provide a description of the function:def popitem(self): if self._impl._items: i = self._impl._items.pop(0) self._impl.incr_version() return i[1], i[2] else: raise KeyError("empty multidict")
[ "Remove and return an arbitrary (key, value) pair." ]
Please provide a description of the function:def update(self, *args, **kwargs): self._extend(args, kwargs, 'update', self._update_items)
[ "Update the dictionary from *other*, overwriting existing keys." ]
Please provide a description of the function:def total(self, xbin1=1, xbin2=-2): return self.hist.integral(xbin1=xbin1, xbin2=xbin2, error=True)
[ "\n Return the total yield and its associated statistical uncertainty.\n " ]
Please provide a description of the function:def sys_names(self): names = {} for osys in self.overall_sys: names[osys.name] = None for hsys in self.histo_sys: names[hsys.name] = None return names.keys()
[ "\n Return a list of unique systematic names from OverallSys and HistoSys\n " ]
Please provide a description of the function:def iter_sys(self): names = self.sys_names() for name in names: osys = self.GetOverallSys(name) hsys = self.GetHistoSys(name) yield name, osys, hsys
[ "\n Iterate over sys_name, overall_sys, histo_sys.\n overall_sys or histo_sys may be None for any given sys_name.\n " ]
Please provide a description of the function:def sys_hist(self, name=None): if name is None: low = self.hist.Clone(shallow=True) high = self.hist.Clone(shallow=True) return low, high osys = self.GetOverallSys(name) hsys = self.GetHistoSys(name) ...
[ "\n Return the effective low and high histogram for a given systematic.\n If this sample does not contain the named systematic then return\n the nominal histogram for both low and high variations.\n " ]
Please provide a description of the function:def total(self, xbin1=1, xbin2=-2): integral, stat_error = self.hist.integral( xbin1=xbin1, xbin2=xbin2, error=True) # sum systematics in quadrature ups = [0] dns = [0] for sys_name in self.sys_names(): ...
[ "\n Return the total yield and its associated statistical and\n systematic uncertainties.\n " ]
Please provide a description of the function:def sys_names(self): names = [] for sample in self.samples: names.extend(sample.sys_names()) return list(set(names))
[ "\n Return a list of unique systematic names from OverallSys and HistoSys\n " ]
Please provide a description of the function:def sys_hist(self, name=None, where=None): total_low, total_high = None, None for sample in self.samples: if where is not None and not where(sample): continue low, high = sample.sys_hist(name) if to...
[ "\n Return the effective total low and high histogram for a given\n systematic over samples in this channel.\n If a sample does not contain the named systematic then its nominal\n histogram is used for both low and high variations.\n\n Parameters\n ----------\n\n nam...
Please provide a description of the function:def total(self, where=None, xbin1=1, xbin2=-2): nominal, _ = self.sys_hist(None, where=where) integral, stat_error = nominal.integral( xbin1=xbin1, xbin2=xbin2, error=True) ups = [0] dns = [0] for sys_name in self....
[ "\n Return the total yield and its associated statistical and\n systematic uncertainties.\n " ]
Please provide a description of the function:def getse(op, arg=None): try: return _se[op] except KeyError: # Continue to opcodes with an effect that depends on arg pass if arg is None: raise ValueError("Opcode stack behaviour depends on arg") def get_func_tup(arg, ...
[ "Get the stack effect of an opcode, as a (pop, push) tuple.\n\n If an arg is needed and is not given, a ValueError is raised.\n If op isn't a simple opcode, that is, the flow doesn't always continue\n to the next opcode, a ValueError is raised.\n " ]
Please provide a description of the function:def printcodelist(codelist, to=sys.stdout): labeldict = {} pendinglabels = [] for i, (op, arg) in enumerate(codelist): if isinstance(op, Label): pendinglabels.append(op) elif op is SetLineno: pass else: ...
[ "Get a code list. Print it nicely." ]
Please provide a description of the function:def recompile(filename): # Most of the code here based on the compile.py module. import os import imp import marshal import struct f = open(filename, 'U') try: timestamp = long(os.fstat(f.fileno()).st_mtime) except AttributeError...
[ "Create a .pyc by disassembling the file and assembling it again, printing\n a message that the reassembled file was loaded." ]
Please provide a description of the function:def recompile_all(path): import os if os.path.isdir(path): for root, dirs, files in os.walk(path): for name in files: if name.endswith('.py'): filename = os.path.abspath(os.path.join(root, name)) ...
[ "recursively recompile all .py files in the directory" ]
Please provide a description of the function:def from_code(cls, co): co_code = co.co_code labels = dict((addr, Label()) for addr in findlabels(co_code)) linestarts = dict(cls._findlinestarts(co)) cellfree = co.co_cellvars + co.co_freevars code = CodeList() n = l...
[ "Disassemble a Python code object into a Code object." ]
Please provide a description of the function:def _compute_stacksize(self): # This is done by scanning the code, and computing for each opcode # the stack state at the opcode. code = self.code # A mapping from labels to their positions in the code list label_pos = dict((...
[ "Get a code list, compute its maximal stack usage.", "Get a code position and the stack state before the operation\n was done, and yield pairs (pos, curstack) for the next positions\n to be explored - those are the positions to which you can get\n from the given (pos, curstack).\n...
Please provide a description of the function:def to_code(self): co_argcount = len(self.args) - self.varargs - self.varkwargs co_stacksize = self._compute_stacksize() co_flags = self._compute_flags() co_consts = [self.docstring] co_names = [] co_varnames = list(s...
[ "Assemble a Python code object from a Code object.", "Find the index of item in a sequence and return it.\n If it is not found in the sequence, and can_append is True,\n it is appended to the sequence.\n\n eq is the equality operator to use.\n " ]
Please provide a description of the function:def qqgraph(h1, h2, quantiles=None): if quantiles is None: quantiles = max(min(len(h1), len(h2)) / 2, 1) nq = quantiles # position where to compute the quantiles in [0, 1] xq = array('d', [0.] * nq) # array to contain the quantiles yq1 = ...
[ "\n Return a Graph of a quantile-quantile (QQ) plot and confidence band\n ", "\n KS_cv: KS critical value\n\n 1.36\n KS_cv = -----------\n sqrt( N )\n\n Where 1.36 is for alpha = 0.05 (confidence level 1-5%=95%, about 2 sigma)\n\n For 1 sigma (alpha=0.32, CL=68%), the v...
Please provide a description of the function:def effective_sample_size(h): sum = 0 ew = 0 w = 0 for bin in h.bins(overflow=False): sum += bin.value ew = bin.error w += ew * ew esum = sum * sum / w return esum
[ "\n Calculate the effective sample size for a histogram\n the same way as ROOT does.\n " ]
Please provide a description of the function:def critical_value(n, p): dn = 1 delta = 0.5 res = ROOT.TMath.KolmogorovProb(dn * sqrt(n)) while res > 1.0001 * p or res < 0.9999 * p: if (res > 1.0001 * p): dn = dn + delta if (res < 0.9999 * p): dn = dn - delta ...
[ "\n This function calculates the critical value given\n n and p, and confidence level = 1 - p.\n " ]
Please provide a description of the function:def dump(obj, root_file, proto=0, key=None): if isinstance(root_file, string_types): root_file = root_open(root_file, 'recreate') own_file = True else: own_file = False ret = Pickler(root_file, proto).dump(obj, key) if own_file: ...
[ "Dump an object into a ROOT TFile.\n\n `root_file` may be an open ROOT file or directory, or a string path to an\n existing ROOT file.\n " ]
Please provide a description of the function:def load(root_file, use_proxy=True, key=None): if isinstance(root_file, string_types): root_file = root_open(root_file) own_file = True else: own_file = False obj = Unpickler(root_file, use_proxy).load(key) if own_file: ro...
[ "Load an object from a ROOT TFile.\n\n `root_file` may be an open ROOT file or directory, or a string path to an\n existing ROOT file.\n " ]
Please provide a description of the function:def dump(self, obj, key=None): if key is None: key = '_pickle' with preserve_current_directory(): self.__file.cd() if sys.version_info[0] < 3: pickle.Pickler.dump(self, obj) else: ...
[ "Write a pickled representation of obj to the open TFile." ]
Please provide a description of the function:def load(self, key=None): if key is None: key = '_pickle' obj = None if _compat_hooks: save = _compat_hooks[0]() try: self.__n += 1 s = self.__file.Get(key + ';{0:d}'.format(self.__n)) ...
[ "Read a pickled object representation from the open file." ]
Please provide a description of the function:def iter_ROOT_classes(): class_index = "http://root.cern.ch/root/html/ClassIndex.html" for s in minidom.parse(urlopen(class_index)).getElementsByTagName("span"): if ("class", "typename") in s.attributes.items(): class_name = s.childNodes[0].n...
[ "\n Iterator over all available ROOT classes\n " ]
Please provide a description of the function:def izip_exact(*iterables): rest = [chain(i, _throw()) for i in iterables[1:]] first = chain(iterables[0], _check(rest)) return zip(*[first] + rest)
[ "\n A lazy izip() that ensures that all iterables have the same length.\n A LengthMismatch exception is raised if the iterables' lengths differ.\n\n Examples\n --------\n\n >>> list(zip_exc([]))\n []\n >>> list(zip_exc((), (), ()))\n []\n >>> list(zip_exc(\"abc\", rang...
Please provide a description of the function:def CMS_label(text="Preliminary 2012", sqrts=8, pad=None): if pad is None: pad = ROOT.gPad with preserve_current_canvas(): pad.cd() left_margin = pad.GetLeftMargin() top_margin = pad.GetTopMargin() ypos = 1 - top_margin / ...
[ " Add a 'CMS Preliminary' style label to the current Pad.\n\n The blurbs are drawn in the top margin. The label \"CMS \" + text is drawn\n in the upper left. If sqrts is None, it will be omitted. Otherwise, it\n will be drawn in the upper right.\n " ]
Please provide a description of the function:def make_channel(name, samples, data=None, verbose=False): if verbose: llog = log['make_channel'] llog.info("creating channel {0}".format(name)) # avoid segfault if name begins with a digit by using "channel_" prefix chan = Channel('channel_{...
[ "\n Create a Channel from a list of Samples\n " ]
Please provide a description of the function:def make_measurement(name, channels, lumi=1.0, lumi_rel_error=0.1, output_prefix='./histfactory', POI=None, const_params=None, verbose=False): ...
[ "\n Create a Measurement from a list of Channels\n " ]
Please provide a description of the function:def make_workspace(measurement, channel=None, name=None, silence=False): context = silence_sout_serr if silence else do_nothing with context(): hist2workspace = ROOT.RooStats.HistFactory.HistoToWorkspaceFactoryFast( measurement) if ch...
[ "\n Create a workspace containing the model for a measurement\n\n If `channel` is None then include all channels in the model\n\n If `silence` is True, then silence HistFactory's output on\n stdout and stderr.\n " ]
Please provide a description of the function:def measurements_from_xml(filename, collect_histograms=True, cd_parent=False, silence=False): if not os.path.isfile(filename): raise OSError("the file {0} does not exist".format(fi...
[ "\n Read in a list of Measurements from XML\n " ]
Please provide a description of the function:def write_measurement(measurement, root_file=None, xml_path=None, output_path=None, output_suffix=None, write_workspaces=False, apply_xml_patch...
[ "\n Write a measurement and RooWorkspaces for all contained channels\n into a ROOT file and write the XML files into a directory.\n\n Parameters\n ----------\n\n measurement : HistFactory::Measurement\n An asrootpy'd ``HistFactory::Measurement`` object\n\n root_file : ROOT TFile or string, ...
Please provide a description of the function:def patch_xml(files, root_file=None, float_precision=3): if float_precision < 0: raise ValueError("precision must be greater than 0") def fix_path(match): path = match.group(1) if path: head, tail = os.path.split(path) ...
[ "\n Apply patches to HistFactory XML output from PrintXML\n " ]
Please provide a description of the function:def split_norm_shape(histosys, nominal_hist): up = histosys.GetHistoHigh() dn = histosys.GetHistoLow() up = up.Clone(name=up.name + '_shape') dn = dn.Clone(name=dn.name + '_shape') n_nominal = nominal_hist.integral(overflow=True) n_up = up.integr...
[ "\n Split a HistoSys into normalization (OverallSys) and shape (HistoSys)\n components.\n\n It is recommended to use OverallSys as much as possible, which tries to\n enforce continuity up to the second derivative during\n interpolation/extrapolation. So, if there is indeed a shape variation, then\n ...
Please provide a description of the function:def path(self): ''' Get the path of the wrapped folder ''' if isinstance(self.dir, Directory): return self.dir._path elif isinstance(self.dir, ROOT.TDirectory): return self.dir.GetPath() elif isinstance(self.dir, _Folde...
[]
Please provide a description of the function:def Get(self, path): ''' Get the (modified) object from path ''' self.getting = path try: obj = self.dir.Get(path) return self.apply_view(obj) except DoesNotExist as dne: #print dir(dne) raise Do...
[]
Please provide a description of the function:def Get(self, path): ''' Merge the objects at path in all subdirectories ''' return self.merge_views(x.Get(path) for x in self.dirs)
[]
Please provide a description of the function:def fixup_msg(lvl, msg): if "switching to batch mode..." in msg and lvl == logging.ERROR: return logging.WARNING, msg return lvl, msg
[ "\n Fixup for this ERROR to a WARNING because it has a reasonable fallback.\n WARNING:ROOT.TGClient.TGClient] can't open display \"localhost:10.0\", switching to batch mode...\n In case you run from a remote ssh session, reconnect with ssh -Y\n " ]
Please provide a description of the function:def python_logging_error_handler(level, root_says_abort, location, msg): from ..utils import quickroot as QROOT if not Initialized.value: try: QROOT.kTRUE except AttributeError: # Python is exiting. Do nothing. ...
[ "\n A python error handler for ROOT which maps ROOT's errors and warnings on\n to python's.\n " ]
Please provide a description of the function:def preserve_current_canvas(): old = ROOT.gPad try: yield finally: if old: old.cd() elif ROOT.gPad: # Put things back how they were before. with invisible_canvas(): # This is a round...
[ "\n Context manager which ensures that the current canvas remains the current\n canvas when the context is left.\n " ]
Please provide a description of the function:def preserve_batch_state(): with LOCK: old = ROOT.gROOT.IsBatch() try: yield finally: ROOT.gROOT.SetBatch(old)
[ "\n Context manager which ensures the batch state is the same on exit as it was\n on entry.\n " ]
Please provide a description of the function:def invisible_canvas(): with preserve_current_canvas(): with preserve_batch_state(): ROOT.gROOT.SetBatch() c = ROOT.TCanvas() try: c.cd() yield c finally: c.Close() c.IsA...
[ "\n Context manager yielding a temporary canvas drawn in batch mode, invisible\n to the user. Original state is restored on exit.\n\n Example use; obtain X axis object without interfering with anything::\n\n with invisible_canvas() as c:\n efficiency.Draw()\n g = efficiency.Get...
Please provide a description of the function:def thread_specific_tmprootdir(): with preserve_current_directory(): dname = "rootpy-tmp/thread/{0}".format( threading.current_thread().ident) d = ROOT.gROOT.mkdir(dname) if not d: d = ROOT.gROOT.GetDirectory(dname...
[ "\n Context manager which makes a thread specific gDirectory to avoid\n interfering with the current file.\n\n Use cases:\n\n A TTree Draw function which doesn't want to interfere with whatever\n gDirectory happens to be.\n\n Multi-threading where there are two threads creating objects...
Please provide a description of the function:def set_directory(robject): if (not hasattr(robject, 'GetDirectory') or not hasattr(robject, 'SetDirectory')): log.warning("Cannot set the directory of a `{0}`".format( type(robject))) # Do nothing yield else: ...
[ "\n Context manager to temporarily set the directory of a ROOT object\n (if possible)\n " ]
Please provide a description of the function:def preserve_set_th1_add_directory(state=True): with LOCK: status = ROOT.TH1.AddDirectoryStatus() try: ROOT.TH1.AddDirectory(state) yield finally: ROOT.TH1.AddDirectory(status)
[ "\n Context manager to temporarily set TH1.AddDirectory() state\n " ]
Please provide a description of the function:def working_directory(path): prev_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
[ "\n A context manager that changes the working directory to the given\n path, and then changes it back to its previous value on exit.\n " ]
Please provide a description of the function:def autobinning(data, method="freedman_diaconis"): name = method.replace("-", "_") try: method = getattr(BinningMethods, name) if not isinstance(method, types.FunctionType): raise AttributeError except AttributeError: rais...
[ "\n This method determines the optimal binning for histogramming.\n\n Parameters\n ----------\n data: 1D array-like\n Input data.\n method: string, one of the following:\n - sturges\n - sturges-doane\n - scott\n - sqrt\n - doane\n - freed...
Please provide a description of the function:def all_methods(cls): def name(fn): return fn.__get__(cls).__name__.replace("_", "-") return sorted(name(f) for f in cls.__dict__.values() if isinstance(f, staticmethod))
[ "\n Return the names of all available binning methods\n " ]
Please provide a description of the function:def sturges_doane(data): n = len(data) return np.log10(n) * np.log2(n) + 3
[ "\n References\n ----------\n .. [1] D. Wilkinson, \"The Grammar of Graphics\", 2005.\n http://books.google.it/books?id=_kRX4LoFfGQC&lpg=PA133&ots=APHb0-p6tY&dq=doane%20binning%20histogram&hl=it&pg=PA133#v=onepage&q=doane%20binning%20histogram&f=false\n " ]
Please provide a description of the function:def doane(data): from scipy.stats import skew n = len(data) sigma = np.sqrt(6. * (n - 2.) / (n + 1.) / (n + 3.)) return 1 + np.log2(n) + \ np.log2(1 + np.abs(skew(data)) / sigma)
[ "\n Modified Doane modified\n " ]
Please provide a description of the function:def knuth(data): import scipy.optimize as optimize def f(data): from scipy.special import gammaln m, M = np.min(data), np.max(data) n = len(data) def fff(x): k = x[0] # number of bin...
[ "\n References\n ----------\n .. [1] K. Knuth, \"Optimal Data-Based Binning for Histograms\", 2006.\n http://arxiv.org/pdf/physics/0605197v1.pdf\n " ]
Please provide a description of the function:def lock(path, poll_interval=5, max_age=60): if max_age < 30: raise ValueError("`max_age` must be at least 30 seconds") if poll_interval < 1: raise ValueError("`poll_interval` must be at least 1 second") if poll_interval >= max_age: r...
[ "\n Aquire a file lock in a thread-safe manner that also reaps stale locks\n possibly left behind by processes that crashed hard.\n " ]
Please provide a description of the function:def proxy_global(name, no_expand_macro=False, fname='func', args=()): if no_expand_macro: # pragma: no cover # handle older ROOT versions without _ExpandMacroFunction wrapping @property def gSomething_no_func(self): glob = self(g...
[ "\n Used to automatically asrootpy ROOT's thread local variables\n " ]
Please provide a description of the function:def AddEntry(self, thing, label=None, style=None): if isinstance(thing, HistStack): things = thing else: things = [thing] for thing in things: if getattr(thing, 'inlegend', True): thing_labe...
[ "\n Add an entry to the legend.\n\n If `label` is None, `thing.GetTitle()` will be used as the label.\n\n If `style` is None, `thing.legendstyle` is used if present,\n otherwise `P`.\n " ]
Please provide a description of the function:def get_seh(): if ON_RTD: return lambda x: x ErrorHandlerFunc_t = ctypes.CFUNCTYPE( None, ctypes.c_int, ctypes.c_bool, ctypes.c_char_p, ctypes.c_char_p) # Required to avoid strange dynamic linker problem on OSX. # See https://gi...
[ "\n Makes a function which can be used to set the ROOT error handler with a\n python function and returns the existing error handler.\n ", "\n Set ROOT's warning/error handler. Returns the existing one.\n " ]
Please provide a description of the function:def get_f_code_idx(): frame = sys._getframe() frame_ptr = id(frame) LARGE_ENOUGH = 20 # Look through the frame object until we find the f_tstate variable, whose # value we know from above. ptrs = [ctypes.c_voidp.from_address(frame_ptr+i*svp) ...
[ "\n How many pointers into PyFrame is the ``f_code`` variable?\n " ]
Please provide a description of the function:def get_frame_pointers(frame=None): if frame is None: frame = sys._getframe(2) frame = id(frame) # http://hg.python.org/cpython/file/3aa530c2db06/Include/frameobject.h#l28 F_TRACE_OFFSET = 6 Ppy_object = ctypes.POINTER(ctypes.py_object) ...
[ "\n Obtain writable pointers to ``frame.f_trace`` and ``frame.f_lineno``.\n\n Very dangerous. Unlikely to be portable between python implementations.\n\n This is hard in general because the ``PyFrameObject`` can have a variable size\n depending on the build configuration. We can get it reliably because ...
Please provide a description of the function:def set_linetrace_on_frame(f, localtrace=None): traceptr, _, _ = get_frame_pointers(f) if localtrace is not None: # Need to incref to avoid the frame causing a double-delete ctypes.pythonapi.Py_IncRef(localtrace) # Not sure if this is the...
[ "\n Non-portable function to modify linetracing.\n\n Remember to enable global tracing with :py:func:`sys.settrace`, otherwise no\n effect!\n " ]
Please provide a description of the function:def re_execute_with_exception(frame, exception, traceback): if sys.gettrace() == globaltrace: # If our trace handler is already installed, that means that this # function has been called twice before the line tracer had a chance to # run. Tha...
[ "\n Dark magic. Causes ``frame`` to raise an exception at the current location\n with ``traceback`` appended to it.\n\n Note that since the line tracer is raising an exception, the interpreter\n disables the global trace, so it's not possible to restore the previous\n tracing conditions.\n " ]
Please provide a description of the function:def _inject_jump(self, where, dest): # We're about to do dangerous things to a function's code content. # We can't make a lock to prevent the interpreter from using those # bytes, so the best we can do is to set the check interval to be high # and just p...
[ "\n Monkeypatch bytecode at ``where`` to force it to jump to ``dest``.\n\n Returns function which puts things back to how they were.\n ", "\n Put the bytecode back to how it was. Good as new.\n " ]
Please provide a description of the function:def fix_ipython_startup(fn): BADSTR = 'TPython::Exec( "" )' GOODSTR = 'TPython::Exec( "" );' if sys.version_info[0] < 3: consts = fn.im_func.func_code.co_consts else: consts = fn.__code__.co_consts if BADSTR not in consts: ret...
[ "\n Attempt to fix IPython startup to not print (Bool_t)1\n " ]
Please provide a description of the function:def update(self, value=None): 'Updates the ProgressBar to a new value.' if value is not None and value is not UnknownLength: if (self.maxval is not UnknownLength and not 0 <= value <= self.maxval and not va...
[]
Please provide a description of the function:def start(self): '''Starts measuring time, and prints the bar at 0%. It returns self so you can use it like this: >>> pbar = ProgressBar().start() >>> for i in range(100): ... # do something ... pbar.update(i+1) ...
[]
Please provide a description of the function:def finish(self): 'Puts the ProgressBar bar in the finished state.' self.finished = True self.update(self.maxval) self.fd.write('\n') if self.signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL) if self.redi...
[]
Please provide a description of the function:def Draw(self, *args, **kwargs): self.reset() output = None while self._rollover(): if output is None: # Make our own copy of the drawn histogram output = self._tree.Draw(*args, **kwargs) ...
[ "\n Loop over subfiles, draw each, and sum the output into a single\n histogram.\n " ]
Please provide a description of the function:def interact_plain(header=UP_LINE, local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None): frame = sys._getframe(stack_depth) variables = {} if local_ns is not None: variables.update(local_ns) ...
[ "\n Create an interactive python console\n " ]
Please provide a description of the function:def hist(hists, stacked=True, reverse=False, xpadding=0, ypadding=.1, yerror_in_padding=True, logy=None, snap=True, axes=None, **kwargs): if axes is None: axes = plt.gca() if logy is...
[ "\n Make a matplotlib hist plot from a ROOT histogram, stack or\n list of histograms.\n\n Parameters\n ----------\n\n hists : Hist, list of Hist, HistStack\n The histogram(s) to be plotted\n\n stacked : bool, optional (default=True)\n If True then stack the histograms with the first ...
Please provide a description of the function:def bar(hists, stacked=True, reverse=False, xerr=False, yerr=True, xpadding=0, ypadding=.1, yerror_in_padding=True, rwidth=0.8, snap=True, axes=None, **kwargs): if axes is None: axes = p...
[ "\n Make a matplotlib bar plot from a ROOT histogram, stack or\n list of histograms.\n\n Parameters\n ----------\n\n hists : Hist, list of Hist, HistStack\n The histogram(s) to be plotted\n\n stacked : bool or string, optional (default=True)\n If True then stack the histograms with t...
Please provide a description of the function:def errorbar(hists, xerr=True, yerr=True, xpadding=0, ypadding=.1, xerror_in_padding=True, yerror_in_padding=True, emptybins=True, snap=True, axes=None, **kwargs): ...
[ "\n Make a matplotlib errorbar plot from a ROOT histogram or graph\n or list of histograms and graphs.\n\n Parameters\n ----------\n\n hists : Hist, Graph or list of Hist and Graph\n The histogram(s) and/or Graph(s) to be plotted\n\n xerr : bool, optional (default=True)\n If True, x ...
Please provide a description of the function:def step(h, logy=None, axes=None, **kwargs): if axes is None: axes = plt.gca() if logy is None: logy = axes.get_yscale() == 'log' _set_defaults(h, kwargs, ['common', 'line']) if kwargs.get('color') is None: kwargs['color'] = h.Get...
[ "\n Make a matplotlib step plot from a ROOT histogram.\n\n Parameters\n ----------\n\n h : Hist\n A rootpy Hist\n\n logy : bool, optional (default=None)\n If True then clip the y range between 1E-300 and 1E300.\n If None (the default) then automatically determine if the axes are\...
Please provide a description of the function:def fill_between(a, b, logy=None, axes=None, **kwargs): if axes is None: axes = plt.gca() if logy is None: logy = axes.get_yscale() == 'log' if not isinstance(a, _Hist) or not isinstance(b, _Hist): raise TypeError( "fill_b...
[ "\n Fill the region between two histograms or graphs.\n\n Parameters\n ----------\n\n a : Hist\n A rootpy Hist\n\n b : Hist\n A rootpy Hist\n\n logy : bool, optional (default=None)\n If True then clip the region between 1E-300 and 1E300.\n If None (the default) then aut...
Please provide a description of the function:def hist2d(h, axes=None, colorbar=False, **kwargs): if axes is None: axes = plt.gca() X, Y = np.meshgrid(list(h.x()), list(h.y())) x = X.ravel() y = Y.ravel() z = np.array(h.z()).T # returns of hist2d: (counts, xedges, yedges, Image) ...
[ "\n Draw a 2D matplotlib histogram plot from a 2D ROOT histogram.\n\n Parameters\n ----------\n\n h : Hist2D\n A rootpy Hist2D\n\n axes : matplotlib Axes instance, optional (default=None)\n The axes to plot on. If None then use the global current axes.\n\n colorbar : Boolean, optiona...
Please provide a description of the function:def imshow(h, axes=None, colorbar=False, **kwargs): kwargs.setdefault('aspect', 'auto') if axes is None: axes = plt.gca() z = np.array(h.z()).T axis_image= axes.imshow( z, extent=[ h.xedges(1), h.xedges(h.nbins(0) + ...
[ "\n Draw a matplotlib imshow plot from a 2D ROOT histogram.\n\n Parameters\n ----------\n\n h : Hist2D\n A rootpy Hist2D\n\n axes : matplotlib Axes instance, optional (default=None)\n The axes to plot on. If None then use the global current axes.\n\n colorbar : Boolean, optional (def...
Please provide a description of the function:def contour(h, axes=None, zoom=None, label_contour=False, **kwargs): if axes is None: axes = plt.gca() x = np.array(list(h.x())) y = np.array(list(h.y())) z = np.array(h.z()).T if zoom is not None: from scipy import ndimage if...
[ "\n Draw a matplotlib contour plot from a 2D ROOT histogram.\n\n Parameters\n ----------\n\n h : Hist2D\n A rootpy Hist2D\n\n axes : matplotlib Axes instance, optional (default=None)\n The axes to plot on. If None then use the global current axes.\n\n zoom : float or sequence, option...
Please provide a description of the function:def _post_init(self): if not hasattr(self, '_buffer'): # only set _buffer if model was not specified in the __init__ self._buffer = TreeBuffer() self.read_branches_on_demand = False self._branch_cache = {} self...
[ "\n The standard rootpy _post_init method that is used to initialize both\n new Trees and Trees retrieved from a File.\n " ]
Please provide a description of the function:def always_read(self, branches): if type(branches) not in (list, tuple): raise TypeError("branches must be a list or tuple") self._always_read = branches
[ "\n Always read these branches, even when in caching mode. Maybe you have\n caching enabled and there are branches you want to be updated for each\n entry even though you never access them directly. This is useful if you\n are iterating over an input tree and writing to an output tree sh...
Please provide a description of the function:def branch_type(cls, branch): typename = branch.GetClassName() if not typename: leaf = branch.GetListOfLeaves()[0] typename = leaf.GetTypeName() # check if leaf has multiple elements leaf_count = leaf.G...
[ "\n Return the string representation for the type of a branch\n " ]
Please provide a description of the function:def create_buffer(self, ignore_unsupported=False): bufferdict = OrderedDict() for branch in self.iterbranches(): # only include activated branches if not self.GetBranchStatus(branch.GetName()): continue ...
[ "\n Create this tree's TreeBuffer\n " ]