idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
251,200
def make_allele_by_consequence ( self , consequence , gene_id , gene_symbol ) : allele_id = None type_id = self . resolve ( consequence , mandatory = False ) if type_id == consequence : LOG . warning ( "Consequence type unmapped: %s" , str ( consequence ) ) type_id = self . globaltt [ 'sequence_variant' ] allele_id = '...
Given a consequence label that describes a variation type create an anonymous variant of the specified gene as an instance of that consequence type .
251,201
def parse ( self , limit : Optional [ int ] = None ) : if limit is not None : LOG . info ( "Only parsing first %d rows" , limit ) LOG . info ( "Parsing files..." ) file_path = '/' . join ( ( self . rawdir , self . files [ 'developmental_disorders' ] [ 'file' ] ) ) with gzip . open ( file_path , 'rt' ) as csvfile : read...
Here we parse each row of the gene to phenotype file
251,202
def _add_gene_disease ( self , row ) : col = self . files [ 'developmental_disorders' ] [ 'columns' ] if len ( row ) != len ( col ) : raise ValueError ( "Unexpected number of fields for row {}" . format ( row ) ) variant_label = "variant of {}" . format ( row [ col . index ( 'gene_symbol' ) ] ) disease_omim_id = row [ ...
Parse and add gene variant disease model Model building happens in _build_gene_disease_model
251,203
def _build_gene_disease_model ( self , gene_id , relation_id , disease_id , variant_label , consequence_predicate = None , consequence_id = None , allelic_requirement = None , pmids = None ) : model = Model ( self . graph ) geno = Genotype ( self . graph ) pmids = [ ] if pmids is None else pmids is_variant = False vari...
Builds gene variant disease model
251,204
def _get_identifiers ( self , limit ) : LOG . info ( "getting identifier mapping" ) line_counter = 0 f = '/' . join ( ( self . rawdir , self . files [ 'identifiers' ] [ 'file' ] ) ) myzip = ZipFile ( f , 'r' ) fname = myzip . namelist ( ) [ 0 ] foundheader = False speciesfilters = 'Homo sapiens,Mus musculus' . split ( ...
This will process the id mapping file provided by Biogrid . The file has a very large header which we scan past then pull the identifiers and make equivalence axioms
251,205
def add_supporting_evidence ( self , evidence_line , evidence_type = None , label = None ) : self . graph . addTriple ( self . association , self . globaltt [ 'has_supporting_evidence_line' ] , evidence_line ) if evidence_type is not None : self . model . addIndividualToGraph ( evidence_line , label , evidence_type ) r...
Add supporting line of evidence node to association id
251,206
def add_association_to_graph ( self ) : Assoc . add_association_to_graph ( self ) if self . start_stage_id or self . end_stage_id is not None : stage_process_id = '-' . join ( ( str ( self . start_stage_id ) , str ( self . end_stage_id ) ) ) stage_process_id = '_:' + re . sub ( r':' , '' , stage_process_id ) self . mod...
Overrides Association by including bnode support
251,207
def parse ( self , limit = None ) : if limit is not None : LOG . info ( "Only parsing first %s rows fo each file" , str ( limit ) ) LOG . info ( "Parsing files..." ) self . _process_straininfo ( limit ) self . _process_ontology_mappings_file ( limit ) self . _process_measurements_file ( limit ) self . _process_strainme...
MPD data is delivered in four separate csv files and one xml file which we process iteratively and write out as one large graph .
251,208
def _add_g2p_assoc ( self , graph , strain_id , sex , assay_id , phenotypes , comment ) : geno = Genotype ( graph ) model = Model ( graph ) eco_id = self . globaltt [ 'experimental phenotypic evidence' ] strain_label = self . idlabel_hash . get ( strain_id ) genotype_id = '_:' + '-' . join ( ( re . sub ( r':' , '' , st...
Create an association between a sex - specific strain id and each of the phenotypes . Here we create a genotype from the strain and a sex - specific genotype . Each of those genotypes are created as anonymous nodes .
251,209
def parse ( self , limit = None ) : if limit is not None : LOG . info ( "Only parsing first %s rows fo each file" , str ( limit ) ) LOG . info ( "Parsing files..." ) if self . test_only : self . test_mode = True for f in [ 'all' ] : file = '/' . join ( ( self . rawdir , self . files [ f ] [ 'file' ] ) ) self . _process...
IMPC data is delivered in three separate csv files OR in one integrated file each with the same file format .
251,210
def addGeneToPathway ( self , gene_id , pathway_id ) : gene_product = '_:' + re . sub ( r':' , '' , gene_id ) + 'product' self . model . addIndividualToGraph ( gene_product , None , self . globaltt [ 'gene_product' ] ) self . graph . addTriple ( gene_id , self . globaltt [ 'has gene product' ] , gene_product ) self . a...
When adding a gene to a pathway we create an intermediate gene product that is involved in the pathway through a blank node .
251,211
def addComponentToPathway ( self , component_id , pathway_id ) : self . graph . addTriple ( component_id , self . globaltt [ 'involved in' ] , pathway_id ) return
This can be used directly when the component is directly involved in the pathway . If a transforming event is performed on the component first then the addGeneToPathway should be used instead .
251,212
def write ( self , fmt = 'turtle' , stream = None ) : fmt_ext = { 'rdfxml' : 'xml' , 'turtle' : 'ttl' , 'nt' : 'nt' , 'nquads' : 'nq' , 'n3' : 'n3' } dest = None if self . name is not None : dest = '/' . join ( ( self . outdir , self . name ) ) if fmt in fmt_ext : dest = '.' . join ( ( dest , fmt_ext . get ( fmt ) ) ) ...
This convenience method will write out all of the graphs associated with the source . Right now these are hardcoded to be a single graph and a src_dataset . ttl and a src_test . ttl If you do not supply stream = stdout it will default write these to files .
251,213
def declareAsOntology ( self , graph ) : model = Model ( graph ) ontology_file_id = 'MonarchData:' + self . name + ".ttl" model . addOntologyDeclaration ( ontology_file_id ) cur_time = datetime . now ( ) t_string = cur_time . strftime ( "%Y-%m-%d" ) ontology_version = t_string archive_url = 'MonarchArchive:' + 'ttl/' +...
The file we output needs to be declared as an ontology including it s version information .
251,214
def remove_backslash_r ( filename , encoding ) : with open ( filename , 'r' , encoding = encoding , newline = r'\n' ) as filereader : contents = filereader . read ( ) contents = re . sub ( r'\r' , '' , contents ) with open ( filename , "w" ) as filewriter : filewriter . truncate ( ) filewriter . write ( contents )
A helpful utility to remove Carriage Return from any file . This will read a file into memory and overwrite the contents of the original file .
251,215
def load_local_translationtable ( self , name ) : localtt_file = 'translationtable/' + name + '.yaml' try : with open ( localtt_file ) : pass except IOError : with open ( localtt_file , 'w' ) as write_yaml : yaml . dump ( { name : name } , write_yaml ) finally : with open ( localtt_file , 'r' ) as read_yaml : localtt =...
Load ingest specific translation from whatever they called something to the ontology label we need to map it to . To facilitate seeing more ontology lables in dipper ingests a reverse mapping from ontology lables to external strings is also generated and available as a dict localtcid
251,216
def addGene ( self , gene_id , gene_label , gene_type = None , gene_description = None ) : if gene_type is None : gene_type = self . globaltt [ 'gene' ] self . model . addClassToGraph ( gene_id , gene_label , gene_type , gene_description ) return
genes are classes
251,217
def get_ncbi_taxon_num_by_label ( label ) : req = { 'db' : 'taxonomy' , 'retmode' : 'json' , 'term' : label } req . update ( EREQ ) request = SESSION . get ( ESEARCH , params = req ) LOG . info ( 'fetching: %s' , request . url ) request . raise_for_status ( ) result = request . json ( ) [ 'esearchresult' ] if 'ERROR' i...
Here we want to look up the NCBI Taxon id using some kind of label . It will only return a result if there is a unique hit .
251,218
def set_association_id ( self , assoc_id = None ) : if assoc_id is None : self . assoc_id = self . make_association_id ( self . definedby , self . sub , self . rel , self . obj ) else : self . assoc_id = assoc_id return self . assoc_id
This will set the association ID based on the internal parts of the association . To be used in cases where an external association identifier should be used .
251,219
def make_association_id ( definedby , sub , pred , obj , attributes = None ) : items_to_hash = [ definedby , sub , pred , obj ] if attributes is not None and len ( attributes ) > 0 : items_to_hash += attributes items_to_hash = [ x for x in items_to_hash if x is not None ] assoc_id = ':' . join ( ( 'MONARCH' , GraphUtil...
A method to create unique identifiers for OBAN - style associations based on all the parts of the association If any of the items is empty or None it will convert it to blank . It effectively digests the string of concatonated values . Subclasses of Assoc can submit an additional array of attributes that will be appede...
251,220
def toRoman ( num ) : if not 0 < num < 5000 : raise ValueError ( "number %n out of range (must be 1..4999)" , num ) if int ( num ) != num : raise TypeError ( "decimals %n can not be converted" , num ) result = "" for numeral , integer in romanNumeralMap : while num >= integer : result += numeral num -= integer return r...
convert integer to Roman numeral
251,221
def fromRoman ( strng ) : if not strng : raise TypeError ( 'Input can not be blank' ) if not romanNumeralPattern . search ( strng ) : raise ValueError ( 'Invalid Roman numeral: %s' , strng ) result = 0 index = 0 for numeral , integer in romanNumeralMap : while strng [ index : index + len ( numeral ) ] == numeral : resu...
convert Roman numeral to integer
251,222
def _process_genotype_backgrounds ( self , limit = None ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "Processing genotype backgrounds" ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'backgrounds' ] [ 'file' ] ) ) geno = Genot...
This table provides a mapping of genotypes to background genotypes Note that the background_id is also a genotype_id .
251,223
def _process_stages ( self , limit = None ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "Processing stages" ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'stage' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "iso-8859-1...
This table provides mappings between ZFIN stage IDs and ZFS terms and includes the starting and ending hours for the developmental stage . Currently only processing the mapping from the ZFIN stage ID to the ZFS ID .
251,224
def _process_genes ( self , limit = None ) : LOG . info ( "Processing genes" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'gene' ] [ 'file' ] ) ) geno = Genotype ( graph ) with open ( raw , 'r' ,...
This table provides the ZFIN gene id the SO type of the gene the gene symbol and the NCBI Gene ID .
251,225
def _process_features ( self , limit = None ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "Processing features" ) line_counter = 0 geno = Genotype ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'features' ] [ 'file' ] ) ) with open ( r...
This module provides information for the intrinsic and extrinsic genotype features of zebrafish . All items here are alterations and are therefore instances .
251,226
def _process_pubinfo ( self , limit = None ) : line_counter = 0 if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'pubs' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "latin-1" ) as csvfile : filereader = csv . re...
This will pull the zfin internal publication information and map them to their equivalent pmid and make labels .
251,227
def _process_pub2pubmed ( self , limit = None ) : line_counter = 0 if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'pub2pubmed' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "latin-1" ) as csvfile : filereader =...
This will pull the zfin internal publication to pubmed mappings . Somewhat redundant with the process_pubinfo method but this includes additional mappings .
251,228
def _process_targeting_reagents ( self , reagent_type , limit = None ) : LOG . info ( "Processing Gene Targeting Reagents" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) geno = Genotype ( graph ) if reagent_type not in [ 'morph' , 'talen' , 'crispr'...
This method processes the gene targeting knockdown reagents such as morpholinos talens and crisprs . We create triples for the reagents and pass the data into a hash map for use in the pheno_enviro method .
251,229
def _process_uniprot_ids ( self , limit = None ) : LOG . info ( "Processing UniProt IDs" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) geno = Genotype ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'uniprot' ] [ 'file' ] ) ) with ope...
This method processes the mappings from ZFIN gene IDs to UniProtKB IDs .
251,230
def get_orthology_evidence_code ( self , abbrev ) : eco_abbrev_map = { 'AA' : 'ECO:0000031' , 'CE' : 'ECO:0000008' , 'CL' : 'ECO:0000044' , 'FC' : 'ECO:0000012' , 'FH' : 'ECO:0000064' , 'IX' : 'ECO:0000040' , 'NS' : None , 'NT' : 'ECO:0000032' , 'SI' : 'ECO:0000094' , 'SL' : 'ECO:0000122' , 'SS' : 'ECO:0000024' , 'SU' ...
move to localtt & globltt
251,231
def _process_diseases ( self , limit = None ) : LOG . info ( "Processing diseases" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 model = Model ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'disease' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "iso-...
This method processes the KEGG disease IDs .
251,232
def _process_genes ( self , limit = None ) : LOG . info ( "Processing genes" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 family = Family ( graph ) geno = Genotype ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'hsa_genes' ] [ 'file...
This method processes the KEGG gene IDs . The label for the gene is pulled as the first symbol in the list of gene symbols ; the rest are added as synonyms . The long - form of the gene name is added as a definition . This is hardcoded to just processes human genes .
251,233
def _process_ortholog_classes ( self , limit = None ) : LOG . info ( "Processing ortholog classes" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'ortholog_classes' ] [ 'file' ] ) ) with open ( raw...
This method add the KEGG orthology classes to the graph .
251,234
def _process_orthologs ( self , raw , limit = None ) : LOG . info ( "Processing orthologs" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 with open ( raw , 'r' , encoding = "iso-8859-1" ) as csvfile : filereader = csv . reader ( csvfile , delimiter ...
This method maps orthologs for a species to the KEGG orthology classes .
251,235
def _process_kegg_disease2gene ( self , limit = None ) : LOG . info ( "Processing KEGG disease to gene" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 geno = Genotype ( graph ) rel = self . globaltt [ 'is marker for' ] noomimset = set ( ) raw = '/' ...
This method creates an association between diseases and their associated genes . We are being conservative here and only processing those diseases for which there is no mapping to OMIM .
251,236
def _process_omim2gene ( self , limit = None ) : LOG . info ( "Processing OMIM to KEGG gene" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 geno = Genotype ( graph ) raw = '/' . join ( ( self . rawdir , self . files [ 'omim2gene' ] [ 'file' ] ) ) wi...
This method maps the OMIM IDs and KEGG gene ID . Currently split based on the link_type field . Equivalent link types are mapped as gene XRefs . Reverse link types are mapped as disease to gene associations . Original link types are currently skipped .
251,237
def _process_genes_kegg2ncbi ( self , limit = None ) : LOG . info ( "Processing KEGG gene IDs to NCBI gene IDs" ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'ncbi' ] [ 'file' ] ) ) with open ( ra...
This method maps the KEGG human gene IDs to the corresponding NCBI Gene IDs .
251,238
def _process_pathway_disease ( self , limit ) : LOG . info ( "Processing KEGG pathways to disease ids" ) if self . test_mode : graph = self . testgraph else : graph = self . graph line_counter = 0 raw = '/' . join ( ( self . rawdir , self . files [ 'pathway_disease' ] [ 'file' ] ) ) with open ( raw , 'r' , encoding = "...
We make a link between the pathway identifiers and any diseases associated with them . Since we model diseases as processes we make a triple saying that the pathway may be causally upstream of or within the disease process .
251,239
def _make_variant_locus_id ( self , gene_id , disease_id ) : alt_locus_id = '_:' + re . sub ( r':' , '' , gene_id ) + '-' + re . sub ( r':' , '' , disease_id ) + 'VL' alt_label = self . label_hash . get ( gene_id ) disease_label = self . label_hash . get ( disease_id ) if alt_label is not None and alt_label != '' : alt...
We actually want the association between the gene and the disease to be via an alternate locus not the wildtype gene itself . so we make an anonymous alternate locus and put that in the association We also make the label for the anonymous class and add it to the label hash
251,240
def _fetch_disambiguating_assoc ( self ) : disambig_file = '/' . join ( ( self . rawdir , self . static_files [ 'publications' ] [ 'file' ] ) ) assoc_file = '/' . join ( ( self . rawdir , self . files [ 'chemical_disease_interactions' ] [ 'file' ] ) ) if os . path . exists ( disambig_file ) : dfile_dt = os . stat ( dis...
For any of the items in the chemical - disease association file that have ambiguous association types we fetch the disambiguated associations using the batch query API and store these in a file . Elsewhere we can loop through the file and create the appropriate associations .
251,241
def _make_association ( self , subject_id , object_id , rel_id , pubmed_ids ) : assoc = G2PAssoc ( self . graph , self . name , subject_id , object_id , rel_id ) if pubmed_ids is not None and len ( pubmed_ids ) > 0 : for pmid in pubmed_ids : ref = Reference ( self . graph , pmid , self . globaltt [ 'journal article' ] ...
Make a reified association given an array of pubmed identifiers .
251,242
def checkIfRemoteIsNewer ( self , localfile , remote_size , remote_modify ) : is_remote_newer = False status = os . stat ( localfile ) LOG . info ( "\nLocal file size: %i" "\nLocal Timestamp: %s" , status [ ST_SIZE ] , datetime . fromtimestamp ( status . st_mtime ) ) remote_dt = Bgee . _convert_ftp_time_to_iso ( remote...
Overrides checkIfRemoteIsNewer in Source class
251,243
def _convert_ftp_time_to_iso ( ftp_time ) : date_time = datetime ( int ( ftp_time [ : 4 ] ) , int ( ftp_time [ 4 : 6 ] ) , int ( ftp_time [ 6 : 8 ] ) , int ( ftp_time [ 8 : 10 ] ) , int ( ftp_time [ 10 : 12 ] ) , int ( ftp_time [ 12 : 14 ] ) ) return date_time
Convert datetime in the format 20160705042714 to a datetime object
251,244
def fetch ( self , is_dl_forced = False ) : cxn = { } cxn [ 'host' ] = 'nif-db.crbs.ucsd.edu' cxn [ 'database' ] = 'disco_crawler' cxn [ 'port' ] = '5432' cxn [ 'user' ] = config . get_config ( ) [ 'user' ] [ 'disco' ] cxn [ 'password' ] = config . get_config ( ) [ 'keys' ] [ cxn [ 'user' ] ] self . dataset . setFileAc...
connection details for DISCO
251,245
def parse ( self , limit = None ) : if limit is not None : LOG . info ( "Only parsing first %s rows of each file" , limit ) if self . test_only : self . test_mode = True LOG . info ( "Parsing files..." ) self . _process_nlx_157874_1_view ( '/' . join ( ( self . rawdir , 'dvp.pr_nlx_157874_1' ) ) , limit ) self . _map_e...
Over ride Source . parse inherited via PostgreSQLSource
251,246
def _process_gxd_genotype_view ( self , limit = None ) : line_counter = 0 if self . test_mode : graph = self . testgraph else : graph = self . graph geno = Genotype ( graph ) model = Model ( graph ) raw = '/' . join ( ( self . rawdir , 'gxd_genotype_view' ) ) LOG . info ( "getting genotypes and their backgrounds" ) wit...
This table indicates the relationship between a genotype and it s background strain . It leverages the Genotype class methods to do this .
251,247
def _process_gxd_genotype_summary_view ( self , limit = None ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 geno_hash = { } raw = '/' . join ( ( self . rawdir , 'gxd_genotype_summary_view' ) ) LOG . info ( "building labels for genotypes" ) with op...
Add the genotype internal id to mgiid mapping to the idhashmap . Also add them as individuals to the graph . We re - format the label to put the background strain in brackets after the gvc .
251,248
def process_mgi_relationship_transgene_genes ( self , limit = None ) : if self . test_mode : graph = self . testgraph else : graph = self . graph LOG . info ( "getting transgene genes" ) raw = '/' . join ( ( self . rawdir , 'mgi_relationship_transgene_genes' ) ) geno = Genotype ( graph ) col = [ 'rel_key' , 'allele_key...
Here we have the relationship between MGI transgene alleles and the non - mouse gene ids that are part of them . We augment the allele with the transgene parts .
251,249
def _getnode ( self , curie ) : node = None if curie [ 0 ] == '_' : if self . are_bnodes_skized is True : node = self . skolemizeBlankNode ( curie ) else : node = BNode ( re . sub ( r'^_:|^_' , '' , curie , 1 ) ) elif curie [ : 4 ] == 'http' or curie [ : 3 ] == 'ftp' : node = URIRef ( curie ) else : iri = RDFGraph . cu...
This is a wrapper for creating a URIRef or Bnode object with a given a curie or iri as a string .
251,250
def add_association_to_graph ( self ) : Assoc . add_association_to_graph ( self ) if self . onset is not None and self . onset != '' : self . graph . addTriple ( self . assoc_id , self . globaltt [ 'onset' ] , self . onset ) if self . frequency is not None and self . frequency != '' : self . graph . addTriple ( self . ...
The reified relationship between a disease and a phenotype is decorated with some provenance information . This makes the assumption that both the disease and phenotype are classes .
251,251
def make_parent_bands ( self , band , child_bands ) : m = re . match ( r'([pq][A-H\d]+(?:\.\d+)?)' , band ) if len ( band ) > 0 : if m : p = str ( band [ 0 : len ( band ) - 1 ] ) p = re . sub ( r'\.$' , '' , p ) if p is not None : child_bands . add ( p ) self . make_parent_bands ( p , child_bands ) else : child_bands =...
this will determine the grouping bands that it belongs to recursively 13q21 . 31 == > 13 13q 13q2 13q21 13q21 . 3 13q21 . 31
251,252
def get_curie ( self , uri ) : prefix = self . get_curie_prefix ( uri ) if prefix is not None : key = self . curie_map [ prefix ] return '%s:%s' % ( prefix , uri [ len ( key ) : len ( uri ) ] ) return None
Get a CURIE from a URI
251,253
def get_uri ( self , curie ) : if curie is None : return None parts = curie . split ( ':' ) if len ( parts ) == 1 : if curie != '' : LOG . error ( "Not a properly formed curie: \"%s\"" , curie ) return None prefix = parts [ 0 ] if prefix in self . curie_map : return '%s%s' % ( self . curie_map . get ( prefix ) , curie ...
Get a URI from a CURIE
251,254
def fetch ( self , is_dl_forced = False ) : host = config . get_config ( ) [ 'dbauth' ] [ 'coriell' ] [ 'host' ] key = config . get_config ( ) [ 'dbauth' ] [ 'coriell' ] [ 'private_key' ] user = config . get_config ( ) [ 'user' ] [ 'coriell' ] passwd = config . get_config ( ) [ 'keys' ] [ user ] with pysftp . Connectio...
Here we connect to the coriell sftp server using private connection details . They dump bi - weekly files with a timestamp in the filename . For each catalog we ping the remote site and pull the most - recently updated file renaming it to our local latest . csv .
251,255
def _process_collection ( self , collection_id , label , page ) : for graph in [ self . graph , self . testgraph ] : model = Model ( graph ) reference = Reference ( graph ) repo_id = 'CoriellCollection:' + collection_id repo_label = label repo_page = page model . addIndividualToGraph ( repo_id , repo_label , self . glo...
This function will process the data supplied internally about the repository from Coriell .
251,256
def _process_genotypes ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , 'genotype' ) ) LOG . info ( "building labels for genotypes" ) geno = Genotype ( graph ) fly_tax = self . globaltt [ 'Drosophi...
Add the genotype internal id to flybase mapping to the idhashmap . Also add them as individuals to the graph .
251,257
def _process_stocks ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , 'stock' ) ) LOG . info ( "building labels for stocks" ) with open ( raw , 'r' ) as f : f . readline ( ) filereader = csv . reade...
Stock definitions . Here we instantiate them as instances of the given taxon .
251,258
def _process_pubs ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) line_counter = 0 raw = '/' . join ( ( self . rawdir , 'pub' ) ) LOG . info ( "building labels for pubs" ) with open ( raw , 'r' ) as f : f . readline ( ) filereader = csv . reader ( f ...
Flybase publications .
251,259
def _process_environments ( self ) : if self . test_mode : graph = self . testgraph else : graph = self . graph raw = '/' . join ( ( self . rawdir , 'environment' ) ) LOG . info ( "building labels for environment" ) env_parts = { } label_map = { } env = Environment ( graph ) with open ( raw , 'r' ) as f : filereader = ...
There s only about 30 environments in which the phenotypes are recorded . There are no externally accessible identifiers for environments so we make anonymous nodes for now . Some of the environments are comprised of > 1 of the other environments ; we do some simple parsing to match the strings of the environmental lab...
251,260
def _process_stock_genotype ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph raw = '/' . join ( ( self . rawdir , 'stock_genotype' ) ) LOG . info ( "processing stock genotype" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimiter = '\t' ...
The genotypes of the stocks .
251,261
def _process_dbxref ( self ) : raw = '/' . join ( ( self . rawdir , 'dbxref' ) ) LOG . info ( "processing dbxrefs" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' ) f . readline ( ) for line in filereader : ( dbxref_id , db_id , accession , version ,...
We bring in the dbxref identifiers and store them in a hashmap for lookup in other functions . Note that some dbxrefs aren t mapped to identifiers . For example 5004018 is mapped to a string endosome & imaginal disc epithelial cell | somatic clone ... In those cases there just isn t a dbxref that s used when referencin...
251,262
def _process_phenotype ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) raw = '/' . join ( ( self . rawdir , 'phenotype' ) ) LOG . info ( "processing phenotype" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimite...
Get the phenotypes and declare the classes . If the observable is unspecified then we assign the phenotype to the cvalue id ; otherwise we convert the phenotype into a uberpheno - style identifier simply based on the anatomical part that s affected ... that is listed as the observable_id concatenated with the literal P...
251,263
def _process_cvterm ( self ) : line_counter = 0 raw = '/' . join ( ( self . rawdir , 'cvterm' ) ) LOG . info ( "processing cvterms" ) with open ( raw , 'r' ) as f : f . readline ( ) filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' ) for line in filereader : line_counter += 1 ( cvterm_id , cv_id , def...
CVterms are the internal identifiers for any controlled vocab or ontology term . Many are xrefd to actual ontologies . The actual external id is stored in the dbxref table which we place into the internal hashmap for lookup with the cvterm id . The name of the external term is stored in the name element of this table a...
251,264
def _process_organisms ( self , limit ) : if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) raw = '/' . join ( ( self . rawdir , 'organism' ) ) LOG . info ( "processing organisms" ) line_counter = 0 with open ( raw , 'r' ) as f : filereader = csv . reader ( f , delimiter...
The internal identifiers for the organisms in flybase
251,265
def _add_gene_equivalencies ( self , xrefs , gene_id , taxon ) : clique_map = self . open_and_parse_yaml ( self . resources [ 'clique_leader' ] ) if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) filter_out = [ 'Vega' , 'IMGT/GENE-DB' , 'Araport' ] for dbxref in xrefs . ...
Add equivalentClass and sameAs relationships
251,266
def _get_gene2pubmed ( self , limit ) : src_key = 'gene2pubmed' if self . test_mode : graph = self . testgraph else : graph = self . graph model = Model ( graph ) LOG . info ( "Processing Gene records" ) line_counter = 0 myfile = '/' . join ( ( self . rawdir , self . files [ src_key ] [ 'file' ] ) ) LOG . info ( "FILE:...
Loops through the gene2pubmed file and adds a simple triple to say that a given publication is_about a gene . Publications are added as NamedIndividuals .
251,267
def process_entries ( self , omimids , transform , included_fields = None , graph = None , limit = None , globaltt = None ) : omimparams = { } if included_fields is not None and included_fields : omimparams [ 'include' ] = ',' . join ( included_fields ) processed_entries = list ( ) cleanomimids = [ o . split ( ':' ) [ ...
Given a list of omim ids this will use the omim API to fetch the entries according to the included_fields passed as a parameter . If a transformation function is supplied this will iterate over each entry and either add the results to the supplied graph or will return a set of processed entries that the calling functio...
251,268
def _process_all ( self , limit ) : omimids = self . _get_omim_ids ( ) LOG . info ( 'Have %i omim numbers to fetch records from their API' , len ( omimids ) ) LOG . info ( 'Have %i omim types ' , len ( self . omim_type ) ) if self . test_mode : graph = self . testgraph else : graph = self . graph geno = Genotype ( grap...
This takes the list of omim identifiers from the omim . txt . Z file and iteratively queries the omim api for the json - formatted data . This will create OMIM classes with the label definition and some synonyms . If an entry is removed it is added as a deprecated class . If an entry is moved it is deprecated and consi...
251,269
def update ( self , key : bytes , value : bytes , node_updates : Sequence [ Hash32 ] ) : validate_is_bytes ( key ) validate_length ( key , self . _key_size ) path_diff = ( to_int ( self . key ) ^ to_int ( key ) ) if path_diff == 0 : self . _value = value else : for bit in reversed ( range ( self . _branch_size ) ) : if...
Merge an update for another key with the one we are tracking internally .
251,270
def _get ( self , key : bytes ) -> Tuple [ bytes , Tuple [ Hash32 ] ] : validate_is_bytes ( key ) validate_length ( key , self . _key_size ) branch = [ ] target_bit = 1 << ( self . depth - 1 ) path = to_int ( key ) node_hash = self . root_hash for _ in range ( self . depth ) : node = self . db [ node_hash ] left , righ...
Returns db value and branch in root - > leaf order
251,271
def set ( self , key : bytes , value : bytes ) -> Tuple [ Hash32 ] : validate_is_bytes ( key ) validate_length ( key , self . _key_size ) validate_is_bytes ( value ) path = to_int ( key ) node = value _ , branch = self . _get ( key ) proof_update = [ ] target_bit = 1 for sibling_node in reversed ( branch ) : node_hash ...
Returns all updated hashes in root - > leaf order
251,272
def delete ( self , key : bytes ) -> Tuple [ Hash32 ] : validate_is_bytes ( key ) validate_length ( key , self . _key_size ) return self . set ( key , self . _default )
Equals to setting the value to None Returns all updated hashes in root - > leaf order
251,273
def next_batch ( self , n = 1 ) : if len ( self . queue ) == 0 : return [ ] batch = list ( reversed ( ( self . queue [ - n : ] ) ) ) self . queue = self . queue [ : - n ] return batch
Return the next requests that should be dispatched .
251,274
def schedule ( self , node_key , parent , depth , leaf_callback , is_raw = False ) : if node_key in self . _existing_nodes : self . logger . debug ( "Node %s already exists in db" % encode_hex ( node_key ) ) return if node_key in self . db : self . _existing_nodes . add ( node_key ) self . logger . debug ( "Node %s alr...
Schedule a request for the node with the given key .
251,275
def get_children ( self , request ) : node = decode_node ( request . data ) return _get_children ( node , request . depth )
Return all children of the node retrieved by the given request .
251,276
def process ( self , results ) : for node_key , data in results : request = self . requests . get ( node_key ) if request is None : self . logger . info ( "No SyncRequest found for %s, maybe we got more than one response for it" % encode_hex ( node_key ) ) return if request . data is not None : raise SyncRequestAlready...
Process request results .
251,277
def check_if_branch_exist ( db , root_hash , key_prefix ) : validate_is_bytes ( key_prefix ) return _check_if_branch_exist ( db , root_hash , encode_to_bin ( key_prefix ) )
Given a key prefix return whether this prefix is the prefix of an existing key in the trie .
251,278
def get_branch ( db , root_hash , key ) : validate_is_bytes ( key ) return tuple ( _get_branch ( db , root_hash , encode_to_bin ( key ) ) )
Get a long - format Merkle branch
251,279
def get_witness_for_key_prefix ( db , node_hash , key ) : validate_is_bytes ( key ) return tuple ( _get_witness_for_key_prefix ( db , node_hash , encode_to_bin ( key ) ) )
Get all witness given a keypath prefix . Include
251,280
def encode_branch_node ( left_child_node_hash , right_child_node_hash ) : validate_is_bytes ( left_child_node_hash ) validate_length ( left_child_node_hash , 32 ) validate_is_bytes ( right_child_node_hash ) validate_length ( right_child_node_hash , 32 ) return BRANCH_TYPE_PREFIX + left_child_node_hash + right_child_nod...
Serializes a branch node
251,281
def encode_leaf_node ( value ) : validate_is_bytes ( value ) if value is None or value == b'' : raise ValidationError ( "Value of leaf node can not be empty" ) return LEAF_TYPE_PREFIX + value
Serializes a leaf node
251,282
def batch_commit ( self , * , do_deletes = False ) : try : yield except Exception as exc : raise exc else : for key , value in self . cache . items ( ) : if value is not DELETED : self . wrapped_db [ key ] = value elif do_deletes : self . wrapped_db . pop ( key , None ) finally : self . cache = { }
Batch and commit and end of context
251,283
def _prune_node ( self , node ) : if self . is_pruning : prune_key , node_body = self . _node_to_db_mapping ( node ) should_prune = ( node_body is not None ) else : should_prune = False yield if should_prune : del self . db [ prune_key ]
Prune the given node if context exits cleanly .
251,284
def _normalize_branch_node ( self , node ) : iter_node = iter ( node ) if any ( iter_node ) and any ( iter_node ) : return node if node [ 16 ] : return [ compute_leaf_key ( [ ] ) , node [ 16 ] ] sub_node_idx , sub_node_hash = next ( ( idx , v ) for idx , v in enumerate ( node [ : 16 ] ) if v ) sub_node = self . get_nod...
A branch node which is left with only a single non - blank item should be turned into either a leaf or extension node .
251,285
def _delete_branch_node ( self , node , trie_key ) : if not trie_key : node [ - 1 ] = BLANK_NODE return self . _normalize_branch_node ( node ) node_to_delete = self . get_node ( node [ trie_key [ 0 ] ] ) sub_node = self . _delete ( node_to_delete , trie_key [ 1 : ] ) encoded_sub_node = self . _persist_node ( sub_node )...
Delete a key from inside or underneath a branch node
251,286
def get ( self , key ) : validate_is_bytes ( key ) return self . _get ( self . root_hash , encode_to_bin ( key ) )
Fetches the value with a given keypath from the given node .
251,287
def set ( self , key , value ) : validate_is_bytes ( key ) validate_is_bytes ( value ) self . root_hash = self . _set ( self . root_hash , encode_to_bin ( key ) , value )
Sets the value at the given keypath from the given node
251,288
def _set ( self , node_hash , keypath , value , if_delete_subtrie = False ) : if node_hash == BLANK_HASH : if value : return self . _hash_and_save ( encode_kv_node ( keypath , self . _hash_and_save ( encode_leaf_node ( value ) ) ) ) else : return BLANK_HASH nodetype , left_child , right_child = parse_node ( self . db [...
If if_delete_subtrie is set to True what it will do is that it take in a keypath and traverse til the end of keypath then delete the whole subtrie of that node .
251,289
def delete ( self , key ) : validate_is_bytes ( key ) self . root_hash = self . _set ( self . root_hash , encode_to_bin ( key ) , b'' )
Equals to setting the value to None
251,290
def delete_subtrie ( self , key ) : validate_is_bytes ( key ) self . root_hash = self . _set ( self . root_hash , encode_to_bin ( key ) , value = b'' , if_delete_subtrie = True , )
Given a key prefix delete the whole subtrie that starts with the key prefix .
251,291
def _hash_and_save ( self , node ) : validate_is_bin_node ( node ) node_hash = keccak ( node ) self . db [ node_hash ] = node return node_hash
Saves a node into the database and returns its hash
251,292
def decode_from_bin ( input_bin ) : for chunk in partition_all ( 8 , input_bin ) : yield sum ( 2 ** exp * bit for exp , bit in enumerate ( reversed ( chunk ) ) )
0100000101010111010000110100100101001001 - > ASCII
251,293
def encode_to_bin ( value ) : for char in value : for exp in EXP : if char & exp : yield True else : yield False
ASCII - > 0100000101010111010000110100100101001001
251,294
def encode_from_bin_keypath ( input_bin ) : padded_bin = bytes ( ( 4 - len ( input_bin ) ) % 4 ) + input_bin prefix = TWO_BITS [ len ( input_bin ) % 4 ] if len ( padded_bin ) % 8 == 4 : return decode_from_bin ( PREFIX_00 + prefix + padded_bin ) else : return decode_from_bin ( PREFIX_100000 + prefix + padded_bin )
Encodes a sequence of 0s and 1s into tightly packed bytes Used in encoding key path of a KV - NODE
251,295
def decode_to_bin_keypath ( path ) : path = encode_to_bin ( path ) if path [ 0 ] == 1 : path = path [ 4 : ] assert path [ 0 : 2 ] == PREFIX_00 padded_len = TWO_BITS . index ( path [ 2 : 4 ] ) return path [ 4 + ( ( 4 - padded_len ) % 4 ) : ]
Decodes bytes into a sequence of 0s and 1s Used in decoding key path of a KV - NODE
251,296
def encode_nibbles ( nibbles ) : if is_nibbles_terminated ( nibbles ) : flag = HP_FLAG_2 else : flag = HP_FLAG_0 raw_nibbles = remove_nibbles_terminator ( nibbles ) is_odd = len ( raw_nibbles ) % 2 if is_odd : flagged_nibbles = tuple ( itertools . chain ( ( flag + 1 , ) , raw_nibbles , ) ) else : flagged_nibbles = tupl...
The Hex Prefix function
251,297
def decode_nibbles ( value ) : nibbles_with_flag = bytes_to_nibbles ( value ) flag = nibbles_with_flag [ 0 ] needs_terminator = flag in { HP_FLAG_2 , HP_FLAG_2 + 1 } is_odd_length = flag in { HP_FLAG_0 + 1 , HP_FLAG_2 + 1 } if is_odd_length : raw_nibbles = nibbles_with_flag [ 1 : ] else : raw_nibbles = nibbles_with_fla...
The inverse of the Hex Prefix function
251,298
def get_local_file ( file ) : try : with open ( file . path ) : yield file . path except NotImplementedError : _ , ext = os . path . splitext ( file . name ) with NamedTemporaryFile ( prefix = 'wagtailvideo-' , suffix = ext ) as tmp : try : file . open ( 'rb' ) for chunk in file . chunks ( ) : tmp . write ( chunk ) fin...
Get a local version of the file downloading it from the remote storage if required . The returned value should be used as a context manager to ensure any temporary files are cleaned up afterwards .
251,299
def rustcall ( func , * args ) : lib . semaphore_err_clear ( ) rv = func ( * args ) err = lib . semaphore_err_get_last_code ( ) if not err : return rv msg = lib . semaphore_err_get_last_message ( ) cls = exceptions_by_code . get ( err , SemaphoreError ) exc = cls ( decode_str ( msg ) ) backtrace = decode_str ( lib . se...
Calls rust method and does some error handling .