idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
34,400
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 (...
Download a file from NCBI Gene s ftp server .
34,401
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
34,402
def read_ncbi_gene2go ( fin_gene2go , taxids = None , ** kws ) : obj = Gene2GoReader ( fin_gene2go , taxids = taxids ) 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 [...
Read NCBI s gene2go . Return gene2go data for user - specified taxids .
34,403
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 .
34,404
def get_assc_pruned ( assc_geneid2gos , min_genecnt = None , max_genecnt = None , prt = sys . stdout ) : if max_genecnt is None and min_genecnt is None : return assc_geneid2gos , set ( ) go2genes_orig = get_b2aset ( assc_geneid2gos ) go2genes_prun = { } for goid , genes in go2genes_orig . items ( ) : num_genes = len ( ...
Remove GO IDs associated with large numbers of genes . Used in stochastic simulations .
34,405
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 't...
Read annotations from either a GAF file or NCBI s gene2go file .
34,406
def get_tcntobj ( go2obj , ** kws ) : annots = read_annotations ( ** kws ) if annots : return TermCounts ( go2obj , annots )
Return a TermCounts object if the user provides an annotation file otherwise None .
34,407
def get_hdrs ( flds_all , ** kws ) : hdrs = kws . get ( 'hdrs' , None ) if hdrs is not None : return hdrs if 'prt_flds' in kws : return kws [ 'prt_flds' ] return flds_all
Return headers given user - specified key - word args .
34,408
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 .
34,409
def wr_hdrs ( self , worksheet , row_idx ) : for col_idx , hdr in enumerate ( self . hdrs ) : worksheet . write ( row_idx , col_idx , hdr , self . fmt_hdr ) row_idx += 1 return row_idx
Print row of column headers
34,410
def wr_data ( self , xlsx_data , row_i , worksheet ) : fld2fmt = self . vars . fld2fmt prt_if = self . vars . prt_if 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_...
Write data into xlsx worksheet .
34,411
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 ( er...
Return an informative message with details of xlsx write attempt .
34,412
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 .
34,413
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 .
34,414
def get_hdrs ( self , ** kws ) : hdrs = get_hdrs ( self . prt_flds , ** kws ) return [ h for h in hdrs if h != "format_txt" ]
Initialize column headers .
34,415
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 ] ) ] fmtname2...
Initialize fmtname2wbfmtobj .
34,416
def get_wbfmt ( self , data_nt = None ) : if data_nt is None or self . b_plain : return self . fmtname2wbfmtobj . get ( 'plain' ) if self . ntfld_wbfmt is not None : return self . __get_wbfmt_usrfld ( data_nt ) if self . b_format_txt : wbfmt = self . __get_wbfmt_format_txt ( data_nt ) if wbfmt is not None : return wbfm...
Return format for text cell .
34,417
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 ) if ntval is not None : return self . fmtname2wbfmtobj . get ( ntval , None )
Return format for text cell from namedtuple field specified by ntfld_wbfmt
34,418
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 .
34,419
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 .
34,420
def get_id2gos ( self , ** kws ) : 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 [ ...
Return geneid2gos or optionally go2geneids .
34,421
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
34,422
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
34,423
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 .
34,424
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
34,425
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 ) prt = sys . stdout num_taxids = len ( taxid2asscs ) prt . write ( ...
Create dict with taxid keys and annotation namedtuple list .
34,426
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 .
34,427
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 .
34,428
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 ...
Initialize go2bordercolor with default to make hdrgos bright blue .
34,429
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 .
34,430
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 .
34,431
def _plot_go_group ( self , hdrgo , usrgos , pltargs , go2parentids ) : gosubdagplotnts = self . _get_gosubdagplotnts ( hdrgo , usrgos , pltargs , go2parentids ) 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 .
34,432
def _get_dotgraphs ( self , hdrgo , usrgos , pltargs , go2parentids ) : gosubdagplotnts = self . _get_gosubdagplotnts ( hdrgo , usrgos , pltargs , go2parentids ) 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 .
34,433
def _get_gosubdagplotnts ( self , hdrgo , usrgos , pltargs , go2parentids ) : dotgraphs = [ ] go2color = pltargs . get_go2color_inst ( hdrgo ) ntpltgo0 = self . _get_pltdag_ancesters ( hdrgo , usrgos , desc = "" ) ntpltgo1 = self . _get_pltdag_path_hdr ( hdrgo , usrgos , desc = "pruned" ) num_go0 = len ( ntpltgo0 . gos...
Get list of GoSubDagPlotNt for plotting an exploratory GODAG for 1 Group of user GOs .
34,434
def _get_gos_upper ( self , ntpltgo1 , max_upper , go2parentids ) : goids_possible = ntpltgo1 . gosubdag . go2obj . keys ( ) 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 .
34,435
def _get_gosrcs_upper ( self , goids , max_upper , go2parentids ) : gosrcs_upper = set ( ) get_nt = self . gosubdag . go2nt . get go2nt = { g : get_nt ( g ) for g in goids } go_nt = sorted ( go2nt . items ( ) , key = lambda t : - 1 * t [ 1 ] . dcnt ) goids_upper = set ( ) for goid , _ in go_nt : goids_upper . add ( goi...
Get GO IDs for the upper portion of the GO DAG .
34,436
def _get_gosubdagplotnt ( self , ntplt , title , go2color , pltargs ) : kws_plt = pltargs . get_kws_plt ( ) kws_plt [ 'id' ] = '"{ID}"' . format ( ID = ntplt . hdrgo ) kws_plt [ 'title' ] = "{TITLE} of {M} user GOs" . format ( TITLE = title , M = ntplt . tot_usrgos ) kws_plt [ 'go2color' ] = go2color kws_plt [ 'go2bord...
Return GoSubDagPlotNt which contains both a GoSubDagPlot object and ntobj .
34,437
def _no_ntplt ( self , ntplt ) : sys . stdout . write ( " {GO_USR:>6,} usr {GO_ALL:>6,} GOs DID NOT WRITE: {B} {D}\n" . format ( B = self . grprobj . get_fout_base ( ntplt . hdrgo ) , D = ntplt . desc , GO_USR = len ( ntplt . gosubdag . go_sources ) , GO_ALL = len ( ntplt . gosubdag . go2obj ) ) )
Print a message about the GO DAG Plot we are NOT plotting .
34,438
def _get_pltdag_ancesters ( self , hdrgo , usrgos , desc = "" ) : go_srcs = usrgos . union ( [ hdrgo ] ) gosubdag = GoSubDag ( go_srcs , self . gosubdag . get_go2obj ( go_srcs ) , relationships = self . gosubdag . relationships , rcntobj = self . gosubdag . rcntobj , go2nt = self . gosubdag . go2nt ) tot_usrgos = len (...
Get GoSubDag containing hdrgo and all usrgos and their ancesters .
34,439
def _get_pltdag_path_hdr ( self , hdrgo , usrgos , desc = "pruned" ) : go_sources = usrgos . union ( [ hdrgo ] ) gosubdag = GoSubDag ( go_sources , self . gosubdag . get_go2obj ( go_sources ) , relationships = self . gosubdag . relationships , rcntobj = self . gosubdag . rcntobj , go2nt = self . gosubdag . go2nt , dst_...
Get GoSubDag with paths from usrgos through hdrgo .
34,440
def wrplt ( self , fout_dir , plt_ext = "png" ) : basename = self . grprobj . get_fout_base ( self . ntplt . hdrgo ) plt_pat = self . get_pltpat ( plt_ext ) fout_basename = plt_pat . format ( BASE = basename ) fout_plt = os . path . join ( fout_dir , fout_basename ) self . gosubdagplot . plt_dag ( fout_plt ) return fou...
Write png containing plot of GoSubDag .
34,441
def get_dotstr ( self ) : dotobj = self . gosubdagplot . get_pydot_graph ( ) dotstr = dotobj . create_dot ( ) return dotstr
Return a string containing DAG graph in Grpahviz s dot language .
34,442
def _get_wrhiercfg ( self ) : prtfmt = self . gosubdag . prt_attr [ 'fmt' ] prtfmt = prtfmt . replace ( '{GO} # ' , '' ) prtfmt = prtfmt . replace ( '{D1:5} ' , '' ) return { 'name2prtfmt' : { 'ITEM' : prtfmt , 'ID' : '{GO}{alt:1}' } , 'max_indent' : self . usrdct . get ( 'max_indent' ) , 'include_only' : self . usrdct...
Initialize print format .
34,443
def _get_goroot ( self , goids_all , namespace ) : root_goid = self . consts . NAMESPACE2GO [ namespace ] if root_goid in goids_all : return root_goid root_goids = set ( ) for goid in goids_all : goterm = self . gosubdag . go2obj [ goid ] if goterm . depth == 0 : root_goids . add ( goterm . id ) if len ( root_goids ) =...
Get the top GO for the set of goids_all .
34,444
def mknts ( self , add_dct ) : nts = [ ] assert len ( add_dct ) == len ( self . nts ) flds = list ( next ( iter ( self . nts ) ) . _fields ) + list ( next ( iter ( add_dct ) ) . keys ( ) ) ntobj = cx . namedtuple ( "ntgoea" , " " . join ( flds ) ) for dct_new , ntgoea in zip ( add_dct , self . nts ) : dct_curr = ntgoea...
Add information from add_dct to a new copy of namedtuples stored in nts .
34,445
def add_f2str ( self , dcts , srcfld , dstfld , dstfmt ) : assert len ( dcts ) == len ( self . nts ) for dct , ntgoea in zip ( dcts , self . nts ) : valorig = getattr ( ntgoea , srcfld ) valstr = dstfmt . format ( valorig ) dct [ dstfld ] = valstr
Add a namedtuple field of type string generated from an existing namedtuple field .
34,446
def get_ntobj ( self ) : if self . nts : return cx . namedtuple ( "ntgoea" , " " . join ( vars ( next ( iter ( self . nts ) ) ) . keys ( ) ) )
Create namedtuple object with GOEA fields .
34,447
def get_info_content ( go_id , termcounts ) : freq = termcounts . get_term_freq ( go_id ) return - 1.0 * math . log ( freq ) if freq else 0
Calculates the information content of a GO term .
34,448
def resnik_sim ( go_id1 , go_id2 , godag , termcounts ) : goterm1 = godag [ go_id1 ] goterm2 = godag [ go_id2 ] if goterm1 . namespace == goterm2 . namespace : msca_goid = deepest_common_ancestor ( [ go_id1 , go_id2 ] , godag ) return get_info_content ( msca_goid , termcounts )
Computes Resnik s similarity measure .
34,449
def lin_sim ( goid1 , goid2 , godag , termcnts ) : sim_r = resnik_sim ( goid1 , goid2 , godag , termcnts ) return lin_sim_calc ( goid1 , goid2 , sim_r , termcnts )
Computes Lin s similarity measure .
34,450
def lin_sim_calc ( goid1 , goid2 , sim_r , termcnts ) : if sim_r is not None : info = get_info_content ( goid1 , termcnts ) + get_info_content ( goid2 , termcnts ) if info != 0 : return ( 2 * sim_r ) / info
Computes Lin s similarity measure using pre - calculated Resnik s similarities .
34,451
def common_parent_go_ids ( goids , godag ) : rec = godag [ goids [ 0 ] ] candidates = rec . get_all_parents ( ) candidates . update ( { goids [ 0 ] } ) for goid in goids [ 1 : ] : rec = godag [ goid ] parents = rec . get_all_parents ( ) parents . update ( { goid } ) candidates . intersection_update ( parents ) return c...
This function finds the common ancestors in the GO tree of the list of goids in the input .
34,452
def deepest_common_ancestor ( goterms , godag ) : return max ( common_parent_go_ids ( goterms , godag ) , key = lambda t : godag [ t ] . depth )
This function gets the nearest common ancestor using the above function . Only returns single most specific - assumes unique exists .
34,453
def min_branch_length ( go_id1 , go_id2 , godag , branch_dist ) : goterm1 = godag [ go_id1 ] goterm2 = godag [ go_id2 ] if goterm1 . namespace == goterm2 . namespace : dca = deepest_common_ancestor ( [ go_id1 , go_id2 ] , godag ) dca_depth = godag [ dca ] . depth depth1 = goterm1 . depth - dca_depth depth2 = goterm2 . ...
Finds the minimum branch length between two terms in the GO DAG .
34,454
def _init_count_terms ( self , annots ) : gonotindag = set ( ) gocnts = self . gocnts go2obj = self . go2obj for terms in annots . values ( ) : allterms = set ( ) for go_id in terms : goobj = go2obj . get ( go_id , None ) if goobj is not None : allterms . add ( go_id ) allterms |= goobj . get_all_parents ( ) else : gon...
Fills in the counts and overall aspect counts .
34,455
def _init_add_goid_alt ( self ) : goid_alts = set ( ) go2cnt_add = { } aspect_counts = self . aspect_counts gocnts = self . gocnts go2obj = self . go2obj for go_id , cnt in gocnts . items ( ) : goobj = go2obj [ go_id ] assert cnt , "NO TERM COUNTS FOR {GO}" . format ( GO = goobj . item_id ) if go_id != goobj . item_id ...
Add alternate GO IDs to term counts .
34,456
def get_term_freq ( self , go_id ) : num_ns = float ( self . get_total_count ( self . go2obj [ go_id ] . namespace ) ) return float ( self . get_count ( go_id ) ) / num_ns if num_ns != 0 else 0
Returns the frequency at which a particular GO term has been observed in the annotations .
34,457
def get_sections ( self , hdrgo , dflt_section = True ) : dflt_list = [ ] if dflt_section : dflt_list = [ self . secdflt ] return self . hdrgo2sections . get ( hdrgo , dflt_list )
Given a header GO return the sections that contain it .
34,458
def get_section_hdrgos ( self ) : return set ( [ h for _ , hs in self . sections for h in hs ] ) if self . sections else set ( )
Get the GO group headers explicitly listed in sections .
34,459
def _chk_sections ( sections ) : if sections : assert len ( sections [ 0 ] ) == 2 , "SECTIONS DATA MUST BE A 2-D LIST. FOUND: {S}" . format ( S = sections ) for _ , hdrgos in sections : chk_goids ( hdrgos , "HdrgosSections::_chk_sections()" )
Check format of user - provided sections variable
34,460
def _init_hdrgos ( self , hdrgos_dflt , hdrgos_usr = None , add_dflt = True ) : if ( hdrgos_usr is None or hdrgos_usr is False ) and not self . sections : return set ( hdrgos_dflt ) hdrgos_init = set ( ) if hdrgos_usr : chk_goids ( hdrgos_usr , "User-provided GO group headers" ) hdrgos_init |= set ( hdrgos_usr ) if sel...
Initialize GO high
34,461
def get_all_parents ( go_objs ) : go_parents = set ( ) for go_obj in go_objs : go_parents |= go_obj . get_all_parents ( ) return go_parents
Return a set containing all GO Term parents of multiple GOTerm objects .
34,462
def prt_hdr ( self , prt = sys . stdout , name = "name " ) : hdr = "{NAME} | # {ITEMS:11} | range | 25th percentile | " " median | 75th percentile | mean | stddev\n" . format ( NAME = name , ITEMS = self . desc ) div = "{DASHES}|---------------|----------------------|" "-----------------|-----...
Print stats header in markdown style .
34,463
def prt_data ( self , name , vals , prt = sys . stdout ) : fld2val = self . get_fld2val ( name , vals ) prt . write ( self . fmt . format ( ** fld2val ) ) return fld2val
Print stats data in markdown style .
34,464
def getstr_data ( self , name , vals ) : fld2val = self . get_fld2val ( name , vals ) return self . fmt . format ( ** fld2val )
Return stats data string in markdown style .
34,465
def get_fld2val ( self , name , vals ) : if vals : return self . _init_fld2val_stats ( name , vals ) return self . _init_fld2val_null ( name )
Describe summary statistics for a list of numbers .
34,466
def _init_fld2val_stats ( self , name , vals ) : vals_stats = stats . describe ( vals ) stddev = math . sqrt ( vals_stats [ 3 ] ) p25 = np . percentile ( vals , 25 ) p50 = np . percentile ( vals , 50 ) p75 = np . percentile ( vals , 75 ) fld2val = { 'name' : name , 'qty' . format ( ITEMS = self . desc ) : vals_stats [ ...
Return statistics on values .
34,467
def _get_str_range ( self , vals_stats ) : minmax = vals_stats [ 1 ] minval = self . fmtstr . format ( minmax [ 0 ] ) maxval = self . fmtstr . format ( minmax [ 1 ] ) return '{A} to {B:6>}' . format ( A = minval , B = maxval )
Return a string containing the range of values .
34,468
def summarize_sec2hdrgos ( self , sec2d_hdrgos ) : hdrgos_all = set ( [ ] ) hdrgos_grouped = set ( ) hdrgos_ungrouped = set ( ) sections_grouped = set ( ) for sectionname , hdrgos in sec2d_hdrgos : self . _chk_hdrgoids ( hdrgos ) hdrgos_all . update ( hdrgos ) if sectionname != HdrgosSections . secdflt : hdrgos_grouped...
Get counts of header GO IDs and sections .
34,469
def summarize_sec2hdrnts ( self , sec2d_hdrnts ) : sec2d_hdrgos = [ ( s , set ( nt . GO for nt in nts ) ) for s , nts in sec2d_hdrnts ] return self . summarize_sec2hdrgos ( sec2d_hdrgos )
Given namedtuples in each sectin get counts of header GO IDs and sections .
34,470
def _chk_hdrgoids ( hdrgos ) : goid = next ( iter ( hdrgos ) ) if isinstance ( goid , str ) and goid [ : 3 ] == "GO:" : return assert False , "HDRGOS DO NOT CONTAIN GO IDs: {E}" . format ( E = goid )
Check that hdrgo set is a set of GO IDs .
34,471
def get_matching_gos ( self , compiled_pattern , ** kws ) : matching_gos = [ ] obo_dag = self . obo_dag prt = kws [ 'prt' ] if 'prt' in kws else self . log prt . write ( '\nPATTERN SEARCH: "{P}"\n' . format ( P = compiled_pattern . pattern ) ) srchgos = kws [ 'gos' ] if 'gos' in kws else self . go2items . keys ( ) for ...
Return all GOs which match the user regex pattern .
34,472
def _summary_matching_gos ( prt , pattern , matching_gos , all_gos ) : msg = 'Found {N} GO(s) out of {M} matching pattern("{P}")\n' num_gos = len ( matching_gos ) num_all = len ( all_gos ) prt . write ( msg . format ( N = num_gos , M = num_all , P = pattern ) )
Print summary for get_matching_gos .
34,473
def _search_vals ( self , compiled_pattern , fld_val ) : matches = [ ] if isinstance ( fld_val , set ) : for val in fld_val : self . _search_val ( matches , compiled_pattern , val ) elif isinstance ( fld_val , str ) : self . _search_val ( matches , compiled_pattern , fld_val ) return matches
Search for user - regex in scalar or iterable data values .
34,474
def _search_val ( matches , compiled_pattern , fld_val ) : mtch = compiled_pattern . search ( fld_val ) if mtch : matches . append ( fld_val )
Search for user - regex in scalar data values .
34,475
def add_children_gos ( self , gos ) : lst = [ ] obo_dag = self . obo_dag get_children = lambda go_obj : list ( go_obj . get_all_children ( ) ) + [ go_obj . id ] for go_id in gos : go_obj = obo_dag [ go_id ] lst . extend ( get_children ( go_obj ) ) return set ( lst )
Return children of input gos plus input gos .
34,476
def get_items ( self , gos ) : items = [ ] for go_id in gos : items . extend ( self . go2items . get ( go_id , [ ] ) ) return set ( items )
Given GO terms return genes or gene products for the GOs .
34,477
def prt_summary ( self , prt = sys . stdout ) : desc = "NtGoeaResults" if self . is_goterm else "namedtuple" prt . write ( "{N} GOEA results from {O}. P-values stored in {P}.\n" . format ( N = len ( self . go2res ) , O = desc , P = self . pval_name ) )
Print summary of GOEA plotting object .
34,478
def set_goid2color_pval ( self , goid2color ) : alpha2col = self . alpha2col if self . pval_name is not None : pval_name = self . pval_name for goid , res in self . go2res . items ( ) : pval = getattr ( res , pval_name , None ) if pval is not None : for alpha , color in alpha2col . items ( ) : if pval <= alpha and res ...
Fill missing colors based on p - value of an enriched GO term .
34,479
def get_goid2color_pval ( self ) : go2color = { } self . set_goid2color_pval ( go2color ) color_dflt = self . alpha2col [ 1.000 ] for goid in self . go2res : if goid not in go2color : go2color [ goid ] = color_dflt return go2color
Return a go2color dict containing GO colors determined by P - value .
34,480
def prttex_summary_cnts_all ( self , prt = sys . stdout ) : cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) self . _prttex_summary_cnts ( prt , cnts )
Print LaTeX format summary of level and depth counts for all active GO Terms .
34,481
def write_summary_cnts_all ( self ) : cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) self . _write_summary_cnts ( cnts )
Write summary of level and depth counts for all active GO Terms .
34,482
def write_summary_cnts ( self , go_ids ) : obo = self . obo cnts = self . get_cnts_levels_depths_recs ( [ obo . get ( GO ) for GO in go_ids ] ) self . _write_summary_cnts ( cnts )
Write summary of level and depth counts for specific GO ids .
34,483
def get_cnts_levels_depths_recs ( recs ) : cnts = cx . defaultdict ( lambda : cx . defaultdict ( cx . Counter ) ) for rec in recs : if rec is not None and not rec . is_obsolete : cnts [ 'level' ] [ rec . level ] [ rec . namespace ] += 1 cnts [ 'depth' ] [ rec . depth ] [ rec . namespace ] += 1 return cnts
Collect counts of levels and depths in a Group of GO Terms .
34,484
def get_data ( self ) : data = [ ] ntobj = cx . namedtuple ( "NtGoCnt" , "Depth_Level BP_D MF_D CC_D BP_L MF_L CC_L" ) cnts = self . get_cnts_levels_depths_recs ( set ( self . obo . values ( ) ) ) max_val = max ( max ( dep for dep in cnts [ 'depth' ] ) , max ( lev for lev in cnts [ 'level' ] ) ) for i in range ( max_va...
Collect counts of GO terms at all levels and depths .
34,485
def main ( ) : obj = GoeaCliFnc ( GoeaCliArgs ( ) . args ) results_specified = obj . get_results ( ) obj . prt_results ( results_specified )
Run gene enrichment analysis .
34,486
def get_objanno ( fin_anno , anno_type = None , ** kws ) : anno_type = get_anno_desc ( fin_anno , anno_type ) if anno_type is not None : if anno_type == 'gene2go' : return Gene2GoReader ( fin_anno , ** kws ) if anno_type == 'gaf' : return GafReader ( fin_anno , hdr_only = kws . get ( 'hdr_only' , False ) , prt = kws . ...
Read annotations in GAF GPAD Entrez gene2go or text format .
34,487
def get_relation_cnt ( self ) : ctr = cx . Counter ( ) for ntgpad in self . associations : if ntgpad . Extension is not None : ctr += ntgpad . Extension . get_relations_cnt ( ) return ctr
Return a Counter containing all relations contained in the Annotation Extensions .
34,488
def _get_id2gos ( self ) : kws = { } if self . args . ev_inc is not None : kws [ 'ev_include' ] = set ( self . args . ev_inc . split ( ',' ) ) if self . args . ev_exc is not None : kws [ 'ev_exclude' ] = set ( self . args . ev_exc . split ( ',' ) ) return self . objanno . get_id2gos ( ** kws )
Return annotations as id2gos
34,489
def _get_objanno ( self , assoc_fn ) : anno_type = get_anno_desc ( assoc_fn , None ) if anno_type is None : anno_type = self . args . annofmt if self . args . annofmt else 'id2gos' kws = { 'taxid' : self . args . taxid } if anno_type == 'gene2go' else { } return get_objanno ( assoc_fn , anno_type , ** kws )
Get an annotation object
34,490
def _init_itemid2name ( self ) : if not hasattr ( self . args , 'id2sym' ) : return None fin_id2sym = self . args . id2sym if fin_id2sym is not None and os . path . exists ( fin_id2sym ) : id2sym = { } cmpl = re . compile ( r'^\s*(\S+)[\s,;]+(\S+)' ) with open ( fin_id2sym ) as ifstrm : for line in ifstrm : mtch = cmpl...
Print gene symbols instead of gene IDs if provided .
34,491
def prt_results ( self , goea_results ) : if self . args . outfile is None : self . _prt_results ( goea_results ) else : outfiles = self . args . outfile . split ( "," ) grpwr = self . prepgrp . get_objgrpwr ( goea_results ) if self . prepgrp else None if grpwr is None : self . prt_outfiles_flat ( goea_results , outfil...
Print GOEA results to the screen or to a file .
34,492
def _prt_results ( self , goea_results ) : min_ratio = self . args . ratio if min_ratio is not None : assert 1 <= min_ratio <= 2 self . objgoea . print_date ( min_ratio = min_ratio , pval = self . args . pval ) results_adj = self . objgoea . get_adj_records ( goea_results , min_ratio , self . args . pval ) if results_a...
Print GOEA results to the screen .
34,493
def chk_genes ( self , study , pop , assoc = None ) : if len ( pop ) < len ( study ) : exit ( "\nERROR: The study file contains more elements than the population file. " "Please check that the study file is a subset of the population file.\n" ) overlap = self . get_overlap ( study , pop ) if overlap < 0.95 : sys . stde...
Check gene sets .
34,494
def get_results_sig ( self ) : print ( "{N:7,} of {M:,} results have uncorrected P-values <= {PVAL}=pval\n" . format ( N = sum ( 1 for r in self . results_all if r . p_uncorrected < self . args . pval ) , M = len ( self . results_all ) , PVAL = self . args . pval ) ) pval_fld = self . get_pval_field ( ) results = [ r f...
Get significant results .
34,495
def get_pval_field ( self ) : pval_fld = self . args . pval_field if pval_fld is not None : if pval_fld [ : 2 ] != 'p_' : pval_fld = 'p_' + pval_fld elif len ( self . methods ) == 1 : pval_fld = 'p_' + self . methods [ 0 ] else : pval_fld = 'p_uncorrected' if self . results_all : assert hasattr ( next ( iter ( self . r...
Get p_uncorrected or the user - specified field for determining significant results .
34,496
def rd_files ( self , study_fn , pop_fn ) : study , pop = self . _read_geneset ( study_fn , pop_fn ) print ( "Study: {0} vs. Population {1}\n" . format ( len ( study ) , len ( pop ) ) ) return study , pop
Read files and return study and population .
34,497
def _read_geneset ( self , study_fn , pop_fn ) : pop = set ( _ . strip ( ) for _ in open ( pop_fn ) if _ . strip ( ) ) study = frozenset ( _ . strip ( ) for _ in open ( study_fn ) if _ . strip ( ) ) if next ( iter ( pop ) ) . isdigit ( ) : pop = set ( int ( g ) for g in pop ) study = frozenset ( int ( g ) for g in stud...
Open files containing genes . Return study genes and population genes .
34,498
def get_objgrpwr ( self , goea_results ) : sortobj = self . get_sortobj ( goea_results ) return GrpWr ( sortobj , self . pval_fld , ver_list = self . ver_list )
Get a GrpWr object to write grouped GOEA results .
34,499
def get_sortobj ( self , goea_results , ** kws ) : nts_goea = MgrNtGOEAs ( goea_results ) . get_goea_nts_prt ( ** kws ) goids = set ( nt . GO for nt in nts_goea ) go2nt = { nt . GO : nt for nt in nts_goea } grprobj = Grouper ( "GOEA" , goids , self . hdrobj , self . grprdflt . gosubdag , go2nt = go2nt ) grprobj . prt_s...
Return a Grouper object given a list of GOEnrichmentRecord .