idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
222,600 | def ftp_get ( fin_src , fout ) : assert fin_src [ : 6 ] == 'ftp://' , fin_src dir_full , fin_ftp = os . path . split ( fin_src [ 6 : ] ) pt0 = dir_full . find ( '/' ) assert pt0 != - 1 , pt0 ftphost = dir_full [ : pt0 ] chg_dir = dir_full [ pt0 + 1 : ] print ( 'FTP RETR {HOST} {DIR} {SRC} -> {DST}' . format ( HOST = ftphost , DIR = chg_dir , SRC = fin_ftp , DST = fout ) ) ftp = FTP ( ftphost ) # connect to host, default port ftp.ncbi.nlm.nih.gov ftp . login ( ) # user anonymous, passwd anonymous@ ftp . cwd ( chg_dir ) # change into "debian" directory gene/DATA cmd = 'RETR {F}' . format ( F = fin_ftp ) # gene2go.gz ftp . retrbinary ( cmd , open ( fout , 'wb' ) . write ) # /usr/home/gene2go.gz ftp . quit ( ) | Download a file from an ftp server | 287 | 8 |
222,601 | def dnld_file ( src_ftp , dst_file , prt = sys . stdout , loading_bar = True ) : if os . path . isfile ( dst_file ) : return do_gunzip = src_ftp [ - 3 : ] == '.gz' and dst_file [ - 3 : ] != '.gz' dst_wget = "{DST}.gz" . format ( DST = dst_file ) if do_gunzip else dst_file # Write to stderr, not stdout so this message will be seen when running nosetests wget_msg = "wget({SRC} out={DST})\n" . format ( SRC = src_ftp , DST = dst_wget ) #### sys.stderr.write(" {WGET}".format(WGET=wget_msg)) #### if loading_bar: #### loading_bar = wget.bar_adaptive try : #### wget.download(src_ftp, out=dst_wget, bar=loading_bar) rsp = http_get ( src_ftp , dst_wget ) if src_ftp [ : 4 ] == 'http' else ftp_get ( src_ftp , dst_wget ) if do_gunzip : if prt is not None : prt . write ( " gunzip {FILE}\n" . format ( FILE = dst_wget ) ) gzip_open_to ( dst_wget , dst_file ) except IOError as errmsg : import traceback traceback . print_exc ( ) sys . stderr . write ( "**FATAL cmd: {WGET}" . format ( WGET = wget_msg ) ) sys . stderr . write ( "**FATAL msg: {ERR}" . format ( ERR = str ( errmsg ) ) ) sys . exit ( 1 ) | Download specified file if necessary . | 425 | 6 |
222,602 | def init_datamembers ( self , rec ) : # pylint: disable=multiple-statements if 'synonym' in self . optional_attrs : rec . synonym = [ ] if 'xref' in self . optional_attrs : rec . xref = set ( ) if 'subset' in self . optional_attrs : rec . subset = set ( ) if 'comment' in self . optional_attrs : rec . comment = "" if 'relationship' in self . optional_attrs : rec . relationship = { } rec . relationship_rev = { } | Initialize current GOTerm with data members for storing optional attributes . | 129 | 13 |
222,603 | def _get_synonym ( self , line ) : mtch = self . attr2cmp [ 'synonym' ] . match ( line ) text , scope , typename , dbxrefs , _ = mtch . groups ( ) typename = typename . strip ( ) dbxrefs = set ( dbxrefs . split ( ', ' ) ) if dbxrefs else set ( ) return self . attr2cmp [ 'synonym nt' ] . _make ( [ text , scope , typename , dbxrefs ] ) | Given line return optional attribute synonym value in a namedtuple . | 121 | 14 |
222,604 | def _get_xref ( self , line ) : # Ex: Wikipedia:Zygotene # Ex: Reactome:REACT_22295 "Addition of a third mannose to ..." mtch = self . attr2cmp [ 'xref' ] . match ( line ) return mtch . group ( 1 ) . replace ( ' ' , '' ) | Given line return optional attribute xref value in a dict of sets . | 79 | 14 |
222,605 | def _init_compile_patterns ( optional_attrs ) : attr2cmp = { } if optional_attrs is None : return attr2cmp # "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr] # "blood vessel formation from pre-existing blood vessels" EXACT systematic_synonym [] # "mitochondrial inheritance" EXACT [] # "tricarboxylate transport protein" RELATED [] {comment="WIkipedia:Mitochondrial_carrier"} if 'synonym' in optional_attrs : attr2cmp [ 'synonym' ] = re . compile ( r'"(\S.*\S)" ([A-Z]+) (.*)\[(.*)\](.*)$' ) attr2cmp [ 'synonym nt' ] = cx . namedtuple ( "synonym" , "text scope typename dbxrefs" ) # Wikipedia:Zygotene # Reactome:REACT_27267 "DHAP from Ery4P and PEP, Mycobacterium tuberculosis" if 'xref' in optional_attrs : attr2cmp [ 'xref' ] = re . compile ( r'^(\S+:\s*\S+)\b(.*)$' ) return attr2cmp | Compile search patterns for optional attributes if needed . | 290 | 10 |
222,606 | def cli ( ) : objcli = WrHierCli ( sys . argv [ 1 : ] ) fouts_txt = objcli . get_fouts ( ) if fouts_txt : for fout_txt in fouts_txt : objcli . wrtxt_hier ( fout_txt ) else : objcli . prt_hier ( sys . stdout ) | Command - line script to print a GO term s lower - level hierarchy . | 85 | 15 |
222,607 | def get_fouts ( self ) : fouts_txt = [ ] if 'o' in self . kws : fouts_txt . append ( self . kws [ 'o' ] ) if 'f' in self . kws : fouts_txt . append ( self . _get_fout_go ( ) ) return fouts_txt | Get output filename . | 77 | 4 |
222,608 | def _get_fout_go ( self ) : assert self . goids , "NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT" base = next ( iter ( self . goids ) ) . replace ( ':' , '' ) upstr = '_up' if 'up' in self . kws else '' return "hier_{BASE}{UP}.{EXT}" . format ( BASE = base , UP = upstr , EXT = 'txt' ) | Get the name of an output file based on the top GO term . | 111 | 14 |
222,609 | def wrtxt_hier ( self , fout_txt ) : with open ( fout_txt , 'wb' ) as prt : self . prt_hier ( prt ) print ( " WROTE: {TXT}" . format ( TXT = fout_txt ) ) | Write hierarchy below specfied GO IDs to an ASCII file . | 64 | 13 |
222,610 | def prt_hier ( self , prt = sys . stdout ) : objwr = WrHierGO ( self . gosubdag , * * self . kws ) assert self . goids , "NO VALID GO IDs WERE PROVIDED" if 'up' not in objwr . usrset : for goid in self . goids : objwr . prt_hier_down ( goid , prt ) else : objwr . prt_hier_up ( self . goids , prt ) | Write hierarchy below specfied GO IDs . | 119 | 9 |
222,611 | def _adj_for_assc ( self ) : if self . gene2gos : gos_assoc = set ( get_b2aset ( self . gene2gos ) . keys ( ) ) if 'item_marks' not in self . kws : self . kws [ 'item_marks' ] = { go : '>' for go in gos_assoc } if 'include_only' not in self . kws : gosubdag = GoSubDag ( gos_assoc , self . gosubdag . go2obj , self . gosubdag . relationships ) self . kws [ 'include_only' ] = gosubdag . go2obj | Print only GO IDs from associations and their ancestors . | 160 | 10 |
222,612 | def calc_pvalue ( self , study_count , study_n , pop_count , pop_n ) : fnc_call = "calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})" . format ( SCNT = study_count , STOT = study_n , PCNT = pop_count , PTOT = pop_n ) raise Exception ( "NOT IMPLEMENTED: {FNC_CALL} using {FNC}." . format ( FNC_CALL = fnc_call , FNC = self . pval_fnc ) ) | pvalues are calculated in derived classes . | 133 | 8 |
222,613 | def _init_pval_obj ( self ) : if self . pval_fnc_name in self . options . keys ( ) : try : fisher_obj = self . options [ self . pval_fnc_name ] ( self . pval_fnc_name , self . log ) except ImportError : print ( "fisher module not installed. Falling back on scipy.stats.fisher_exact" ) fisher_obj = self . options [ 'fisher_scipy_stats' ] ( 'fisher_scipy_stats' , self . log ) return fisher_obj raise Exception ( "PVALUE FUNCTION({FNC}) NOT FOUND" . format ( FNC = self . pval_fnc_name ) ) | Returns a Fisher object based on user - input . | 168 | 10 |
222,614 | def check_version ( self , name , majorv = 2 , minorv = 7 ) : if sys . version_info . major == majorv and sys . version_info . minor != minorv : sys . stderr . write ( "ERROR: %s is only for >= Python %d.%d but you are running %d.%d\n" % ( name , majorv , minorv , sys . version_info . major , sys . version_info . minor ) ) sys . exit ( 1 ) | Make sure the package runs on the supported Python version | 111 | 10 |
222,615 | def get_init ( self , filename = "__init__.py" ) : import ast with open ( filename ) as init_file : module = ast . parse ( init_file . read ( ) ) itr = lambda x : ( ast . literal_eval ( node . value ) for node in ast . walk ( module ) if isinstance ( node , ast . Assign ) and node . targets [ 0 ] . id == x ) try : return next ( itr ( "__author__" ) ) , next ( itr ( "__email__" ) ) , next ( itr ( "__license__" ) ) , next ( itr ( "__version__" ) ) except StopIteration : raise ValueError ( "One of author, email, license, or version" " cannot be found in {}" . format ( filename ) ) | Get various info from the package without importing them | 181 | 9 |
222,616 | def missing_requirements ( self , specifiers ) : for specifier in specifiers : try : pkg_resources . require ( specifier ) except pkg_resources . DistributionNotFound : yield specifier | Find what s missing | 44 | 4 |
222,617 | def install_requirements ( self , requires ) : # Temporarily install dependencies required by setup.py before trying to import them. sys . path [ 0 : 0 ] = [ 'setup-requires' ] pkg_resources . working_set . add_entry ( 'setup-requires' ) to_install = list ( self . missing_requirements ( requires ) ) if to_install : cmd = [ sys . executable , "-m" , "pip" , "install" , "-t" , "setup-requires" ] + to_install subprocess . call ( cmd ) | Install the listed requirements | 125 | 4 |
222,618 | def get_long_description ( self , filename = 'README.md' ) : try : import pypandoc description = pypandoc . convert_file ( 'README.md' , 'rst' , 'md' ) except ( IOError , ImportError ) : description = open ( "README.md" ) . read ( ) return description | I really prefer Markdown to reStructuredText . PyPi does not . | 79 | 16 |
222,619 | def prt_gos ( self , prt = sys . stdout , * * kws_usr ) : # deprecated # Keyword arguments (control content): hdrgo_prt section_prt use_sections # desc2nts contains: (sections hdrgo_prt sortobj) or (flat hdrgo_prt sortobj) desc2nts = self . get_desc2nts ( * * kws_usr ) # Keyword arguments (control print format): prt prtfmt self . prt_nts ( desc2nts , prt , kws_usr . get ( 'prtfmt' ) ) return desc2nts | Sort user GO ids grouped under broader GO terms or sections . Print to screen . | 148 | 17 |
222,620 | def get_nts_flat ( self , hdrgo_prt = True , use_sections = True ) : # Either there are no sections OR we are not using them if self . sectobj is None or not use_sections : return self . sortgos . get_nts_sorted ( hdrgo_prt , hdrgos = self . grprobj . get_hdrgos ( ) , hdrgo_sort = True ) if not use_sections : return self . sectobj . get_sorted_nts_omit_section ( hdrgo_prt , hdrgo_sort = True ) return None | Return a flat list of sorted nts . | 143 | 9 |
222,621 | def get_sections_2d ( self ) : sections_hdrgos_act = [ ] hdrgos_act_all = self . get_hdrgos ( ) # Header GOs actually used to group hdrgos_act_secs = set ( ) if self . hdrobj . sections : for section_name , hdrgos_all_lst in self . hdrobj . sections : # print("GGGGGGGGGGGGGGGGG {N:3} {NAME}".format(N=len(hdrgos_all_lst), NAME=section_name)) hdrgos_all_set = set ( hdrgos_all_lst ) hdrgos_act_set = hdrgos_all_set . intersection ( hdrgos_act_all ) if hdrgos_act_set : hdrgos_act_secs |= hdrgos_act_set # Use original order of header GOs found in sections hdrgos_act_lst = [ ] hdrgos_act_ctr = cx . Counter ( ) for hdrgo_p in hdrgos_all_lst : # Header GO that may or may not be used. if hdrgo_p in hdrgos_act_set and hdrgos_act_ctr [ hdrgo_p ] == 0 : hdrgos_act_lst . append ( hdrgo_p ) hdrgos_act_ctr [ hdrgo_p ] += 1 sections_hdrgos_act . append ( ( section_name , hdrgos_act_lst ) ) # print(">>>>>>>>>>>>>>> hdrgos_act_all {N:3}".format(N=len(hdrgos_act_all))) # print(">>>>>>>>>>>>>>> hdrgos_act_secs {N:3}".format(N=len(hdrgos_act_secs))) hdrgos_act_rem = hdrgos_act_all . difference ( hdrgos_act_secs ) if hdrgos_act_rem : # print("RRRRRRRRRRR {N:3}".format(N=len(hdrgos_act_rem))) sections_hdrgos_act . append ( ( self . hdrobj . secdflt , hdrgos_act_rem ) ) else : sections_hdrgos_act . append ( ( self . hdrobj . secdflt , hdrgos_act_all ) ) return sections_hdrgos_act | Get 2 - D list of sections and hdrgos sets actually used in grouping . | 588 | 18 |
222,622 | def get_usrgos_g_section ( self , section = None ) : if section is None : section = self . hdrobj . secdflt if section is True : return self . usrgos # Get dict of sections and hdrgos actually used in grouping section2hdrgos = cx . OrderedDict ( self . get_sections_2d ( ) ) hdrgos_lst = section2hdrgos . get ( section , None ) if hdrgos_lst is not None : hdrgos_set = set ( hdrgos_lst ) hdrgos_u = hdrgos_set . intersection ( self . hdrgo_is_usrgo ) hdrgos_h = hdrgos_set . intersection ( self . hdrgo2usrgos . keys ( ) ) usrgos = set ( [ u for h in hdrgos_h for u in self . hdrgo2usrgos . get ( h ) ] ) usrgos |= hdrgos_u return usrgos return set ( ) | Get usrgos in a requested section . | 246 | 9 |
222,623 | def get_section2usrnts ( self ) : sec_nts = [ ] for section_name , _ in self . get_sections_2d ( ) : usrgos = self . get_usrgos_g_section ( section_name ) sec_nts . append ( ( section_name , [ self . go2nt . get ( u ) for u in usrgos ] ) ) return cx . OrderedDict ( sec_nts ) | Get dict section2usrnts . | 102 | 8 |
222,624 | def get_section2items ( self , itemkey ) : sec_items = [ ] section2usrnts = self . get_section2usrnts ( ) for section , usrnts in section2usrnts . items ( ) : items = set ( [ e for nt in usrnts for e in getattr ( nt , itemkey , set ( ) ) ] ) sec_items . append ( ( section , items ) ) return cx . OrderedDict ( sec_items ) | Collect all items into a single set per section . | 110 | 10 |
222,625 | def get_hdrgos_g_usrgos ( self , usrgos ) : hdrgos_for_usrgos = set ( ) hdrgos_all = self . get_hdrgos ( ) usrgo2hdrgo = self . get_usrgo2hdrgo ( ) for usrgo in usrgos : if usrgo in hdrgos_all : hdrgos_for_usrgos . add ( usrgo ) continue hdrgo_cur = usrgo2hdrgo . get ( usrgo , None ) if hdrgo_cur is not None : hdrgos_for_usrgos . add ( hdrgo_cur ) return hdrgos_for_usrgos | Return hdrgos which contain the usrgos . | 173 | 12 |
222,626 | def get_section_hdrgos_nts ( self , sortby = None ) : nts_all = [ ] section_hdrgos_actual = self . get_sections_2d ( ) flds_all = [ 'Section' ] + self . gosubdag . prt_attr [ 'flds' ] ntobj = cx . namedtuple ( "NtGoSec" , " " . join ( flds_all ) ) flds_go = None if sortby is None : sortby = lambda nt : - 1 * nt . dcnt for section_name , hdrgos_actual in section_hdrgos_actual : nts_sec = [ ] for hdrgo_nt in self . gosubdag . get_go2nt ( hdrgos_actual ) . values ( ) : if flds_go is None : flds_go = hdrgo_nt . _fields key2val = { key : val for key , val in zip ( flds_go , list ( hdrgo_nt ) ) } key2val [ 'Section' ] = section_name nts_sec . append ( ntobj ( * * key2val ) ) nts_all . extend ( sorted ( nts_sec , key = sortby ) ) return nts_all | Get a flat list of sections and hdrgos actually used in grouping . | 305 | 16 |
222,627 | def get_sections_2d_nts ( self , sortby = None ) : sections_2d_nts = [ ] for section_name , hdrgos_actual in self . get_sections_2d ( ) : hdrgo_nts = self . gosubdag . get_nts ( hdrgos_actual , sortby = sortby ) sections_2d_nts . append ( ( section_name , hdrgo_nts ) ) return sections_2d_nts | Get high GO IDs that are actually used to group current set of GO IDs . | 116 | 16 |
222,628 | def get_usrgos_g_hdrgos ( self , hdrgos ) : usrgos_all = set ( ) if isinstance ( hdrgos , str ) : hdrgos = [ hdrgos ] for hdrgo in hdrgos : usrgos_cur = self . hdrgo2usrgos . get ( hdrgo , None ) if usrgos_cur is not None : usrgos_all |= usrgos_cur if hdrgo in self . hdrgo_is_usrgo : usrgos_all . add ( hdrgo ) return usrgos_all | Return usrgos under provided hdrgos . | 144 | 11 |
222,629 | def get_hdrgo2usrgos ( self , hdrgos ) : get_usrgos = self . hdrgo2usrgos . get hdrgos_actual = self . get_hdrgos ( ) . intersection ( hdrgos ) return { h : get_usrgos ( h ) for h in hdrgos_actual } | Return a subset of hdrgo2usrgos . | 83 | 12 |
222,630 | def get_usrgo2hdrgo ( self ) : usrgo2hdrgo = { } for hdrgo , usrgos in self . hdrgo2usrgos . items ( ) : for usrgo in usrgos : assert usrgo not in usrgo2hdrgo usrgo2hdrgo [ usrgo ] = hdrgo # Add usrgos which are also a hdrgo and the GO group contains no other GO IDs for goid in self . hdrgo_is_usrgo : usrgo2hdrgo [ goid ] = goid assert len ( self . usrgos ) <= len ( usrgo2hdrgo ) , "USRGOS({U}) != USRGO2HDRGO({H}): {GOs}" . format ( U = len ( self . usrgos ) , H = len ( usrgo2hdrgo ) , GOs = self . usrgos . symmetric_difference ( set ( usrgo2hdrgo . keys ( ) ) ) ) return usrgo2hdrgo | Return a dict with all user GO IDs as keys and their respective header GOs as values . | 244 | 19 |
222,631 | def get_go2sectiontxt ( self ) : go2txt = { } _get_secs = self . hdrobj . get_sections hdrgo2sectxt = { h : " " . join ( _get_secs ( h ) ) for h in self . get_hdrgos ( ) } usrgo2hdrgo = self . get_usrgo2hdrgo ( ) for goid , ntgo in self . go2nt . items ( ) : hdrgo = ntgo . GO if ntgo . is_hdrgo else usrgo2hdrgo [ ntgo . GO ] go2txt [ goid ] = hdrgo2sectxt [ hdrgo ] return go2txt | Return a dict with actual header and user GO IDs as keys and their sections as values . | 165 | 18 |
222,632 | def get_usrgo2sections ( self ) : usrgo2sections = cx . defaultdict ( set ) usrgo2hdrgo = self . get_usrgo2hdrgo ( ) get_sections = self . hdrobj . get_sections for usrgo , hdrgo in usrgo2hdrgo . items ( ) : sections = set ( get_sections ( hdrgo ) ) usrgo2sections [ usrgo ] |= sections assert len ( usrgo2sections ) >= len ( self . usrgos ) , "uGOS({U}) != uGO2sections({H}): {GOs}" . format ( U = len ( self . usrgos ) , H = len ( usrgo2sections ) , GOs = self . usrgos . symmetric_difference ( set ( usrgo2sections . keys ( ) ) ) ) return usrgo2sections | Return a dict with all user GO IDs as keys and their sections as values . | 203 | 16 |
222,633 | def get_fout_base ( self , goid , name = None , pre = "gogrp" ) : goobj = self . gosubdag . go2obj [ goid ] if name is None : name = self . grpname . replace ( " " , "_" ) sections = "_" . join ( self . hdrobj . get_sections ( goid ) ) return "{PRE}_{BP}_{NAME}_{SEC}_{DSTR}_{D1s}_{GO}" . format ( PRE = pre , BP = Consts . NAMESPACE2NS [ goobj . namespace ] , NAME = self . _str_replace ( name ) , SEC = self . _str_replace ( self . _str_replace ( sections ) ) , GO = goid . replace ( ":" , "" ) , DSTR = self . _get_depthsr ( goobj ) , D1s = self . gosubdag . go2nt [ goobj . id ] . D1 ) | Get filename for a group of GO IDs under a single header GO ID . | 223 | 15 |
222,634 | def _get_depthsr ( self , goobj ) : if 'reldepth' in self . gosubdag . prt_attr [ 'flds' ] : return "R{R:02}" . format ( R = goobj . reldepth ) return "D{D:02}" . format ( D = goobj . depth ) | Return DNN or RNN depending on if relationships are loaded . | 81 | 13 |
222,635 | def _str_replace ( txt ) : txt = txt . replace ( "," , "" ) txt = txt . replace ( " " , "_" ) txt = txt . replace ( ":" , "" ) txt = txt . replace ( "." , "" ) txt = txt . replace ( "/" , "" ) txt = txt . replace ( "" , "" ) return txt | Makes a small text amenable to being used in a filename . | 91 | 14 |
222,636 | def get_prtfmt_list ( self , flds , add_nl = True ) : fmts = [ ] for fld in flds : if fld [ : 2 ] == 'p_' : fmts . append ( '{{{FLD}:8.2e}}' . format ( FLD = fld ) ) elif fld in self . default_fld2fmt : fmts . append ( self . default_fld2fmt [ fld ] ) else : raise Exception ( "UNKNOWN FORMAT: {FLD}" . format ( FLD = fld ) ) if add_nl : fmts . append ( "\n" ) return fmts | Get print format given fields . | 156 | 6 |
222,637 | def main ( ) : import argparse prs = argparse . ArgumentParser ( __doc__ , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) prs . add_argument ( '--taxon_id' , type = str , help = 'NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe' ) prs . add_argument ( '--golr_url' , default = 'http://golr.geneontology.org/solr/' , type = str , help = 'NCBI taxon ID, must match exact species/strain used by GO Central, e.g. 4896 for S Pombe' ) prs . add_argument ( '-o' , default = None , type = str , help = "Specifies the name of the output file" ) prs . add_argument ( '--max_rows' , default = 100000 , type = int , help = "maximum rows to be fetched" ) args = prs . parse_args ( ) solr = pysolr . Solr ( args . golr_url , timeout = 30 ) sys . stderr . write ( "TAX:" + args . taxon_id + "\n" ) results = solr . search ( q = 'document_category:"bioentity" AND taxon:"NCBITaxon:' + args . taxon_id + '"' , fl = 'bioentity_label,annotation_class_list' , rows = args . max_rows ) sys . stderr . write ( "NUM GENES:" + str ( len ( results ) ) + "\n" ) if ( len ( results ) == 0 ) : sys . stderr . write ( "NO RESULTS" ) exit ( 1 ) if ( len ( results ) == args . max_rows ) : sys . stderr . write ( "max_rows set too low" ) exit ( 1 ) file_out = sys . stdout if args . o is None else open ( args . o , 'w' ) for r in results : gene_symbol = r [ 'bioentity_label' ] sys . stderr . write ( gene_symbol + "\n" ) if 'annotation_class_list' in r : file_out . write ( r [ 'bioentity_label' ] + "\t" + ';' . join ( r [ 'annotation_class_list' ] ) + "\n" ) else : sys . stderr . write ( "no annotations for " + gene_symbol + "\n" ) if args . o is not None : file_out . close ( ) sys . stdout . write ( " WROTE: {}\n" . format ( args . o ) ) | Fetch simple gene - term assocaitions from Golr using bioentity document type one line per gene . | 618 | 22 |
222,638 | def get_short_plot_name ( self , goobj ) : name = goobj . name if self . _keep_this ( name ) : return self . replace_greek ( name ) name = name . replace ( "cellular response to chemical stimulus" , "cellular rsp. to chemical stim." ) depth = goobj . depth if depth > 1 : name = name . replace ( "regulation of " , "reg. of " ) name = name . replace ( "positive reg" , "+reg" ) name = name . replace ( "negative reg" , "-reg" ) name = name . replace ( "involved in" , "in" ) if depth > 2 : name = name . replace ( "antigen processing and presentation" , "a.p.p" ) name = name . replace ( "MHC class I" , "MHC-I" ) if depth == 4 : if goobj . id == "GO:0002460" : before = " " . join ( [ "adaptive immune response based on somatic recombination of" , "immune receptors built from immunoglobulin superfamily domains" ] ) name = name . replace ( before , "rsp. based on somatic recombination of Ig immune receptors" ) if depth > 3 : name = name . replace ( "signaling pathway" , "sig. pw." ) name = name . replace ( "response" , "rsp." ) name = name . replace ( "immunoglobulin superfamily domains" , "Ig domains" ) name = name . replace ( "immunoglobulin" , "Ig" ) if depth > 4 : name = name . replace ( "production" , "prod." ) if depth == 6 or depth == 5 : name = name . replace ( "tumor necrosis factor" , "TNF" ) name = self . replace_greek ( name ) return name | Shorten some GO names so plots are smaller . | 412 | 10 |
222,639 | def shorten_go_name_ptbl1 ( self , name ) : if self . _keep_this ( name ) : return name name = name . replace ( "negative" , "neg." ) name = name . replace ( "positive" , "pos." ) name = name . replace ( "response" , "rsp." ) name = name . replace ( "regulation" , "reg." ) name = name . replace ( "antigen processing and presentation" , "app." ) return name | Shorten GO name for tables in paper . | 106 | 9 |
222,640 | def shorten_go_name_ptbl3 ( self , name , dcnt ) : if self . _keep_this ( name ) : return name name = name . replace ( "positive regulation of immune system process" , "+ reg. of immune sys. process" ) name = name . replace ( "positive regulation of immune response" , "+ reg. of immune response" ) name = name . replace ( "positive regulation of cytokine production" , "+ reg. of cytokine production" ) if dcnt < 40 : name = name . replace ( "antigen processing and presentation" , "a.p.p." ) if dcnt < 10 : name = name . replace ( "negative" , "-" ) name = name . replace ( "positive" , "+" ) #name = name.replace("tumor necrosis factor production", "tumor necrosis factor prod.") name = name . replace ( "tumor necrosis factor production" , "TNF production" ) if dcnt < 4 : name = name . replace ( "regulation" , "reg." ) name = name . replace ( "exogenous " , "" ) name = name . replace ( " via " , " w/" ) name = name . replace ( "T cell mediated cytotoxicity" , "cytotoxicity via T cell" ) name = name . replace ( 'involved in' , 'in' ) name = name . replace ( '-positive' , '+' ) return name | Shorten GO description for Table 3 in manuscript . | 313 | 10 |
222,641 | def shorten_go_name_all ( self , name ) : name = self . replace_greek ( name ) name = name . replace ( "MHC class I" , "MHC-I" ) return name | Shorten GO name for tables in paper supplemental materials and plots . | 47 | 13 |
222,642 | def _keep_this ( self , name ) : for keep_name in self . keep : if name == keep_name : return True return False | Return True if there are to be no modifications to name . | 31 | 12 |
222,643 | def read_d1_letter ( fin_txt ) : go2letter = { } re_goid = re . compile ( r"(GO:\d{7})" ) with open ( fin_txt ) as ifstrm : for line in ifstrm : mtch = re_goid . search ( line ) if mtch and line [ : 1 ] != ' ' : # Alias is expected to be the first character go2letter [ mtch . group ( 1 ) ] = line [ : 1 ] return go2letter | Reads letter aliases from a text file created by GoDepth1LettersWr . | 114 | 17 |
222,644 | def get_goids_sections ( sections ) : goids_all = set ( ) for _ , goids_sec in sections : goids_all |= set ( goids_sec ) return goids_all | Return all the GO IDs in a 2 - D sections list . | 47 | 13 |
222,645 | def prt_txt ( self , prt = sys . stdout , pre = '' ) : data_nts = self . get_d1nts ( ) for ntdata in data_nts : prt . write ( "{PRE}{L:1} {NS} {d:6,} D{D:02} {GO} {NAME}\n" . format ( PRE = pre , L = ntdata . D1 , d = ntdata . dcnt , NS = ntdata . NS , D = ntdata . depth , GO = ntdata . GO , NAME = ntdata . name ) ) return data_nts | Print letters descendant count and GO information . | 144 | 8 |
222,646 | def wr_xlsx ( self , fout_xlsx = "gos_depth01.xlsx" , * * kws ) : data_nts = self . get_d1nts ( ) if 'fld2col_widths' not in kws : kws [ 'fld2col_widths' ] = { 'D1' : 6 , 'NS' : 3 , 'depth' : 5 , 'GO' : 12 , 'name' : 40 } if 'hdrs' not in kws : kws [ 'hdrs' ] = self . hdrs wr_xlsx_tbl ( fout_xlsx , data_nts , * * kws ) | Write xlsx table of depth - 01 GO terms and their letter representation . | 160 | 16 |
222,647 | def get_d1nts ( self ) : data = [ ] ntdata = cx . namedtuple ( "NtPrt" , "D1 NS dcnt depth GO name" ) namespace = None for ntlet in sorted ( self . goone2ntletter . values ( ) , key = lambda nt : [ nt . goobj . namespace , - 1 * nt . dcnt , nt . D1 ] ) : goobj = ntlet . goobj goid = goobj . id assert len ( goobj . parents ) == 1 if namespace != goobj . namespace : namespace = goobj . namespace ntns = self . ns2nt [ namespace ] pobj = ntns . goobj ns2 = self . str2ns [ goobj . namespace ] data . append ( ntdata . _make ( [ " " , ns2 , ntns . dcnt , pobj . depth , pobj . id , pobj . name ] ) ) data . append ( ntdata . _make ( [ ntlet . D1 , self . str2ns [ namespace ] , ntlet . dcnt , goobj . depth , goid , goobj . name ] ) ) return data | Get letters for depth - 01 GO terms descendants count and GO information . | 266 | 14 |
222,648 | def _init_ns2nt ( rcntobj ) : go2dcnt = rcntobj . go2dcnt ntobj = cx . namedtuple ( "NtD1" , "D1 dcnt goobj" ) d0s = rcntobj . depth2goobjs [ 0 ] ns_nt = [ ( o . namespace , ntobj ( D1 = "" , dcnt = go2dcnt [ o . id ] , goobj = o ) ) for o in d0s ] return cx . OrderedDict ( ns_nt ) | Save depth - 00 GO terms ordered using descendants cnt . | 125 | 12 |
222,649 | def _get_xlsx_kws ( self , * * kws_usr ) : kws_xlsx = { 'fld2col_widths' : self . _get_fld2col_widths ( * * kws_usr ) , 'items' : 'GO IDs' } remaining_keys = set ( [ 'title' , 'hdrs' , 'prt_flds' , 'fld2fmt' , 'ntval2wbfmtdict' , 'ntfld_wbfmt' ] ) for usr_key , usr_val in kws_usr . items ( ) : if usr_key in remaining_keys : kws_xlsx [ usr_key ] = usr_val return kws_xlsx | Return keyword arguments relevant to writing an xlsx . | 178 | 11 |
222,650 | def _adjust_prt_flds ( self , kws_xlsx , desc2nts , shade_hdrgos ) : # Use xlsx prt_flds from the user, if provided if "prt_flds" in kws_xlsx : return kws_xlsx [ "prt_flds" ] # If the user did not provide specific fields to print in an xlsx file: dont_print = set ( [ 'hdr_idx' , 'is_hdrgo' , 'is_usrgo' ] ) # Are we printing GO group headers? # Build new list of xlsx print fields, excluding those which add no new information prt_flds_adjusted = [ ] # Get all namedtuple fields nt_flds = self . sortobj . get_fields ( desc2nts ) # Keep fields intended for print and optionally gray-shade field (format_txt) # print('FFFFFFFFFFFFFFF WrXlsxSortedGos::_adjust_prt_flds:', nt_flds) for nt_fld in nt_flds : if nt_fld not in dont_print : # Only add grey-shade to hdrgo and section name rows if hdrgo_prt=True if nt_fld == "format_txt" : if shade_hdrgos is True : prt_flds_adjusted . append ( nt_fld ) else : prt_flds_adjusted . append ( nt_fld ) kws_xlsx [ 'prt_flds' ] = prt_flds_adjusted | Print user - requested fields or provided fields minus info fields . | 385 | 12 |
222,651 | def _get_fld2col_widths ( self , * * kws ) : fld2col_widths = self . _init_fld2col_widths ( ) if 'fld2col_widths' not in kws : return fld2col_widths for fld , val in kws [ 'fld2col_widths' ] . items ( ) : fld2col_widths [ fld ] = val return fld2col_widths | Return xlsx column widths based on default and user - specified field - value pairs . | 110 | 19 |
222,652 | def _init_fld2col_widths ( self ) : # GO info namedtuple fields: NS dcnt level depth GO D1 name # GO header namedtuple fields: format_txt hdr_idx fld2col_widths = GoSubDagWr . fld2col_widths . copy ( ) for fld , wid in self . oprtfmt . default_fld2col_widths . items ( ) : fld2col_widths [ fld ] = wid for fld in get_hdridx_flds ( ) : fld2col_widths [ fld ] = 2 return fld2col_widths | Return default column widths for writing an Excel Spreadsheet . | 150 | 12 |
222,653 | def _get_shade_hdrgos ( * * kws ) : # KWS: shade_hdrgos hdrgo_prt section_sortby top_n if 'shade_hdrgos' in kws : return kws [ 'shade_hdrgos' ] # Return user-sepcified hdrgo_prt, if provided if 'hdrgo_prt' in kws : return kws [ 'hdrgo_prt' ] # If no hdrgo_prt provided, set hdrgo_prt to False if: # * section_sortby == True # * section_sortby = user_sort # * top_n == N if 'section_sortby' in kws and kws [ 'section_sortby' ] : return False if 'top_n' in kws and isinstance ( kws [ 'top_n' ] , int ) : return False return True | If no hdrgo_prt specified and these conditions are present - > hdrgo_prt = F . | 212 | 25 |
222,654 | def dflt_sortby_objgoea ( goea_res ) : return [ getattr ( goea_res , 'enrichment' ) , getattr ( goea_res , 'namespace' ) , getattr ( goea_res , 'p_uncorrected' ) , getattr ( goea_res , 'depth' ) , getattr ( goea_res , 'GO' ) ] | Default sorting of GOEA results . | 91 | 7 |
222,655 | def dflt_sortby_ntgoea ( ntgoea ) : return [ ntgoea . enrichment , ntgoea . namespace , ntgoea . p_uncorrected , ntgoea . depth , ntgoea . GO ] | Default sorting of GOEA results stored in namedtuples . | 58 | 12 |
222,656 | def get_goea_nts_prt ( self , fldnames = None , * * usr_kws ) : kws = usr_kws . copy ( ) if 'not_fldnames' not in kws : kws [ 'not_fldnames' ] = [ 'goterm' , 'parents' , 'children' , 'id' ] if 'rpt_fmt' not in kws : kws [ 'rpt_fmt' ] = True return self . get_goea_nts_all ( fldnames , * * kws ) | Return list of namedtuples removing fields which are redundant or verbose . | 132 | 15 |
222,657 | def _get_field_values ( item , fldnames , rpt_fmt = None , itemid2name = None ) : if hasattr ( item , "_fldsdefprt" ) : # Is a GOEnrichmentRecord return item . get_field_values ( fldnames , rpt_fmt , itemid2name ) if hasattr ( item , "_fields" ) : # Is a namedtuple return [ getattr ( item , f ) for f in fldnames ] | Return fieldnames and values of either a namedtuple or GOEnrichmentRecord . | 111 | 18 |
222,658 | def _get_fieldnames ( item ) : if hasattr ( item , "_fldsdefprt" ) : # Is a GOEnrichmentRecord return item . get_prtflds_all ( ) if hasattr ( item , "_fields" ) : # Is a namedtuple return item . _fields | Return fieldnames of either a namedtuple or GOEnrichmentRecord . | 69 | 16 |
222,659 | def get_bordercolor ( self ) : hdrgos_all = self . grprobj . hdrobj . get_hdrgos ( ) hdrgos_unused = hdrgos_all . difference ( self . hdrgos_actual ) go2bordercolor = { } # hdrgos that went unused for hdrgo in hdrgos_unused : go2bordercolor [ hdrgo ] = self . hdrcol_all # hdrgos used in this grouping that are NOT usrgos for hdrgo in self . grprobj . hdrgo2usrgos . keys ( ) : go2bordercolor [ hdrgo ] = self . hdrcol_all # hdrgos used in this grouping that ARE usrgos for hdrgo in self . grprobj . hdrgo_is_usrgo : go2bordercolor [ hdrgo ] = 'blue' # usrgos which are NOT hdrgos usrgos_rem = self . grprobj . usrgos . difference ( self . grprobj . hdrgo_is_usrgo ) for usrgo in usrgos_rem : go2bordercolor [ usrgo ] = '#029386' # teal # print("{N:5} hdrgos actual".format(N=len(self.hdrgos_actual))) # print("{N:5} hdrgos unused".format(N=len(hdrgos_unused))) # print("{N:5} hdrgos only BLACK".format(N=len(self.grprobj.hdrgo2usrgos.keys()))) # print("{N:5} usrgos".format(N=len(self.grprobj.usrgos))) # print("{N:5} usrgos AND hdrgos BLUE".format(N=len(self.grprobj.hdrgo_is_usrgo))) # print("{N:5} usrgos Only".format(N=len(usrgos_rem))) return go2bordercolor | Get bordercolor based on hdrgos and usergos . | 487 | 16 |
222,660 | def get_go2color_users ( self , usrgo_color = '#feffa3' , # yellow hdrusrgo_color = '#d4ffea' , # green hdrgo_color = '#eee6f6' ) : # purple go2color = { } # Color user GO IDs for goid in self . usrgos : go2color [ goid ] = usrgo_color # Color header GO IDs. Headers which are also GO IDs get their own color. for goid_hdr in self . hdrgos_actual : go2color [ goid_hdr ] = hdrusrgo_color if goid_hdr in self . usrgos else hdrgo_color return go2color | Get go2color for GO DAG plots . | 169 | 10 |
222,661 | def run ( self , name , goea_nts , log ) : objaart = AArtGeneProductSetsOne ( name , goea_nts , self ) if self . hdrobj . sections : return objaart . prt_report_grp1 ( log ) else : return objaart . prt_report_grp0 ( log ) | Run gene product ASCII art . | 81 | 6 |
222,662 | def get_chr2idx ( self ) : return { chr ( ascii_int ) : idx for idx , ascii_int in enumerate ( self . all_chrints ) } | Return a dict with the ASCII art character as key and its index as value . | 48 | 16 |
222,663 | def _init_kws ( self ) : # Return user-specified GO formatting, if specfied: if 'fmtgo' not in self . kws : self . kws [ 'fmtgo' ] = self . grprdflt . gosubdag . prt_attr [ 'fmt' ] + "\n" if 'fmtgo2' not in self . kws : self . kws [ 'fmtgo2' ] = self . grprdflt . gosubdag . prt_attr [ 'fmt' ] + "\n" if 'fmtgene' not in self . kws : if 'itemid2name' not in self . kws : self . kws [ 'fmtgene' ] = "{AART} {ID}\n" else : self . kws [ 'fmtgene' ] = "{AART} {ID} {NAME}\n" if 'fmtgene2' not in self . kws : self . kws [ 'fmtgene2' ] = self . kws [ 'fmtgene' ] | Fill default values for keyword args if necessary . | 247 | 9 |
222,664 | def _init_relationships ( self , relationships_arg ) : if relationships_arg : relationships_all = self . _get_all_relationships ( ) if relationships_arg is True : return relationships_all else : return relationships_all . intersection ( relationships_arg ) return set ( ) | Return a set of relationships found in all subset GO Terms . | 62 | 12 |
222,665 | def _get_all_relationships ( self ) : relationships_all = set ( ) for goterm in self . go2obj . values ( ) : if goterm . relationship : relationships_all . update ( goterm . relationship ) if goterm . relationship_rev : relationships_all . update ( goterm . relationship_rev ) return relationships_all | Return all relationships seen in GO Dag subset . | 75 | 9 |
222,666 | def _init_gos ( self , go_sources_arg , relationships_arg ) : # No GO sources provided if not go_sources_arg : assert self . go2obj_orig , "go2obj MUST BE PRESENT IF go_sources IS NOT" self . go_sources = set ( self . go2obj_orig ) self . go2obj = self . go2obj_orig sys . stdout . write ( "**NOTE: {N:,} SOURCE GO IDS\n" . format ( N = len ( self . go_sources ) ) ) return # GO sources provided go_sources = self . _init_go_sources ( go_sources_arg , self . go2obj_orig ) # Create new go2obj_user subset matching GO sources # Fill with source and parent GO IDs and alternate GO IDs go2obj_user = { } objrel = CurNHigher ( relationships_arg , self . go2obj_orig ) objrel . get_id2obj_cur_n_high ( go2obj_user , go_sources ) # Add additional GOTerm information, if needed for user task kws_gos = { k : v for k , v in self . kws . items ( ) if k in self . kws_aux_gos } if kws_gos : self . _add_goterms_kws ( go2obj_user , kws_gos ) self . go_sources = go_sources self . go2obj = go2obj_user | Initialize GO sources . | 343 | 5 |
222,667 | def _add_goterms_kws ( self , go2obj_user , kws_gos ) : if 'go2color' in kws_gos : for goid in kws_gos [ 'go2color' ] . keys ( ) : self . _add_goterms ( go2obj_user , goid ) | Add more GOTerms to go2obj_user if requested and relevant . | 78 | 16 |
222,668 | def _add_goterms ( self , go2obj_user , goid ) : goterm = self . go2obj_orig [ goid ] if goid != goterm . id and goterm . id in go2obj_user and goid not in go2obj_user : go2obj_user [ goid ] = goterm | Add alt GO IDs to go2obj subset if requested and relevant . | 76 | 14 |
222,669 | def _init_go_sources ( self , go_sources_arg , go2obj_arg ) : gos_user = set ( go_sources_arg ) if 'children' in self . kws and self . kws [ 'children' ] : gos_user |= get_leaf_children ( gos_user , go2obj_arg ) gos_godag = set ( go2obj_arg ) gos_source = gos_user . intersection ( gos_godag ) gos_missing = gos_user . difference ( gos_godag ) if not gos_missing : return gos_source sys . stdout . write ( "{N} GO IDs NOT FOUND IN GO DAG: {GOs}\n" . format ( N = len ( gos_missing ) , GOs = " " . join ( [ str ( e ) for e in gos_missing ] ) ) ) return gos_source | Return GO sources which are present in GODag . | 212 | 10 |
222,670 | def get_rcntobj ( self ) : # rcntobj value in kws can be: None, False, True, CountRelatives object if 'rcntobj' in self . kws : rcntobj = self . kws [ 'rcntobj' ] if isinstance ( rcntobj , CountRelatives ) : return rcntobj return CountRelatives ( self . go2obj , # Subset go2obj contains only items needed by go_sources self . relationships , dcnt = 'dcnt' in self . kw_elems , go2letter = self . kws . get ( 'go2letter' ) ) | Return None or user - provided CountRelatives object . | 139 | 11 |
222,671 | def get_prt_fmt ( self , alt = False ) : # prt_fmt = [ # rcnt # '{GO} # {NS} L{level:02} D{depth:02} {GO_name}', # '{GO} # {NS} {dcnt:6,} L{level:02} D{depth:02} {D1:5} {GO_name}'] prt_fmt = [ ] if alt : prt_fmt . append ( '{GO}{alt:1}' ) else : prt_fmt . append ( '{GO}' ) prt_fmt . append ( '# {NS}' ) if 'dcnt' in self . prt_flds : prt_fmt . append ( '{dcnt:5}' ) if 'childcnt' in self . prt_flds : prt_fmt . append ( '{childcnt:3}' ) if 'tcnt' in self . prt_flds : prt_fmt . append ( "{tcnt:7,}" ) if 'tfreq' in self . prt_flds : prt_fmt . append ( "{tfreq:8.6f}" ) if 'tinfo' in self . prt_flds : prt_fmt . append ( "{tinfo:5.2f}" ) prt_fmt . append ( 'L{level:02} D{depth:02}' ) if self . relationships : prt_fmt . append ( 'R{reldepth:02}' ) if 'D1' in self . prt_flds : prt_fmt . append ( '{D1:5}' ) if 'REL' in self . prt_flds : prt_fmt . append ( '{REL}' ) prt_fmt . append ( '{rel}' ) prt_fmt . append ( '{GO_name}' ) return " " . join ( prt_fmt ) | Return the format for printing GO named tuples and their related information . | 469 | 14 |
222,672 | def _init_kwelems ( self ) : ret = set ( ) if 'rcntobj' in self . kws : ret . add ( 'dcnt' ) ret . add ( 'D1' ) if 'tcntobj' in self . kws : ret . add ( 'tcnt' ) ret . add ( 'tfreq' ) ret . add ( 'tinfo' ) return ret | Init set elements . | 88 | 4 |
222,673 | def get_relations_cnt ( self ) : return cx . Counter ( [ e . relation for es in self . exts for e in es ] ) | Get the set of all relations . | 33 | 7 |
222,674 | def _init_equiv ( self ) : gocolored_all = set ( self . go2color ) go2obj_usr = self . gosubdag . go2obj go2color_add = { } for gocolored_cur , color in self . go2color . items ( ) : # Ignore GOs in go2color that are not in the user set if gocolored_cur in go2obj_usr : goobj = go2obj_usr [ gocolored_cur ] goids_equiv = goobj . alt_ids . union ( [ goobj . id ] ) # mrk_alt = "*" if gocolored_cur != goobj.id else "" # print("COLORED({}) KEY({}){:1} ALL({})".format( # gocolored_cur, goobj.id, mrk_alt, goids_equiv)) # Loop through GO IDs which are not colored, but are equivalent to colored GO IDs. for goid_add in goids_equiv . difference ( gocolored_all ) : if goid_add in go2color_add : print ( '**TBD: TWO DIFFERENT COLORS FOR EQUIV GO ID' ) # pylint: disable=superfluous-parens go2color_add [ goid_add ] = color # print("ADDING {N} GO IDs TO go2color".format(N=len(go2color_add))) for goid , color in go2color_add . items ( ) : self . go2color [ goid ] = color | Add equivalent GO IDs to go2color if necessary . | 352 | 11 |
222,675 | def get_pvalue ( self ) : if self . method_flds : return getattr ( self , "p_{m}" . format ( m = self . get_method_name ( ) ) ) return getattr ( self , "p_uncorrected" ) | Returns pval for 1st method if it exists . Else returns uncorrected pval . | 59 | 19 |
222,676 | def set_corrected_pval ( self , nt_method , pvalue ) : self . method_flds . append ( nt_method ) fieldname = "" . join ( [ "p_" , nt_method . fieldname ] ) setattr ( self , fieldname , pvalue ) | Add object attribute based on method name . | 68 | 8 |
222,677 | def _chk_fields ( field_data , field_formatter ) : if len ( field_data ) == len ( field_formatter ) : return len_dat = len ( field_data ) len_fmt = len ( field_formatter ) msg = [ "FIELD DATA({d}) != FORMATTER({f})" . format ( d = len_dat , f = len_fmt ) , "DAT({N}): {D}" . format ( N = len_dat , D = field_data ) , "FMT({N}): {F}" . format ( N = len_fmt , F = field_formatter ) ] raise Exception ( "\n" . join ( msg ) ) | Check that expected fields are present . | 156 | 7 |
222,678 | def set_goterm ( self , go2obj ) : if self . GO in go2obj : goterm = go2obj [ self . GO ] self . goterm = goterm self . name = goterm . name self . depth = goterm . depth self . NS = self . namespace2NS [ self . goterm . namespace ] | Set goterm and copy GOTerm s name and namespace . | 73 | 12 |
222,679 | def _init_enrichment ( self ) : if self . study_n : return 'e' if ( ( 1.0 * self . study_count / self . study_n ) > ( 1.0 * self . pop_count / self . pop_n ) ) else 'p' return 'p' | Mark as enriched or purified . | 68 | 6 |
222,680 | def get_prtflds_default ( self ) : return self . _fldsdefprt [ : - 1 ] + [ "p_{M}" . format ( M = m . fieldname ) for m in self . method_flds ] + [ self . _fldsdefprt [ - 1 ] ] | Get default fields . | 72 | 4 |
222,681 | def get_prtflds_all ( self ) : flds = [ ] dont_add = set ( [ '_parents' , 'method_flds' , 'relationship_rev' , 'relationship' ] ) # Fields: GO NS enrichment name ratio_in_study ratio_in_pop p_uncorrected # depth study_count p_sm_bonferroni p_fdr_bh study_items self . _flds_append ( flds , self . get_prtflds_default ( ) , dont_add ) # Fields: GO NS goterm # ratio_in_pop pop_n pop_count pop_items name # ratio_in_study study_n study_count study_items # method_flds enrichment p_uncorrected p_sm_bonferroni p_fdr_bh self . _flds_append ( flds , vars ( self ) . keys ( ) , dont_add ) # Fields: name level is_obsolete namespace id depth parents children _parents alt_ids self . _flds_append ( flds , vars ( self . goterm ) . keys ( ) , dont_add ) return flds | When converting to a namedtuple get all possible fields in their original order . | 270 | 16 |
222,682 | def _flds_append ( flds , addthese , dont_add ) : for fld in addthese : if fld not in flds and fld not in dont_add : flds . append ( fld ) | Retain order of fields as we add them once to the list . | 53 | 14 |
222,683 | def get_field_values ( self , fldnames , rpt_fmt = True , itemid2name = None ) : row = [ ] # Loop through each user field desired for fld in fldnames : # 1. Check the GOEnrichmentRecord's attributes val = getattr ( self , fld , None ) if val is not None : if rpt_fmt : val = self . _get_rpt_fmt ( fld , val , itemid2name ) row . append ( val ) else : # 2. Check the GO object for the field val = getattr ( self . goterm , fld , None ) if rpt_fmt : val = self . _get_rpt_fmt ( fld , val , itemid2name ) if val is not None : row . append ( val ) else : # 3. Field not found, raise Exception self . _err_fld ( fld , fldnames ) if rpt_fmt : assert not isinstance ( val , list ) , "UNEXPECTED LIST: FIELD({F}) VALUE({V}) FMT({P})" . format ( P = rpt_fmt , F = fld , V = val ) return row | Get flat namedtuple fields for one GOEnrichmentRecord . | 271 | 14 |
222,684 | def _get_rpt_fmt ( fld , val , itemid2name = None ) : if fld . startswith ( "ratio_" ) : return "{N}/{TOT}" . format ( N = val [ 0 ] , TOT = val [ 1 ] ) elif fld in set ( [ 'study_items' , 'pop_items' , 'alt_ids' ] ) : if itemid2name is not None : val = [ itemid2name . get ( v , v ) for v in val ] return ", " . join ( [ str ( v ) for v in sorted ( val ) ] ) return val | Return values in a format amenable to printing in a table . | 143 | 13 |
222,685 | def _err_fld ( self , fld , fldnames ) : msg = [ 'ERROR. UNRECOGNIZED FIELD({F})' . format ( F = fld ) ] actual_flds = set ( self . get_prtflds_default ( ) + self . goterm . __dict__ . keys ( ) ) bad_flds = set ( fldnames ) . difference ( set ( actual_flds ) ) if bad_flds : msg . append ( "\nGOEA RESULT FIELDS: {}" . format ( " " . join ( self . _fldsdefprt ) ) ) msg . append ( "GO FIELDS: {}" . format ( " " . join ( self . goterm . __dict__ . keys ( ) ) ) ) msg . append ( "\nFATAL: {N} UNEXPECTED FIELDS({F})\n" . format ( N = len ( bad_flds ) , F = " " . join ( bad_flds ) ) ) msg . append ( " {N} User-provided fields:" . format ( N = len ( fldnames ) ) ) for idx , fld in enumerate ( fldnames , 1 ) : mrk = "ERROR -->" if fld in bad_flds else "" msg . append ( " {M:>9} {I:>2}) {F}" . format ( M = mrk , I = idx , F = fld ) ) raise Exception ( "\n" . join ( msg ) ) | Unrecognized field . Print detailed Failure message . | 349 | 10 |
222,686 | def run_study_nts ( self , study , * * kws ) : goea_results = self . run_study ( study , * * kws ) return MgrNtGOEAs ( goea_results ) . get_goea_nts_all ( ) | Run GOEA on study ids . Return results as a list of namedtuples . | 62 | 18 |
222,687 | def get_results_msg ( self , results , study ) : # To convert msg list to string: "\n".join(msg) msg = [ ] if results : fmt = "{M:6,} GO terms are associated with {N:6,} of {NT:6,}" stu_items , num_gos_stu = self . get_item_cnt ( results , "study_items" ) pop_items , num_gos_pop = self . get_item_cnt ( results , "pop_items" ) stu_txt = fmt . format ( N = len ( stu_items ) , M = num_gos_stu , NT = len ( set ( study ) ) ) pop_txt = fmt . format ( N = len ( pop_items ) , M = num_gos_pop , NT = self . pop_n ) msg . append ( "{POP} population items" . format ( POP = pop_txt ) ) msg . append ( "{STU} study items" . format ( STU = stu_txt ) ) return msg | Return summary for GOEA results . | 239 | 7 |
222,688 | def get_pval_uncorr ( self , study , log = sys . stdout ) : results = [ ] study_in_pop = self . pop . intersection ( study ) # " 99% 378 of 382 study items found in population" go2studyitems = get_terms ( "study" , study_in_pop , self . assoc , self . obo_dag , log ) pop_n , study_n = self . pop_n , len ( study_in_pop ) allterms = set ( go2studyitems ) . union ( set ( self . go2popitems ) ) if log is not None : # Some study genes may not have been found in the population. Report from orig study_n_orig = len ( study ) perc = 100.0 * study_n / study_n_orig if study_n_orig != 0 else 0.0 log . write ( "{R:3.0f}% {N:>6,} of {M:>6,} study items found in population({P})\n" . format ( N = study_n , M = study_n_orig , P = pop_n , R = perc ) ) if study_n : log . write ( "Calculating {N:,} uncorrected p-values using {PFNC}\n" . format ( N = len ( allterms ) , PFNC = self . pval_obj . name ) ) # If no study genes were found in the population, return empty GOEA results if not study_n : return [ ] calc_pvalue = self . pval_obj . calc_pvalue for goid in allterms : study_items = go2studyitems . get ( goid , set ( ) ) study_count = len ( study_items ) pop_items = self . go2popitems . get ( goid , set ( ) ) pop_count = len ( pop_items ) one_record = GOEnrichmentRecord ( goid , p_uncorrected = calc_pvalue ( study_count , study_n , pop_count , pop_n ) , study_items = study_items , pop_items = pop_items , ratio_in_study = ( study_count , study_n ) , ratio_in_pop = ( pop_count , pop_n ) ) results . append ( one_record ) return results | Calculate the uncorrected pvalues for study items . | 520 | 13 |
222,689 | def get_study_items ( results ) : study_items = set ( ) for obj in results : study_items . update ( obj . study_items ) return study_items | Return a list of study items associated with the given results . | 38 | 12 |
222,690 | def _update_pvalcorr ( ntmt , corrected_pvals ) : if corrected_pvals is None : return for rec , val in zip ( ntmt . results , corrected_pvals ) : rec . set_corrected_pval ( ntmt . nt_method , val ) | Add data members to store multiple test corrections . | 68 | 9 |
222,691 | def wr_txt ( self , fout_txt , goea_results , prtfmt = None , * * kws ) : if not goea_results : sys . stdout . write ( " 0 GOEA results. NOT WRITING {FOUT}\n" . format ( FOUT = fout_txt ) ) return with open ( fout_txt , 'w' ) as prt : if 'title' in kws : prt . write ( "{TITLE}\n" . format ( TITLE = kws [ 'title' ] ) ) data_nts = self . prt_txt ( prt , goea_results , prtfmt , * * kws ) log = self . log if self . log is not None else sys . stdout log . write ( " {N:>5} GOEA results for {CUR:5} study items. WROTE: {F}\n" . format ( N = len ( data_nts ) , CUR = len ( MgrNtGOEAs ( goea_results ) . get_study_items ( ) ) , F = fout_txt ) ) | Print GOEA results to text file . | 249 | 8 |
222,692 | def prt_txt ( prt , goea_results , prtfmt = None , * * kws ) : objprt = PrtFmt ( ) if prtfmt is None : flds = [ 'GO' , 'NS' , 'p_uncorrected' , 'ratio_in_study' , 'ratio_in_pop' , 'depth' , 'name' , 'study_items' ] prtfmt = objprt . get_prtfmt_str ( flds ) prtfmt = objprt . adjust_prtfmt ( prtfmt ) prt_flds = RPT . get_fmtflds ( prtfmt ) data_nts = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( prt_flds , * * kws ) RPT . prt_txt ( prt , data_nts , prtfmt , prt_flds , * * kws ) return data_nts | Print GOEA results in text format . | 235 | 8 |
222,693 | def wr_xlsx ( self , fout_xlsx , goea_results , * * kws ) : # kws: prt_if indent itemid2name(study_items) objprt = PrtFmt ( ) prt_flds = kws . get ( 'prt_flds' , self . get_prtflds_default ( goea_results ) ) xlsx_data = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( prt_flds , * * kws ) if 'fld2col_widths' not in kws : kws [ 'fld2col_widths' ] = { f : objprt . default_fld2col_widths . get ( f , 8 ) for f in prt_flds } RPT . wr_xlsx ( fout_xlsx , xlsx_data , * * kws ) | Write a xlsx file . | 225 | 7 |
222,694 | def wr_tsv ( self , fout_tsv , goea_results , * * kws ) : prt_flds = kws . get ( 'prt_flds' , self . get_prtflds_default ( goea_results ) ) tsv_data = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( prt_flds , * * kws ) RPT . wr_tsv ( fout_tsv , tsv_data , * * kws ) | Write tab - separated table data to file | 129 | 8 |
222,695 | def prt_tsv ( self , prt , goea_results , * * kws ) : prt_flds = kws . get ( 'prt_flds' , self . get_prtflds_default ( goea_results ) ) tsv_data = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( prt_flds , * * kws ) RPT . prt_tsv ( prt , tsv_data , * * kws ) | Write tab - separated table data | 125 | 6 |
222,696 | def get_ns2nts ( results , fldnames = None , * * kws ) : ns2nts = cx . defaultdict ( list ) nts = MgrNtGOEAs ( results ) . get_goea_nts_all ( fldnames , * * kws ) for ntgoea in nts : ns2nts [ ntgoea . NS ] . append ( ntgoea ) return ns2nts | Get namedtuples of GOEA results split into BP MF CC . | 101 | 14 |
222,697 | def print_date ( min_ratio = None , pval = 0.05 ) : import goatools # Header contains provenance and parameters date = datetime . date . today ( ) print ( "# Generated by GOATOOLS v{0} ({1})" . format ( goatools . __version__ , date ) ) print ( "# min_ratio={0} pval={1}" . format ( min_ratio , pval ) ) | Print GOATOOLS version and the date the GOEA was run . | 98 | 15 |
222,698 | def print_results ( self , results , min_ratio = None , indent = False , pval = 0.05 , prt = sys . stdout ) : results_adj = self . get_adj_records ( results , min_ratio , pval ) self . print_results_adj ( results_adj , indent , prt ) | Print GOEA results with some additional statistics calculated . | 76 | 10 |
222,699 | def get_adj_records ( results , min_ratio = None , pval = 0.05 ) : records = [ ] for rec in results : # calculate some additional statistics # (over_under, is_ratio_different) rec . update_remaining_fldsdefprt ( min_ratio = min_ratio ) if pval is not None and rec . p_uncorrected >= pval : continue if rec . is_ratio_different : records . append ( rec ) return records | Return GOEA results with some additional statistics calculated . | 113 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.