idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
18,800
def extract_filestem ( data ) : escapes = re . compile ( r"[\s/,#\(\)]" ) escname = re . sub ( escapes , '_' , data [ 'AssemblyName' ] ) return '_' . join ( [ data [ 'AssemblyAccession' ] , escname ] )
Extract filestem from Entrez eSummary data .
18,801
def write_contigs ( asm_uid , contig_uids , batchsize = 10000 ) : logger . info ( "Collecting contig data for %s" , asm_uid ) asm_record = Entrez . read ( entrez_retry ( Entrez . esummary , db = 'assembly' , id = asm_uid , rettype = 'text' ) , validate = False ) asm_organism = asm_record [ 'DocumentSummarySet' ] [ 'Doc...
Writes assembly contigs out to a single FASTA file in the script s designated output directory .
18,802
def logreport_downloaded ( accession , skippedlist , accessiondict , uidaccdict ) : for vid in accessiondict [ accession . split ( '.' ) [ 0 ] ] : if vid in skippedlist : status = "NOT DOWNLOADED" else : status = "DOWNLOADED" logger . warning ( "\t\t%s: %s - %s" , vid , uidaccdict [ vid ] , status )
Reports to logger whether alternative assemblies for an accession that was missing have been downloaded
18,803
def calculate_tetra_zscores ( infilenames ) : org_tetraz = { } for filename in infilenames : org = os . path . splitext ( os . path . split ( filename ) [ - 1 ] ) [ 0 ] org_tetraz [ org ] = calculate_tetra_zscore ( filename ) return org_tetraz
Returns dictionary of TETRA Z - scores for each input file .
18,804
def calculate_tetra_zscore ( filename ) : counts = ( collections . defaultdict ( int ) , collections . defaultdict ( int ) , collections . defaultdict ( int ) , collections . defaultdict ( int ) ) for rec in SeqIO . parse ( filename , 'fasta' ) : for seq in [ str ( rec . seq ) . upper ( ) , str ( rec . seq . reverse_co...
Returns TETRA Z - score for the sequence in the passed file .
18,805
def calculate_correlations ( tetra_z ) : orgs = sorted ( tetra_z . keys ( ) ) correlations = pd . DataFrame ( index = orgs , columns = orgs , dtype = float ) . fillna ( 1.0 ) for idx , org1 in enumerate ( orgs [ : - 1 ] ) : for org2 in orgs [ idx + 1 : ] : assert sorted ( tetra_z [ org1 ] . keys ( ) ) == sorted ( tetra...
Returns dataframe of Pearson correlation coefficients .
18,806
def get_labels ( filename , logger = None ) : labeldict = { } if filename is not None : if logger : logger . info ( "Reading labels from %s" , filename ) with open ( filename , "r" ) as ifh : count = 0 for line in ifh . readlines ( ) : count += 1 try : key , label = line . strip ( ) . split ( "\t" ) except ValueError :...
Returns a dictionary of alternative sequence labels or None
18,807
def add_tot_length ( self , qname , sname , value , sym = True ) : self . alignment_lengths . loc [ qname , sname ] = value if sym : self . alignment_lengths . loc [ sname , qname ] = value
Add a total length value to self . alignment_lengths .
18,808
def add_sim_errors ( self , qname , sname , value , sym = True ) : self . similarity_errors . loc [ qname , sname ] = value if sym : self . similarity_errors . loc [ sname , qname ] = value
Add a similarity error value to self . similarity_errors .
18,809
def add_pid ( self , qname , sname , value , sym = True ) : self . percentage_identity . loc [ qname , sname ] = value if sym : self . percentage_identity . loc [ sname , qname ] = value
Add a percentage identity value to self . percentage_identity .
18,810
def add_coverage ( self , qname , sname , qcover , scover = None ) : self . alignment_coverage . loc [ qname , sname ] = qcover if scover : self . alignment_coverage . loc [ sname , qname ] = scover
Add percentage coverage values to self . alignment_coverage .
18,811
def get_db_name ( self , fname ) : return self . funcs . db_func ( fname , self . outdir , self . exes . format_exe ) [ 1 ]
Return database filename
18,812
def build_blast_cmd ( self , fname , dbname ) : return self . funcs . blastn_func ( fname , dbname , self . outdir , self . exes . blast_exe )
Return BLASTN command
18,813
def fragment_fasta_files ( infiles , outdirname , fragsize ) : outfnames = [ ] for fname in infiles : outstem , outext = os . path . splitext ( os . path . split ( fname ) [ - 1 ] ) outfname = os . path . join ( outdirname , outstem ) + "-fragments" + outext outseqs = [ ] count = 0 for seq in SeqIO . parse ( fname , "f...
Chops sequences of the passed files into fragments returns filenames .
18,814
def get_fraglength_dict ( fastafiles ) : fraglength_dict = { } for filename in fastafiles : qname = os . path . split ( filename ) [ - 1 ] . split ( "-fragments" ) [ 0 ] fraglength_dict [ qname ] = get_fragment_lengths ( filename ) return fraglength_dict
Returns dictionary of sequence fragment lengths keyed by query name .
18,815
def get_fragment_lengths ( fastafile ) : fraglengths = { } for seq in SeqIO . parse ( fastafile , "fasta" ) : fraglengths [ seq . id ] = len ( seq ) return fraglengths
Returns dictionary of sequence fragment lengths keyed by fragment ID .
18,816
def build_db_jobs ( infiles , blastcmds ) : dbjobdict = { } for idx , fname in enumerate ( infiles ) : dbjobdict [ blastcmds . get_db_name ( fname ) ] = pyani_jobs . Job ( "%s_db_%06d" % ( blastcmds . prefix , idx ) , blastcmds . build_db_cmd ( fname ) ) return dbjobdict
Returns dictionary of db - building commands keyed by dbname .
18,817
def make_blastcmd_builder ( mode , outdir , format_exe = None , blast_exe = None , prefix = "ANIBLAST" ) : if mode == "ANIb" : blastcmds = BLASTcmds ( BLASTfunctions ( construct_makeblastdb_cmd , construct_blastn_cmdline ) , BLASTexes ( format_exe or pyani_config . MAKEBLASTDB_DEFAULT , blast_exe or pyani_config . BLAS...
Returns BLASTcmds object for construction of BLAST commands .
18,818
def make_job_graph ( infiles , fragfiles , blastcmds ) : joblist = [ ] dbjobdict = build_db_jobs ( infiles , blastcmds ) jobnum = len ( dbjobdict ) for idx , fname1 in enumerate ( fragfiles [ : - 1 ] ) : for fname2 in fragfiles [ idx + 1 : ] : jobnum += 1 jobs = [ pyani_jobs . Job ( "%s_exe_%06d_a" % ( blastcmds . pref...
Return a job dependency graph based on the passed input sequence files .
18,819
def construct_makeblastdb_cmd ( filename , outdir , blastdb_exe = pyani_config . MAKEBLASTDB_DEFAULT ) : title = os . path . splitext ( os . path . split ( filename ) [ - 1 ] ) [ 0 ] outfilename = os . path . join ( outdir , os . path . split ( filename ) [ - 1 ] ) return ( "{0} -dbtype nucl -in {1} -title {2} -out {3}...
Returns a single makeblastdb command .
18,820
def construct_formatdb_cmd ( filename , outdir , blastdb_exe = pyani_config . FORMATDB_DEFAULT ) : title = os . path . splitext ( os . path . split ( filename ) [ - 1 ] ) [ 0 ] newfilename = os . path . join ( outdir , os . path . split ( filename ) [ - 1 ] ) shutil . copy ( filename , newfilename ) return ( "{0} -p F ...
Returns a single formatdb command .
18,821
def generate_blastn_commands ( filenames , outdir , blast_exe = None , mode = "ANIb" ) : if mode == "ANIb" : construct_blast_cmdline = construct_blastn_cmdline else : construct_blast_cmdline = construct_blastall_cmdline cmdlines = [ ] for idx , fname1 in enumerate ( filenames [ : - 1 ] ) : dbname1 = fname1 . replace ( ...
Return a list of blastn command - lines for ANIm
18,822
def construct_blastn_cmdline ( fname1 , fname2 , outdir , blastn_exe = pyani_config . BLASTN_DEFAULT ) : fstem1 = os . path . splitext ( os . path . split ( fname1 ) [ - 1 ] ) [ 0 ] fstem2 = os . path . splitext ( os . path . split ( fname2 ) [ - 1 ] ) [ 0 ] fstem1 = fstem1 . replace ( "-fragments" , "" ) prefix = os ....
Returns a single blastn command .
18,823
def construct_blastall_cmdline ( fname1 , fname2 , outdir , blastall_exe = pyani_config . BLASTALL_DEFAULT ) : fstem1 = os . path . splitext ( os . path . split ( fname1 ) [ - 1 ] ) [ 0 ] fstem2 = os . path . splitext ( os . path . split ( fname2 ) [ - 1 ] ) [ 0 ] fstem1 = fstem1 . replace ( "-fragments" , "" ) prefix ...
Returns a single blastall command .
18,824
def process_blast ( blast_dir , org_lengths , fraglengths = None , mode = "ANIb" , identity = 0.3 , coverage = 0.7 , logger = None , ) : blastfiles = pyani_files . get_input_files ( blast_dir , ".blast_tab" ) results = ANIResults ( list ( org_lengths . keys ( ) ) , mode ) for org , length in list ( org_lengths . items ...
Returns a tuple of ANIb results for . blast_tab files in the output dir .
18,825
def split_seq ( iterable , size ) : elm = iter ( iterable ) item = list ( itertools . islice ( elm , size ) ) while item : yield item item = list ( itertools . islice ( elm , size ) )
Splits a passed iterable into chunks of a given size .
18,826
def build_joblist ( jobgraph ) : jobset = set ( ) for job in jobgraph : jobset = populate_jobset ( job , jobset , depth = 1 ) return list ( jobset )
Returns a list of jobs from a passed jobgraph .
18,827
def compile_jobgroups_from_joblist ( joblist , jgprefix , sgegroupsize ) : jobcmds = defaultdict ( list ) for job in joblist : jobcmds [ job . command . split ( ' ' , 1 ) [ 0 ] ] . append ( job . command ) jobgroups = [ ] for cmds in list ( jobcmds . items ( ) ) : sublists = split_seq ( cmds [ 1 ] , sgegroupsize ) coun...
Return list of jobgroups rather than list of jobs .
18,828
def run_dependency_graph ( jobgraph , logger = None , jgprefix = "ANIm_SGE_JG" , sgegroupsize = 10000 , sgeargs = None ) : joblist = build_joblist ( jobgraph ) dep_count = 0 if logger : logger . info ( "Jobs to run with scheduler" ) for job in joblist : logger . info ( "{0}: {1}" . format ( job . name , job . command )...
Creates and runs GridEngine scripts for jobs based on the passed jobgraph .
18,829
def populate_jobset ( job , jobset , depth ) : jobset . add ( job ) if len ( job . dependencies ) == 0 : return jobset for j in job . dependencies : jobset = populate_jobset ( j , jobset , depth + 1 ) return jobset
Creates a set of jobs containing jobs at difference depths of the dependency tree retaining dependencies as strings not Jobs .
18,830
def build_job_scripts ( root_dir , jobs ) : for job in jobs : scriptpath = os . path . join ( root_dir , "jobs" , job . name ) with open ( scriptpath , "w" ) as scriptfile : scriptfile . write ( "#!/bin/sh\n#$ -S /bin/bash\n%s\n" % job . script ) job . scriptpath = scriptpath
Constructs the script for each passed Job in the jobs iterable
18,831
def extract_submittable_jobs ( waiting ) : submittable = set ( ) for job in waiting : unsatisfied = sum ( [ ( subjob . submitted is False ) for subjob in job . dependencies ] ) if unsatisfied == 0 : submittable . add ( job ) return list ( submittable )
Obtain a list of jobs that are able to be submitted from the passed list of pending jobs
18,832
def submit_safe_jobs ( root_dir , jobs , sgeargs = None ) : for job in jobs : job . out = os . path . join ( root_dir , "stdout" ) job . err = os . path . join ( root_dir , "stderr" ) args = " -N %s " % ( job . name ) args += " -cwd " args += " -o %s -e %s " % ( job . out , job . err ) if isinstance ( job , JobGroup ) ...
Submit the passed list of jobs to the Grid Engine server using the passed directory as the root for scheduler output .
18,833
def submit_jobs ( root_dir , jobs , sgeargs = None ) : waiting = list ( jobs ) while len ( waiting ) > 0 : submittable = extract_submittable_jobs ( waiting ) submit_safe_jobs ( root_dir , submittable , sgeargs ) for job in submittable : waiting . remove ( job )
Submit each of the passed jobs to the SGE server using the passed directory as root for SGE output .
18,834
def build_and_submit_jobs ( root_dir , jobs , sgeargs = None ) : if not isinstance ( jobs , list ) : jobs = [ jobs ] build_directories ( root_dir ) build_job_scripts ( root_dir , jobs ) submit_jobs ( root_dir , jobs , sgeargs )
Submits the passed iterable of Job objects to SGE placing SGE s output in the passed root directory
18,835
def params_mpl ( df ) : return { 'ANIb_alignment_lengths' : ( 'afmhot' , df . values . min ( ) , df . values . max ( ) ) , 'ANIb_percentage_identity' : ( 'spbnd_BuRd' , 0 , 1 ) , 'ANIb_alignment_coverage' : ( 'BuRd' , 0 , 1 ) , 'ANIb_hadamard' : ( 'hadamard_BuRd' , 0 , 1 ) , 'ANIb_similarity_errors' : ( 'afmhot' , df ....
Returns dict of matplotlib parameters dependent on dataframe .
18,836
def download_file ( fname , target_dir = None , force = False ) : target_dir = target_dir or temporary_dir ( ) target_fname = os . path . join ( target_dir , fname ) if force or not os . path . isfile ( target_fname ) : url = urljoin ( datasets_url , fname ) urlretrieve ( url , target_fname ) return target_fname
Download fname from the datasets_url and save it to target_dir unless the file already exists and force is False .
18,837
def parse_idx ( fd ) : DATA_TYPES = { 0x08 : 'B' , 0x09 : 'b' , 0x0b : 'h' , 0x0c : 'i' , 0x0d : 'f' , 0x0e : 'd' } header = fd . read ( 4 ) if len ( header ) != 4 : raise IdxDecodeError ( 'Invalid IDX file, ' 'file empty or does not contain a full header.' ) zeros , data_type , num_dimensions = struct . unpack ( '>HBB...
Parse an IDX file and return it as a numpy array .
18,838
def download_and_parse_mnist_file ( fname , target_dir = None , force = False ) : fname = download_file ( fname , target_dir = target_dir , force = force ) fopen = gzip . open if os . path . splitext ( fname ) [ 1 ] == '.gz' else open with fopen ( fname , 'rb' ) as fd : return parse_idx ( fd )
Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array .
18,839
def fetch_next_page ( self ) : for page in self : return page else : return Page ( self . _resultset . cursor , iter ( ( ) ) )
Fetch the next Page of results .
18,840
def count ( self , * , page_size = DEFAULT_BATCH_SIZE , ** options ) : entities = 0 options = QueryOptions ( self ) . replace ( keys_only = True ) for page in self . paginate ( page_size = page_size , ** options ) : entities += len ( list ( page ) ) return entities
Counts the number of entities that match this query .
18,841
def delete ( self , * , page_size = DEFAULT_BATCH_SIZE , ** options ) : from . model import delete_multi deleted = 0 options = QueryOptions ( self ) . replace ( keys_only = True ) for page in self . paginate ( page_size = page_size , ** options ) : keys = list ( page ) deleted += len ( keys ) delete_multi ( keys ) retu...
Deletes all the entities that match this query .
18,842
def get ( self , ** options ) : sub_query = self . with_limit ( 1 ) options = QueryOptions ( sub_query ) . replace ( batch_size = 1 ) for result in sub_query . run ( ** options ) : return result return None
Run this query and get the first result .
18,843
def paginate ( self , * , page_size , ** options ) : return Pages ( self . _prepare ( ) , page_size , QueryOptions ( self , ** options ) )
Run this query and return a page iterator .
18,844
def namespace ( namespace ) : try : current_namespace = _namespace . current except AttributeError : current_namespace = None set_namespace ( namespace ) try : yield finally : set_namespace ( current_namespace )
Context manager for stacking the current thread - local default namespace . Exiting the context sets the thread - local default namespace back to the previously - set namespace . If there is no previous namespace then the thread - local namespace is cleared .
18,845
def lookup_model_by_kind ( kind ) : model = _known_models . get ( kind ) if model is None : raise RuntimeError ( f"Model for kind {kind!r} not found." ) return model
Look up the model instance for a given Datastore kind .
18,846
def delete_multi ( keys ) : if not keys : return adapter = None for key in keys : if key . is_partial : raise RuntimeError ( f"Key {key!r} is partial." ) model = lookup_model_by_kind ( key . kind ) if adapter is None : adapter = model . _adapter model . pre_delete_hook ( key ) adapter . delete_multi ( keys ) for key in...
Delete a set of entitites from Datastore by their respective keys .
18,847
def get_multi ( keys ) : if not keys : return [ ] adapter = None for key in keys : if key . is_partial : raise RuntimeError ( f"Key {key!r} is partial." ) model = lookup_model_by_kind ( key . kind ) if adapter is None : adapter = model . _adapter model . pre_get_hook ( key ) entities_data , entities = adapter . get_mul...
Get a set of entities from Datastore by their respective keys .
18,848
def put_multi ( entities ) : if not entities : return [ ] adapter , requests = None , [ ] for entity in entities : if adapter is None : adapter = entity . _adapter entity . pre_put_hook ( ) requests . append ( PutRequest ( entity . key , entity . unindexed_properties , entity ) ) keys = adapter . put_multi ( requests )...
Persist a set of entities to Datastore .
18,849
def from_path ( cls , * path , namespace = None ) : parent = None for i in range ( 0 , len ( path ) , 2 ) : parent = cls ( * path [ i : i + 2 ] , parent = parent , namespace = namespace ) return parent
Build up a Datastore key from a path .
18,850
def validate ( self , value ) : if isinstance ( value , self . _types ) : return value elif self . optional and value is None : return [ ] if self . repeated else None elif self . repeated and isinstance ( value , ( tuple , list ) ) and all ( isinstance ( x , self . _types ) for x in value ) : return value else : raise...
Validates that value can be assigned to this Property .
18,851
def prepare_to_store ( self , entity , value ) : if value is None and not self . optional : raise RuntimeError ( f"Property {self.name_on_model} requires a value." ) return value
Prepare value for storage . Called by the Model for each Property value pair it contains before handing the data off to an adapter .
18,852
def get ( cls , id_or_name , * , parent = None , namespace = None ) : return Key ( cls , id_or_name , parent = parent , namespace = namespace ) . get ( )
Get an entity by id .
18,853
def init_app ( self , app , env_file = None , verbose_mode = False ) : if self . app is None : self . app = app self . verbose_mode = verbose_mode if env_file is None : env_file = os . path . join ( os . getcwd ( ) , ".env" ) if not os . path . exists ( env_file ) : warnings . warn ( "can't read {0} - it doesn't exist"...
Imports . env file .
18,854
def __import_vars ( self , env_file ) : with open ( env_file , "r" ) as f : for line in f : try : line = line . lstrip ( ) if line . startswith ( 'export' ) : line = line . replace ( 'export' , '' , 1 ) key , val = line . strip ( ) . split ( '=' , 1 ) except ValueError : pass else : if not callable ( val ) : if self . ...
Actual importing function .
18,855
def process_response ( self , request , response ) : if hasattr ( request , 'COUNTRY_CODE' ) : response . set_cookie ( key = constants . COUNTRY_COOKIE_NAME , value = request . COUNTRY_CODE , max_age = settings . LANGUAGE_COOKIE_AGE , path = settings . LANGUAGE_COOKIE_PATH , domain = settings . LANGUAGE_COOKIE_DOMAIN )...
Shares config with the language cookie as they serve a similar purpose
18,856
def create_option ( self , name , value , label , selected , index , subindex = None , attrs = None ) : index = str ( index ) if subindex is None else "%s%s%s" % ( index , self . id_separator , subindex ) if attrs is None : attrs = { } option_attrs = self . build_attrs ( self . attrs , attrs ) if self . option_inherits...
Patch to use nicer ids .
18,857
def current_version ( ) : filepath = os . path . abspath ( project_root / "directory_components" / "version.py" ) version_py = get_file_string ( filepath ) regex = re . compile ( Utils . get_version ) if regex . search ( version_py ) is not None : current_version = regex . search ( version_py ) . group ( 0 ) print ( co...
Get current version of directory - components .
18,858
def get_file_string ( filepath ) : with open ( os . path . abspath ( filepath ) ) as f : return f . read ( )
Get string from file .
18,859
def replace_in_dirs ( version ) : print ( color ( "Upgrading directory-components dependency in all repos..." , fg = 'blue' , style = 'bold' ) ) for dirname in Utils . dirs : replace = "directory-components=={}" . format ( version ) replace_in_files ( dirname , replace ) done ( version )
Look through dirs and run replace_in_files in each .
18,860
def replace_in_files ( dirname , replace ) : filepath = os . path . abspath ( dirname / "requirements.in" ) if os . path . isfile ( filepath ) and header_footer_exists ( filepath ) : replaced = re . sub ( Utils . exp , replace , get_file_string ( filepath ) ) with open ( filepath , "w" ) as f : f . write ( replaced ) p...
Replace current version with new version in requirements files .
18,861
def header_footer_exists ( filepath ) : with open ( filepath ) as f : return re . search ( Utils . exp , f . read ( ) )
Check if directory - components is listed in requirements files .
18,862
def linedelimited ( inlist , delimiter ) : outstr = '' for item in inlist : if type ( item ) != StringType : item = str ( item ) outstr = outstr + item + delimiter outstr = outstr [ 0 : - 1 ] return outstr
Returns a string composed of elements in inlist with each element separated by delimiter . Used by function writedelimited . Use \ t for tab - delimiting .
18,863
def lineincustcols ( inlist , colsizes ) : outstr = '' for i in range ( len ( inlist ) ) : if type ( inlist [ i ] ) != StringType : item = str ( inlist [ i ] ) else : item = inlist [ i ] size = len ( item ) if size <= colsizes [ i ] : for j in range ( colsizes [ i ] - size ) : outstr = outstr + ' ' outstr = outstr + it...
Returns a string composed of elements in inlist with each element right - aligned in a column of width specified by a sequence colsizes . The length of colsizes must be greater than or equal to the number of columns in inlist .
18,864
def list2string ( inlist , delimit = ' ' ) : stringlist = [ makestr ( _ ) for _ in inlist ] return string . join ( stringlist , delimit )
Converts a 1D list to a single long string for file output using the string . join function .
18,865
def replace ( inlst , oldval , newval ) : lst = inlst * 1 for i in range ( len ( lst ) ) : if type ( lst [ i ] ) not in [ ListType , TupleType ] : if lst [ i ] == oldval : lst [ i ] = newval else : lst [ i ] = replace ( lst [ i ] , oldval , newval ) return lst
Replaces all occurrences of oldval with newval recursively .
18,866
def duplicates ( inlist ) : dups = [ ] for i in range ( len ( inlist ) ) : if inlist [ i ] in inlist [ i + 1 : ] : dups . append ( inlist [ i ] ) return dups
Returns duplicate items in the FIRST dimension of the passed list .
18,867
def nonrepeats ( inlist ) : nonrepeats = [ ] for i in range ( len ( inlist ) ) : if inlist . count ( inlist [ i ] ) == 1 : nonrepeats . append ( inlist [ i ] ) return nonrepeats
Returns items that are NOT duplicated in the first dim of the passed list .
18,868
def lz ( inlist , score ) : z = ( score - mean ( inlist ) ) / samplestdev ( inlist ) return z
Returns the z - score for a given input score given that score and the list from which that score came . Not appropriate for population calculations .
18,869
def llinregress ( x , y ) : TINY = 1.0e-20 if len ( x ) != len ( y ) : raise ValueError ( 'Input values not paired in linregress. Aborting.' ) n = len ( x ) x = [ float ( _ ) for _ in x ] y = [ float ( _ ) for _ in y ] xmean = mean ( x ) ymean = mean ( y ) r_num = float ( n * ( summult ( x , y ) ) - sum ( x ) * sum ( ...
Calculates a regression line on x y pairs .
18,870
def lks_2samp ( data1 , data2 ) : j1 = 0 j2 = 0 fn1 = 0.0 fn2 = 0.0 n1 = len ( data1 ) n2 = len ( data2 ) en1 = n1 en2 = n2 d = 0.0 data1 . sort ( ) data2 . sort ( ) while j1 < n1 and j2 < n2 : d1 = data1 [ j1 ] d2 = data2 [ j2 ] if d1 <= d2 : fn1 = ( j1 ) / float ( en1 ) j1 = j1 + 1 if d2 <= d1 : fn2 = ( j2 ) / float ...
Computes the Kolmogorov - Smirnof statistic on 2 samples . From Numerical Recipies in C page 493 .
18,871
def lranksums ( x , y ) : n1 = len ( x ) n2 = len ( y ) alldata = x + y ranked = rankdata ( alldata ) x = ranked [ : n1 ] y = ranked [ n1 : ] s = sum ( x ) expected = n1 * ( n1 + n2 + 1 ) / 2.0 z = ( s - expected ) / math . sqrt ( n1 * n2 * ( n1 + n2 + 1 ) / 12.0 ) prob = 2 * ( 1.0 - zprob ( abs ( z ) ) ) return z , pr...
Calculates the rank sums statistic on the provided scores and returns the result . Use only when the n in each condition is > 20 and you have 2 independent samples of ranks .
18,872
def lkruskalwallish ( * args ) : args = list ( args ) n = [ 0 ] * len ( args ) all = [ ] n = [ len ( _ ) for _ in args ] for i in range ( len ( args ) ) : all = all + args [ i ] ranked = rankdata ( all ) T = tiecorrect ( ranked ) for i in range ( len ( args ) ) : args [ i ] = ranked [ 0 : n [ i ] ] del ranked [ 0 : n [...
The Kruskal - Wallis H - test is a non - parametric ANOVA for 3 or more groups requiring at least 5 subjects in each group . This function calculates the Kruskal - Wallis H - test for 3 or more independent samples and returns the result .
18,873
def lksprob ( alam ) : fac = 2.0 sum = 0.0 termbf = 0.0 a2 = - 2.0 * alam * alam for j in range ( 1 , 201 ) : term = fac * math . exp ( a2 * j * j ) sum = sum + term if math . fabs ( term ) <= ( 0.001 * termbf ) or math . fabs ( term ) < ( 1.0e-8 * sum ) : return sum fac = - fac termbf = math . fabs ( term ) return 1.0
Computes a Kolmolgorov - Smirnov t - test significance level . Adapted from Numerical Recipies .
18,874
def outputpairedstats ( fname , writemode , name1 , n1 , m1 , se1 , min1 , max1 , name2 , n2 , m2 , se2 , min2 , max2 , statname , stat , prob ) : suffix = '' try : x = prob . shape prob = prob [ 0 ] except : pass if prob < 0.001 : suffix = ' ***' elif prob < 0.01 : suffix = ' **' elif prob < 0.05 : suffix = ' *' ti...
Prints or write to a file stats for two groups using the name n mean sterr min and max for each group as well as the statistic name its value and the associated p - value .
18,875
def GeneReader ( fh , format = 'gff' ) : known_formats = ( 'gff' , 'gtf' , 'bed' ) if format not in known_formats : print ( '%s format not in %s' % ( format , "," . join ( known_formats ) ) , file = sys . stderr ) raise Exception ( '?' ) if format == 'bed' : for line in fh : f = line . strip ( ) . split ( ) chrom = f [...
yield chrom strand gene_exons name
18,876
def get ( self , start , length ) : assert length >= 0 , "Length must be non-negative (got %d)" % length assert start >= 0 , "Start must be greater than 0 (got %d)" % start assert start + length <= self . length , "Interval beyond end of sequence (%s..%s > %s)" % ( start , start + length , self . length ) if not self ....
Fetch subsequence starting at position start with length length . This method is picky about parameters the requested interval must have non - negative length and fit entirely inside the NIB sequence the returned string will contain exactly length characters or an AssertionError will be generated .
18,877
def read_scoring_scheme ( f , gap_open , gap_extend , gap1 = "-" , gap2 = None , ** kwargs ) : close_it = False if ( type ( f ) == str ) : f = file ( f , "rt" ) close_it = True ss = build_scoring_scheme ( "" . join ( [ line for line in f ] ) , gap_open , gap_extend , gap1 = gap1 , gap2 = gap2 , ** kwargs ) if ( close_i...
Initialize scoring scheme from a file containint a blastz style text blob . f can be either a file or the name of a file .
18,878
def shuffle_columns ( a ) : mask = range ( a . text_size ) random . shuffle ( mask ) for c in a . components : c . text = '' . join ( [ c . text [ i ] for i in mask ] )
Randomize the columns of an alignment
18,879
def slice_by_component ( self , component_index , start , end ) : if type ( component_index ) == type ( 0 ) : ref = self . components [ component_index ] elif type ( component_index ) == type ( "" ) : ref = self . get_component_by_src ( component_index ) elif type ( component_index ) == Component : ref = component_inde...
Return a slice of the alignment corresponding to an coordinate interval in a specific component .
18,880
def remove_all_gap_columns ( self ) : seqs = [ ] for c in self . components : try : seqs . append ( list ( c . text ) ) except TypeError : seqs . append ( None ) i = 0 text_size = self . text_size while i < text_size : all_gap = True for seq in seqs : if seq is None : continue if seq [ i ] != '-' : all_gap = False if a...
Remove any columns containing only gaps from alignment components text of components is modified IN PLACE .
18,881
def slice_by_coord ( self , start , end ) : start_col = self . coord_to_col ( start ) end_col = self . coord_to_col ( end ) if ( self . strand == '-' ) : ( start_col , end_col ) = ( end_col , start_col ) return self . slice ( start_col , end_col )
Return the slice of the component corresponding to a coordinate interval .
18,882
def coord_to_col ( self , pos ) : start , end = self . get_forward_strand_start ( ) , self . get_forward_strand_end ( ) if pos < start or pos > end : raise ValueError ( "Range error: %d not in %d-%d" % ( pos , start , end ) ) if not self . index : self . index = list ( ) if ( self . strand == '-' ) : for x in range ( l...
Return the alignment column index corresponding to coordinate pos .
18,883
def get_components_for_species ( alignment , species ) : if len ( alignment . components ) < len ( species ) : return None index = dict ( [ ( c . src . split ( '.' ) [ 0 ] , c ) for c in alignment . components ] ) try : return [ index [ s ] for s in species ] except : return None
Return the component for each species in the list species or None
18,884
def read_next_maf ( file , species_to_lengths = None , parse_e_rows = False ) : alignment = Alignment ( species_to_lengths = species_to_lengths ) line = readline ( file , skip_blank = True ) if not line : return None fields = line . split ( ) if fields [ 0 ] != 'a' : raise Exception ( "Expected 'a ...' line" ) alignmen...
Read the next MAF block from file and return as an Alignment instance . If parse_i_rows is true empty components will be created when e rows are encountered .
18,885
def readline ( file , skip_blank = False ) : while 1 : line = file . readline ( ) if not line : return None if line [ 0 ] != '#' and not ( skip_blank and line . isspace ( ) ) : return line
Read a line from provided file skipping any blank or comment lines
18,886
def parse_attributes ( fields ) : attributes = { } for field in fields : pair = field . split ( '=' ) attributes [ pair [ 0 ] ] = pair [ 1 ] return attributes
Parse list of key = value strings into a dict
18,887
def as_dict ( self , key = "id" ) : rval = { } for motif in self : rval [ getattr ( motif , key ) ] = motif return rval
Return a dictionary containing all remaining motifs using key as the dictionary key .
18,888
def parse_record ( self , lines ) : temp_lines = [ ] for line in lines : fields = line . rstrip ( "\r\n" ) . split ( None , 1 ) if len ( fields ) == 1 : fields . append ( "" ) temp_lines . append ( fields ) lines = temp_lines motif = TransfacMotif ( ) current_line = 0 while 1 : if current_line >= len ( lines ) : break ...
Parse a TRANSFAC record out of lines and return a motif .
18,889
def bit_clone ( bits ) : new = BitSet ( bits . size ) new . ior ( bits ) return new
Clone a bitset
18,890
def throw_random ( lengths , mask ) : saved = None for i in range ( maxtries ) : try : return throw_random_bits ( lengths , mask ) except MaxtriesException as e : saved = e continue raise e
Try multiple times to run throw_random
18,891
def as_bits ( region_start , region_length , intervals ) : bits = BitSet ( region_length ) for chr , start , stop in intervals : bits . set_range ( start - region_start , stop - start ) return bits
Convert a set of intervals overlapping a region of a chromosome into a bitset for just that region with the bits covered by the intervals set .
18,892
def interval_lengths ( bits ) : end = 0 while 1 : start = bits . next_set ( end ) if start == bits . size : break end = bits . next_clear ( start ) yield end - start
Get the length distribution of all contiguous runs of set bits from
18,893
def count_overlap ( bits1 , bits2 ) : b = BitSet ( bits1 . size ) b |= bits1 b &= bits2 return b . count_range ( 0 , b . size )
Count the number of bits that overlap between two sets
18,894
def overlapping_in_bed ( fname , r_chr , r_start , r_stop ) : rval = [ ] for line in open ( fname ) : if line . startswith ( "#" ) or line . startswith ( "track" ) : continue fields = line . split ( ) chr , start , stop = fields [ 0 ] , int ( fields [ 1 ] ) , int ( fields [ 2 ] ) if chr == r_chr and start < r_stop and ...
Get from a bed all intervals that overlap the region defined by r_chr r_start r_stop .
18,895
def tile_interval ( sources , index , ref_src , start , end , seq_db = None ) : assert sources [ 0 ] . split ( '.' ) [ 0 ] == ref_src . split ( '.' ) [ 0 ] , "%s != %s" % ( sources [ 0 ] . split ( '.' ) [ 0 ] , ref_src . split ( '.' ) [ 0 ] ) base_len = end - start blocks = index . get ( ref_src , start , end ) blocks ...
Tile maf blocks onto an interval . The resulting block will span the interval exactly and contain the column from the highest scoring alignment at each position .
18,896
def get_fill_char ( maf_status ) : if maf_status in ( maf . MAF_NEW_STATUS , maf . MAF_MAYBE_NEW_STATUS , maf . MAF_NEW_NESTED_STATUS , maf . MAF_MAYBE_NEW_NESTED_STATUS ) : return "*" elif maf_status in ( maf . MAF_INVERSE_STATUS , maf . MAF_INSERT_STATUS ) : return "=" elif maf_status in ( maf . MAF_CONTIG_STATUS , m...
Return the character that should be used to fill between blocks having a given status
18,897
def guess_fill_char ( left_comp , right_comp ) : return "*" if ( left_comp . src == right_comp . src and left_comp . strand != right_comp . strand ) : if left_comp . end == right_comp . start : return "-" return "*"
For the case where there is no annotated synteny we will try to guess it
18,898
def remove_all_gap_columns ( texts ) : seqs = [ list ( t ) for t in texts ] i = 0 text_size = len ( texts [ 0 ] ) while i < text_size : all_gap = True for seq in seqs : if seq [ i ] not in ( '-' , '#' , '*' , '=' , 'X' , '@' ) : all_gap = False if all_gap : for seq in seqs : del seq [ i ] text_size -= 1 else : i += 1 r...
Remove any columns containing only gaps from alignment texts
18,899
def cross_lists ( * sets ) : wheels = [ iter ( _ ) for _ in sets ] digits = [ next ( it ) for it in wheels ] while True : yield digits [ : ] for i in range ( len ( digits ) - 1 , - 1 , - 1 ) : try : digits [ i ] = next ( wheels [ i ] ) break except StopIteration : wheels [ i ] = iter ( sets [ i ] ) digits [ i ] = next ...
Return the cross product of the arguments