idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
29,700 | def to_json_path ( graph : BELGraph , path : str , ** kwargs ) -> None : with open ( os . path . expanduser ( path ) , 'w' ) as f : to_json_file ( graph , file = f , ** kwargs ) | Write this graph to the given path as a Node - Link JSON . |
29,701 | def to_json_file ( graph : BELGraph , file : TextIO , ** kwargs ) -> None : graph_json_dict = to_json ( graph ) json . dump ( graph_json_dict , file , ensure_ascii = False , ** kwargs ) | Write this graph as Node - Link JSON to a file . |
29,702 | def to_jsons ( graph : BELGraph , ** kwargs ) -> str : graph_json_str = to_json ( graph ) return json . dumps ( graph_json_str , ensure_ascii = False , ** kwargs ) | Dump this graph as a Node - Link JSON object to a string . |
29,703 | def from_json ( graph_json_dict : Mapping [ str , Any ] , check_version = True ) -> BELGraph : graph = node_link_graph ( graph_json_dict ) return ensure_version ( graph , check_version = check_version ) | Build a graph from Node - Link JSON Object . |
29,704 | def from_json_path ( path : str , check_version : bool = True ) -> BELGraph : with open ( os . path . expanduser ( path ) ) as f : return from_json_file ( f , check_version = check_version ) | Build a graph from a file containing Node - Link JSON . |
29,705 | def from_json_file ( file : TextIO , check_version = True ) -> BELGraph : graph_json_dict = json . load ( file ) return from_json ( graph_json_dict , check_version = check_version ) | Build a graph from the Node - Link JSON contained in the given file . |
29,706 | def from_jsons ( graph_json_str : str , check_version : bool = True ) -> BELGraph : graph_json_dict = json . loads ( graph_json_str ) return from_json ( graph_json_dict , check_version = check_version ) | Read a BEL graph from a Node - Link JSON string . |
29,707 | def node_link_data ( graph : BELGraph ) -> Mapping [ str , Any ] : nodes = sorted ( graph , key = methodcaller ( 'as_bel' ) ) mapping = dict ( zip ( nodes , count ( ) ) ) return { 'directed' : True , 'multigraph' : True , 'graph' : graph . graph . copy ( ) , 'nodes' : [ _augment_node ( node ) for node in nodes ] , 'lin... | Convert a BEL graph to a node - link format . |
29,708 | def _augment_node ( node : BaseEntity ) -> BaseEntity : rv = node . copy ( ) rv [ 'id' ] = node . as_sha512 ( ) rv [ 'bel' ] = node . as_bel ( ) for m in chain ( node . get ( MEMBERS , [ ] ) , node . get ( REACTANTS , [ ] ) , node . get ( PRODUCTS , [ ] ) ) : m . update ( _augment_node ( m ) ) return rv | Add the SHA - 512 identifier to a node s dictionary . |
29,709 | def parse_lines ( self , lines : Iterable [ str ] ) -> List [ ParseResults ] : return [ self . parseString ( line , line_number ) for line_number , line in enumerate ( lines ) ] | Parse multiple lines in succession . |
29,710 | def parseString ( self , line : str , line_number : int = 0 ) -> ParseResults : self . _line_number = line_number return self . language . parseString ( line ) | Parse a string with the language represented by this parser . |
29,711 | def streamline ( self ) : t = time . time ( ) self . language . streamline ( ) log . info ( 'streamlined %s in %.02f seconds' , self . __class__ . __name__ , time . time ( ) - t ) | Streamline the language represented by this parser to make queries run faster . |
29,712 | def iter_children ( graph , node : BaseEntity ) -> Iterable [ BaseEntity ] : return ( node for node , _ , d in graph . in_edges ( node , data = True ) if d [ RELATION ] == IS_A ) | Iterate over children of the node . |
29,713 | def transfer_causal_edges ( graph , source : BaseEntity , target : BaseEntity ) -> Iterable [ str ] : for _ , v , data in graph . out_edges ( source , data = True ) : if data [ RELATION ] not in CAUSAL_RELATIONS : continue yield graph . add_qualified_edge ( target , v , relation = data [ RELATION ] , evidence = data [ ... | Transfer causal edges that the source has to the target and yield the resulting hashes . |
29,714 | def _get_protocol_tuple ( data : Dict [ str , Any ] ) -> Tuple [ str , List , Dict ] : return data [ 'function' ] , data . get ( 'args' , [ ] ) , data . get ( 'kwargs' , { } ) | Convert a dictionary to a tuple . |
29,715 | def from_functions ( functions ) -> 'Pipeline' : result = Pipeline ( ) for func in functions : result . append ( func ) return result | Build a pipeline from a list of functions . |
29,716 | def _get_function ( self , name : str ) : f = mapped . get ( name ) if f is None : raise MissingPipelineFunctionError ( '{} is not registered as a pipeline function' . format ( name ) ) if name in universe_map and name in in_place_map : return self . _wrap_in_place ( self . _wrap_universe ( f ) ) if name in universe_ma... | Wrap a function with the universe and in - place . |
29,717 | def extend ( self , protocol : Union [ Iterable [ Dict ] , 'Pipeline' ] ) -> 'Pipeline' : for data in protocol : name , args , kwargs = _get_protocol_tuple ( data ) self . append ( name , * args , ** kwargs ) return self | Add another pipeline to the end of the current pipeline . |
29,718 | def _run_helper ( self , graph , protocol : Iterable [ Dict ] ) : result = graph for entry in protocol : meta_entry = entry . get ( 'meta' ) if meta_entry is None : name , args , kwargs = _get_protocol_tuple ( entry ) func = self . _get_function ( name ) result = func ( result , * args , ** kwargs ) else : networks = (... | Help run the protocol . |
29,719 | def run ( self , graph , universe = None ) : self . universe = universe or graph . copy ( ) return self . _run_helper ( graph . copy ( ) , self . protocol ) | Run the contained protocol on a seed graph . |
29,720 | def _wrap_universe ( self , func ) : @ wraps ( func ) def wrapper ( graph , * args , ** kwargs ) : if self . universe is None : raise MissingUniverseError ( 'Can not run universe function [{}] - No universe is set' . format ( func . __name__ ) ) return func ( self . universe , graph , * args , ** kwargs ) return wrappe... | Take a function that needs a universe graph as the first argument and returns a wrapped one . |
29,721 | def _wrap_in_place ( func ) : @ wraps ( func ) def wrapper ( graph , * args , ** kwargs ) : func ( graph , * args , ** kwargs ) return graph return wrapper | Take a function that doesn t return the graph and returns the graph . |
29,722 | def dump ( self , file : TextIO , ** kwargs ) -> None : return json . dump ( self . to_json ( ) , file , ** kwargs ) | Dump this protocol to a file in JSON . |
29,723 | def _build_meta ( meta : str , pipelines : Iterable [ 'Pipeline' ] ) -> 'Pipeline' : return Pipeline ( protocol = [ { 'meta' : meta , 'pipelines' : [ pipeline . protocol for pipeline in pipelines ] } , ] ) | Build a pipeline with a given meta - argument . |
29,724 | def get_names ( graph ) : rv = defaultdict ( set ) for namespace , name in _identifier_filtered_iterator ( graph ) : rv [ namespace ] . add ( name ) return dict ( rv ) | Get all names for each namespace . |
29,725 | def count_variants ( graph ) : return Counter ( variant_data [ KIND ] for data in graph if has_variant ( graph , data ) for variant_data in data [ VARIANTS ] ) | Count how many of each type of variant a graph has . |
29,726 | def get_top_hubs ( graph , * , n : Optional [ int ] = 15 ) -> List [ Tuple [ BaseEntity , int ] ] : return Counter ( dict ( graph . degree ( ) ) ) . most_common ( n = n ) | Get the top hubs in the graph by BEL . |
29,727 | def _pathology_iterator ( graph ) : for node in itt . chain . from_iterable ( graph . edges ( ) ) : if isinstance ( node , Pathology ) : yield node | Iterate over edges in which either the source or target is a pathology node . |
29,728 | def get_top_pathologies ( graph , n : Optional [ int ] = 15 ) -> List [ Tuple [ BaseEntity , int ] ] : return count_pathologies ( graph ) . most_common ( n ) | Get the top highest relationship - having edges in the graph by BEL . |
29,729 | def enrich_proteins_with_rnas ( graph ) : for protein_node in list ( graph ) : if not isinstance ( protein_node , Protein ) : continue if protein_node . variants : continue rna_node = protein_node . get_rna ( ) graph . add_translation ( rna_node , protein_node ) | Add the corresponding RNA node for each protein node and connect them with a translation edge . |
29,730 | def get_upstream_causal_subgraph ( graph , nbunch : Union [ BaseEntity , Iterable [ BaseEntity ] ] ) : return get_subgraph_by_edge_filter ( graph , build_upstream_edge_predicate ( nbunch ) ) | Induce a sub - graph from all of the upstream causal entities of the nodes in the nbunch . |
29,731 | def get_downstream_causal_subgraph ( graph , nbunch : Union [ BaseEntity , Iterable [ BaseEntity ] ] ) : return get_subgraph_by_edge_filter ( graph , build_downstream_edge_predicate ( nbunch ) ) | Induce a sub - graph from all of the downstream causal entities of the nodes in the nbunch . |
29,732 | def cleanup ( graph , subgraphs ) : for subgraph in subgraphs . values ( ) : update_node_helper ( graph , subgraph ) update_metadata ( graph , subgraph ) | Clean up the metadata in the subgraphs . |
29,733 | def get_fragment_language ( ) -> ParserElement : _fragment_value_inner = fragment_range | missing_fragment ( FRAGMENT_MISSING ) _fragment_value = _fragment_value_inner | And ( [ Suppress ( '"' ) , _fragment_value_inner , Suppress ( '"' ) ] ) parser_element = fragment_tag + nest ( _fragment_value + Optional ( WCW + quot... | Build a protein fragment parser . |
29,734 | def get_protein_modification_language ( identifier_qualified : ParserElement ) -> ParserElement : pmod_identifier = MatchFirst ( [ identifier_qualified , pmod_default_ns , pmod_legacy_ns ] ) return pmod_tag + nest ( Group ( pmod_identifier ) ( IDENTIFIER ) + Optional ( WCW + amino_acid ( PMOD_CODE ) + Optional ( WCW + ... | Build a protein modification parser . |
29,735 | def upload_cbn_dir ( dir_path , manager ) : t = time . time ( ) for jfg_path in os . listdir ( dir_path ) : if not jfg_path . endswith ( '.jgf' ) : continue path = os . path . join ( dir_path , jfg_path ) log . info ( 'opening %s' , path ) with open ( path ) as f : cbn_jgif_dict = json . load ( f ) graph = pybel . from... | Uploads CBN data to edge store |
29,736 | def _activity_helper ( modifier : str , location = None ) : rv = { MODIFIER : modifier } if location : rv [ LOCATION ] = location return rv | Make an activity dictionary . |
29,737 | def translocation ( from_loc , to_loc ) : rv = _activity_helper ( TRANSLOCATION ) rv [ EFFECT ] = { FROM_LOC : Entity ( namespace = BEL_DEFAULT_NAMESPACE , name = from_loc ) if isinstance ( from_loc , str ) else from_loc , TO_LOC : Entity ( namespace = BEL_DEFAULT_NAMESPACE , name = to_loc ) if isinstance ( to_loc , st... | Make a translocation dictionary . |
29,738 | def iterate_pubmed_identifiers ( graph ) -> Iterable [ str ] : return ( data [ CITATION ] [ CITATION_REFERENCE ] . strip ( ) for _ , _ , data in graph . edges ( data = True ) if has_pubmed ( data ) ) | Iterate over all PubMed identifiers in a graph . |
29,739 | def remove_filtered_edges ( graph , edge_predicates = None ) : edges = list ( filter_edges ( graph , edge_predicates = edge_predicates ) ) graph . remove_edges_from ( edges ) | Remove edges passing the given edge predicates . |
29,740 | def remove_filtered_nodes ( graph , node_predicates = None ) : nodes = list ( filter_nodes ( graph , node_predicates = node_predicates ) ) graph . remove_nodes_from ( nodes ) | Remove nodes passing the given node predicates . |
29,741 | def get_subgraph_by_neighborhood ( graph , nodes : Iterable [ BaseEntity ] ) : node_set = set ( nodes ) if not any ( node in graph for node in node_set ) : return rv = graph . fresh_copy ( ) rv . add_edges_from ( itt . chain ( graph . in_edges ( nodes , keys = True , data = True ) , graph . out_edges ( nodes , keys = T... | Get a BEL graph around the neighborhoods of the given nodes . |
29,742 | def get_gene_modification_language ( identifier_qualified : ParserElement ) -> ParserElement : gmod_identifier = MatchFirst ( [ identifier_qualified , gmod_default_ns , ] ) return gmod_tag + nest ( Group ( gmod_identifier ) ( IDENTIFIER ) ) | Build a gene modification parser . |
29,743 | def expand_dict ( flat_dict , sep = '_' ) : res = { } rdict = defaultdict ( list ) for flat_key , value in flat_dict . items ( ) : key = flat_key . split ( sep , 1 ) if 1 == len ( key ) : res [ key [ 0 ] ] = value else : rdict [ key [ 0 ] ] . append ( ( key [ 1 : ] , value ) ) for k , v in rdict . items ( ) : res [ k ]... | Expand a flattened dictionary . |
29,744 | def tokenize_version ( version_string : str ) -> Tuple [ int , int , int ] : before_dash = version_string . split ( '-' ) [ 0 ] major , minor , patch = before_dash . split ( '.' ) [ : 3 ] return int ( major ) , int ( minor ) , int ( patch ) | Tokenize a version string to a tuple . |
29,745 | def parse_datetime ( s : str ) -> datetime . date : for fmt in ( CREATION_DATE_FMT , PUBLISHED_DATE_FMT , PUBLISHED_DATE_FMT_2 ) : try : dt = datetime . strptime ( s , fmt ) except ValueError : pass else : return dt raise ValueError ( 'Incorrect datetime format for {}' . format ( s ) ) | Try to parse a datetime object from a standard datetime format or date format . |
29,746 | def _get_edge_tuple ( source , target , edge_data : EdgeData , ) -> Tuple [ str , str , str , Optional [ str ] , Tuple [ str , Optional [ Tuple ] , Optional [ Tuple ] ] ] : return ( source . as_bel ( ) , target . as_bel ( ) , _get_citation_str ( edge_data ) , edge_data . get ( EVIDENCE ) , canonicalize_edge ( edge_data... | Convert an edge to a consistent tuple . |
29,747 | def hash_edge ( source , target , edge_data : EdgeData ) -> str : edge_tuple = _get_edge_tuple ( source , target , edge_data ) return _hash_tuple ( edge_tuple ) | Convert an edge tuple to a SHA - 512 hash . |
29,748 | def subdict_matches ( target : Mapping , query : Mapping , partial_match : bool = True ) -> bool : for k , v in query . items ( ) : if k not in target : return False elif not isinstance ( v , ( int , str , dict , Iterable ) ) : raise ValueError ( 'invalid value: {}' . format ( v ) ) elif isinstance ( v , ( int , str ) ... | Check if all the keys in the query dict are in the target dict and that their values match . |
29,749 | def hash_dump ( data ) -> str : return hashlib . sha512 ( json . dumps ( data , sort_keys = True ) . encode ( 'utf-8' ) ) . hexdigest ( ) | Hash an arbitrary JSON dictionary by dumping it in sorted order encoding it in UTF - 8 then hashing the bytes . |
29,750 | def hash_evidence ( text : str , type : str , reference : str ) -> str : s = u'{type}:{reference}:{text}' . format ( type = type , reference = reference , text = text ) return hashlib . sha512 ( s . encode ( 'utf8' ) ) . hexdigest ( ) | Create a hash for an evidence and its citation . |
29,751 | def canonicalize_edge ( edge_data : EdgeData ) -> Tuple [ str , Optional [ Tuple ] , Optional [ Tuple ] ] : return ( edge_data [ RELATION ] , _canonicalize_edge_modifications ( edge_data . get ( SUBJECT ) ) , _canonicalize_edge_modifications ( edge_data . get ( OBJECT ) ) , ) | Canonicalize the edge to a tuple based on the relation subject modifications and object modifications . |
29,752 | def _canonicalize_edge_modifications ( edge_data : EdgeData ) -> Optional [ Tuple ] : if edge_data is None : return modifier = edge_data . get ( MODIFIER ) location = edge_data . get ( LOCATION ) effect = edge_data . get ( EFFECT ) if modifier is None and location is None : return result = [ ] if modifier == ACTIVITY :... | Return the SUBJECT or OBJECT entry of a PyBEL edge data dictionary as a canonical tuple . |
29,753 | def get_subgraphs_by_citation ( graph ) : rv = defaultdict ( graph . fresh_copy ) for u , v , key , data in graph . edges ( keys = True , data = True ) : if CITATION not in data : continue dk = data [ CITATION ] [ CITATION_TYPE ] , data [ CITATION ] [ CITATION_REFERENCE ] rv [ dk ] . add_edge ( u , v , key = key , ** d... | Stratify the graph based on citations . |
29,754 | def raise_for_missing_citation ( self , line : str , position : int ) -> None : if self . citation_clearing and not self . citation : raise MissingCitationException ( self . get_line_number ( ) , line , position ) | Raise an exception if there is no citation present in the parser . |
29,755 | def handle_annotation_key ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : key = tokens [ 'key' ] self . raise_for_missing_citation ( line , position ) self . raise_for_undefined_annotation ( line , position , key ) return tokens | Handle an annotation key before parsing to validate that it s either enumerated or as a regex . |
29,756 | def handle_set_statement_group ( self , _ , __ , tokens : ParseResults ) -> ParseResults : self . statement_group = tokens [ 'group' ] return tokens | Handle a SET STATEMENT_GROUP = X statement . |
29,757 | def handle_set_evidence ( self , _ , __ , tokens : ParseResults ) -> ParseResults : self . evidence = tokens [ 'value' ] return tokens | Handle a SET Evidence = statement . |
29,758 | def handle_set_command ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : key , value = tokens [ 'key' ] , tokens [ 'value' ] self . raise_for_invalid_annotation_value ( line , position , key , value ) self . annotations [ key ] = value return tokens | Handle a SET X = Y statement . |
29,759 | def handle_unset_statement_group ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : if self . statement_group is None : raise MissingAnnotationKeyWarning ( self . get_line_number ( ) , line , position , BEL_KEYWORD_STATEMENT_GROUP ) self . statement_group = None return tokens | Unset the statement group or raises an exception if it is not set . |
29,760 | def handle_unset_citation ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : if not self . citation : raise MissingAnnotationKeyWarning ( self . get_line_number ( ) , line , position , BEL_KEYWORD_CITATION ) self . clear_citation ( ) return tokens | Unset the citation or raise an exception if it is not set . |
29,761 | def handle_unset_evidence ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : if self . evidence is None : raise MissingAnnotationKeyWarning ( self . get_line_number ( ) , line , position , tokens [ EVIDENCE ] ) self . evidence = None return tokens | Unset the evidence or throws an exception if it is not already set . |
29,762 | def validate_unset_command ( self , line : str , position : int , annotation : str ) -> None : if annotation not in self . annotations : raise MissingAnnotationKeyWarning ( self . get_line_number ( ) , line , position , annotation ) | Raise an exception when trying to UNSET X if X is not already set . |
29,763 | def handle_unset_command ( self , line : str , position : int , tokens : ParseResults ) -> ParseResults : key = tokens [ 'key' ] self . validate_unset_command ( line , position , key ) del self . annotations [ key ] return tokens | Handle an UNSET X statement or raises an exception if it is not already set . |
29,764 | def get_annotations ( self ) -> Dict : return { EVIDENCE : self . evidence , CITATION : self . citation . copy ( ) , ANNOTATIONS : self . annotations . copy ( ) } | Get the current annotations . |
29,765 | def get_missing_required_annotations ( self ) -> List [ str ] : return [ required_annotation for required_annotation in self . required_annotations if required_annotation not in self . annotations ] | Return missing required annotations . |
29,766 | def clear_citation ( self ) : self . citation . clear ( ) if self . citation_clearing : self . evidence = None self . annotations . clear ( ) | Clear the citation and if citation clearing is enabled clear the evidence and annotations . |
29,767 | def clear ( self ) : self . statement_group = None self . citation . clear ( ) self . evidence = None self . annotations . clear ( ) | Clear the statement_group citation evidence and annotations . |
29,768 | def map_cbn ( d ) : for i , edge in enumerate ( d [ 'graph' ] [ 'edges' ] ) : if 'metadata' not in d [ 'graph' ] [ 'edges' ] [ i ] : continue if 'evidences' not in d [ 'graph' ] [ 'edges' ] [ i ] [ 'metadata' ] : continue for j , evidence in enumerate ( d [ 'graph' ] [ 'edges' ] [ i ] [ 'metadata' ] [ 'evidences' ] ) :... | Pre - processes the JSON from the CBN . |
29,769 | def from_jgif ( graph_jgif_dict ) : graph = BELGraph ( ) root = graph_jgif_dict [ 'graph' ] if 'label' in root : graph . name = root [ 'label' ] if 'metadata' in root : metadata = root [ 'metadata' ] for key in METADATA_INSERT_KEYS : if key in metadata : graph . document [ key ] = metadata [ key ] parser = BELParser ( ... | Build a BEL graph from a JGIF JSON object . |
29,770 | def to_jgif ( graph ) : node_bel = { } u_v_r_bel = { } nodes_entry = [ ] edges_entry = [ ] for i , node in enumerate ( sorted ( graph , key = methodcaller ( 'as_bel' ) ) ) : node_bel [ node ] = bel = node . as_bel ( ) nodes_entry . append ( { 'id' : bel , 'label' : bel , 'nodeId' : i , 'bel_function_type' : node [ FUNC... | Build a JGIF dictionary from a BEL graph . |
29,771 | def get_subgraph ( graph , seed_method : Optional [ str ] = None , seed_data : Optional [ Any ] = None , expand_nodes : Optional [ List [ BaseEntity ] ] = None , remove_nodes : Optional [ List [ BaseEntity ] ] = None , ) : if seed_method == SEED_TYPE_INDUCTION : result = get_subgraph_by_induction ( graph , seed_data ) ... | Run a pipeline query on graph with multiple sub - graph filters and expanders . |
29,772 | def _remove_pathologies_oop ( graph ) : rv = graph . copy ( ) victims = [ node for node in rv if node [ FUNCTION ] == PATHOLOGY ] rv . remove_nodes_from ( victims ) return rv | Remove pathology nodes from the graph . |
29,773 | def get_random_path ( graph ) -> List [ BaseEntity ] : wg = graph . to_undirected ( ) nodes = wg . nodes ( ) def pick_random_pair ( ) -> Tuple [ BaseEntity , BaseEntity ] : return random . sample ( nodes , k = 2 ) source , target = pick_random_pair ( ) tries = 0 sentinel_tries = 5 while not nx . has_path ( wg , source ... | Get a random path from the graph as a list of nodes . |
29,774 | def to_bytes ( graph : BELGraph , protocol : int = HIGHEST_PROTOCOL ) -> bytes : raise_for_not_bel ( graph ) return dumps ( graph , protocol = protocol ) | Convert a graph to bytes with pickle . |
29,775 | def from_pickle ( path : Union [ str , BinaryIO ] , check_version : bool = True ) -> BELGraph : graph = nx . read_gpickle ( path ) raise_for_not_bel ( graph ) if check_version : raise_for_old_graph ( graph ) return graph | Read a graph from a pickle file . |
29,776 | def build_annotation_dict_all_filter ( annotations : Mapping [ str , Iterable [ str ] ] ) -> EdgePredicate : if not annotations : return keep_edge_permissive @ edge_predicate def annotation_dict_all_filter ( edge_data : EdgeData ) -> bool : return _annotation_dict_all_filter ( edge_data , query = annotations ) return a... | Build an edge predicate for edges whose annotations are super - dictionaries of the given dictionary . |
29,777 | def build_annotation_dict_any_filter ( annotations : Mapping [ str , Iterable [ str ] ] ) -> EdgePredicate : if not annotations : return keep_edge_permissive @ edge_predicate def annotation_dict_any_filter ( edge_data : EdgeData ) -> bool : return _annotation_dict_any_filter ( edge_data , query = annotations ) return a... | Build an edge predicate that passes for edges whose data dictionaries match the given dictionary . |
29,778 | def build_upstream_edge_predicate ( nodes : Iterable [ BaseEntity ] ) -> EdgePredicate : nodes = set ( nodes ) def upstream_filter ( graph : BELGraph , u : BaseEntity , v : BaseEntity , k : str ) -> bool : return v in nodes and graph [ u ] [ v ] [ k ] [ RELATION ] in CAUSAL_RELATIONS return upstream_filter | Build an edge predicate that pass for relations for which one of the given nodes is the object . |
29,779 | def build_downstream_edge_predicate ( nodes : Iterable [ BaseEntity ] ) -> EdgePredicate : nodes = set ( nodes ) def downstream_filter ( graph : BELGraph , u : BaseEntity , v : BaseEntity , k : str ) -> bool : return u in nodes and graph [ u ] [ v ] [ k ] [ RELATION ] in CAUSAL_RELATIONS return downstream_filter | Build an edge predicate that passes for edges for which one of the given nodes is the subject . |
29,780 | def build_relation_predicate ( relations : Strings ) -> EdgePredicate : if isinstance ( relations , str ) : @ edge_predicate def relation_predicate ( edge_data : EdgeData ) -> bool : return edge_data [ RELATION ] == relations elif isinstance ( relations , Iterable ) : relation_set = set ( relations ) @ edge_predicate d... | Build an edge predicate that passes for edges with the given relation . |
29,781 | def _register_function ( name : str , func , universe : bool , in_place : bool ) : if name in mapped : mapped_func = mapped [ name ] raise PipelineNameError ( '{name} is already registered with {func_mod}.{func_name}' . format ( name = name , func_mod = mapped_func . __module__ , func_name = mapped_func . __name__ ) ) ... | Register a transformation function under the given name . |
29,782 | def _build_register_function ( universe : bool , in_place : bool ) : def register ( func ) : return _register_function ( func . __name__ , func , universe , in_place ) return register | Build a decorator function to tag transformation functions . |
29,783 | def register_deprecated ( deprecated_name : str ) : if deprecated_name in mapped : raise DeprecationMappingError ( 'function name already mapped. can not register as deprecated name.' ) def register_deprecated_f ( func ) : name = func . __name__ log . debug ( '%s is deprecated. please migrate to %s' , deprecated_name ,... | Register a function as deprecated . |
29,784 | def get_transformation ( name : str ) : func = mapped . get ( name ) if func is None : raise MissingPipelineFunctionError ( '{} is not registered as a pipeline function' . format ( name ) ) return func | Get a transformation function and error if its name is not registered . |
29,785 | def _random_edge_iterator ( graph , n_edges : int ) -> Iterable [ Tuple [ BaseEntity , BaseEntity , int , Mapping ] ] : edges = list ( graph . edges ( ) ) edge_sample = random . sample ( edges , n_edges ) for u , v in edge_sample : keys = list ( graph [ u ] [ v ] ) k = random . choice ( keys ) yield u , v , k , graph [... | Get a random set of edges from the graph and randomly samples a key from each . |
29,786 | def get_graph_with_random_edges ( graph , n_edges : int ) : result = graph . fresh_copy ( ) result . add_edges_from ( _random_edge_iterator ( graph , n_edges ) ) update_metadata ( graph , result ) update_node_helper ( graph , result ) return result | Build a new graph from a seeding of edges . |
29,787 | def get_random_node ( graph , node_blacklist : Set [ BaseEntity ] , invert_degrees : Optional [ bool ] = None , ) -> Optional [ BaseEntity ] : try : nodes , degrees = zip ( * ( ( node , degree ) for node , degree in sorted ( graph . degree ( ) , key = itemgetter ( 1 ) ) if node not in node_blacklist ) ) except ValueErr... | Choose a node from the graph with probabilities based on their degrees . |
29,788 | def _helper ( result , graph , number_edges_remaining : int , node_blacklist : Set [ BaseEntity ] , invert_degrees : Optional [ bool ] = None , ) : original_node_count = graph . number_of_nodes ( ) log . debug ( 'adding remaining %d edges' , number_edges_remaining ) for _ in range ( number_edges_remaining ) : source , ... | Help build a random graph . |
29,789 | def get_random_subgraph ( graph , number_edges = None , number_seed_edges = None , seed = None , invert_degrees = None ) : if number_edges is None : number_edges = SAMPLE_RANDOM_EDGE_COUNT if number_seed_edges is None : number_seed_edges = SAMPLE_RANDOM_EDGE_SEED_COUNT if seed is not None : random . seed ( seed ) if gr... | Generate a random subgraph based on weighted random walks from random seed edges . |
29,790 | def next_index ( self ) -> int : return bisect . bisect_right ( self . totals , random . random ( ) * self . total ) | Get a random index . |
29,791 | def from_name ( cls , name ) : return Author ( name = name , sha512 = cls . hash_name ( name ) ) | Create an author by name automatically populating the hash . |
29,792 | def has_name_in ( cls , names ) : return cls . sha512 . in_ ( { cls . hash_name ( name ) for name in names } ) | Build a filter if the author has any of the given names . |
29,793 | def raise_for_old_graph ( graph ) : graph_version = tokenize_version ( graph . pybel_version ) if graph_version < PYBEL_MINIMUM_IMPORT_VERSION : raise ImportVersionWarning ( graph_version , PYBEL_MINIMUM_IMPORT_VERSION ) | Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL . |
29,794 | def nest ( * content ) : if len ( content ) == 0 : raise ValueError ( 'no arguments supplied' ) return And ( [ LPF , content [ 0 ] ] + list ( itt . chain . from_iterable ( zip ( itt . repeat ( C ) , content [ 1 : ] ) ) ) + [ RPF ] ) | Define a delimited list by enumerating each element of the list . |
29,795 | def triple ( subject , relation , obj ) : return And ( [ Group ( subject ) ( SUBJECT ) , relation ( RELATION ) , Group ( obj ) ( OBJECT ) ] ) | Build a simple triple in PyParsing that has a subject relation object format . |
29,796 | def get_truncation_language ( ) -> ParserElement : l1 = truncation_tag + nest ( amino_acid ( AMINO_ACID ) + ppc . integer ( TRUNCATION_POSITION ) ) l1 . setParseAction ( _handle_trunc ) l2 = truncation_tag + nest ( ppc . integer ( TRUNCATION_POSITION ) ) l2 . setParseAction ( _handle_trunc_legacy ) return l1 | l2 | Build a parser for protein truncations . |
29,797 | def aliases_categories ( chr ) : l = 0 r = len ( categories_data [ 'code_points_ranges' ] ) - 1 c = ord ( chr ) while r >= l : m = ( l + r ) // 2 if c < categories_data [ 'code_points_ranges' ] [ m ] [ 0 ] : r = m - 1 elif c > categories_data [ 'code_points_ranges' ] [ m ] [ 1 ] : l = m + 1 else : return ( categories_d... | Retrieves the script block alias and unicode category for a unicode character . |
29,798 | def is_mixed_script ( string , allowed_aliases = [ 'COMMON' ] ) : allowed_aliases = [ a . upper ( ) for a in allowed_aliases ] cats = unique_aliases ( string ) - set ( allowed_aliases ) return len ( cats ) > 1 | Checks if string contains mixed - scripts content excluding script blocks aliases in allowed_aliases . |
29,799 | def is_confusable ( string , greedy = False , preferred_aliases = [ ] ) : preferred_aliases = [ a . upper ( ) for a in preferred_aliases ] outputs = [ ] checked = set ( ) for char in string : if char in checked : continue checked . add ( char ) char_alias = alias ( char ) if char_alias in preferred_aliases : continue f... | Checks if string contains characters which might be confusable with characters from preferred_aliases . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.