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,300
def get_go2nt ( self , goea_results ) : go2obj = self . objaartall . grprdflt . gosubdag . go2obj # Add string version of P-values goea_nts = MgrNtGOEAs ( goea_results ) . get_nts_strpval ( ) return { go2obj [ nt . GO ] . id : nt for nt in goea_nts if nt . GO in go2obj }
Return go2nt with added formatted string versions of the P - values .
113
15
222,301
def get_sec2gos ( sortobj ) : sec_gos = [ ] for section_name , nts in sortobj . get_desc2nts_fnc ( hdrgo_prt = True ) [ 'sections' ] : sec_gos . append ( ( section_name , set ( nt . GO for nt in nts ) ) ) return cx . OrderedDict ( sec_gos )
Initialize section_name2goids .
95
9
222,302
def get_gene2gos ( go2nt ) : gene2gos = cx . defaultdict ( set ) nt0 = next ( iter ( go2nt . values ( ) ) ) b_str = isinstance ( nt0 . study_items , str ) # print("NNNNTTTT", nt0) for goid , ntgo in go2nt . items ( ) : study_items = ntgo . study_items . split ( ', ' ) if b_str else ntgo . study_items for geneid in study_items : gene2gos [ geneid ] . add ( goid ) if b_str : b_set = set ( isinstance ( g . isdigit ( ) , int ) for g in nt0 . study_items . split ( ', ' ) ) if b_set == set ( [ True ] ) : return { int ( g ) : gos for g , gos in gene2gos . items ( ) } return { g : gos for g , gos in gene2gos . items ( ) }
Create a gene product to GO set dict .
236
9
222,303
def get_gene2aart ( gene2section2gos , sec2chr ) : geneid2str = { } for geneid , section2gos_gene in gene2section2gos . items ( ) : letters = [ abc if s in section2gos_gene else "." for s , abc in sec2chr . items ( ) ] geneid2str [ geneid ] = "" . join ( letters ) return geneid2str
Return a string for each gene representing GO section membership .
105
11
222,304
def get_gene2section2gos ( gene2gos , sec2gos ) : gene2section2gos = { } for geneid , gos_gene in gene2gos . items ( ) : section2gos = { } for section_name , gos_sec in sec2gos . items ( ) : gos_secgene = gos_gene . intersection ( gos_sec ) if gos_secgene : section2gos [ section_name ] = gos_secgene gene2section2gos [ geneid ] = section2gos return gene2section2gos
Get a list of section aliases for each gene product ID .
142
12
222,305
def _init_objcolor ( self , node_opts , * * kwu ) : objgoea = node_opts . kws [ 'dict' ] . get ( 'objgoea' , None ) # kwu: go2color go2bordercolor dflt_bordercolor key2col return Go2Color ( self . gosubdag , objgoea , * * kwu )
Return user - created Go2Color object or create one .
92
12
222,306
def _init_gonodeopts ( self , * * kws_usr ) : options = GoNodeOpts ( self . gosubdag , * * self . kws [ 'node_go' ] ) # Add parent edge count if either is in kws: parentcnt, prt_pcnt if not options . kws [ 'set' ] . isdisjoint ( [ 'parentcnt' , 'prt_pcnt' ] ) : options . kws [ 'dict' ] [ 'c2ps' ] = self . edgesobj . get_c2ps ( ) # GoeaResults(kws['goea_results'], **self.kws['goea']) if 'goea_results' in kws else None if 'goea_results' in kws_usr : objgoea = GoeaResults ( kws_usr [ 'goea_results' ] , * * self . kws [ 'goea' ] ) options . kws [ 'dict' ] [ 'objgoea' ] = objgoea return options
Initialize a GO Node plot options object GoNodeOpts .
237
13
222,307
def prt_goids ( self , prt ) : fmt = self . gosubdag . prt_attr [ 'fmta' ] nts = sorted ( self . gosubdag . go2nt . values ( ) , key = lambda nt : [ nt . NS , nt . depth , nt . alt ] ) _get_color = self . pydotnodego . go2color . get for ntgo in nts : gostr = fmt . format ( * * ntgo . _asdict ( ) ) col = _get_color ( ntgo . GO , "" ) prt . write ( "{COLOR:7} {GO}\n" . format ( COLOR = col , GO = gostr ) )
Print all GO IDs in the plot plus their color .
168
11
222,308
def _init_kws ( self , * * kws_usr ) : kws_self = { } user_keys = set ( kws_usr ) for objname , expset in self . exp_keys . items ( ) : usrkeys_curr = user_keys . intersection ( expset ) kws_self [ objname ] = get_kwargs ( kws_usr , usrkeys_curr , usrkeys_curr ) dpi = str ( kws_self [ 'dag' ] . get ( 'dpi' , self . dflts [ 'dpi' ] ) ) kws_self [ 'dag' ] [ 'dpi' ] = dpi return kws_self
Return a dict containing user - specified plotting options .
163
10
222,309
def _prt_edge ( dag_edge , attr ) : # sequence parent_graph points attributes type parent_edge_list print ( "Edge {ATTR}: {VAL}" . format ( ATTR = attr , VAL = dag_edge . obj_dict [ attr ] ) )
Print edge attribute
63
3
222,310
def prt_goids ( self , goids = None , prtfmt = None , sortby = True , prt = sys . stdout ) : if goids is None : goids = self . go_sources nts = self . get_nts ( goids , sortby ) if prtfmt is None : prtfmt = self . prt_attr [ 'fmta' ] for ntgo in nts : key2val = ntgo . _asdict ( ) prt . write ( "{GO}\n" . format ( GO = prtfmt . format ( * * key2val ) ) ) return nts
Given GO IDs print decriptive info about each GO Term .
141
13
222,311
def get_nts ( self , goids = None , sortby = None ) : nts = [ ] # User GO IDs if goids is None : goids = self . go_sources else : chk_goids ( goids , "GoSubDag::get_nts" ) if goids : ntobj = cx . namedtuple ( "NtGo" , " " . join ( self . prt_attr [ 'flds' ] ) ) go2nt = self . get_go2nt ( goids ) for goid , ntgo in self . _get_sorted_go2nt ( go2nt , sortby ) : assert ntgo is not None , "{GO} NOT IN go2nt" . format ( GO = goid ) if goid == ntgo . GO : nts . append ( ntgo ) else : fld2vals = ntgo . _asdict ( ) fld2vals [ 'GO' ] = goid nts . append ( ntobj ( * * fld2vals ) ) return nts
Given GO IDs get a list of namedtuples .
241
11
222,312
def get_go2nt ( self , goids ) : get_nt = self . go2nt goids_present = set ( goids ) . intersection ( self . go2obj ) if len ( goids_present ) != len ( goids ) : print ( "GO IDs NOT FOUND IN DAG: {GOs}" . format ( GOs = " " . join ( set ( goids ) . difference ( goids_present ) ) ) ) return { g : get_nt [ g ] for g in goids_present }
Return dict of GO ID as key and GO object information in namedtuple .
117
16
222,313
def get_key_goids ( self , goids ) : go2obj = self . go2obj return set ( go2obj [ go ] . id for go in goids )
Given GO IDs return key GO IDs .
40
8
222,314
def prt_objdesc ( self , prt ) : txt = "INITIALIZING GoSubDag: {N:3} sources in {M:3} GOs rcnt({R}). {A} alt GO IDs\n" alt2obj = { go : o for go , o in self . go2obj . items ( ) if go != o . id } prt . write ( txt . format ( N = len ( self . go_sources ) , M = len ( self . go2obj ) , R = self . rcntobj is not None , A = len ( alt2obj ) ) ) prt . write ( " GoSubDag: namedtuple fields: {FLDS}\n" . format ( FLDS = " " . join ( self . prt_attr [ 'flds' ] ) ) ) prt . write ( " GoSubDag: relationships: {RELS}\n" . format ( RELS = self . relationships ) )
Return description of this GoSubDag object .
218
10
222,315
def _init_taxids ( taxid , taxids ) : ret = set ( ) if taxids is not None : if taxids is True : return True if isinstance ( taxids , int ) : ret . add ( taxids ) else : ret . update ( taxids ) if taxid is not None : ret . add ( taxid ) if not ret : ret . add ( 9606 ) # pylint: disable=superfluous-parens print ( '**NOTE: DEFAULT TAXID STORED FROM gene2go IS 9606 (human)\n' ) return ret
Return taxid set
126
4
222,316
def init_associations ( self , fin_anno , taxids = None ) : nts = [ ] if fin_anno is None : return nts tic = timeit . default_timer ( ) lnum = - 1 line = "\t" * len ( self . flds ) try : with open ( fin_anno ) as ifstrm : category2ns = { 'Process' : 'BP' , 'Function' : 'MF' , 'Component' : 'CC' } ntobj = cx . namedtuple ( 'ntanno' , self . flds ) # Get: 1) Specified taxids, default taxid(human), or all taxids get_all = taxids is True taxids = self . taxids for lnum , line in enumerate ( ifstrm , 1 ) : # Read data if line [ 0 ] != '#' : vals = line . split ( '\t' ) taxid = int ( vals [ 0 ] ) if get_all or taxid in taxids : # assert len(vals) == 8 ntd = ntobj ( tax_id = taxid , DB_ID = int ( vals [ 1 ] ) , GO_ID = vals [ 2 ] , Evidence_Code = vals [ 3 ] , Qualifier = self . _get_qualifiers ( vals [ 4 ] ) , GO_term = vals [ 5 ] , DB_Reference = self . _get_pmids ( vals [ 6 ] ) , NS = category2ns [ vals [ 7 ] . rstrip ( ) ] ) #self._chk_qualifiers(qualifiers, lnum, ntd) nts . append ( ntd ) # Read header elif line [ 0 ] == '#' : assert line [ 1 : - 1 ] . split ( '\t' ) == self . hdrs # pylint: disable=broad-except except Exception as inst : import traceback traceback . print_exc ( ) sys . stderr . write ( "\n **FATAL: {MSG}\n\n" . format ( MSG = str ( inst ) ) ) sys . stderr . write ( "**FATAL: {FIN}[{LNUM}]:\n{L}" . format ( FIN = fin_anno , L = line , LNUM = lnum ) ) self . _prt_line_detail ( sys . stdout , line , lnum ) sys . exit ( 1 ) print ( 'HMS:{HMS} {N:7,} annotations READ: {ANNO}' . format ( N = len ( nts ) , ANNO = fin_anno , HMS = str ( datetime . timedelta ( seconds = ( timeit . default_timer ( ) - tic ) ) ) ) ) return nts
Read annotation file . Store annotation data in a list of namedtuples .
621
15
222,317
def _prt_line_detail ( self , prt , line , lnum = "" ) : data = zip ( self . flds , line . split ( '\t' ) ) txt = [ "{:2}) {:13} {}" . format ( i , hdr , val ) for i , ( hdr , val ) in enumerate ( data ) ] prt . write ( "{LNUM}\n{TXT}\n" . format ( LNUM = lnum , TXT = '\n' . join ( txt ) ) )
Print each field and its value .
121
7
222,318
def chk_associations ( self , fout_err = "gaf.err" ) : obj = GafData ( "2.1" ) return obj . chk ( self . associations , fout_err )
Check that fields are legal in GAF
50
8
222,319
def _update_ret ( ret , goids , go2color ) : if goids : ret [ 'GOs' ] . update ( goids ) if go2color : for goid , color in go2color . items ( ) : ret [ 'go2color' ] [ goid ] = color
Update GOs and go2color in dict with goids and go2color .
66
17
222,320
def _plt_gogrouped ( self , goids , go2color_usr , * * kws ) : fout_img = self . get_outfile ( kws [ 'outfile' ] , goids ) sections = read_sections ( kws [ 'sections' ] , exclude_ungrouped = True ) # print ("KWWSSSSSSSS", kws) # kws_plt = {k:v for k, v in kws.items if k in self.kws_plt} grprobj_cur = self . _get_grprobj ( goids , sections ) # GO: purple=hdr-only, green=hdr&usr, yellow=usr-only # BORDER: Black=hdr Blu=hdr&usr grpcolor = GrouperColors ( grprobj_cur ) # get_bordercolor get_go2color_users grp_go2color = grpcolor . get_go2color_users ( ) grp_go2bordercolor = grpcolor . get_bordercolor ( ) for goid , color in go2color_usr . items ( ) : grp_go2color [ goid ] = color objcolor = Go2Color ( self . gosubdag , objgoea = None , go2color = grp_go2color , go2bordercolor = grp_go2bordercolor ) go2txt = GrouperPlot . get_go2txt ( grprobj_cur , grp_go2color , grp_go2bordercolor ) objplt = GoSubDagPlot ( self . gosubdag , Go2Color = objcolor , go2txt = go2txt , * * kws ) objplt . prt_goids ( sys . stdout ) objplt . plt_dag ( fout_img ) sys . stdout . write ( "{N:>6} sections read\n" . format ( N = "NO" if sections is None else len ( sections ) ) ) return fout_img
Plot grouped GO IDs .
471
5
222,321
def _get_grprobj ( self , goids , sections ) : grprdflt = GrouperDflts ( self . gosubdag , "goslim_generic.obo" ) hdrobj = HdrgosSections ( self . gosubdag , grprdflt . hdrgos_dflt , sections ) return Grouper ( "sections" , goids , hdrobj , self . gosubdag )
Get Grouper given GO IDs and sections .
105
10
222,322
def _get_kwsdag ( self , goids , go2obj , * * kws_all ) : kws_dag = { } # Term Counts for GO Term information score tcntobj = self . _get_tcntobj ( goids , go2obj , * * kws_all ) # TermCounts or None if tcntobj is not None : kws_dag [ 'tcntobj' ] = tcntobj # GO letters specified by the user if 'go_aliases' in kws_all : fin_go_aliases = kws_all [ 'go_aliases' ] if os . path . exists ( fin_go_aliases ) : go2letter = read_d1_letter ( fin_go_aliases ) if go2letter : kws_dag [ 'go2letter' ] = go2letter return kws_dag
Get keyword args for a GoSubDag .
199
10
222,323
def _chk_docopts ( self , kws ) : # outfile should contain .png, .png, etc. outfile = kws [ 'outfile' ] if len ( kws ) == 2 and os . path . basename ( kws [ 'obo' ] ) == "go-basic.obo" and kws [ 'outfile' ] == self . dflt_outfile : self . _err ( "NO GO IDS SPECFIED" , err = False ) if 'obo' in outfile : self . _err ( "BAD outfile({O})" . format ( O = outfile ) ) if 'gaf' in kws and 'gene2go' in kws : self . _err ( "SPECIFY ANNOTAIONS FROM ONE FILE" ) if 'gene2go' in kws : if 'taxid' not in kws : self . _err ( "SPECIFIY taxid WHEN READ NCBI'S gene2go FILE" )
Check for common user command - line errors .
221
9
222,324
def _err ( self , msg , err = True ) : severity = "FATAL" if err else "NOTE" txt = "" . join ( [ self . objdoc . doc , "User's command-line:\n\n" , " % go_plot.py {ARGS}\n\n" . format ( ARGS = " " . join ( sys . argv [ 1 : ] ) ) , "**{SEV}: {MSG}\n" . format ( SEV = severity , MSG = msg ) ] ) if err : raise RuntimeError ( txt ) sys . stdout . write ( txt ) sys . exit ( 0 )
Print useage and error before exiting .
142
8
222,325
def get_outfile ( self , outfile , goids = None ) : # 1. Use the user-specfied output filename for the GO Term plot if outfile != self . dflt_outfile : return outfile # 2. If only plotting 1 GO term, use GO is in plot name if goids is not None and len ( goids ) == 1 : goid = next ( iter ( goids ) ) goobj = self . gosubdag . go2obj [ goid ] fout = "GO_{NN}_{NM}" . format ( NN = goid . replace ( "GO:" , "" ) , NM = goobj . name ) return "." . join ( [ re . sub ( r"[\s#'()+,-./:<=>\[\]_}]" , '_' , fout ) , 'png' ] ) # 3. Return default name return self . dflt_outfile
Return output file for GO Term plot .
204
8
222,326
def _get_optional_attrs ( kws ) : vals = OboOptionalAttrs . attributes . intersection ( kws . keys ( ) ) if 'sections' in kws : vals . add ( 'relationship' ) if 'norel' in kws : vals . discard ( 'relationship' ) return vals
Given keyword args return optional_attributes to be loaded into the GODag .
74
16
222,327
def _read_sections ( ifile ) : if os . path . exists ( ifile ) : return read_sections ( ifile , exclude_ungrouped = True , prt = None )
Read sections_in . txt file if it exists .
42
12
222,328
def get_paths_from_to ( self , goobj_start , goid_end = None , dn0_up1 = True ) : paths = [ ] # Queue of terms to be examined (and storage for their paths) working_q = cx . deque ( [ [ goobj_start ] ] ) # Loop thru GO terms until we have examined all needed GO terms adjfnc = self . adjdir [ dn0_up1 ] while working_q : #print "WORKING QUEUE LEN({})".format(len(working_q)) path_curr = working_q . popleft ( ) goobj_curr = path_curr [ - 1 ] go_adjlst = adjfnc ( goobj_curr ) #print 'END', goid_end, goobj_curr # If this GO term is the endpoint, Stop. Store path. if ( goid_end is not None and goobj_curr . id == goid_end ) or ( goid_end is None and not go_adjlst ) : paths . append ( path_curr ) # Else if this GO term is the not the end, add neighbors to path else : for go_neighbor in go_adjlst : if go_neighbor not in path_curr : #print "{}'s NEIGHBOR IS {}".format(goobj_curr.id, go_neighbor.id) new_path = path_curr + [ go_neighbor ] #sys.stdout.write(" {}'s {} {}\n".format(goobj_curr, up_dn, go_neighbor)) working_q . append ( new_path ) #self.prt_paths(paths) return paths
Get a list of paths from goobj_start to either top or goid_end .
397
19
222,329
def prt_paths ( paths , prt = sys . stdout ) : pat = "PATHES: {GO} L{L:02} D{D:02}\n" for path in paths : for go_obj in path : prt . write ( pat . format ( GO = go_obj . id , L = go_obj . level , D = go_obj . depth ) ) prt . write ( "\n" )
Print list of paths .
96
5
222,330
def prt_keys ( self , prt , pre ) : prt . write ( '{PRE}Relationship to parent: {ABC}\n' . format ( PRE = pre , ABC = '' . join ( self . rel2chr . values ( ) ) ) ) for rel , alias in self . rel2chr . items ( ) : prt . write ( '{PRE} {A} {DESC}\n' . format ( PRE = pre , A = alias , DESC = rel ) ) prt . write ( '\n{PRE}Relationship to child: {ABC}\n' . format ( PRE = pre , ABC = '' . join ( self . rev2chr . values ( ) ) ) ) for rel , alias in self . rev2chr . items ( ) : prt . write ( '{PRE} {A} {DESC}\n' . format ( PRE = pre , A = alias , DESC = rel ) )
Print the alias for a relationship and its alias .
208
10
222,331
def _get_id2gos ( self , associations , * * kws ) : options = AnnoOptions ( self . evobj , * * kws ) # Default reduction is to remove. For all options, see goatools/anno/opts.py: # * Evidence_Code == ND -> No biological data No biological Data available # * Qualifiers contain NOT assc = self . reduce_annotations ( associations , options ) return self . _get_dbid2goids ( assc ) if options . b_geneid2gos else self . _get_goid2dbids ( assc )
Return given associations in a dict id2gos
134
10
222,332
def get_date_yyyymmdd ( yyyymmdd ) : return date ( int ( yyyymmdd [ : 4 ] ) , int ( yyyymmdd [ 4 : 6 ] , base = 10 ) , int ( yyyymmdd [ 6 : ] , base = 10 ) )
Return datetime . date given string .
64
8
222,333
def hms ( self , msg , tic = None , prt = sys . stdout ) : if tic is None : tic = self . tic now = timeit . default_timer ( ) hms = str ( datetime . timedelta ( seconds = ( now - tic ) ) ) prt . write ( '{HMS}: {MSG}\n' . format ( HMS = hms , MSG = msg ) ) return now
Print elapsed time and message .
97
6
222,334
def chk_qualifiers ( self ) : if self . name == 'id2gos' : return for ntd in self . associations : # print(ntd) qual = ntd . Qualifier assert isinstance ( qual , set ) , '{NAME}: QUALIFIER MUST BE A LIST: {NT}' . format ( NAME = self . name , NT = ntd ) assert qual != set ( [ '' ] ) , ntd assert qual != set ( [ '-' ] ) , ntd assert 'always' not in qual , 'SPEC SAID IT WOULD BE THERE'
Check format of qualifier
127
4
222,335
def _has_not_qual ( ntd ) : for qual in ntd . Qualifier : if 'not' in qual : return True if 'NOT' in qual : return True return False
Return True if the qualifiers contain a NOT
41
8
222,336
def _get_sorted_section ( self , nts_section ) : #pylint: disable=unnecessary-lambda if self . section_sortby is True : return sorted ( nts_section , key = lambda nt : self . sortgos . usrgo_sortby ( nt ) ) if self . section_sortby is False or self . section_sortby is None : return nts_section # print('SORT GO IDS IN A SECTION') return sorted ( nts_section , key = lambda nt : self . section_sortby ( nt ) )
Sort GO IDs in each section if requested by user .
130
11
222,337
def get_relationship_targets ( item_ids , relationships , id2rec ) : # Requirements to use this function: # 1) item Terms must have been loaded with 'relationships' # 2) item IDs in 'item_ids' arguement must be present in id2rec # 3) Arg, 'relationships' must be True or an iterable reltgt_objs_all = set ( ) for goid in item_ids : obj = id2rec [ goid ] for reltype , reltgt_objs_cur in obj . relationship . items ( ) : if relationships is True or reltype in relationships : reltgt_objs_all . update ( reltgt_objs_cur ) return reltgt_objs_all
Get item ID set of item IDs in a relationship target set .
168
13
222,338
def _get_id2parents ( id2parents , item_id , item_obj ) : if item_id in id2parents : return id2parents [ item_id ] parent_ids = set ( ) for parent_obj in item_obj . parents : parent_id = parent_obj . item_id parent_ids . add ( parent_id ) parent_ids |= _get_id2parents ( id2parents , parent_id , parent_obj ) id2parents [ item_id ] = parent_ids return parent_ids
Add the parent item IDs for one item object and their parents .
118
13
222,339
def _get_id2children ( id2children , item_id , item_obj ) : if item_id in id2children : return id2children [ item_id ] child_ids = set ( ) for child_obj in item_obj . children : child_id = child_obj . item_id child_ids . add ( child_id ) child_ids |= _get_id2children ( id2children , child_id , child_obj ) id2children [ item_id ] = child_ids return child_ids
Add the child item IDs for one item object and their children .
118
13
222,340
def _get_id2upper ( id2upper , item_id , item_obj ) : if item_id in id2upper : return id2upper [ item_id ] upper_ids = set ( ) for upper_obj in item_obj . get_goterms_upper ( ) : upper_id = upper_obj . item_id upper_ids . add ( upper_id ) upper_ids |= _get_id2upper ( id2upper , upper_id , upper_obj ) id2upper [ item_id ] = upper_ids return upper_ids
Add the parent item IDs for one item object and their upper .
126
13
222,341
def _get_id2lower ( id2lower , item_id , item_obj ) : if item_id in id2lower : return id2lower [ item_id ] lower_ids = set ( ) for lower_obj in item_obj . get_goterms_lower ( ) : lower_id = lower_obj . item_id lower_ids . add ( lower_id ) lower_ids |= _get_id2lower ( id2lower , lower_id , lower_obj ) id2lower [ item_id ] = lower_ids return lower_ids
Add the lower item IDs for one item object and the objects below them .
126
15
222,342
def fill_parentidid2obj_r0 ( self , id2obj , child_obj ) : for parent_obj in child_obj . parents : if parent_obj . item_id not in id2obj : id2obj [ parent_obj . item_id ] = parent_obj self . fill_parentidid2obj_r0 ( id2obj , parent_obj )
Fill id2obj with all parent key item IDs and their objects .
85
14
222,343
def prt_ver ( self , prt ) : if self . ver_list is not None : prt . write ( "# Versions:\n# {VER}\n\n" . format ( VER = "\n# " . join ( self . ver_list ) ) )
Print version of GO - DAG for the GO and for GO slims .
60
16
222,344
def get_sections_2dnt ( self , sec2d_go ) : return [ ( nm , self . get_ntgos_sorted ( gos ) ) for nm , gos in sec2d_go ]
Return a sections list containing sorted lists of namedtuples .
50
12
222,345
def get_ntgos_sorted ( self , hdrgos ) : go2nt = self . grprobj . go2nt return sorted ( [ go2nt [ go ] for go in hdrgos if go in go2nt ] , key = self . fncsortnt )
Return sorted Grouper namedtuples if there are user GO IDs underneath .
65
16
222,346
def prt_ntgos ( self , prt , ntgos ) : for ntgo in ntgos : key2val = ntgo . _asdict ( ) prt . write ( "{GO_LINE}\n" . format ( GO_LINE = self . prtfmt . format ( * * key2val ) ) )
Print the Grouper namedtuples .
75
9
222,347
def wr_py_sections_new ( self , fout_py , doc = None ) : sections = self . grprobj . get_sections_2d ( ) return self . wr_py_sections ( fout_py , sections , doc )
Write the first sections file .
55
6
222,348
def wr_py_sections ( self , fout_py , sections , doc = None ) : if sections is None : sections = self . grprobj . get_sections_2d ( ) sec2d_nt = self . get_sections_2dnt ( sections ) # lists of GO Grouper namedtuples with open ( fout_py , 'w' ) as prt : self . _prt_py_sections ( sec2d_nt , prt , doc ) dat = SummarySec2dHdrGos ( ) . summarize_sec2hdrgos ( sections ) sys . stdout . write ( self . grprobj . fmtsum . format ( GO_DESC = 'hdr' , SECs = len ( dat [ 'S' ] ) , GOs = len ( dat [ 'G' ] ) , UNGRP = len ( dat [ 'U' ] ) , undesc = "unused" , ACTION = "WROTE:" , FILE = fout_py ) )
Write sections 2 - D list into a Python format list .
224
12
222,349
def _prt_py_sections ( self , sec2d_nt , prt = sys . stdout , doc = None ) : if doc is None : doc = 'Sections variable' prt . write ( '"""{DOC}"""\n\n' . format ( DOC = doc ) ) self . prt_ver ( prt ) prt . write ( "# pylint: disable=line-too-long\n" ) strcnt = self . get_summary_str ( sec2d_nt ) prt . write ( "SECTIONS = [ # {CNTS}\n" . format ( CNTS = strcnt ) ) prt . write ( ' # ("New Section", [\n' ) prt . write ( ' # ]),\n' ) for section_name , nthdrgos in sec2d_nt : self . _prt_py_section ( prt , section_name , nthdrgos ) prt . write ( "]\n" )
Print sections 2 - D list into a Python format list .
225
12
222,350
def _prt_py_section ( self , prt , section_name , ntgos ) : prt . write ( ' ("{SEC}", [ # {N} GO-headers\n' . format ( SEC = section_name , N = len ( ntgos ) ) ) self . prt_ntgos ( prt , ntgos ) prt . write ( " ]),\n" )
Print one section and its GO headers .
92
8
222,351
def prt_goid_cnt ( self , prt = sys . stdout ) : for section_name , hdrgos_sec in self . grprobj . get_sections_2d ( ) : prt . write ( "{NAME} {Us:5,} {Hs:5,} {SEC}\n" . format ( NAME = self . grprobj . grpname , Us = len ( self . grprobj . get_usrgos_g_hdrgos ( hdrgos_sec ) ) , Hs = len ( hdrgos_sec ) , SEC = section_name ) )
Get number of hdrgos and usrgos in each section .
141
15
222,352
def wr_txt_grouping_gos ( self ) : prt_goids = self . grprobj . gosubdag . prt_goids for hdrgo , usrgos in self . grprobj . hdrgo2usrgos . items ( ) : keygos = usrgos . union ( [ hdrgo ] ) fout_txt = "{BASE}.txt" . format ( BASE = self . grprobj . get_fout_base ( hdrgo ) ) with open ( fout_txt , 'w' ) as prt : prt_goids ( keygos , prt = prt ) sys . stdout . write ( " {N:5,} GO IDs WROTE: {TXT}\n" . format ( N = len ( keygos ) , TXT = fout_txt ) )
Write one file per GO group .
192
7
222,353
def wr_txt_section_hdrgos ( self , fout_txt , sortby = None , prt_section = True ) : sec2d_go = self . grprobj . get_sections_2d ( ) # lists of GO IDs sec2d_nt = self . get_sections_2dnt ( sec2d_go ) # lists of GO Grouper namedtuples if sortby is None : sortby = self . fncsortnt with open ( fout_txt , 'w' ) as prt : self . prt_ver ( prt ) prt . write ( "# GROUP NAME: {NAME}\n" . format ( NAME = self . grprobj . grpname ) ) for section_name , nthdrgos_actual in sec2d_nt : if prt_section : prt . write ( "# SECTION: {SECTION}\n" . format ( SECTION = section_name ) ) self . prt_ntgos ( prt , nthdrgos_actual ) if prt_section : prt . write ( "\n" ) dat = SummarySec2dHdrGos ( ) . summarize_sec2hdrgos ( sec2d_go ) sys . stdout . write ( self . grprobj . fmtsum . format ( GO_DESC = 'hdr' , SECs = len ( dat [ 'S' ] ) , GOs = len ( dat [ 'G' ] ) , UNGRP = len ( dat [ 'U' ] ) , undesc = "unused" , ACTION = "WROTE:" , FILE = fout_txt ) ) return sec2d_nt
Write high GO IDs that are actually used to group current set of GO IDs .
371
16
222,354
def prt_num_sig ( self , prt = sys . stdout , alpha = 0.05 ) : ctr = self . get_num_sig ( alpha ) prt . write ( "{N:6,} TOTAL: {TXT}\n" . format ( N = len ( self . nts ) , TXT = " " . join ( [ "FDR({FDR:4})" . format ( FDR = ctr [ 'FDR' ] ) , "Bonferroni({B:4})" . format ( B = ctr [ 'Bonferroni' ] ) , "Benjamini({B:4})" . format ( B = ctr [ 'Benjamini' ] ) , "PValue({P:4})" . format ( P = ctr [ 'PValue' ] ) , os . path . basename ( self . fin_davidchart ) ] ) ) )
Print the number of significant GO terms .
203
8
222,355
def get_num_sig ( self , alpha = 0.05 ) : # Get the number of significant GO terms ctr = cx . Counter ( ) flds = set ( [ 'FDR' , 'Bonferroni' , 'Benjamini' , 'PValue' ] ) for ntd in self . nts : for fld in flds : if getattr ( ntd , fld ) < alpha : ctr [ fld ] += 1 return ctr
Print the number of significant results using various metrics .
105
10
222,356
def get_nts ( self , fin_davidchart ) : nts = [ ] with open ( fin_davidchart ) as ifstrm : hdr_seen = False for line in ifstrm : line = line . rstrip ( ) flds = line . split ( '\t' ) if hdr_seen : ntd = self . _init_nt ( flds ) nts . append ( ntd ) else : if line [ : 8 ] == 'Category' : assert len ( flds ) == 13 , len ( flds ) hdr_seen = True sys . stdout . write ( " READ {N:5} GO IDs from DAVID Chart: {TSV}\n" . format ( N = len ( nts ) , TSV = fin_davidchart ) ) return nts
Read DAVID Chart file . Store each line in a namedtuple .
182
15
222,357
def _init_nt ( self , flds ) : term = flds [ 1 ] genes_str = flds [ 5 ] # pylint: disable=bad-whitespace return self . ntobj ( Category = flds [ 0 ] , GO = term [ : 10 ] , # 1 GO:0045202~synapse name = term [ 10 : ] , # 1 GO:0045202~synapse Count = int ( flds [ 2 ] ) , # 2 94 Perc = float ( flds [ 3 ] ) , # 3 9.456740442655935 PValue = float ( flds [ 4 ] ) , # 4 6.102654380458156E-20 Genes = genes_str , # 5 ['ENSMUSG00000052613', ...] Genes_set = self . get_genes ( genes_str ) , # 5 ['ENSMUSG00000052613', ...] List_Total = int ( flds [ 6 ] ) , # 6 920 Pop_Hits = int ( flds [ 7 ] ) , # 7 444 Pop_Total = int ( flds [ 8 ] ) , # 8 12002 Fold_Enrichment = float ( flds [ 9 ] ) , # 9 2.7619173521347435 Bonferroni = float ( flds [ 10 ] ) , # 10 3.3930758355347344E-17 Benjamini = float ( flds [ 11 ] ) , # 11 3.3930758355347344E-17 FDR = float ( flds [ 12 ] ) )
Given string fields from a DAVID chart file return namedtuple .
359
14
222,358
def get_genes ( genes_str ) : gene_set = genes_str . split ( ', ' ) if gene_set and gene_set [ 0 ] . isdigit ( ) : gene_set = set ( int ( g ) for g in gene_set ) return gene_set
Given a string containng genes return a list .
62
10
222,359
def get_extensions ( extstr ) : # Extension examples: # has_direct_input(UniProtKB:P37840),occurs_in(GO:0005576) # part_of(UBERON:0006618),part_of(UBERON:0002302) # occurs_in(CL:0000988)|occurs_in(CL:0001021) if not extstr : return None exts = [ ] for ext_lst in extstr . split ( '|' ) : grp = [ ] for ext in ext_lst . split ( ',' ) : idx = ext . find ( '(' ) if idx != - 1 and ext [ - 1 ] == ')' : grp . append ( AnnotationExtension ( ext [ : idx ] , ext [ idx + 1 : - 1 ] ) ) else : # Ignore improperly formatted Extensions sys . stdout . write ( 'BAD Extension({E})\n' . format ( E = ext ) ) exts . append ( grp ) return AnnotationExtensions ( exts )
Return zero or greater Annotation Extensions given a line of text .
238
13
222,360
def _set_intvals ( kws , keys ) : for key in keys : if key in kws : kws [ key ] = int ( kws [ key ] )
Convert keyword values to int .
38
7
222,361
def _chk_docopt_exit ( self , args , exp_letters ) : if args is None : args = sys . argv [ 1 : ] keys_all = self . exp_keys . union ( self . exp_elems ) if exp_letters : keys_all |= exp_letters unknown_args = self . _chk_docunknown ( args , keys_all ) if unknown_args : raise RuntimeError ( "{USAGE}\n **FATAL: UNKNOWN ARGS: {UNK}" . format ( USAGE = self . doc , UNK = " " . join ( unknown_args ) ) )
Check if docopt exit was for an unknown argument .
137
11
222,362
def _chk_docopt_kws ( self , docdict , exp ) : for key , val in docdict . items ( ) : if isinstance ( val , str ) : assert '=' not in val , self . _err ( "'=' FOUND IN VALUE" , key , val , exp ) elif key != 'help' and key not in self . exp_keys and key not in self . exp_elems : raise RuntimeError ( self . _err ( "UNKNOWN KEY" , key , val , exp ) )
Check for common user errors when running from the command - line .
116
13
222,363
def _chk_docunknown ( args , exp ) : unknown = [ ] for arg in args : if arg [ : 2 ] == '--' : val = arg [ 2 : ] if val not in exp : unknown . append ( arg ) elif arg [ : 1 ] == '-' : val = arg [ 1 : ] if val not in exp : unknown . append ( arg ) if '-h' in unknown or '--help' in unknown : return [ ] return unknown
Return any unknown args .
102
5
222,364
def dnld_goa ( self , species , ext = 'gaf' , item = None , fileout = None ) : basename = self . get_basename ( species , ext , item ) src = os . path . join ( self . ftp_src_goa , species . upper ( ) , "{F}.gz" . format ( F = basename ) ) dst = os . path . join ( os . getcwd ( ) , basename ) if fileout is None else fileout dnld_file ( src , dst , prt = sys . stdout , loading_bar = None ) return dst
Download GOA source file name on EMBL - EBI ftp server .
136
16
222,365
def read_associations ( assoc_fn , anno_type = 'id2gos' , * * kws ) : # kws get_objanno: taxids hdr_only prt allow_missing_symbol obj = get_objanno ( assoc_fn , anno_type , * * kws ) # kws get_id2gos: ev_include ev_exclude keep_ND keep_NOT b_geneid2gos go2geneids return obj . get_id2gos ( * * kws )
Return associatinos in id2gos format
127
10
222,366
def dnld_ncbi_gene_file ( fin , force_dnld = False , log = sys . stdout , loading_bar = True ) : if not os . path . exists ( fin ) or force_dnld : import gzip fin_dir , fin_base = os . path . split ( fin ) fin_gz = "{F}.gz" . format ( F = fin_base ) fin_gz = os . path . join ( fin_dir , fin_gz ) if os . path . exists ( fin_gz ) : os . remove ( fin_gz ) fin_ftp = "ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/{F}.gz" . format ( F = fin_base ) ## if log is not None: ## log.write(" DOWNLOADING GZIP: {GZ}\n".format(GZ=fin_ftp)) ## if loading_bar: ## loading_bar = wget.bar_adaptive ## wget.download(fin_ftp, bar=loading_bar) ## rsp = wget(fin_ftp) ftp_get ( fin_ftp , fin_gz ) with gzip . open ( fin_gz , 'rb' ) as zstrm : if log is not None : log . write ( "\n READ GZIP: {F}\n" . format ( F = fin_gz ) ) with open ( fin , 'wb' ) as ostrm : ostrm . write ( zstrm . read ( ) ) if log is not None : log . write ( " WROTE UNZIPPED: {F}\n" . format ( F = fin ) )
Download a file from NCBI Gene s ftp server .
372
12
222,367
def dnld_annofile ( fin_anno , anno_type ) : if os . path . exists ( fin_anno ) : return anno_type = get_anno_desc ( fin_anno , anno_type ) if anno_type == 'gene2go' : dnld_ncbi_gene_file ( fin_anno ) if anno_type in { 'gaf' , 'gpad' } : dnld_annotation ( fin_anno )
Download annotation file if needed
116
5
222,368
def read_ncbi_gene2go ( fin_gene2go , taxids = None , * * kws ) : obj = Gene2GoReader ( fin_gene2go , taxids = taxids ) # By default, return id2gos. User can cause go2geneids to be returned by: # >>> read_ncbi_gene2go(..., go2geneids=True if 'taxid2asscs' not in kws : if len ( obj . taxid2asscs ) == 1 : taxid = next ( iter ( obj . taxid2asscs ) ) kws_ncbi = { k : v for k , v in kws . items ( ) if k in AnnoOptions . keys_exp } kws_ncbi [ 'taxid' ] = taxid return obj . get_id2gos ( * * kws_ncbi ) # Optional detailed associations split by taxid and having both ID2GOs & GO2IDs # e.g., taxid2asscs = defaultdict(lambda: defaultdict(lambda: defaultdict(set)) t2asscs_ret = obj . get_taxid2asscs ( taxids , * * kws ) t2asscs_usr = kws . get ( 'taxid2asscs' , defaultdict ( lambda : defaultdict ( lambda : defaultdict ( set ) ) ) ) if 'taxid2asscs' in kws : obj . fill_taxid2asscs ( t2asscs_usr , t2asscs_ret ) return obj . get_id2gos_all ( t2asscs_ret )
Read NCBI s gene2go . Return gene2go data for user - specified taxids .
363
20
222,369
def get_b2aset ( a2bset ) : b2aset = { } for a_item , bset in a2bset . items ( ) : for b_item in bset : if b_item in b2aset : b2aset [ b_item ] . add ( a_item ) else : b2aset [ b_item ] = set ( [ a_item ] ) return b2aset
Given gene2gos return go2genes . Given go2genes return gene2gos .
97
22
222,370
def get_assc_pruned ( assc_geneid2gos , min_genecnt = None , max_genecnt = None , prt = sys . stdout ) : # DEFN WAS: get_assc_pruned(assc_geneid2gos, max_genecnt=None, prt=sys.stdout): # ADDED min_genecnt argument and functionality if max_genecnt is None and min_genecnt is None : return assc_geneid2gos , set ( ) go2genes_orig = get_b2aset ( assc_geneid2gos ) # go2genes_prun = {go:gs for go, gs in go2genes_orig.items() if len(gs) <= max_genecnt} go2genes_prun = { } for goid , genes in go2genes_orig . items ( ) : num_genes = len ( genes ) if ( min_genecnt is None or num_genes >= min_genecnt ) and ( max_genecnt is None or num_genes <= max_genecnt ) : go2genes_prun [ goid ] = genes num_was = len ( go2genes_orig ) num_now = len ( go2genes_prun ) gos_rm = set ( go2genes_orig . keys ( ) ) . difference ( set ( go2genes_prun . keys ( ) ) ) assert num_was - num_now == len ( gos_rm ) if prt is not None : if min_genecnt is None : min_genecnt = 1 if max_genecnt is None : max_genecnt = "Max" prt . write ( "{N:4} GO IDs pruned. Kept {NOW} GOs assc w/({m} to {M} genes)\n" . format ( m = min_genecnt , M = max_genecnt , N = num_was - num_now , NOW = num_now ) ) return get_b2aset ( go2genes_prun ) , gos_rm
Remove GO IDs associated with large numbers of genes . Used in stochastic simulations .
495
17
222,371
def read_annotations ( * * kws ) : if 'gaf' not in kws and 'gene2go' not in kws : return gene2gos = None if 'gaf' in kws : gene2gos = read_gaf ( kws [ 'gaf' ] , prt = sys . stdout ) if not gene2gos : raise RuntimeError ( "NO ASSOCIATIONS LOADED FROM {F}" . format ( F = kws [ 'gaf' ] ) ) elif 'gene2go' in kws : assert 'taxid' in kws , 'taxid IS REQUIRED WHEN READING gene2go' gene2gos = read_ncbi_gene2go ( kws [ 'gene2go' ] , taxids = [ kws [ 'taxid' ] ] ) if not gene2gos : raise RuntimeError ( "NO ASSOCIATIONS LOADED FROM {F} FOR TAXID({T})" . format ( F = kws [ 'gene2go' ] , T = kws [ 'taxid' ] ) ) return gene2gos
Read annotations from either a GAF file or NCBI s gene2go file .
255
17
222,372
def get_tcntobj ( go2obj , * * kws ) : # kws: gaf gene2go annots = read_annotations ( * * kws ) if annots : return TermCounts ( go2obj , annots )
Return a TermCounts object if the user provides an annotation file otherwise None .
55
16
222,373
def get_hdrs ( flds_all , * * kws ) : # Return Headers if the user explicitly lists them. hdrs = kws . get ( 'hdrs' , None ) if hdrs is not None : return hdrs # User may specify a subset of fields or a column order using prt_flds if 'prt_flds' in kws : return kws [ 'prt_flds' ] # All fields in the namedtuple will be in the headers return flds_all
Return headers given user - specified key - word args .
121
11
222,374
def wr_row_mergeall ( self , worksheet , txtstr , fmt , row_idx ) : hdridxval = len ( self . hdrs ) - 1 worksheet . merge_range ( row_idx , 0 , row_idx , hdridxval , txtstr , fmt ) return row_idx + 1
Merge all columns and place text string in widened cell .
80
12
222,375
def wr_hdrs ( self , worksheet , row_idx ) : for col_idx , hdr in enumerate ( self . hdrs ) : # print("ROW({R}) COL({C}) HDR({H}) FMT({F})\n".format( # R=row_idx, C=col_idx, H=hdr, F=self.fmt_hdr)) worksheet . write ( row_idx , col_idx , hdr , self . fmt_hdr ) row_idx += 1 return row_idx
Print row of column headers
128
5
222,376
def wr_data ( self , xlsx_data , row_i , worksheet ) : fld2fmt = self . vars . fld2fmt # User may specify to skip rows based on values in row prt_if = self . vars . prt_if # User may specify a subset of columns to print or # a column ordering different from the _fields seen in the namedtuple prt_flds = self . wbfmtobj . get_prt_flds ( ) get_wbfmt = self . wbfmtobj . get_wbfmt if self . vars . sort_by is not None : xlsx_data = sorted ( xlsx_data , key = self . vars . sort_by ) try : for data_nt in xlsx_data : if prt_if is None or prt_if ( data_nt ) : wbfmt = get_wbfmt ( data_nt ) # xlsxwriter.format.Format created w/add_format # Print an xlsx row by printing each column in order. for col_i , fld in enumerate ( prt_flds ) : try : # If fld "format_txt" present, use val for formatting, but don't print. val = getattr ( data_nt , fld , "" ) # Optional user-formatting of specific fields, eg, pval: "{:8.2e}" # If field value is empty (""), don't use fld2fmt if fld2fmt is not None and fld in fld2fmt and val != "" and val != "*" : val = fld2fmt [ fld ] . format ( val ) worksheet . write ( row_i , col_i , val , wbfmt ) except : raise RuntimeError ( self . _get_err_msg ( row_i , col_i , fld , val , prt_flds ) ) row_i += 1 except RuntimeError as inst : import traceback traceback . print_exc ( ) sys . stderr . write ( "\n **FATAL in wr_data: {MSG}\n\n" . format ( MSG = str ( inst ) ) ) sys . exit ( 1 ) return row_i
Write data into xlsx worksheet .
507
9
222,377
def _get_err_msg ( row , col , fld , val , prt_flds ) : import traceback traceback . print_exc ( ) err_msg = ( "ROW({R}) COL({C}) FIELD({F}) VAL({V})\n" . format ( R = row , C = col , F = fld , V = val ) , "PRINT FIELDS({N}): {F}" . format ( N = len ( prt_flds ) , F = " " . join ( prt_flds ) ) ) return "\n" . join ( err_msg )
Return an informative message with details of xlsx write attempt .
139
13
222,378
def add_worksheet ( self ) : wsh = self . workbook . add_worksheet ( ) if self . vars . fld2col_widths is not None : self . set_xlsx_colwidths ( wsh , self . vars . fld2col_widths , self . wbfmtobj . get_prt_flds ( ) ) return wsh
Add a worksheet to the workbook .
89
9
222,379
def set_xlsx_colwidths ( worksheet , fld2col_widths , fldnames ) : for col_idx , fld in enumerate ( fldnames ) : col_width = fld2col_widths . get ( fld , None ) if col_width is not None : worksheet . set_column ( col_idx , col_idx , col_width )
Set xlsx column widths using fld2col_widths .
92
16
222,380
def get_hdrs ( self , * * kws ) : hdrs = get_hdrs ( self . prt_flds , * * kws ) # Values in a "format_txt" "column" are used for formatting, not printing return [ h for h in hdrs if h != "format_txt" ]
Initialize column headers .
74
5
222,381
def _init_fmtname2wbfmtobj ( self , workbook , * * kws ) : wbfmtdict = [ kws . get ( 'format_txt0' , self . dflt_wbfmtdict [ 0 ] ) , kws . get ( 'format_txt1' , self . dflt_wbfmtdict [ 1 ] ) , kws . get ( 'format_txt2' , self . dflt_wbfmtdict [ 2 ] ) , kws . get ( 'format_txt3' , self . dflt_wbfmtdict [ 3 ] ) ] fmtname2wbfmtobj = { 'plain' : workbook . add_format ( wbfmtdict [ 0 ] ) , 'plain bold' : workbook . add_format ( wbfmtdict [ 3 ] ) , 'very light grey' : workbook . add_format ( wbfmtdict [ 1 ] ) , 'light grey' : workbook . add_format ( wbfmtdict [ 2 ] ) } # Use a xlsx namedtuple field value to set row color ntval2wbfmtdict = kws . get ( 'ntval2wbfmtdict' , None ) if ntval2wbfmtdict is not None : for ntval , wbfmtdict in ntval2wbfmtdict . items ( ) : fmtname2wbfmtobj [ ntval ] = workbook . add_format ( wbfmtdict ) if 'ntfld_wbfmt' not in kws : sys . stdout . write ( "**WARNING: 'ntfld_wbfmt' NOT PRESENT\n" ) return fmtname2wbfmtobj
Initialize fmtname2wbfmtobj .
394
10
222,382
def get_wbfmt ( self , data_nt = None ) : if data_nt is None or self . b_plain : return self . fmtname2wbfmtobj . get ( 'plain' ) # User namedtuple field/value for color if self . ntfld_wbfmt is not None : return self . __get_wbfmt_usrfld ( data_nt ) # namedtuple format_txt for color/bold/border if self . b_format_txt : wbfmt = self . __get_wbfmt_format_txt ( data_nt ) if wbfmt is not None : return wbfmt # 'ntfld_wbfmt': namedtuple field which contains a value used as a key for a xlsx format # 'ntval2wbfmtdict': namedtuple value and corresponding xlsx format dict. return self . fmtname2wbfmtobj . get ( 'plain' )
Return format for text cell .
211
6
222,383
def __get_wbfmt_usrfld ( self , data_nt ) : if self . ntfld_wbfmt is not None : if isinstance ( self . ntfld_wbfmt , str ) : ntval = getattr ( data_nt , self . ntfld_wbfmt , None ) # Ex: 'section' if ntval is not None : return self . fmtname2wbfmtobj . get ( ntval , None )
Return format for text cell from namedtuple field specified by ntfld_wbfmt
106
19
222,384
def __get_wbfmt_format_txt ( self , data_nt ) : format_txt_val = getattr ( data_nt , "format_txt" ) if format_txt_val == 1 : return self . fmtname2wbfmtobj . get ( "very light grey" ) if format_txt_val == 2 : return self . fmtname2wbfmtobj . get ( "light grey" ) return self . fmtname2wbfmtobj . get ( format_txt_val )
Return format for text cell from namedtuple field format_txt .
112
14
222,385
def get_fmt_section ( self ) : if self . b_format_txt : return self . fmtname2wbfmtobj . get ( "light grey" ) return self . fmtname2wbfmtobj . get ( "plain bold" )
Grey if printing header GOs and plain if not printing header GOs .
56
15
222,386
def get_id2gos ( self , * * kws ) : #### def get_annotations_dct(self, taxid, options): if len ( self . taxid2asscs ) == 1 : taxid = next ( iter ( self . taxid2asscs . keys ( ) ) ) return self . _get_id2gos ( self . taxid2asscs [ taxid ] , * * kws ) assert 'taxid' in kws , "**FATAL: 'taxid' NOT FOUND IN Gene2GoReader::get_id2gos({KW})" . format ( KW = kws ) taxid = kws [ 'taxid' ] assert taxid in self . taxid2asscs , '**FATAL: TAXID({T}) DATA MISSING' . format ( T = taxid ) return self . _get_id2gos ( self . taxid2asscs [ taxid ] , * * kws )
Return geneid2gos or optionally go2geneids .
219
14
222,387
def get_name ( self ) : if len ( self . taxid2asscs ) == 1 : return '{BASE}_{TAXID}' . format ( BASE = self . name , TAXID = next ( iter ( self . taxid2asscs . keys ( ) ) ) ) return '{BASE}_various' . format ( BASE = self . name )
Get name using taxid
84
5
222,388
def get_taxid ( self ) : return next ( iter ( self . taxid2asscs . keys ( ) ) ) if len ( self . taxid2asscs ) == 1 else True
Return taxid if one was provided . Other wise return True representing all taxids
42
16
222,389
def fill_taxid2asscs ( taxid2asscs_usr , taxid2asscs_ret ) : for taxid , ab_ret in taxid2asscs_ret . items ( ) : taxid2asscs_usr [ taxid ] [ 'ID2GOs' ] = ab_ret [ 'ID2GOs' ] taxid2asscs_usr [ taxid ] [ 'GO2IDs' ] = ab_ret [ 'GO2IDs' ]
Fill user taxid2asscs for backward compatibility .
106
11
222,390
def _get_taxids ( self , taxids = None ) : taxid_keys = set ( self . taxid2asscs . keys ( ) ) return taxid_keys if taxids is None else set ( taxids ) . intersection ( taxid_keys )
Return user - specified taxids or taxids in self . taxid2asscs
58
17
222,391
def _init_taxid2asscs ( self ) : taxid2asscs = cx . defaultdict ( list ) for ntanno in self . associations : taxid2asscs [ ntanno . tax_id ] . append ( ntanno ) assert len ( taxid2asscs ) != 0 , "**FATAL: NO TAXIDS: {F}" . format ( F = self . filename ) # """Print the number of taxids stored.""" prt = sys . stdout num_taxids = len ( taxid2asscs ) prt . write ( '{N} taxids stored' . format ( N = num_taxids ) ) if num_taxids < 5 : prt . write ( ': {Ts}' . format ( Ts = ' ' . join ( sorted ( str ( t ) for t in taxid2asscs ) ) ) ) prt . write ( '\n' ) return dict ( taxid2asscs )
Create dict with taxid keys and annotation namedtuple list .
215
13
222,392
def get_go2color_inst ( self , hdrgo ) : go2color = self . go2color . copy ( ) go2color [ hdrgo ] = self . hdrgo_dflt_color return go2color
Get a copy of go2color with GO group header colored .
52
13
222,393
def get_kws_plt ( self ) : kws_plt = { } for key_plt in self . keys_plt : key_val = getattr ( self , key_plt , None ) if key_val is not None : kws_plt [ key_plt ] = key_val elif key_plt in self . kws : kws_plt [ key_plt ] = self . kws [ key_plt ] return kws_plt
Get keyword args for GoSubDagPlot from self unless they are None .
112
16
222,394
def _init_go2bordercolor ( objcolors , * * kws ) : go2bordercolor_ret = objcolors . get_bordercolor ( ) if 'go2bordercolor' not in kws : return go2bordercolor_ret go2bordercolor_usr = kws [ 'go2bordercolor' ] goids = set ( go2bordercolor_ret ) . intersection ( go2bordercolor_usr ) for goid in goids : go2bordercolor_usr [ goid ] = go2bordercolor_ret [ goid ] return go2bordercolor_usr
Initialize go2bordercolor with default to make hdrgos bright blue .
153
19
222,395
def plot_groups_unplaced ( self , fout_dir = "." , * * kws_pltargs ) : hdrgos = self . grprobj . get_hdrgos_unplaced ( ) pltargs = PltGroupedGosArgs ( self . grprobj , fout_dir = fout_dir , * * kws_pltargs ) return self . _plot_groups_hdrgos ( hdrgos , pltargs )
Plot GO DAGs for groups of user GOs which are not in a section .
109
18
222,396
def _get_plt_data ( self , hdrgos_usr ) : hdrgo2usrgos = self . grprobj . get_hdrgo2usrgos ( hdrgos_usr ) usrgos_actual = set ( [ u for us in hdrgo2usrgos . values ( ) for u in us ] ) go2obj = self . gosubdag . get_go2obj ( usrgos_actual . union ( hdrgo2usrgos . keys ( ) ) ) return hdrgo2usrgos , go2obj
Given User GO IDs return their GO headers and other GO info .
131
13
222,397
def _plot_go_group ( self , hdrgo , usrgos , pltargs , go2parentids ) : gosubdagplotnts = self . _get_gosubdagplotnts ( hdrgo , usrgos , pltargs , go2parentids ) # Create pngs and return png names pngs = [ obj . wrplt ( pltargs . fout_dir , pltargs . plt_ext ) for obj in gosubdagplotnts ] return pngs
Plot an exploratory GO DAG for a single Group of user GOs .
123
16
222,398
def _get_dotgraphs ( self , hdrgo , usrgos , pltargs , go2parentids ) : gosubdagplotnts = self . _get_gosubdagplotnts ( hdrgo , usrgos , pltargs , go2parentids ) # Create DAG graphs as dot language strings. Loop through GoSubDagPlotNt list dotstrs = [ obj . get_dotstr ( ) for obj in gosubdagplotnts ] return dotstrs
Get a GO DAG in a dot - language string for a single Group of user GOs .
117
20
222,399
def _get_gos_upper ( self , ntpltgo1 , max_upper , go2parentids ) : # Get GO IDs which are in the hdrgo path goids_possible = ntpltgo1 . gosubdag . go2obj . keys ( ) # Get upper GO IDs which have the most descendants return self . _get_gosrcs_upper ( goids_possible , max_upper , go2parentids )
Plot a GO DAG for the upper portion of a single Group of user GOs .
104
18