idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
41,000
def from_str ( cls , s ) : ast_obj = ast . parse ( s ) . body [ 0 ] if not isinstance ( ast_obj , cls . _expected_ast_type ) : raise AssertionError ( 'Expected ast of type {!r} but got {!r}' . format ( cls . _expected_ast_type , ast_obj ) ) return cls ( ast_obj )
Construct an import object from a string .
41,001
def sort ( imports , separate = True , import_before_from = True , ** classify_kwargs ) : if separate : def classify_func ( obj ) : return classify_import ( obj . import_statement . module , ** classify_kwargs ) types = ImportType . __all__ else : def classify_func ( obj ) : return classify_import ( obj . import_statem...
Sort import objects into groups .
41,002
def classify_import ( module_name , application_directories = ( '.' , ) ) : base , _ , _ = module_name . partition ( '.' ) found , module_path , is_builtin = _get_module_info ( base , application_directories , ) if base == '__future__' : return ImportType . FUTURE elif base == '' : return ImportType . APPLICATION elif ...
Classifies an import by its package .
41,003
def _arg_parser ( ) : parser = argparse . ArgumentParser ( description = __doc__ ) parser . add_argument ( 'xml' , nargs = '*' ) return parser
Factory for creating the argument parser
41,004
def validate_cnxml ( * content_filepaths ) : content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ] return jing ( CNXML_JING_RNG , * content_filepaths )
Validates the given CNXML file against the cnxml - jing . rng RNG .
41,005
def validate_collxml ( * content_filepaths ) : content_filepaths = [ Path ( path ) . resolve ( ) for path in content_filepaths ] return jing ( COLLXML_JING_RNG , * content_filepaths )
Validates the given COLLXML file against the collxml - jing . rng RNG .
41,006
def action ( args ) : log . info ( 'loading reference package' ) r = refpkg . Refpkg ( args . refpkg , create = False ) q = r . contents for i in range ( args . n ) : if q [ 'rollback' ] is None : log . error ( 'Cannot rollback {} changes; ' 'refpkg only records {} changes.' . format ( args . n , i ) ) return 1 else : ...
Roll back commands on a refpkg .
41,007
def set_targets ( x , delta = 10 ) : data = [ ] for row , _ in x . iterrows ( ) : if row == x . shape [ 0 ] - 1 : break curr_close = x . close [ row ] next_close = x . close [ row + 1 ] high_close = next_close + ( delta / 2 ) low_close = next_close - ( delta / 2 ) if curr_close < low_close : target = TARGET_CODES [ 'be...
Sets target market trend for a date
41,008
def eval_features ( json ) : return { 'close' : json [ - 1 ] [ 'close' ] , 'sma' : SMA . eval_from_json ( json ) , 'rsi' : RSI . eval_from_json ( json ) , 'so' : SO . eval_from_json ( json ) , 'obv' : OBV . eval_from_json ( json ) }
Gets technical analysis features from market data JSONs
41,009
def target_code_to_name ( code ) : TARGET_NAMES = { v : k for k , v in TARGET_CODES . items ( ) } return TARGET_NAMES [ code ]
Converts an int target code to a target name
41,010
def setup_model ( x , y , model_type = 'random_forest' , seed = None , ** kwargs ) : assert len ( x ) > 1 and len ( y ) > 1 , 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))' . format ( len ( x ) , len ( y ) ) sets = namedtuple ( 'Datasets' , [ 'train' , 'test' ] ) x_train...
Initializes a machine learning model
41,011
def get_json ( self ) : today = dt . now ( ) DIRECTION = 'last' epochs = date . get_end_start_epochs ( today . year , today . month , today . day , DIRECTION , self . unit , self . count ) return poloniex . chart_json ( epochs [ 'shifted' ] , epochs [ 'initial' ] , self . period , self . symbol ) [ 0 ]
Gets market chart data from today to a previous date
41,012
def set_features ( self , partition = 1 ) : if len ( self . json ) < partition + 1 : raise ValueError ( 'Not enough dates for the specified partition size: {0}. Try a smaller partition.' . format ( partition ) ) data = [ ] for offset in range ( len ( self . json ) - partition ) : json = self . json [ offset : offset +...
Parses market data JSON for technical analysis indicators
41,013
def set_long_features ( self , features , columns_to_set = [ ] , partition = 2 ) : features_long = self . set_features ( partition = 2 * partition ) unwanted_features = [ f for f in features . columns if f not in columns_to_set ] features_long = features_long . drop ( unwanted_features , axis = 1 ) features_long . colu...
Sets features of double the duration
41,014
def feature_importances ( self ) : feature_names = [ feature for feature in self . features . train ] return list ( zip ( feature_names , self . feature_importances_ ) )
Return list of features and their importance in classification
41,015
def stop ( self ) : if self . _http_server is not None : self . _http_server . stop ( ) tornado . ioloop . IOLoop . instance ( ) . add_callback ( tornado . ioloop . IOLoop . instance ( ) . stop )
Stop the worker .
41,016
def run ( self ) : setproctitle . setproctitle ( "{:s}: worker {:s}" . format ( self . context . config . name , self . _tornado_app . settings [ 'interface' ] . name ) ) self . logger . info ( "Worker '%s' has been started with pid %d" , self . _tornado_app . settings [ 'interface' ] . name , os . getpid ( ) ) self . ...
Tornado worker which handles HTTP requests .
41,017
def initialize ( self ) : self . main_pid = os . getpid ( ) self . processes . extend ( self . init_service_processes ( ) ) self . processes . extend ( self . init_tornado_workers ( ) )
Initialize instance attributes . You can override this method in the subclasses .
41,018
def scratch_file ( unlink = True , ** kwargs ) : kwargs [ 'delete' ] = False tf = tempfile . NamedTemporaryFile ( ** kwargs ) tf . close ( ) try : yield tf . name finally : if unlink : os . unlink ( tf . name )
Create a temporary file and return its name .
41,019
def open ( self , name , * mode ) : return self . file_factory ( self . file_path ( name ) , * mode )
Return an open file object for a file in the reference package .
41,020
def open_resource ( self , resource , * mode ) : return self . open ( self . resource_name ( resource ) , * mode )
Return an open file object for a particular named resource in this reference package .
41,021
def resource_name ( self , resource ) : if not ( resource in self . contents [ 'files' ] ) : raise ValueError ( "No such resource %r in refpkg" % ( resource , ) ) return self . contents [ 'files' ] [ resource ]
Return the name of the file within the reference package for a particular named resource .
41,022
def resource_md5 ( self , resource ) : if not ( resource in self . contents [ 'md5' ] ) : raise ValueError ( "No such resource %r in refpkg" % ( resource , ) ) return self . contents [ 'md5' ] [ resource ]
Return the stored MD5 sum for a particular named resource .
41,023
def _set_defaults ( self ) : self . contents . setdefault ( 'log' , [ ] ) self . contents . setdefault ( 'rollback' , None ) self . contents . setdefault ( 'rollforward' , None )
Set some default values in the manifest .
41,024
def _sync_to_disk ( self ) : with self . open_manifest ( 'w' ) as h : json . dump ( self . contents , h , indent = 4 ) h . write ( '\n' )
Write any changes made on Refpkg to disk .
41,025
def _sync_from_disk ( self ) : try : fobj = self . open_manifest ( 'r' ) except IOError as e : if e . errno == errno . ENOENT : raise ValueError ( "couldn't find manifest file in %s" % ( self . path , ) ) elif e . errno == errno . ENOTDIR : raise ValueError ( "%s is not a directory" % ( self . path , ) ) else : raise w...
Read any changes made on disk to this Refpkg .
41,026
def _add_file ( self , key , path ) : filename = os . path . basename ( path ) base , ext = os . path . splitext ( filename ) if os . path . exists ( self . file_path ( filename ) ) : with tempfile . NamedTemporaryFile ( dir = self . path , prefix = base , suffix = ext ) as tf : filename = os . path . basename ( tf . n...
Copy a file into the reference package .
41,027
def is_invalid ( self ) : for k in [ 'metadata' , 'files' , 'md5' ] : if not ( k in self . contents ) : return "Manifest file missing key %s" % k if not ( isinstance ( self . contents [ k ] , dict ) ) : return "Key %s in manifest did not refer to a dictionary" % k if not ( 'rollback' in self . contents ) : return "Mani...
Check if this RefPkg is invalid .
41,028
def reroot ( self , rppr = None , pretend = False ) : with scratch_file ( prefix = 'tree' , suffix = '.tre' ) as name : subprocess . check_call ( [ rppr or 'rppr' , 'reroot' , '-c' , self . path , '-o' , name ] ) if not ( pretend ) : self . update_file ( 'tree' , name ) self . _log ( 'Rerooting refpkg' )
Reroot the phylogenetic tree .
41,029
def update_phylo_model ( self , stats_type , stats_file , frequency_type = None ) : if frequency_type not in ( None , 'model' , 'empirical' ) : raise ValueError ( 'Unknown frequency type: "{0}"' . format ( frequency_type ) ) if frequency_type and stats_type not in ( None , 'PhyML' ) : raise ValueError ( 'Frequency type...
Parse a stats log and use it to update phylo_model .
41,030
def rollback ( self ) : if self . contents [ 'rollback' ] is None : raise ValueError ( "No operation to roll back on refpkg" ) future_msg = self . contents [ 'log' ] [ 0 ] rolledback_log = self . contents [ 'log' ] [ 1 : ] rollforward = copy . deepcopy ( self . contents ) rollforward . pop ( 'rollback' ) self . content...
Revert the previous modification to the refpkg .
41,031
def rollforward ( self ) : if self . contents [ 'rollforward' ] is None : raise ValueError ( "No operation to roll forward on refpkg" ) new_log_message = self . contents [ 'rollforward' ] [ 0 ] new_contents = self . contents [ 'rollforward' ] [ 1 ] new_contents [ 'log' ] = [ new_log_message ] + self . contents . pop ( ...
Restore a reverted modification to the refpkg .
41,032
def strip ( self ) : self . _sync_from_disk ( ) current_filenames = set ( self . contents [ 'files' ] . values ( ) ) all_filenames = set ( os . listdir ( self . path ) ) to_delete = all_filenames . difference ( current_filenames ) to_delete . discard ( 'CONTENTS.json' ) for f in to_delete : self . _delete_file ( f ) se...
Remove rollbacks rollforwards and all non - current files .
41,033
def start_transaction ( self ) : if self . current_transaction : raise ValueError ( "There is already a transaction going" ) else : initial_state = copy . deepcopy ( self . contents ) self . current_transaction = { 'rollback' : initial_state , 'log' : '(Transaction left no log message)' }
Begin a transaction to group operations on the refpkg .
41,034
def is_ill_formed ( self ) : m = self . is_invalid ( ) if m : return m required_keys = ( 'aln_fasta' , 'aln_sto' , 'seq_info' , 'tree' , 'taxonomy' , 'phylo_model' ) for k in required_keys : if k not in self . contents [ 'files' ] : return "RefPkg has no key " + k with self . open_resource ( 'aln_fasta' ) as f : firstl...
Stronger set of checks than is_invalid for Refpkg .
41,035
def load_db ( self ) : db = taxdb . Taxdb ( ) db . create_tables ( ) reader = csv . DictReader ( self . open_resource ( 'taxonomy' , 'rU' ) ) db . insert_from_taxtable ( lambda : reader . _fieldnames , reader ) curs = db . cursor ( ) reader = csv . DictReader ( self . open_resource ( 'seq_info' , 'rU' ) ) curs . execut...
Load the taxonomy into a sqlite3 database .
41,036
def most_recent_common_ancestor ( self , * ts ) : if len ( ts ) > 200 : res = self . _large_mrca ( ts ) else : res = self . _small_mrca ( ts ) if res : ( res , ) , = res else : raise NoAncestor ( ) return res
Find the MRCA of some tax_ids .
41,037
def main ( args = None ) : parser = ArgumentParser ( add_help = False ) parser . add_argument ( '-s' , '--settings' , dest = 'settings' , action = 'store' , type = str , default = None , help = _ ( 'application settings module' ) ) try : settings = get_app_settings ( parser , args ) except ImportError as exc : parser ....
Run management command handled from command line .
41,038
def as_length ( self , value ) : new_vec = self . copy ( ) new_vec . length = value return new_vec
Return a new vector scaled to given length
41,039
def as_percent ( self , value ) : new_vec = self . copy ( ) new_vec . length = value * self . length return new_vec
Return a new vector scaled by given decimal percent
41,040
def angle ( self , vec , unit = 'rad' ) : if not isinstance ( vec , self . __class__ ) : raise TypeError ( 'Angle operand must be of class {}' . format ( self . __class__ . __name__ ) ) if unit not in [ 'deg' , 'rad' ] : raise ValueError ( 'Only units of rad or deg are supported' ) denom = self . length * vec . length ...
Calculate the angle between two Vectors
41,041
def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray )
Array of vector lengths
41,042
def cross ( self , vec ) : if not isinstance ( vec , Vector3Array ) : raise TypeError ( 'Cross product operand must be a Vector3Array' ) if self . nV != 1 and vec . nV != 1 and self . nV != vec . nV : raise ValueError ( 'Cross product operands must have the same ' 'number of elements.' ) return Vector3Array ( np . cros...
Cross product with another Vector3Array
41,043
def eval_rs ( gains , losses ) : count = len ( gains ) + len ( losses ) avg_gains = stats . avg ( gains , count = count ) if gains else 1 avg_losses = stats . avg ( losses , count = count ) if losses else 1 if avg_losses == 0 : return avg_gains else : return avg_gains / avg_losses
Evaluates the RS variable in RSI algorithm
41,044
def action ( args ) : log . info ( 'loading reference package' ) pkg = refpkg . Refpkg ( args . refpkg , create = False ) with open ( pkg . file_abspath ( 'seq_info' ) , 'rU' ) as seq_info : seqinfo = list ( csv . DictReader ( seq_info ) ) snames = [ row [ 'seqname' ] for row in seqinfo ] if args . seq_names : print ( ...
Show information about reference packages .
41,045
def json_to_url ( json , symbol ) : start = json [ 0 ] [ 'date' ] end = json [ - 1 ] [ 'date' ] diff = end - start periods = [ 300 , 900 , 1800 , 7200 , 14400 , 86400 ] diffs = { } for p in periods : diffs [ p ] = abs ( 1 - ( p / ( diff / len ( json ) ) ) ) period = min ( diffs , key = diffs . get ) url = ( 'https://po...
Converts a JSON to a URL by the Poloniex API
41,046
def parse_changes ( json ) : changes = [ ] dates = len ( json ) for date in range ( 1 , dates ) : last_close = json [ date - 1 ] [ 'close' ] now_close = json [ date ] [ 'close' ] changes . append ( now_close - last_close ) logger . debug ( 'Market Changes (from JSON):\n{0}' . format ( changes ) ) return changes
Gets price changes from JSON
41,047
def get_gains_losses ( changes ) : res = { 'gains' : [ ] , 'losses' : [ ] } for change in changes : if change > 0 : res [ 'gains' ] . append ( change ) else : res [ 'losses' ] . append ( change * - 1 ) logger . debug ( 'Gains: {0}' . format ( res [ 'gains' ] ) ) logger . debug ( 'Losses: {0}' . format ( res [ 'losses' ...
Categorizes changes into gains and losses
41,048
def get_attribute ( json , attr ) : res = [ json [ entry ] [ attr ] for entry , _ in enumerate ( json ) ] logger . debug ( '{0}s (from JSON):\n{1}' . format ( attr , res ) ) return res
Gets the values of an attribute from JSON
41,049
def get_json_shift ( year , month , day , unit , count , period , symbol ) : epochs = date . get_end_start_epochs ( year , month , day , 'last' , unit , count ) return chart_json ( epochs [ 'shifted' ] , epochs [ 'initial' ] , period , symbol ) [ 0 ]
Gets JSON from shifted date by the Poloniex API
41,050
def filter_ranks ( results ) : for _ , group in itertools . groupby ( results , operator . itemgetter ( 0 ) ) : yield next ( group )
Find just the first rank for all the results for a given tax_id .
41,051
def eval_algorithm ( closing , low , high ) : if high - low == 0 : return 100 * ( closing - low ) else : return 100 * ( closing - low ) / ( high - low )
Evaluates the SO algorithm
41,052
def avg ( vals , count = None ) : sum = 0 for v in vals : sum += v if count is None : count = len ( vals ) return float ( sum ) / count
Returns the average value
41,053
def db_connect ( engine , schema = None , clobber = False ) : if schema is None : base = declarative_base ( ) else : try : engine . execute ( sqlalchemy . schema . CreateSchema ( schema ) ) except sqlalchemy . exc . ProgrammingError as err : logging . warn ( err ) base = declarative_base ( metadata = MetaData ( schema ...
Create a connection object to a database . Attempt to establish a schema . If there are existing tables delete them if clobber is True and return otherwise . Returns a sqlalchemy engine object .
41,054
def read_nodes ( rows , source_id = 1 ) : ncbi_keys = [ 'tax_id' , 'parent_id' , 'rank' , 'embl_code' , 'division_id' ] extra_keys = [ 'source_id' , 'is_valid' ] is_valid = True ncbi_cols = len ( ncbi_keys ) rank = ncbi_keys . index ( 'rank' ) parent_id = ncbi_keys . index ( 'parent_id' ) row = next ( rows ) row [ rank...
Return an iterator of rows ready to insert into table nodes .
41,055
def fetch_data ( dest_dir = '.' , clobber = False , url = DATA_URL ) : dest_dir = os . path . abspath ( dest_dir ) try : os . mkdir ( dest_dir ) except OSError : pass fout = os . path . join ( dest_dir , os . path . split ( url ) [ - 1 ] ) if os . access ( fout , os . F_OK ) and not clobber : downloaded = False logging...
Download data from NCBI required to generate local taxonomy database . Default url is ncbi . DATA_URL
41,056
def read_archive ( archive , fname ) : zfile = zipfile . ZipFile ( archive ) contents = zfile . open ( fname , 'r' ) fobj = io . TextIOWrapper ( contents ) seen = set ( ) for line in fobj : line = line . rstrip ( '\t|\n' ) if line not in seen : yield line . split ( '\t|\t' ) seen . add ( line )
Return an iterator of unique rows from a zip archive .
41,057
def prepend_schema ( self , name ) : return '.' . join ( [ self . schema , name ] ) if self . schema else name
Prepend schema name to name when a schema is specified
41,058
def load_table ( self , table , rows , colnames = None , limit = None ) : conn = self . engine . raw_connection ( ) cur = conn . cursor ( ) colnames = colnames or next ( rows ) cmd = 'INSERT INTO {table} ({colnames}) VALUES ({placeholders})' . format ( table = self . tables [ table ] , colnames = ', ' . join ( colnames...
Load rows into table table . If colnames is not provided the first element of rows must provide column names .
41,059
def load_archive ( self , archive ) : self . load_table ( 'source' , rows = [ ( 'ncbi' , DATA_URL ) ] , colnames = [ 'name' , 'description' ] , ) conn = self . engine . raw_connection ( ) cur = conn . cursor ( ) cmd = "select id from {source} where name = 'ncbi'" . format ( ** self . tables ) cur . execute ( cmd ) sour...
Load data from the zip archive of the NCBI taxonomy .
41,060
def date_to_epoch ( year , month , day ) : return int ( date_to_delorean ( year , month , day ) . epoch )
Converts a date to epoch in UTC
41,061
def get_end_start_epochs ( year , month , day , direction , unit , count ) : if year or month or day : if not year : year = 2017 if not month : month = 1 if not day : day = 1 initial_delorean = date_to_delorean ( year , month , day ) else : count += 1 initial_delorean = now_delorean ( ) initial_epoch = int ( initial_de...
Gets epoch from a start date and epoch from a shifted date
41,062
def add_child ( self , child ) : assert child != self child . parent = self child . ranks = self . ranks child . index = self . index assert child . tax_id not in self . index self . index [ child . tax_id ] = child self . children . add ( child )
Add a child to this node .
41,063
def remove_child ( self , child ) : assert child in self . children self . children . remove ( child ) self . index . pop ( child . tax_id ) if child . parent is self : child . parent = None if child . index is self . index : child . index = None for n in child : if n is child : continue self . index . pop ( n . tax_id...
Remove a child from this node .
41,064
def drop ( self ) : if self . is_root : raise ValueError ( "Cannot drop root node!" ) parent = self . parent for child in self . children : child . parent = parent parent . children . add ( child ) self . children = set ( ) parent . sequence_ids . update ( self . sequence_ids ) self . sequence_ids = set ( ) parent . re...
Remove this node from the taxonomy maintaining child subtrees by adding them to the node s parent and moving sequences at this node to the parent .
41,065
def prune_unrepresented ( self ) : for node in self . depth_first_iter ( self_first = False ) : if ( not node . children and not node . sequence_ids and node is not self ) : node . parent . remove_child ( node )
Remove nodes without sequences or children below this node .
41,066
def at_rank ( self , rank ) : s = self while s : if s . rank == rank : return s s = s . parent raise ValueError ( "No node at rank {0} for {1}" . format ( rank , self . tax_id ) )
Find the node above this node at rank rank
41,067
def depth_first_iter ( self , self_first = True ) : if self_first : yield self for child in list ( self . children ) : for i in child . depth_first_iter ( self_first ) : yield i if not self_first : yield self
Iterate over nodes below this node optionally yielding children before self .
41,068
def path ( self , tax_ids ) : assert tax_ids [ 0 ] == self . tax_id if len ( tax_ids ) == 1 : return self n = tax_ids [ 1 ] try : child = next ( i for i in self . children if i . tax_id == n ) except StopIteration : raise ValueError ( n ) return child . path ( tax_ids [ 1 : ] )
Get the node at the end of the path described by tax_ids .
41,069
def lineage ( self ) : if not self . parent : return [ self ] else : L = self . parent . lineage ( ) L . append ( self ) return L
Return all nodes between this node and the root including this one .
41,070
def write_taxtable ( self , out_fp , ** kwargs ) : ranks_represented = frozenset ( i . rank for i in self ) | frozenset ( i . rank for i in self . lineage ( ) ) ranks = [ i for i in self . ranks if i in ranks_represented ] assert len ( ranks_represented ) == len ( ranks ) def node_record ( node ) : parent_id = node . p...
Write a taxtable for this node and all descendants including the lineage leading to this node .
41,071
def populate_from_seqinfo ( self , seqinfo ) : for row in csv . DictReader ( seqinfo ) : node = self . index . get ( row [ 'tax_id' ] ) if node : node . sequence_ids . add ( row [ 'seqname' ] )
Populate sequence_ids below this node from a seqinfo file object .
41,072
def collapse ( self , remove = False ) : descendants = iter ( self ) assert next ( descendants ) is self for descendant in descendants : self . sequence_ids . update ( descendant . sequence_ids ) descendant . sequence_ids . clear ( ) if remove : for node in self . children : self . remove_child ( node )
Move all sequence_ids in the subtree below this node to this node .
41,073
def write_seqinfo ( self , out_fp , include_name = True ) : header = [ 'seqname' , 'tax_id' ] if include_name : header . append ( 'tax_name' ) w = csv . DictWriter ( out_fp , header , quoting = csv . QUOTE_NONNUMERIC , lineterminator = '\n' , extrasaction = 'ignore' ) w . writeheader ( ) rows = ( { 'seqname' : seq_id ,...
Write a simple seq_info file suitable for use in taxtastic . Useful for printing out the results of collapsing tax nodes - super bare bones just tax_id and seqname .
41,074
def from_taxtable ( cls , taxtable_fp ) : r = csv . reader ( taxtable_fp ) headers = next ( r ) rows = ( collections . OrderedDict ( list ( zip ( headers , i ) ) ) for i in r ) row = next ( rows ) root = cls ( rank = row [ 'rank' ] , tax_id = row [ 'tax_id' ] , name = row [ 'tax_name' ] ) path_root = headers . index ( ...
Generate a node from an open handle to a taxtable as generated by taxit taxtable
41,075
def get_children ( engine , parent_ids , rank = 'species' , schema = None ) : if not parent_ids : return [ ] nodes = schema + '.nodes' if schema else 'nodes' names = schema + '.names' if schema else 'names' cmd = ( 'select tax_id, tax_name, rank ' 'from {} join {} using (tax_id) ' 'where parent_id = :tax_id and is_prim...
Recursively fetch children of tax_ids in parent_ids until the rank of rank
41,076
def action ( args ) : log . info ( 'loading reference package' ) pairs = [ p . split ( '=' , 1 ) for p in args . changes ] if args . metadata : rp = refpkg . Refpkg ( args . refpkg , create = False ) rp . start_transaction ( ) for key , value in pairs : rp . update_metadata ( key , value ) rp . commit_transaction ( 'Up...
Updates a Refpkg with new files .
41,077
def parse_arguments ( argv ) : parser = argparse . ArgumentParser ( description = DESCRIPTION ) base_parser = argparse . ArgumentParser ( add_help = False ) parser . add_argument ( '-V' , '--version' , action = 'version' , version = 'taxit v' + version , help = 'Print the version number and exit' ) parser . add_argumen...
Create the argument parser
41,078
def execute ( self , statements , exc = IntegrityError , rasie_as = ValueError ) : Session = sessionmaker ( bind = self . engine ) session = Session ( ) try : for statement in statements : session . execute ( statement ) except exc as err : session . rollback ( ) raise rasie_as ( str ( err ) ) else : session . commit (...
Execute statements in a session and perform a rollback on error . exc is a single exception object or a tuple of objects to be used in the except clause . The error message is re - raised as the exception specified by raise_as .
41,079
def _node ( self , tax_id ) : s = select ( [ self . nodes . c . parent_id , self . nodes . c . rank ] , self . nodes . c . tax_id == tax_id ) res = s . execute ( ) output = res . fetchone ( ) if not output : msg = 'value "{}" not found in nodes.tax_id' . format ( tax_id ) raise ValueError ( msg ) else : return output
Returns parent_id rank
41,080
def primary_from_id ( self , tax_id ) : s = select ( [ self . names . c . tax_name ] , and_ ( self . names . c . tax_id == tax_id , self . names . c . is_primary ) ) res = s . execute ( ) output = res . fetchone ( ) if not output : msg = 'value "{}" not found in names.tax_id' . format ( tax_id ) raise ValueError ( msg ...
Returns primary taxonomic name associated with tax_id
41,081
def primary_from_name ( self , tax_name ) : names = self . names s1 = select ( [ names . c . tax_id , names . c . is_primary ] , names . c . tax_name == tax_name ) log . debug ( str ( s1 ) ) res = s1 . execute ( ) . fetchone ( ) if res : tax_id , is_primary = res else : msg = '"{}" not found in names.tax_names' . forma...
Return tax_id and primary tax_name corresponding to tax_name .
41,082
def lineage ( self , tax_id = None , tax_name = None ) : if not bool ( tax_id ) ^ bool ( tax_name ) : msg = 'Exactly one of tax_id and tax_name may be provided.' raise ValueError ( msg ) if tax_name : tax_id , primary_name , is_primary = self . primary_from_name ( tax_name ) else : primary_name = None lintups = self . ...
Public method for returning a lineage ; includes tax_name and rank
41,083
def verify_rank_integrity ( self , tax_id , rank , parent_id , children ) : def _lower ( n1 , n2 ) : return self . ranks . index ( n1 ) < self . ranks . index ( n2 ) if rank not in self . ranks : raise TaxonIntegrityError ( 'rank "{}" is undefined' . format ( rank ) ) parent_rank = self . rank ( parent_id ) if not _low...
Confirm that for each node the parent ranks and children ranks are coherent
41,084
def add_node ( self , tax_id , parent_id , rank , names , source_name , children = None , is_valid = True , execute = True , ** ignored ) : if ignored : log . info ( 'some arguments were ignored: {} ' . format ( str ( ignored ) ) ) children = children or [ ] self . verify_rank_integrity ( tax_id , rank , parent_id , ch...
Add a node to the taxonomy .
41,085
def add_names ( self , tax_id , names , execute = True ) : primary_names = [ n [ 'tax_name' ] for n in names if n . get ( 'is_primary' ) ] if len ( primary_names ) > 1 : raise ValueError ( '`is_primary` may be True for no more than one name in `names`' ) statements = [ ] for namevals in names : if 'tax_id' in namevals ...
Associate one or more names with tax_id .
41,086
def tax_ids ( self ) : fetch = select ( [ self . nodes . c . tax_id ] ) . execute ( ) . fetchall ( ) ids = [ t [ 0 ] for t in fetch ] return ids
Return all tax_ids in node table
41,087
def validate_db ( sqlalchemy_bind , is_enabled = ENABLE_DB ) : def decorator ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : def is_db_responsive ( ) : try : sqlalchemy_bind . session . query ( '1' ) . first_or_404 ( ) except : return False else : return True if is_enabled and is_db_responsive ( ) : re...
Checks if a DB is authorized and responding before executing the function
41,088
def get_new_nodes ( fname ) : with open ( fname , 'rU' ) as infile : infile = ( line for line in infile if not line . startswith ( '#' ) ) reader = list ( csv . DictReader ( infile ) ) rows = ( d for d in reader if d [ 'tax_id' ] ) for d in rows : if 'children' in d : if d [ 'children' ] : d [ 'children' ] = [ x . stri...
Return an iterator of dicts given a . csv - format file .
41,089
def parse_raxml ( handle ) : s = '' . join ( handle . readlines ( ) ) result = { } try_set_fields ( result , r'(?P<program>RAxML version [0-9.]+)' , s ) try_set_fields ( result , r'(?P<datatype>DNA|RNA|AA)' , s ) result [ 'empirical_frequencies' ] = ( result [ 'datatype' ] != 'AA' or re . search ( 'empirical base frequ...
Parse RAxML s summary output .
41,090
def parse_stockholm ( fobj ) : names = OrderedDict ( ) found_eof = False for line in fobj : line = line . strip ( ) if line == '//' : found_eof = True elif line . startswith ( '#' ) or not line . strip ( ) : continue else : name , __ = line . split ( None , 1 ) names [ name ] = None if not found_eof : raise ValueError ...
Return a list of names from an Stockholm - format sequence alignment file . fobj is an open file or another object representing a sequence of lines .
41,091
def has_rppr ( rppr_name = 'rppr' ) : with open ( os . devnull ) as dn : try : subprocess . check_call ( [ rppr_name ] , stdout = dn , stderr = dn ) except OSError as e : if e . errno == os . errno . ENOENT : return False else : raise except subprocess . CalledProcessError as e : pass return True
Check for rppr binary in path
41,092
def add_database_args ( parser ) : parser . add_argument ( 'url' , nargs = '?' , default = 'sqlite:///ncbi_taxonomy.db' , type = sqlite_default ( ) , help = ( 'Database string URI or filename. If no database scheme ' 'specified \"sqlite:///\" will be prepended. [%(default)s]' ) ) db_parser = parser . add_argument_grou...
Add a standard set of database arguments for argparse
41,093
def sqlite_default ( ) : def parse_url ( url ) : if url . endswith ( '.db' ) or url . endswith ( '.sqlite' ) : if not url . startswith ( 'sqlite:///' ) : url = 'sqlite:///' + url elif url . endswith ( '.cfg' ) or url . endswith ( '.conf' ) : conf = configparser . SafeConfigParser ( allow_no_value = True ) conf . option...
Prepend default scheme if none is specified . This helps provides backwards compatibility with old versions of taxtastic where sqlite was the automatic default database .
41,094
def action ( args ) : log . info ( 'loading reference package' ) refpkg . Refpkg ( args . refpkg , create = False ) . strip ( )
Strips non - current files and rollback information from a refpkg .
41,095
def name ( self ) : try : return self . config_parser . get ( 'application' , 'name' ) except CONFIGPARSER_EXC : return super ( IniConfig , self ) . name
Application name . It s used as a process name .
41,096
def tz_file ( name ) : try : filepath = tz_path ( name ) return open ( filepath , 'rb' ) except TimezoneNotFound : try : from pkg_resources import resource_stream except ImportError : resource_stream = None if resource_stream is not None : try : return resource_stream ( __name__ , 'zoneinfo/' + name ) except FileNotFou...
Open a timezone file from the zoneinfo subdir for reading .
41,097
def tz_path ( name ) : if not name : raise ValueError ( 'Invalid timezone' ) name_parts = name . lstrip ( '/' ) . split ( '/' ) for part in name_parts : if part == os . path . pardir or os . path . sep in part : raise ValueError ( 'Bad path segment: %r' % part ) filepath = os . path . join ( _DIRECTORY , * name_parts )...
Return the path to a timezone file .
41,098
def get_timezones ( ) : base_dir = _DIRECTORY zones = ( ) for root , dirs , files in os . walk ( base_dir ) : for basename in files : zone = os . path . join ( root , basename ) if os . path . isdir ( zone ) : continue zone = os . path . relpath ( zone , base_dir ) with open ( os . path . join ( root , basename ) , 'rb...
Get the supported timezones .
41,099
def award_points ( target , key , reason = "" , source = None ) : point_value , points = get_points ( key ) if not ALLOW_NEGATIVE_TOTALS : total = points_awarded ( target ) if total + points < 0 : reason = reason + "(floored from {0} to 0)" . format ( points ) points = - total apv = AwardedPointValue ( points = points ...
Awards target the point value for key . If key is an integer then it s a one off assignment and should be interpreted as the actual point value .