idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
245,800 | def indirect_age_standardization ( e , b , s_e , s_b , n , alpha = 0.05 ) : smr = standardized_mortality_ratio ( e , b , s_e , s_b , n ) s_r_all = sum ( s_e * 1.0 ) / sum ( s_b * 1.0 ) adjusted_r = s_r_all * smr e_by_n = sum_by_n ( e , 1.0 , n ) log_smr = np . log ( smr ) log_smr_sd = 1.0 / np . sqrt ( e_by_n ) norm_thres = norm . ppf ( 1 - 0.5 * alpha ) log_smr_lower = log_smr - norm_thres * log_smr_sd log_smr_upper = log_smr + norm_thres * log_smr_sd smr_lower = np . exp ( log_smr_lower ) * s_r_all smr_upper = np . exp ( log_smr_upper ) * s_r_all res = list ( zip ( adjusted_r , smr_lower , smr_upper ) ) return res | A utility function to compute rate through indirect age standardization | 278 | 11 |
245,801 | def _univariate_handler ( df , cols , stat = None , w = None , inplace = True , pvalue = 'sim' , outvals = None , swapname = '' , * * kwargs ) : ### Preprocess if not inplace : new_df = df . copy ( ) _univariate_handler ( new_df , cols , stat = stat , w = w , pvalue = pvalue , inplace = True , outvals = outvals , swapname = swapname , * * kwargs ) return new_df if w is None : for name in df . _metadata : this_obj = df . __dict__ . get ( name ) if isinstance ( this_obj , W ) : w = this_obj if w is None : raise Exception ( 'Weights not provided and no weights attached to frame!' ' Please provide a weight or attach a weight to the' ' dataframe' ) ### Prep indexes if outvals is None : outvals = [ ] outvals . insert ( 0 , '_statistic' ) if pvalue . lower ( ) in [ 'all' , 'both' , '*' ] : raise NotImplementedError ( "If you want more than one type of PValue,add" " the targeted pvalue type to outvals. For example:" " Geary(df, cols=['HOVAL'], w=w, outvals=['p_z_sim', " "'p_rand']" ) # this is nontrivial, since we # can't know which p_value types are on the object without computing it. # This is because we don't flag them with @properties, so they're just # arbitrarily assigned post-facto. One solution might be to post-process the # objects, determine which pvalue types are available, and then grab them # all if needed. if pvalue is not '' : outvals . append ( 'p_' + pvalue . lower ( ) ) if isinstance ( cols , str ) : cols = [ cols ] ### Make closure around weights & apply columnwise def column_stat ( column ) : return stat ( column . values , w = w , * * kwargs ) stat_objs = df [ cols ] . apply ( column_stat ) ### Assign into dataframe for col in cols : stat_obj = stat_objs [ col ] y = kwargs . get ( 'y' ) if y is not None : col += '-' + y . name outcols = [ '_' . join ( ( col , val ) ) for val in outvals ] for colname , attname in zip ( outcols , outvals ) : df [ colname ] = stat_obj . __getattribute__ ( attname ) if swapname is not '' : df . columns = [ _swap_ending ( col , swapname ) if col . endswith ( '_statistic' ) else col for col in df . columns ] | Compute a univariate descriptive statistic stat over columns cols in df . | 644 | 15 |
245,802 | def _bivariate_handler ( df , x , y = None , w = None , inplace = True , pvalue = 'sim' , outvals = None , * * kwargs ) : real_swapname = kwargs . pop ( 'swapname' , '' ) if isinstance ( y , str ) : y = [ y ] if isinstance ( x , str ) : x = [ x ] if not inplace : new_df = df . copy ( ) _bivariate_handler ( new_df , x , y = y , w = w , inplace = True , swapname = real_swapname , pvalue = pvalue , outvals = outvals , * * kwargs ) return new_df if y is None : y = x for xi , yi in _it . product ( x , y ) : if xi == yi : continue _univariate_handler ( df , cols = xi , w = w , y = df [ yi ] , inplace = True , pvalue = pvalue , outvals = outvals , swapname = '' , * * kwargs ) if real_swapname is not '' : df . columns = [ _swap_ending ( col , real_swapname ) if col . endswith ( '_statistic' ) else col for col in df . columns ] | Compute a descriptive bivariate statistic over two sets of columns x and y contained in df . | 299 | 19 |
245,803 | def _swap_ending ( s , ending , delim = '_' ) : parts = [ x for x in s . split ( delim ) [ : - 1 ] if x != '' ] parts . append ( ending ) return delim . join ( parts ) | Replace the ending of a string delimited into an arbitrary number of chunks by delim with the ending provided | 54 | 21 |
245,804 | def is_sequence ( i , include = None ) : return ( hasattr ( i , '__getitem__' ) and iterable ( i ) or bool ( include ) and isinstance ( i , include ) ) | Return a boolean indicating whether i is a sequence in the SymPy sense . If anything that fails the test below should be included as being a sequence for your application set include to that object s type ; multiple types should be passed as a tuple of types . | 46 | 51 |
245,805 | def as_int ( n ) : try : result = int ( n ) if result != n : raise TypeError except TypeError : raise ValueError ( '%s is not an integer' % n ) return result | Convert the argument to a builtin integer . | 45 | 10 |
245,806 | def default_sort_key ( item , order = None ) : from sympy . core import S , Basic from sympy . core . sympify import sympify , SympifyError from sympy . core . compatibility import iterable if isinstance ( item , Basic ) : return item . sort_key ( order = order ) if iterable ( item , exclude = string_types ) : if isinstance ( item , dict ) : args = item . items ( ) unordered = True elif isinstance ( item , set ) : args = item unordered = True else : # e.g. tuple, list args = list ( item ) unordered = False args = [ default_sort_key ( arg , order = order ) for arg in args ] if unordered : # e.g. dict, set args = sorted ( args ) cls_index , args = 10 , ( len ( args ) , tuple ( args ) ) else : if not isinstance ( item , string_types ) : try : item = sympify ( item ) except SympifyError : # e.g. lambda x: x pass else : if isinstance ( item , Basic ) : # e.g int -> Integer return default_sort_key ( item ) # e.g. UndefinedFunction # e.g. str cls_index , args = 0 , ( 1 , ( str ( item ) , ) ) return ( cls_index , 0 , item . __class__ . __name__ ) , args , S . One . sort_key ( ) , S . One | Return a key that can be used for sorting . | 332 | 10 |
245,807 | def var ( names , * * args ) : def traverse ( symbols , frame ) : """Recursively inject symbols to the global namespace. """ for symbol in symbols : if isinstance ( symbol , Basic ) : frame . f_globals [ symbol . __str__ ( ) ] = symbol # Once we hace an undefined function class # implemented, put a check for function here else : traverse ( symbol , frame ) from inspect import currentframe frame = currentframe ( ) . f_back try : syms = symbols ( names , * * args ) if syms is not None : if isinstance ( syms , Basic ) : frame . f_globals [ syms . __str__ ( ) ] = syms # Once we hace an undefined function class # implemented, put a check for function here else : traverse ( syms , frame ) finally : del frame # break cyclic dependencies as stated in inspect docs return syms | Create symbols and inject them into the global namespace . | 197 | 10 |
245,808 | def _combine_attribute_arguments ( self , attr_dict , attr ) : # Note: Code & comments unchanged from DirectedHypergraph # If no attribute dict was passed, treat the keyword # arguments as the dict if attr_dict is None : attr_dict = attr # Otherwise, combine the passed attribute dict with # the keyword arguments else : try : attr_dict . update ( attr ) except AttributeError : raise AttributeError ( "attr_dict argument \ must be a dictionary." ) return attr_dict | Combines attr_dict and attr dictionaries by updating attr_dict with attr . | 118 | 21 |
245,809 | def remove_node ( self , node ) : if not self . has_node ( node ) : raise ValueError ( "No such node exists." ) # Loop over every hyperedge in the star of the node; # i.e., over every hyperedge that contains the node for hyperedge_id in self . _star [ node ] : frozen_nodes = self . _hyperedge_attributes [ hyperedge_id ] [ "__frozen_nodes" ] # Remove the node set composing the hyperedge del self . _node_set_to_hyperedge [ frozen_nodes ] # Remove this hyperedge's attributes del self . _hyperedge_attributes [ hyperedge_id ] # Remove node's star del self . _star [ node ] # Remove node's attributes dictionary del self . _node_attributes [ node ] | Removes a node and its attributes from the hypergraph . Removes every hyperedge that contains this node . | 193 | 23 |
245,810 | def add_hyperedge ( self , nodes , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) # Don't allow empty node set (invalid hyperedge) if not nodes : raise ValueError ( "nodes argument cannot be empty." ) # Use frozensets for node sets to allow for hashable keys frozen_nodes = frozenset ( nodes ) is_new_hyperedge = not self . has_hyperedge ( frozen_nodes ) if is_new_hyperedge : # Add nodes to graph (if not already present) self . add_nodes ( frozen_nodes ) # Create new hyperedge name to use as reference for that hyperedge hyperedge_id = self . _assign_next_hyperedge_id ( ) # For each node in the node set, add hyperedge to the node's star for node in frozen_nodes : self . _star [ node ] . add ( hyperedge_id ) # Add the hyperedge ID as the hyperedge that the node set composes self . _node_set_to_hyperedge [ frozen_nodes ] = hyperedge_id # Assign some special attributes to this hyperedge. We assign # a default weight of 1 to the hyperedge. We also store the # original node set in order to return them exactly as the # user passed them into add_hyperedge. self . _hyperedge_attributes [ hyperedge_id ] = { "nodes" : nodes , "__frozen_nodes" : frozen_nodes , "weight" : 1 } else : # If its not a new hyperedge, just get its ID to update attributes hyperedge_id = self . _node_set_to_hyperedge [ frozen_nodes ] # Set attributes and return hyperedge ID self . _hyperedge_attributes [ hyperedge_id ] . update ( attr_dict ) return hyperedge_id | Adds a hyperedge to the hypergraph along with any related attributes of the hyperedge . This method will automatically add any node from the node set that was not in the hypergraph . A hyperedge without a weight attribute specified will be assigned the default value of 1 . | 469 | 57 |
245,811 | def add_hyperedges ( self , hyperedges , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) hyperedge_ids = [ ] for nodes in hyperedges : hyperedge_id = self . add_hyperedge ( nodes , attr_dict . copy ( ) ) hyperedge_ids . append ( hyperedge_id ) return hyperedge_ids | Adds multiple hyperedges to the graph along with any related attributes of the hyperedges . If any node of a hyperedge has not previously been added to the hypergraph it will automatically be added here . Hyperedges without a weight attribute specified will be assigned the default value of 1 . | 112 | 61 |
245,812 | def get_hyperedge_id ( self , nodes ) : frozen_nodes = frozenset ( nodes ) if not self . has_hyperedge ( frozen_nodes ) : raise ValueError ( "No such hyperedge exists." ) return self . _node_set_to_hyperedge [ frozen_nodes ] | From a set of nodes returns the ID of the hyperedge that this set comprises . | 76 | 18 |
245,813 | def get_hyperedge_attribute ( self , hyperedge_id , attribute_name ) : # Note: Code unchanged from DirectedHypergraph if not self . has_hyperedge_id ( hyperedge_id ) : raise ValueError ( "No such hyperedge exists." ) elif attribute_name not in self . _hyperedge_attributes [ hyperedge_id ] : raise ValueError ( "No such attribute exists." ) else : return copy . copy ( self . _hyperedge_attributes [ hyperedge_id ] [ attribute_name ] ) | Given a hyperedge ID and the name of an attribute get a copy of that hyperedge s attribute . | 132 | 23 |
245,814 | def get_hyperedge_attributes ( self , hyperedge_id ) : if not self . has_hyperedge_id ( hyperedge_id ) : raise ValueError ( "No such hyperedge exists." ) dict_to_copy = self . _hyperedge_attributes [ hyperedge_id ] . items ( ) attributes = { } for attr_name , attr_value in dict_to_copy : if attr_name != "__frozen_nodes" : attributes [ attr_name ] = copy . copy ( attr_value ) return attributes | Given a hyperedge ID get a dictionary of copies of that hyperedge s attributes . | 135 | 19 |
245,815 | def get_star ( self , node ) : if node not in self . _node_attributes : raise ValueError ( "No such node exists." ) return self . _star [ node ] . copy ( ) | Given a node get a copy of that node s star that is the set of hyperedges that the node belongs to . | 45 | 25 |
245,816 | def _F_outdegree ( H , F ) : if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) return F ( [ len ( H . get_forward_star ( node ) ) for node in H . get_node_set ( ) ] ) | Returns the result of a function F applied to the set of outdegrees in in the hypergraph . | 72 | 21 |
245,817 | def _F_indegree ( H , F ) : if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) return F ( [ len ( H . get_backward_star ( node ) ) for node in H . get_node_set ( ) ] ) | Returns the result of a function F applied to the list of indegrees in in the hypergraph . | 74 | 21 |
245,818 | def _F_hyperedge_tail_cardinality ( H , F ) : if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) return F ( [ len ( H . get_hyperedge_tail ( hyperedge_id ) ) for hyperedge_id in H . get_hyperedge_id_set ( ) ] ) | Returns the result of a function F applied to the set of cardinalities of hyperedge tails in the hypergraph . | 96 | 24 |
245,819 | def _F_hyperedge_head_cardinality ( H , F ) : if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) return F ( [ len ( H . get_hyperedge_head ( hyperedge_id ) ) for hyperedge_id in H . get_hyperedge_id_set ( ) ] ) | Returns the result of a function F applied to the set of cardinalities of hyperedge heads in the hypergraph . | 96 | 24 |
245,820 | def get_hyperedge_weight_matrix ( H , hyperedge_ids_to_indices ) : # Combined 2 methods into 1; this could be written better hyperedge_weights = { } for hyperedge_id in H . hyperedge_id_iterator ( ) : hyperedge_weights . update ( { hyperedge_ids_to_indices [ hyperedge_id ] : H . get_hyperedge_weight ( hyperedge_id ) } ) hyperedge_weight_vector = [ ] for i in range ( len ( hyperedge_weights . keys ( ) ) ) : hyperedge_weight_vector . append ( hyperedge_weights . get ( i ) ) return sparse . diags ( [ hyperedge_weight_vector ] , [ 0 ] ) | Creates the diagonal matrix W of hyperedge weights as a sparse matrix . | 182 | 16 |
245,821 | def get_hyperedge_degree_matrix ( M ) : degrees = M . sum ( 0 ) . transpose ( ) new_degree = [ ] for degree in degrees : new_degree . append ( int ( degree [ 0 : ] ) ) return sparse . diags ( [ new_degree ] , [ 0 ] ) | Creates the diagonal matrix of hyperedge degrees D_e as a sparse matrix where a hyperedge degree is the cardinality of the hyperedge . | 71 | 33 |
245,822 | def fast_inverse ( M ) : diags = M . diagonal ( ) new_diag = [ ] for value in diags : new_diag . append ( 1.0 / value ) return sparse . diags ( [ new_diag ] , [ 0 ] ) | Computes the inverse of a diagonal matrix . | 60 | 9 |
245,823 | def node_iterator ( self ) : return iter ( self . _node_attributes ) def has_hypernode ( self , hypernode ) : """Determines if a specific hypernode is present in the hypergraph. :param node: reference to hypernode whose presence is being checked. :returns: bool -- true iff the node exists in the hypergraph. """ return hypernode in self . _hypernode_attributes | Provides an iterator over the nodes . | 91 | 8 |
245,824 | def add_hypernode ( self , hypernode , composing_nodes = set ( ) , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) # If the hypernode hasn't previously been added, add it along # with its attributes if not self . has_hypernode ( hypernode ) : attr_dict [ "__composing_nodes" ] = composing_nodes added_nodes = composing_nodes removed_nodes = set ( ) self . _hypernode_attributes [ hypernode ] = attr_dict # Otherwise, just update the hypernode's attributes else : self . _hypernode_attributes [ hypernode ] . update ( attr_dict ) added_nodes = composing_nodes - self . _hypernode_attributes [ hypernode ] [ "__composing_nodes" ] removed_nodes = self . _hypernode_attributes [ hypernode ] [ "__composing_nodes" ] - composing_nodes # For every "composing node" added to this hypernode, update # those nodes attributes to be members of this hypernode for node in added_nodes : _add_hypernode_membership ( node , hypernode ) # For every "composing node" added to this hypernode, update # those nodes attributes to no longer be members of this hypernode for node in remove_nodes : _remove_hypernode_membership ( node , hypernode ) | Adds a hypernode to the graph along with any related attributes of the hypernode . | 335 | 17 |
245,825 | def _create_random_starter ( node_count ) : pi = np . zeros ( node_count , dtype = float ) for i in range ( node_count ) : pi [ i ] = random . random ( ) summation = np . sum ( pi ) for i in range ( node_count ) : pi [ i ] = pi [ i ] / summation return pi | Creates the random starter for the random walk . | 82 | 10 |
245,826 | def _has_converged ( pi_star , pi ) : node_count = pi . shape [ 0 ] EPS = 10e-6 for i in range ( node_count ) : if pi [ i ] - pi_star [ i ] > EPS : return False return True | Checks if the random walk has converged . | 60 | 10 |
245,827 | def add_element ( self , priority , element , count = None ) : if count is None : count = next ( self . counter ) entry = [ priority , count , element ] self . element_finder [ element ] = entry heapq . heappush ( self . pq , entry ) | Adds an element with a specific priority . | 62 | 8 |
245,828 | def reprioritize ( self , priority , element ) : if element not in self . element_finder : raise ValueError ( "No such element in the priority queue." ) entry = self . element_finder [ element ] self . add_element ( priority , element , entry [ 1 ] ) entry [ 1 ] = self . INVALID | Updates the priority of an element . | 72 | 8 |
245,829 | def contains_element ( self , element ) : return ( element in self . element_finder ) and ( self . element_finder [ element ] [ 1 ] != self . INVALID ) | Determines if an element is contained in the priority queue . | 40 | 13 |
245,830 | def is_empty ( self ) : while self . pq : if self . pq [ 0 ] [ 1 ] != self . INVALID : return False else : _ , _ , element = heapq . heappop ( self . pq ) if element in self . element_finder : del self . element_finder [ element ] return True | Determines if the priority queue has any elements . Performs removal of any elements that were marked - as - invalid . | 74 | 25 |
245,831 | def is_connected ( H , source_node , target_node ) : visited_nodes , Pv , Pe = visit ( H , source_node ) return target_node in visited_nodes | Checks if a target node is connected to a source node . That is this method determines if a target node can be visited from the source node in the sense of the Visit algorithm . | 42 | 37 |
245,832 | def is_b_connected ( H , source_node , target_node ) : b_visited_nodes , Pv , Pe , v = b_visit ( H , source_node ) return target_node in b_visited_nodes | Checks if a target node is B - connected to a source node . | 55 | 15 |
245,833 | def is_f_connected ( H , source_node , target_node ) : f_visited_nodes , Pv , Pe , v = f_visit ( H , source_node ) return target_node in f_visited_nodes | Checks if a target node is F - connected to a source node . | 55 | 15 |
245,834 | def from_networkx_graph ( nx_graph ) : import networkx as nx if not isinstance ( nx_graph , nx . Graph ) : raise TypeError ( "Transformation only applicable to undirected \ NetworkX graphs" ) G = UndirectedHypergraph ( ) for node in nx_graph . nodes_iter ( ) : G . add_node ( node , copy . copy ( nx_graph . node [ node ] ) ) for edge in nx_graph . edges_iter ( ) : G . add_hyperedge ( [ edge [ 0 ] , edge [ 1 ] ] , copy . copy ( nx_graph [ edge [ 0 ] ] [ edge [ 1 ] ] ) ) return G | Returns an UndirectedHypergraph object that is the graph equivalent of the given NetworkX Graph object . | 160 | 21 |
245,835 | def from_networkx_digraph ( nx_digraph ) : import networkx as nx if not isinstance ( nx_digraph , nx . DiGraph ) : raise TypeError ( "Transformation only applicable to directed \ NetworkX graphs" ) G = DirectedHypergraph ( ) for node in nx_digraph . nodes_iter ( ) : G . add_node ( node , copy . copy ( nx_digraph . node [ node ] ) ) for edge in nx_digraph . edges_iter ( ) : tail_node = edge [ 0 ] head_node = edge [ 1 ] G . add_hyperedge ( tail_node , head_node , copy . copy ( nx_digraph [ tail_node ] [ head_node ] ) ) return G | Returns a DirectedHypergraph object that is the graph equivalent of the given NetworkX DiGraph object . | 175 | 21 |
245,836 | def get_tail_incidence_matrix ( H , nodes_to_indices , hyperedge_ids_to_indices ) : if not isinstance ( H , DirectedHypergraph ) : raise TypeError ( "Algorithm only applicable to directed hypergraphs" ) rows , cols = [ ] , [ ] for hyperedge_id , hyperedge_index in hyperedge_ids_to_indices . items ( ) : for node in H . get_hyperedge_tail ( hyperedge_id ) : # get the mapping between the node and its ID rows . append ( nodes_to_indices . get ( node ) ) cols . append ( hyperedge_index ) values = np . ones ( len ( rows ) , dtype = int ) node_count = len ( H . get_node_set ( ) ) hyperedge_count = len ( H . get_hyperedge_id_set ( ) ) return sparse . csc_matrix ( ( values , ( rows , cols ) ) , shape = ( node_count , hyperedge_count ) ) | Creates the incidence matrix of the tail nodes of the given hypergraph as a sparse matrix . | 246 | 19 |
245,837 | def add_node ( self , node , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) # If the node hasn't previously been added, add it along # with its attributes if not self . has_node ( node ) : self . _node_attributes [ node ] = attr_dict self . _forward_star [ node ] = set ( ) self . _backward_star [ node ] = set ( ) # Otherwise, just update the node's attributes else : self . _node_attributes [ node ] . update ( attr_dict ) | Adds a node to the graph along with any related attributes of the node . | 145 | 15 |
245,838 | def add_nodes ( self , nodes , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) for node in nodes : # Note: This won't behave properly if the node is actually a tuple if type ( node ) is tuple : # See ("B", {label="negative"}) in the documentation example new_node , node_attr_dict = node # Create a new dictionary and load it with node_attr_dict and # attr_dict, with the former (node_attr_dict) taking precedence new_dict = attr_dict . copy ( ) new_dict . update ( node_attr_dict ) self . add_node ( new_node , new_dict ) else : # See "A" in the documentation example self . add_node ( node , attr_dict . copy ( ) ) | Adds multiple nodes to the graph along with any related attributes of the nodes . | 200 | 15 |
245,839 | def remove_node ( self , node ) : if not self . has_node ( node ) : raise ValueError ( "No such node exists." ) # Remove every hyperedge which is in the forward star of the node forward_star = self . get_forward_star ( node ) for hyperedge_id in forward_star : self . remove_hyperedge ( hyperedge_id ) # Remove every hyperedge which is in the backward star of the node # but that is not also in the forward start of the node (to handle # overlapping hyperedges) backward_star = self . get_backward_star ( node ) for hyperedge_id in backward_star - forward_star : self . remove_hyperedge ( hyperedge_id ) # Remove node's forward and backward star del self . _forward_star [ node ] del self . _backward_star [ node ] # Remove node's attributes dictionary del self . _node_attributes [ node ] | Removes a node and its attributes from the hypergraph . Removes every hyperedge that contains this node in either the head or the tail . | 215 | 30 |
245,840 | def get_node_attribute ( self , node , attribute_name ) : if not self . has_node ( node ) : raise ValueError ( "No such node exists." ) elif attribute_name not in self . _node_attributes [ node ] : raise ValueError ( "No such attribute exists." ) else : return copy . copy ( self . _node_attributes [ node ] [ attribute_name ] ) | Given a node and the name of an attribute get a copy of that node s attribute . | 90 | 18 |
245,841 | def get_node_attributes ( self , node ) : if not self . has_node ( node ) : raise ValueError ( "No such node exists." ) attributes = { } for attr_name , attr_value in self . _node_attributes [ node ] . items ( ) : attributes [ attr_name ] = copy . copy ( attr_value ) return attributes | Given a node get a dictionary with copies of that node s attributes . | 84 | 14 |
245,842 | def add_hyperedge ( self , tail , head , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) # Don't allow both empty tail and head containers (invalid hyperedge) if not tail and not head : raise ValueError ( "tail and head arguments \ cannot both be empty." ) # Use frozensets for tail and head sets to allow for hashable keys frozen_tail = frozenset ( tail ) frozen_head = frozenset ( head ) # Initialize a successor dictionary for the tail and head, respectively if frozen_tail not in self . _successors : self . _successors [ frozen_tail ] = { } if frozen_head not in self . _predecessors : self . _predecessors [ frozen_head ] = { } is_new_hyperedge = not self . has_hyperedge ( frozen_tail , frozen_head ) if is_new_hyperedge : # Add tail and head nodes to graph (if not already present) self . add_nodes ( frozen_head ) self . add_nodes ( frozen_tail ) # Create new hyperedge name to use as reference for that hyperedge hyperedge_id = self . _assign_next_hyperedge_id ( ) # Add hyperedge to the forward-star and to the backward-star # for each node in the tail and head sets, respectively for node in frozen_tail : self . _forward_star [ node ] . add ( hyperedge_id ) for node in frozen_head : self . _backward_star [ node ] . add ( hyperedge_id ) # Add the hyperedge as the successors and predecessors # of the tail set and head set, respectively self . _successors [ frozen_tail ] [ frozen_head ] = hyperedge_id self . _predecessors [ frozen_head ] [ frozen_tail ] = hyperedge_id # Assign some special attributes to this hyperedge. We assign # a default weight of 1 to the hyperedge. We also store the # original tail and head sets in order to return them exactly # as the user passed them into add_hyperedge. self . _hyperedge_attributes [ hyperedge_id ] = { "tail" : tail , "__frozen_tail" : frozen_tail , "head" : head , "__frozen_head" : frozen_head , "weight" : 1 } else : # If its not a new hyperedge, just get its ID to update attributes hyperedge_id = self . _successors [ frozen_tail ] [ frozen_head ] # Set attributes and return hyperedge ID self . _hyperedge_attributes [ hyperedge_id ] . update ( attr_dict ) return hyperedge_id | Adds a hyperedge to the hypergraph along with any related attributes of the hyperedge . This method will automatically add any node from the tail and head that was not in the hypergraph . A hyperedge without a weight attribute specified will be assigned the default value of 1 . | 643 | 58 |
245,843 | def add_hyperedges ( self , hyperedges , attr_dict = None , * * attr ) : attr_dict = self . _combine_attribute_arguments ( attr_dict , attr ) hyperedge_ids = [ ] for hyperedge in hyperedges : if len ( hyperedge ) == 3 : # See ("A", "C"), ("B"), {weight: 2}) in the # documentation example tail , head , hyperedge_attr_dict = hyperedge # Create a new dictionary and load it with node_attr_dict and # attr_dict, with the former (node_attr_dict) taking precedence new_dict = attr_dict . copy ( ) new_dict . update ( hyperedge_attr_dict ) hyperedge_id = self . add_hyperedge ( tail , head , new_dict ) else : # See (["A", "B"], ["C", "D"]) in the documentation example tail , head = hyperedge hyperedge_id = self . add_hyperedge ( tail , head , attr_dict . copy ( ) ) hyperedge_ids . append ( hyperedge_id ) return hyperedge_ids | Adds multiple hyperedges to the graph along with any related attributes of the hyperedges . If any node in the tail or head of any hyperedge has not previously been added to the hypergraph it will automatically be added here . Hyperedges without a weight attribute specified will be assigned the default value of 1 . | 273 | 66 |
245,844 | def get_hyperedge_id ( self , tail , head ) : frozen_tail = frozenset ( tail ) frozen_head = frozenset ( head ) if not self . has_hyperedge ( frozen_tail , frozen_head ) : raise ValueError ( "No such hyperedge exists." ) return self . _successors [ frozen_tail ] [ frozen_head ] | From a tail and head set of nodes returns the ID of the hyperedge that these sets comprise . | 86 | 21 |
245,845 | 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 . | 49 | 13 |
245,846 | 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 . | 51 | 13 |
245,847 | 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 ( ) return set ( self . _successors [ frozen_tail ] . values ( ) ) | Given a tail set of nodes get a list of edges of which the node set is the tail of each edge . | 82 | 23 |
245,848 | 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 : return set ( ) return set ( self . _predecessors [ frozen_head ] . values ( ) ) | Given a head set of nodes get a list of edges of which the node set is the head of each edge . | 85 | 23 |
245,849 | 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 : return False return True | Indicates whether the hypergraph is a BF - hypergraph . A BF - hypergraph consists of only B - hyperedges and F - hyperedges . See is_B_hypergraph or is_F_hypergraph for more details . | 86 | 51 |
245,850 | 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 hypergraph induced by the provided set of nodes . That is the induced subhypergraph s node set corresponds precisely to the nodes provided and the coressponding hyperedges in the subhypergraph are only those from the original graph consist of tail and head sets that are subsets of the provided nodes . | 53 | 77 |
245,851 | 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 raise KeyError ( 'Key not found: %r' % key ) | Return a list of all values matching the key . | 80 | 10 |
245,852 | def extend ( self , * args , * * kwargs ) : self . _extend ( args , kwargs , 'extend' , self . _extend_items ) | Extend current MultiDict with more values . | 40 | 10 |
245,853 | 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 . | 54 | 14 |
245,854 | 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 : ret . append ( item [ 2 ] ) del self . _impl . _items [ i ] self . _impl . incr_version ( ) found = True if not found : if default is _marker : raise KeyError ( key ) else : return default else : ret . reverse ( ) return ret | Remove all occurrences of key and return the list of corresponding values . | 140 | 13 |
245,855 | def total ( self , xbin1 = 1 , xbin2 = - 2 ) : return self . hist . integral ( xbin1 = xbin1 , xbin2 = xbin2 , error = True ) | Return the total yield and its associated statistical uncertainty . | 46 | 10 |
245,856 | def iter_sys ( self ) : names = self . sys_names ( ) for name in names : osys = self . GetOverallSys ( name ) hsys = self . GetHistoSys ( name ) yield name , osys , hsys | Iterate over sys_name overall_sys histo_sys . overall_sys or histo_sys may be None for any given sys_name . | 53 | 32 |
245,857 | 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 ) if osys is None : osys_high , osys_low = 1. , 1. else : osys_high , osys_low = osys . high , osys . low if hsys is None : hsys_high = self . hist . Clone ( shallow = True ) hsys_low = self . hist . Clone ( shallow = True ) else : hsys_high = hsys . high . Clone ( shallow = True ) hsys_low = hsys . low . Clone ( shallow = True ) return hsys_low * osys_low , hsys_high * osys_high | Return the effective low and high histogram for a given systematic . If this sample does not contain the named systematic then return the nominal histogram for both low and high variations . | 200 | 35 |
245,858 | 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 total_low is None : total_low = low . Clone ( shallow = True ) else : total_low += low if total_high is None : total_high = high . Clone ( shallow = True ) else : total_high += high return total_low , total_high | Return the effective total low and high histogram for a given systematic over samples in this channel . If a sample does not contain the named systematic then its nominal histogram is used for both low and high variations . | 119 | 42 |
245,859 | def apply_snapshot ( self , argset ) : clone = self . Clone ( ) args = [ var for var in argset if not ( var . name . startswith ( 'binWidth_obs_x_' ) or var . name . startswith ( 'gamma_stat' ) or var . name . startswith ( 'nom_' ) ) ] # handle NormFactors first nargs = [ ] for var in args : is_norm = False name = var . name . replace ( 'alpha_' , '' ) for sample in clone . samples : if sample . GetNormFactor ( name ) is not None : log . info ( "applying snapshot of {0} on sample {1}" . format ( name , sample . name ) ) is_norm = True # scale the entire sample sample *= var . value # add an OverallSys for the error osys = OverallSys ( name , low = 1. - var . error / var . value , high = 1. + var . error / var . value ) sample . AddOverallSys ( osys ) # remove the NormFactor sample . RemoveNormFactor ( name ) if not is_norm : nargs . append ( var ) # modify the nominal shape and systematics for sample in clone . samples : # check that hist is not NULL if sample . hist is None : raise RuntimeError ( "sample {0} does not have a " "nominal histogram" . format ( sample . name ) ) nominal = sample . hist . Clone ( shallow = True ) for var in nargs : name = var . name . replace ( 'alpha_' , '' ) if not sample . has_sys ( name ) : continue log . info ( "applying snapshot of {0} on sample {1}" . format ( name , sample . name ) ) low , high = sample . sys_hist ( name ) # modify nominal val = var . value if val > 0 : sample . hist += ( high - nominal ) * val elif val < 0 : sample . hist += ( nominal - low ) * val # TODO: # modify OverallSys # modify HistoSys return clone | Create a clone of this Channel where histograms are modified according to the values of the nuisance parameters in the snapshot . This is useful when creating post - fit distribution plots . | 454 | 34 |
245,860 | 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 : while pendinglabels : labeldict [ pendinglabels . pop ( ) ] = i lineno = None islabel = False for i , ( op , arg ) in enumerate ( codelist ) : if op is SetLineno : lineno = arg print >> to continue if isinstance ( op , Label ) : islabel = True continue if lineno is None : linenostr = '' else : linenostr = str ( lineno ) lineno = None if islabel : islabelstr = '>>' islabel = False else : islabelstr = '' if op in hasconst : argstr = repr ( arg ) elif op in hasjump : try : argstr = 'to ' + str ( labeldict [ arg ] ) except KeyError : argstr = repr ( arg ) elif op in hasarg : argstr = str ( arg ) else : argstr = '' print >> to , '%3s %2s %4d %-20s %s' % ( linenostr , islabelstr , i , op , argstr ) | Get a code list . Print it nicely . | 302 | 9 |
245,861 | 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 : timestamp = long ( os . stat ( filename ) . st_mtime ) codestring = f . read ( ) f . close ( ) if codestring and codestring [ - 1 ] != '\n' : codestring = codestring + '\n' try : codeobject = compile ( codestring , filename , 'exec' ) except SyntaxError : print >> sys . stderr , "Skipping %s - syntax error." % filename return cod = Code . from_code ( codeobject ) message = "reassembled %r imported.\n" % filename cod . code [ : 0 ] = [ # __import__('sys').stderr.write(message) ( LOAD_GLOBAL , '__import__' ) , ( LOAD_CONST , 'sys' ) , ( CALL_FUNCTION , 1 ) , ( LOAD_ATTR , 'stderr' ) , ( LOAD_ATTR , 'write' ) , ( LOAD_CONST , message ) , ( CALL_FUNCTION , 1 ) , ( POP_TOP , None ) , ] codeobject2 = cod . to_code ( ) fc = open ( filename + 'c' , 'wb' ) fc . write ( '\0\0\0\0' ) fc . write ( struct . pack ( '<l' , timestamp ) ) marshal . dump ( codeobject2 , fc ) fc . flush ( ) fc . seek ( 0 , 0 ) fc . write ( imp . get_magic ( ) ) fc . close ( ) | Create a . pyc by disassembling the file and assembling it again printing a message that the reassembled file was loaded . | 418 | 26 |
245,862 | 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 ) ) print >> sys . stderr , filename recompile ( filename ) else : filename = os . path . abspath ( path ) recompile ( filename ) | recursively recompile all . py files in the directory | 106 | 12 |
245,863 | 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 = len ( co_code ) i = 0 extended_arg = 0 while i < n : op = Opcode ( ord ( co_code [ i ] ) ) if i in labels : code . append ( ( labels [ i ] , None ) ) if i in linestarts : code . append ( ( SetLineno , linestarts [ i ] ) ) i += 1 if op in hascode : lastop , lastarg = code [ - 1 ] if lastop != LOAD_CONST : raise ValueError ( "%s should be preceded by LOAD_CONST code" % op ) code [ - 1 ] = ( LOAD_CONST , Code . from_code ( lastarg ) ) if op not in hasarg : code . append ( ( op , None ) ) else : arg = ord ( co_code [ i ] ) + ord ( co_code [ i + 1 ] ) * 256 + extended_arg extended_arg = 0 i += 2 if op == opcode . EXTENDED_ARG : extended_arg = arg << 16 elif op in hasconst : code . append ( ( op , co . co_consts [ arg ] ) ) elif op in hasname : code . append ( ( op , co . co_names [ arg ] ) ) elif op in hasjabs : code . append ( ( op , labels [ arg ] ) ) elif op in hasjrel : code . append ( ( op , labels [ i + arg ] ) ) elif op in haslocal : code . append ( ( op , co . co_varnames [ arg ] ) ) elif op in hascompare : code . append ( ( op , cmp_op [ arg ] ) ) elif op in hasfree : code . append ( ( op , cellfree [ arg ] ) ) else : code . append ( ( op , arg ) ) varargs = bool ( co . co_flags & CO_VARARGS ) varkwargs = bool ( co . co_flags & CO_VARKEYWORDS ) newlocals = bool ( co . co_flags & CO_NEWLOCALS ) args = co . co_varnames [ : co . co_argcount + varargs + varkwargs ] if co . co_consts and isinstance ( co . co_consts [ 0 ] , basestring ) : docstring = co . co_consts [ 0 ] else : docstring = None return cls ( code = code , freevars = co . co_freevars , args = args , varargs = varargs , varkwargs = varkwargs , newlocals = newlocals , name = co . co_name , filename = co . co_filename , firstlineno = co . co_firstlineno , docstring = docstring , ) | Disassemble a Python code object into a Code object . | 697 | 12 |
245,864 | 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 | Calculate the effective sample size for a histogram the same way as ROOT does . | 61 | 19 |
245,865 | 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 delta = delta / 2. res = ROOT . TMath . KolmogorovProb ( dn * sqrt ( n ) ) return dn | This function calculates the critical value given n and p and confidence level = 1 - p . | 131 | 18 |
245,866 | 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 : root_file . Close ( ) return ret | Dump an object into a ROOT TFile . | 92 | 11 |
245,867 | 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 : root_file . Close ( ) return obj | Load an object from a ROOT TFile . | 88 | 10 |
245,868 | 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 : super ( Pickler , self ) . dump ( obj ) s = ROOT . TObjString ( self . __io . getvalue ( ) ) self . __io . reopen ( ) s . Write ( key ) self . __file . GetFile ( ) . Flush ( ) self . __pmap . clear ( ) | Write a pickled representation of obj to the open TFile . | 135 | 13 |
245,869 | 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 ) ) self . __io . setvalue ( s . GetName ( ) ) if sys . version_info [ 0 ] < 3 : obj = pickle . Unpickler . load ( self ) else : obj = super ( Unpickler , self ) . load ( ) self . __io . reopen ( ) finally : if _compat_hooks : save = _compat_hooks [ 1 ] ( save ) return obj | Read a pickled object representation from the open file . | 172 | 11 |
245,870 | 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 ] . nodeValue try : yield getattr ( QROOT , class_name ) except AttributeError : pass | Iterator over all available ROOT classes | 118 | 7 |
245,871 | 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 / 2. l = ROOT . TLatex ( left_margin , ypos , "CMS " + text ) l . SetTextAlign ( 12 ) # left-middle l . SetNDC ( ) # The text is 90% as tall as the margin it lives in. l . SetTextSize ( 0.90 * top_margin ) l . Draw ( ) keepalive ( pad , l ) # Draw sqrt(s) label, if desired if sqrts : right_margin = pad . GetRightMargin ( ) p = ROOT . TLatex ( 1 - right_margin , ypos , "#sqrt{{s}}={0:d}TeV" . format ( sqrts ) ) p . SetTextAlign ( 32 ) # right-middle p . SetNDC ( ) p . SetTextSize ( 0.90 * top_margin ) p . Draw ( ) keepalive ( pad , p ) else : p = None pad . Modified ( ) pad . Update ( ) return l , p | Add a CMS Preliminary style label to the current Pad . | 306 | 12 |
245,872 | 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_{0}' . format ( name ) ) chan . SetStatErrorConfig ( 0.05 , "Poisson" ) if data is not None : if verbose : llog . info ( "setting data" ) chan . SetData ( data ) for sample in samples : if verbose : llog . info ( "adding sample {0}" . format ( sample . GetName ( ) ) ) chan . AddSample ( sample ) return chan | Create a Channel from a list of Samples | 175 | 9 |
245,873 | def make_measurement ( name , channels , lumi = 1.0 , lumi_rel_error = 0.1 , output_prefix = './histfactory' , POI = None , const_params = None , verbose = False ) : if verbose : llog = log [ 'make_measurement' ] llog . info ( "creating measurement {0}" . format ( name ) ) if not isinstance ( channels , ( list , tuple ) ) : channels = [ channels ] # Create the measurement meas = Measurement ( 'measurement_{0}' . format ( name ) , '' ) meas . SetOutputFilePrefix ( output_prefix ) if POI is not None : if isinstance ( POI , string_types ) : if verbose : llog . info ( "setting POI {0}" . format ( POI ) ) meas . SetPOI ( POI ) else : if verbose : llog . info ( "adding POIs {0}" . format ( ', ' . join ( POI ) ) ) for p in POI : meas . AddPOI ( p ) if verbose : llog . info ( "setting lumi={0:f} +/- {1:f}" . format ( lumi , lumi_rel_error ) ) meas . lumi = lumi meas . lumi_rel_error = lumi_rel_error for channel in channels : if verbose : llog . info ( "adding channel {0}" . format ( channel . GetName ( ) ) ) meas . AddChannel ( channel ) if const_params is not None : if verbose : llog . info ( "adding constant parameters {0}" . format ( ', ' . join ( const_params ) ) ) for param in const_params : meas . AddConstantParam ( param ) return meas | Create a Measurement from a list of Channels | 398 | 10 |
245,874 | 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 channel is not None : workspace = hist2workspace . MakeSingleChannelModel ( measurement , channel ) else : workspace = hist2workspace . MakeCombinedModel ( measurement ) workspace = asrootpy ( workspace ) keepalive ( workspace , measurement ) if name is not None : workspace . SetName ( 'workspace_{0}' . format ( name ) ) return workspace | Create a workspace containing the model for a measurement | 146 | 9 |
245,875 | 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 ( filename ) ) silence_context = silence_sout_serr if silence else do_nothing filename = os . path . abspath ( os . path . normpath ( filename ) ) if cd_parent : xml_directory = os . path . dirname ( filename ) parent = os . path . abspath ( os . path . join ( xml_directory , os . pardir ) ) cd_context = working_directory else : parent = None cd_context = do_nothing log . info ( "parsing XML in {0} ..." . format ( filename ) ) with cd_context ( parent ) : parser = ROOT . RooStats . HistFactory . ConfigParser ( ) with silence_context ( ) : measurements_vect = parser . GetMeasurementsFromXML ( filename ) # prevent measurements_vect from being garbage collected ROOT . SetOwnership ( measurements_vect , False ) measurements = [ ] for m in measurements_vect : if collect_histograms : with silence_context ( ) : m . CollectHistograms ( ) measurements . append ( asrootpy ( m ) ) return measurements | Read in a list of Measurements from XML | 295 | 9 |
245,876 | def write_measurement ( measurement , root_file = None , xml_path = None , output_path = None , output_suffix = None , write_workspaces = False , apply_xml_patches = True , silence = False ) : context = silence_sout_serr if silence else do_nothing output_name = measurement . name if output_suffix is not None : output_name += '_{0}' . format ( output_suffix ) output_name = output_name . replace ( ' ' , '_' ) if xml_path is None : xml_path = 'xml_{0}' . format ( output_name ) if output_path is not None : xml_path = os . path . join ( output_path , xml_path ) if not os . path . exists ( xml_path ) : mkdir_p ( xml_path ) if root_file is None : root_file = 'ws_{0}.root' . format ( output_name ) if output_path is not None : root_file = os . path . join ( output_path , root_file ) own_file = False if isinstance ( root_file , string_types ) : root_file = root_open ( root_file , 'recreate' ) own_file = True with preserve_current_directory ( ) : root_file . cd ( ) log . info ( "writing histograms and measurement in {0} ..." . format ( root_file . GetName ( ) ) ) with context ( ) : measurement . writeToFile ( root_file ) # get modified measurement out_m = root_file . Get ( measurement . name ) log . info ( "writing XML in {0} ..." . format ( xml_path ) ) with context ( ) : out_m . PrintXML ( xml_path ) if write_workspaces : log . info ( "writing combined model in {0} ..." . format ( root_file . GetName ( ) ) ) workspace = make_workspace ( measurement , silence = silence ) workspace . Write ( ) for channel in measurement . channels : log . info ( "writing model for channel `{0}` in {1} ..." . format ( channel . name , root_file . GetName ( ) ) ) workspace = make_workspace ( measurement , channel = channel , silence = silence ) workspace . Write ( ) if apply_xml_patches : # patch the output XML to avoid HistFactory bugs patch_xml ( glob ( os . path . join ( xml_path , '*.xml' ) ) , root_file = os . path . basename ( root_file . GetName ( ) ) ) if own_file : root_file . Close ( ) | Write a measurement and RooWorkspaces for all contained channels into a ROOT file and write the XML files into a directory . | 586 | 26 |
245,877 | 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 ) new_path = os . path . join ( os . path . basename ( head ) , tail ) else : new_path = '' return '<Input>{0}</Input>' . format ( new_path ) for xmlfilename in files : xmlfilename = os . path . abspath ( os . path . normpath ( xmlfilename ) ) patched_xmlfilename = '{0}.tmp' . format ( xmlfilename ) log . info ( "patching {0} ..." . format ( xmlfilename ) ) fin = open ( xmlfilename , 'r' ) fout = open ( patched_xmlfilename , 'w' ) for line in fin : if root_file is not None : line = re . sub ( 'InputFile="[^"]*"' , 'InputFile="{0}"' . format ( root_file ) , line ) line = line . replace ( '<StatError Activate="True" InputFile="" ' 'HistoName="" HistoPath="" />' , '<StatError Activate="True" />' ) line = re . sub ( '<Combination OutputFilePrefix="(\S*)" >' , '<Combination OutputFilePrefix="hist2workspace" >' , line ) line = re . sub ( '\w+=""' , '' , line ) line = re . sub ( '\s+/>' , ' />' , line ) line = re . sub ( '(\S)\s+</' , r'\1</' , line ) # HistFactory bug: line = re . sub ( 'InputFileHigh="\S+"' , '' , line ) line = re . sub ( 'InputFileLow="\S+"' , '' , line ) # HistFactory bug: line = line . replace ( '<ParamSetting Const="True"></ParamSetting>' , '' ) # chop off floats to desired precision line = re . sub ( r'"(\d*\.\d{{{0:d},}})"' . format ( float_precision + 1 ) , lambda x : '"{0}"' . format ( str ( round ( float ( x . group ( 1 ) ) , float_precision ) ) ) , line ) line = re . sub ( '"\s\s+(\S)' , r'" \1' , line ) line = re . sub ( '<Input>(.*)</Input>' , fix_path , line ) fout . write ( line ) fin . close ( ) fout . close ( ) shutil . move ( patched_xmlfilename , xmlfilename ) if not os . path . isfile ( os . path . join ( os . path . dirname ( xmlfilename ) , 'HistFactorySchema.dtd' ) ) : rootsys = os . getenv ( 'ROOTSYS' , None ) if rootsys is not None : dtdfile = os . path . join ( rootsys , 'etc/HistFactorySchema.dtd' ) target = os . path . dirname ( xmlfilename ) if os . path . isfile ( dtdfile ) : log . info ( "copying {0} to {1} ..." . format ( dtdfile , target ) ) shutil . copy ( dtdfile , target ) else : log . warning ( "{0} does not exist" . format ( dtdfile ) ) else : log . warning ( "$ROOTSYS is not set so cannot find HistFactorySchema.dtd" ) | Apply patches to HistFactory XML output from PrintXML | 859 | 11 |
245,878 | def path ( self ) : if isinstance ( self . dir , Directory ) : return self . dir . _path elif isinstance ( self . dir , ROOT . TDirectory ) : return self . dir . GetPath ( ) elif isinstance ( self . dir , _FolderView ) : return self . dir . path ( ) else : return str ( self . dir ) | Get the path of the wrapped folder | 81 | 7 |
245,879 | def Get ( self , path ) : return self . merge_views ( x . Get ( path ) for x in self . dirs ) | Merge the objects at path in all subdirectories | 29 | 11 |
245,880 | 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. return QROOT . kInfo , QROOT . kWarning , QROOT . kError , QROOT . kFatal , QROOT . kSysError QROOT . gErrorIgnoreLevel Initialized . value = True try : QROOT . kTRUE except RuntimeError : # Note: If the above causes us problems, it's because this logging # handler has been called multiple times already with an # exception. In that case we need to force upstream to raise it. _ , exc , traceback = sys . exc_info ( ) caller = sys . _getframe ( 2 ) re_execute_with_exception ( caller , exc , traceback ) if level < QROOT . gErrorIgnoreLevel : # Needed to silence some "normal" startup warnings # (copied from PyROOT Utility.cxx) return if sys . version_info [ 0 ] >= 3 : location = location . decode ( 'utf-8' ) msg = msg . decode ( 'utf-8' ) log = ROOT_log . getChild ( location . replace ( "::" , "." ) ) if level >= QROOT . kSysError or level >= QROOT . kFatal : lvl = logging . CRITICAL elif level >= QROOT . kError : lvl = logging . ERROR elif level >= QROOT . kWarning : lvl = logging . WARNING elif level >= QROOT . kInfo : lvl = logging . INFO else : lvl = logging . DEBUG if not SANE_REGEX . match ( msg ) : # Not ASCII characters. Escape them. msg = repr ( msg ) [ 1 : - 1 ] # Apply fixups to improve consistency of errors/warnings lvl , msg = fixup_msg ( lvl , msg ) log . log ( lvl , msg ) # String checks are used because we need a way of (un)forcing abort without # modifying a global variable (gErrorAbortLevel) for the multithread tests abort = lvl >= ABORT_LEVEL or "rootpy.ALWAYSABORT" in msg or root_says_abort if abort and not "rootpy.NEVERABORT" in msg : caller = sys . _getframe ( 1 ) try : # We can't raise an exception from here because ctypes/PyROOT swallows it. # Hence the need for dark magic, we re-raise it within a trace. from . . import ROOTError raise ROOTError ( level , location , msg ) except RuntimeError : _ , exc , traceback = sys . exc_info ( ) if SHOWTRACE . enabled : from traceback import print_stack print_stack ( caller ) if DANGER . enabled : # Avert your eyes, dark magic be within... re_execute_with_exception ( caller , exc , traceback ) if root_says_abort : log . critical ( "abort().. expect a stack trace" ) ctypes . CDLL ( None ) . abort ( ) | A python error handler for ROOT which maps ROOT s errors and warnings on to python s . | 712 | 20 |
245,881 | 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-about way of resetting gPad to None. # No other technique I tried could do it. pass | Context manager which ensures that the current canvas remains the current canvas when the context is left . | 82 | 18 |
245,882 | def preserve_batch_state ( ) : with LOCK : old = ROOT . gROOT . IsBatch ( ) try : yield finally : ROOT . gROOT . SetBatch ( old ) | Context manager which ensures the batch state is the same on exit as it was on entry . | 45 | 18 |
245,883 | 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 ( ) . Destructor ( c ) | Context manager yielding a temporary canvas drawn in batch mode invisible to the user . Original state is restored on exit . | 78 | 22 |
245,884 | 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 ) assert d , "Unexpected failure, can't cd to tmpdir." d . cd ( ) yield d | Context manager which makes a thread specific gDirectory to avoid interfering with the current file . | 105 | 17 |
245,885 | def working_directory ( path ) : prev_cwd = os . getcwd ( ) os . chdir ( path ) try : yield finally : os . chdir ( prev_cwd ) | A context manager that changes the working directory to the given path and then changes it back to its previous value on exit . | 42 | 24 |
245,886 | def autobinning ( data , method = "freedman_diaconis" ) : name = method . replace ( "-" , "_" ) try : method = getattr ( BinningMethods , name ) if not isinstance ( method , types . FunctionType ) : raise AttributeError except AttributeError : raise ValueError ( "`{0}` is not a valid binning method" . format ( name ) ) if len ( data ) < 4 : return 1 , np . min ( data ) , np . max ( data ) return int ( np . ceil ( method ( data ) ) ) , np . min ( data ) , np . max ( data ) | This method determines the optimal binning for histogramming . | 143 | 12 |
245,887 | 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 ) ) | Return the names of all available binning methods | 69 | 9 |
245,888 | 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 ) | Modified Doane modified | 84 | 5 |
245,889 | 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 : raise ValueError ( "`poll_interval` must be less than `max_age`" ) proc = '{0:d}@{1}' . format ( os . getpid ( ) , platform . node ( ) ) lock = LockFile ( path ) log . debug ( "{0} attempting to lock {1}" . format ( proc , path ) ) while not lock . i_am_locking ( ) : if lock . is_locked ( ) : # Protect against race condition try : # Check age of the lock file age = time . time ( ) - os . stat ( lock . lock_file ) [ stat . ST_MTIME ] # Break the lock if too old (considered stale) if age > max_age : lock . break_lock ( ) # What if lock was released and reacquired in the meantime? # We don't want to break a fresh lock! # If a lock is stale then we may have many threads # attempting to break it here at the "same time". # Avoid the possibility of some thread trying to break the # lock after it has already been broken and after the first # other thread attempting to acquire the lock by sleeping # for 0.5 seconds below. log . warning ( "{0} broke lock on {1} " "that is {2:d} seconds old" . format ( proc , path , int ( age ) ) ) except OSError : # Lock was released just now # os.path.exists(lock.lock_file) is False # OSError may be raised by os.stat() or lock.break_lock() above pass time . sleep ( 0.5 ) try : log . debug ( "{0} waiting for {1:d} seconds " "for lock on {2} to be released" . format ( proc , poll_interval , path ) ) # Use float() here since acquire sleeps for timeout/10 lock . acquire ( timeout = float ( poll_interval ) ) except LockTimeout : pass log . debug ( "{0} locked {1}" . format ( proc , path ) ) yield lock lock . release ( ) log . debug ( "{0} released lock on {1}" . format ( proc , path ) ) | Aquire a file lock in a thread - safe manner that also reaps stale locks possibly left behind by processes that crashed hard . | 553 | 26 |
245,890 | 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 ( getattr ( ROOT , name ) ) # create a fake func() that just returns self def func ( ) : return glob glob . func = func return glob return gSomething_no_func @ property def gSomething ( self ) : obj_func = getattr ( getattr ( ROOT , name ) , fname ) try : obj = obj_func ( * args ) except ReferenceError : # null pointer return None # asrootpy return self ( obj ) return gSomething | Used to automatically asrootpy ROOT s thread local variables | 176 | 12 |
245,891 | 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_label = thing . GetTitle ( ) if label is None else label thing_style = getattr ( thing , 'legendstyle' , 'P' ) if style is None else style super ( Legend , self ) . AddEntry ( thing , thing_label , thing_style ) keepalive ( self , thing ) | Add an entry to the legend . | 126 | 7 |
245,892 | 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://github.com/rootpy/rootpy/issues/256 import ROOT dll = get_dll ( "libCore" ) SetErrorHandler = None try : if dll : SetErrorHandler = dll . _Z15SetErrorHandlerPFvibPKcS0_E except AttributeError : pass if not SetErrorHandler : log . warning ( "Couldn't find SetErrorHandler. " "Please submit a rootpy bug report." ) return lambda x : None SetErrorHandler . restype = ErrorHandlerFunc_t SetErrorHandler . argtypes = ErrorHandlerFunc_t , def _SetErrorHandler ( fn ) : """ Set ROOT's warning/error handler. Returns the existing one. """ log . debug ( "called SetErrorHandler()" ) eh = ErrorHandlerFunc_t ( fn ) # ``eh`` can get garbage collected unless kept alive, leading to a segfault. _keep_alive . append ( eh ) return SetErrorHandler ( eh ) return _SetErrorHandler | Makes a function which can be used to set the ROOT error handler with a python function and returns the existing error handler . | 305 | 26 |
245,893 | 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 ) for i in range ( LARGE_ENOUGH ) ] # Find its index into the structure ptrs = [ p . value for p in ptrs ] fcode_ptr = id ( frame . f_code ) try : threadstate_idx = ptrs . index ( fcode_ptr ) except ValueError : log . critical ( "rootpy bug! Please report this." ) raise return threadstate_idx | How many pointers into PyFrame is the f_code variable? | 173 | 13 |
245,894 | 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 ) trace = Ppy_object . from_address ( frame + ( F_CODE_IDX + F_TRACE_OFFSET ) * svp ) LASTI_OFFSET = F_TRACE_OFFSET + 4 lasti_addr = LASTI_OFFSET lineno_addr = LASTI_OFFSET + ctypes . sizeof ( ctypes . c_int ) f_lineno = ctypes . c_int . from_address ( lineno_addr ) f_lasti = ctypes . c_int . from_address ( lasti_addr ) return trace , f_lineno , f_lasti | Obtain writable pointers to frame . f_trace and frame . f_lineno . | 229 | 19 |
245,895 | 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 best way to do this, but it works. addr = id ( localtrace ) else : addr = 0 traceptr . contents = ctypes . py_object . from_address ( addr ) | Non - portable function to modify linetracing . | 116 | 10 |
245,896 | 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. That can happen if more than one exception was logged. return call_lineno = frame . f_lineno def intercept_next_line ( f , why , * args ) : if f is not frame : return set_linetrace_on_frame ( f ) # Undo modifications to the callers code (ick ick ick) back_like_nothing_happened ( ) # Raise exception in (almost) the perfect place (except for duplication) if sys . version_info [ 0 ] < 3 : #raise exception.__class__, exception, traceback raise exception raise exception . with_traceback ( traceback ) set_linetrace_on_frame ( frame , intercept_next_line ) linestarts = list ( dis . findlinestarts ( frame . f_code ) ) linestarts = [ a for a , l in linestarts if l >= call_lineno ] # Jump target dest = linestarts [ 0 ] oc = frame . f_code . co_code [ frame . f_lasti ] if sys . version_info [ 0 ] < 3 : oc = ord ( oc ) opcode_size = 2 if oc >= opcode . HAVE_ARGUMENT else 0 # Opcode to overwrite where = frame . f_lasti + 1 + opcode_size #dis.disco(frame.f_code) pc = PyCodeObject . from_address ( id ( frame . f_code ) ) back_like_nothing_happened = pc . co_code . contents . inject_jump ( where , dest ) #print("#"*100) #dis.disco(frame.f_code) sys . settrace ( globaltrace ) | Dark magic . Causes frame to raise an exception at the current location with traceback appended to it . | 433 | 21 |
245,897 | 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 pray that this keeps other threads at bay. if sys . version_info [ 0 ] < 3 : old_check_interval = sys . getcheckinterval ( ) sys . setcheckinterval ( 2 ** 20 ) else : old_check_interval = sys . getswitchinterval ( ) sys . setswitchinterval ( 1000 ) pb = ctypes . pointer ( self . ob_sval ) orig_bytes = [ pb [ where + i ] [ 0 ] for i in range ( 3 ) ] v = struct . pack ( "<BH" , opcode . opmap [ "JUMP_ABSOLUTE" ] , dest ) # Overwrite code to cause it to jump to the target if sys . version_info [ 0 ] < 3 : for i in range ( 3 ) : pb [ where + i ] [ 0 ] = ord ( v [ i ] ) else : for i in range ( 3 ) : pb [ where + i ] [ 0 ] = v [ i ] def tidy_up ( ) : """ Put the bytecode back to how it was. Good as new. """ if sys . version_info [ 0 ] < 3 : sys . setcheckinterval ( old_check_interval ) else : sys . setswitchinterval ( old_check_interval ) for i in range ( 3 ) : pb [ where + i ] [ 0 ] = orig_bytes [ i ] return tidy_up | Monkeypatch bytecode at where to force it to jump to dest . | 374 | 15 |
245,898 | 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 ) if output is not None : output = output . Clone ( ) # Make it memory resident (histograms) if hasattr ( output , 'SetDirectory' ) : output . SetDirectory ( 0 ) else : newoutput = self . _tree . Draw ( * args , * * kwargs ) if newoutput is not None : if isinstance ( output , _GraphBase ) : output . Append ( newoutput ) else : # histogram output += newoutput return output | Loop over subfiles draw each and sum the output into a single histogram . | 164 | 16 |
245,899 | 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 ) else : variables . update ( frame . f_locals ) if global_ns is not None : variables . update ( local_ns ) else : variables . update ( frame . f_globals ) shell = code . InteractiveConsole ( variables ) return shell . interact ( banner = header ) | Create an interactive python console | 131 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.