_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q273000
Coalescent.attach_to_tree
test
def attach_to_tree(self): ''' attaches the the merger cost to each branch length interpolator in the tree. ''' for clade in self.tree.find_clades(): if clade.up is not None: clade.branch_length_interpolator.merger_cost = self.cost
python
{ "resource": "" }
q273001
Coalescent.optimize_Tc
test
def optimize_Tc(self): ''' determines the coalescent time scale that optimizes the coalescent likelihood of the tree ''' from scipy.optimize import minimize_scalar initial_Tc = self.Tc def cost(Tc): self.set_Tc(Tc) return -self.total_LH() ...
python
{ "resource": "" }
q273002
prof2seq
test
def prof2seq(profile, gtr, sample_from_prof=False, normalize=True): """ Convert profile to sequence and normalize profile across sites. Parameters ---------- profile : numpy 2D array Profile. Shape of the profile should be (L x a), where L - sequence length, a - alphabet size. ...
python
{ "resource": "" }
q273003
normalize_profile
test
def normalize_profile(in_profile, log=False, return_offset = True): """return a normalized version of a profile matrix Parameters ---------- in_profile : np.array shape Lxq, will be normalized to one across each row log : bool, optional treat the input as log probabilities retur...
python
{ "resource": "" }
q273004
TreeAnc.gtr
test
def gtr(self, value): """ Set a new GTR object Parameters ----------- value : GTR the new GTR object """ if not (isinstance(value, GTR) or isinstance(value, GTR_site_specific)): raise TypeError(" GTR instance expected") self._gtr...
python
{ "resource": "" }
q273005
TreeAnc.set_gtr
test
def set_gtr(self, in_gtr, **kwargs): """ Create new GTR model if needed, and set the model as an attribute of the TreeAnc class Parameters ----------- in_gtr : str, GTR The gtr model to be assigned. If string is passed, it is taken as the name o...
python
{ "resource": "" }
q273006
TreeAnc.seq_len
test
def seq_len(self,L): """set the length of the uncompressed sequence. its inverse 'one_mutation' is frequently used as a general length scale. This can't be changed once it is set. Parameters ---------- L : int length of the sequence alignment """ ...
python
{ "resource": "" }
q273007
TreeAnc._attach_sequences_to_nodes
test
def _attach_sequences_to_nodes(self): ''' For each node of the tree, check whether there is a sequence available in the alignment and assign this sequence as a character array ''' failed_leaves= 0 if self.is_vcf: # if alignment is specified as difference from ...
python
{ "resource": "" }
q273008
TreeAnc.prepare_tree
test
def prepare_tree(self): """ Set link to parent and calculate distance to root for all tree nodes. Should be run once the tree is read and after every rerooting, topology change or branch length optimizations. """ self.tree.root.branch_length = 0.001 self.tree.root...
python
{ "resource": "" }
q273009
TreeAnc._prepare_nodes
test
def _prepare_nodes(self): """ Set auxilliary parameters to every node of the tree. """ self.tree.root.up = None self.tree.root.bad_branch=self.tree.root.bad_branch if hasattr(self.tree.root, 'bad_branch') else False internal_node_count = 0 for clade in self.tree.g...
python
{ "resource": "" }
q273010
TreeAnc._calc_dist2root
test
def _calc_dist2root(self): """ For each node in the tree, set its root-to-node distance as dist2root attribute """ self.tree.root.dist2root = 0.0 for clade in self.tree.get_nonterminals(order='preorder'): # parents first for c in clade.clades: ...
python
{ "resource": "" }
q273011
TreeAnc.reconstruct_anc
test
def reconstruct_anc(self, method='probabilistic', infer_gtr=False, marginal=False, **kwargs): """Reconstruct ancestral sequences Parameters ---------- method : str Method to use. Supported values are "fitch" and "ml" infer_gtr : bool ...
python
{ "resource": "" }
q273012
TreeAnc.get_branch_mutation_matrix
test
def get_branch_mutation_matrix(self, node, full_sequence=False): """uses results from marginal ancestral inference to return a joint distribution of the sequence states at both ends of the branch. Parameters ---------- node : Phylo.clade node of the tree full...
python
{ "resource": "" }
q273013
TreeAnc.expanded_sequence
test
def expanded_sequence(self, node, include_additional_constant_sites=False): """ Expand a nodes compressed sequence into the real sequence Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : np.array Sequence...
python
{ "resource": "" }
q273014
TreeAnc._fitch_anc
test
def _fitch_anc(self, **kwargs): """ Reconstruct ancestral states using Fitch's algorithm. The method requires sequences to be assigned to leaves. It implements the iteration from leaves to the root constructing the Fitch profiles for each character of the sequence, and then by pr...
python
{ "resource": "" }
q273015
TreeAnc._fitch_state
test
def _fitch_state(self, node, pos): """ Determine the Fitch profile for a single character of the node's sequence. The profile is essentially the intersection between the children's profiles or, if the former is empty, the union of the profiles. Parameters ---------- ...
python
{ "resource": "" }
q273016
TreeAnc._fitch_intersect
test
def _fitch_intersect(self, arrays): """ Find the intersection of any number of 1D arrays. Return the sorted, unique values that are in all of the input arrays. Adapted from numpy.lib.arraysetops.intersect1d """ def pairwise_intersect(arr1, arr2): s2 = set(arr2...
python
{ "resource": "" }
q273017
TreeAnc.sequence_LH
test
def sequence_LH(self, pos=None, full_sequence=False): """return the likelihood of the observed sequences given the tree Parameters ---------- pos : int, optional position in the sequence, if none, the sum over all positions will be returned full_sequence : bool, opti...
python
{ "resource": "" }
q273018
TreeAnc.ancestral_likelihood
test
def ancestral_likelihood(self): """ Calculate the likelihood of the given realization of the sequences in the tree Returns ------- log_lh : float The tree likelihood given the sequences """ log_lh = np.zeros(self.multiplicity.shape[0]) ...
python
{ "resource": "" }
q273019
TreeAnc._branch_length_to_gtr
test
def _branch_length_to_gtr(self, node): """ Set branch lengths to either mutation lengths of given branch lengths. The assigend values are to be used in the following ML analysis. """ if self.use_mutation_length: return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, n...
python
{ "resource": "" }
q273020
TreeAnc.optimize_branch_length
test
def optimize_branch_length(self, mode='joint', **kwargs): """ Perform optimization for the branch lengths of the entire tree. This method only does a single path and needs to be iterated. **Note** this method assumes that each node stores information about its sequence as numpy....
python
{ "resource": "" }
q273021
TreeAnc.optimize_branch_length_global
test
def optimize_branch_length_global(self, **kwargs): """ EXPERIMENTAL GLOBAL OPTIMIZATION """ self.logger("TreeAnc.optimize_branch_length_global: running branch length optimization...",1) def neg_log(s): for si, n in zip(s, self.tree.find_clades(order='preorder')): ...
python
{ "resource": "" }
q273022
TreeAnc.optimal_branch_length
test
def optimal_branch_length(self, node): ''' Calculate optimal branch length given the sequences of node and parent Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ------- new_len : float Optimal...
python
{ "resource": "" }
q273023
TreeAnc.optimize_seq_and_branch_len
test
def optimize_seq_and_branch_len(self,reuse_branch_len=True, prune_short=True, marginal_sequences=False, branch_length_mode='joint', max_iter=5, infer_gtr=False, **kwargs): """ Iteratively set branch lengths and reconstruct ancestral...
python
{ "resource": "" }
q273024
TreeAnc.get_reconstructed_alignment
test
def get_reconstructed_alignment(self): """ Get the multiple sequence alignment, including reconstructed sequences for the internal nodes. Returns ------- new_aln : MultipleSeqAlignment Alignment including sequences of all internal nodes """ fr...
python
{ "resource": "" }
q273025
GTR_site_specific.Q
test
def Q(self): """function that return the product of the transition matrix and the equilibrium frequencies to obtain the rate matrix of the GTR model """ tmp = np.einsum('ia,ij->ija', self.Pi, self.W) diag_vals = np.sum(tmp, axis=0) for x in range(tmp.shape[-...
python
{ "resource": "" }
q273026
GTR_site_specific.custom
test
def custom(cls, mu=1.0, pi=None, W=None, **kwargs): """ Create a GTR model by specifying the matrix explicitly Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibriu...
python
{ "resource": "" }
q273027
GTR.standard
test
def standard(model, **kwargs): """ Create standard model of molecular evolution. Parameters ---------- model : str Model to create. See list of available models below **kwargs: Key word arguments to be passed to the model **Available ...
python
{ "resource": "" }
q273028
GTR._check_fix_Q
test
def _check_fix_Q(self, fixed_mu=False): """ Check the main diagonal of Q and fix it in case it does not corresond the definition of the rate matrix. Should be run every time when creating custom GTR model. """ # fix Q self.Pi /= self.Pi.sum() # correct the Pi manu...
python
{ "resource": "" }
q273029
GTR.prob_t_compressed
test
def prob_t_compressed(self, seq_pair, multiplicity, t, return_log=False): ''' Calculate the probability of observing a sequence pair at a distance t, for compressed sequences Parameters ---------- seq_pair : numpy array :code:`np.array([(0,1), (2,2), ()..]...
python
{ "resource": "" }
q273030
GTR.optimal_t
test
def optimal_t(self, seq_p, seq_ch, pattern_multiplicity=None, ignore_gaps=False): ''' Find the optimal distance between the two sequences Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence ...
python
{ "resource": "" }
q273031
GTR.optimal_t_compressed
test
def optimal_t_compressed(self, seq_pair, multiplicity, profiles=False, tol=1e-10): """ Find the optimal distance between the two sequences, for compressed sequences Parameters ---------- seq_pair : compressed_sequence_pair Compressed representation of sequences alo...
python
{ "resource": "" }
q273032
GTR.prob_t_profiles
test
def prob_t_profiles(self, profile_pair, multiplicity, t, return_log=False, ignore_gaps=True): ''' Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions ...
python
{ "resource": "" }
q273033
GTR.evolve
test
def evolve(self, profile, t, return_log=False): """ Compute the probability of the sequence state of the child at time t later, given the parent profile. Parameters ---------- profile : numpy.array Sequence profile. Shape = (L, a), where L - seq...
python
{ "resource": "" }
q273034
GTR.sequence_logLH
test
def sequence_logLH(self,seq, pattern_multiplicity=None): """ Returns the log-likelihood of sampling a sequence from equilibrium frequency. Expects a sequence as numpy array Parameters ---------- seq : numpy array Compressed sequence as an array of chars ...
python
{ "resource": "" }
q273035
TreeTime._set_branch_length_mode
test
def _set_branch_length_mode(self, branch_length_mode): ''' if branch_length mode is not explicitly set, set according to empirical branch length distribution in input tree Parameters ---------- branch_length_mode : str, 'input', 'joint', 'marginal' if the m...
python
{ "resource": "" }
q273036
TreeTime.clock_filter
test
def clock_filter(self, reroot='least-squares', n_iqd=None, plot=False): ''' Labels outlier branches that don't seem to follow a molecular clock and excludes them from subsequent molecular clock estimation and the timetree propagation. Parameters ---------- reroo...
python
{ "resource": "" }
q273037
TreeTime.plot_root_to_tip
test
def plot_root_to_tip(self, add_internal=False, label=True, ax=None): """ Plot root-to-tip regression Parameters ---------- add_internal : bool If true, plot inte`rnal node positions label : bool If true, label the plots ax : matplotlib axe...
python
{ "resource": "" }
q273038
TreeTime.resolve_polytomies
test
def resolve_polytomies(self, merge_compressed=False): """ Resolve the polytomies on the tree. The function scans the tree, resolves polytomies if present, and re-optimizes the tree with new topology. Note that polytomies are only resolved if that would result in higher likelihoo...
python
{ "resource": "" }
q273039
TreeTime.print_lh
test
def print_lh(self, joint=True): """ Print the total likelihood of the tree given the constrained leaves Parameters ---------- joint : bool If true, print joint LH, else print marginal LH """ try: u_lh = self.tree.unconstrained_sequence_...
python
{ "resource": "" }
q273040
TreeTime.add_coalescent_model
test
def add_coalescent_model(self, Tc, **kwargs): """Add a coalescent model to the tree and optionally optimze Parameters ---------- Tc : float,str If this is a float, it will be interpreted as the inverse merger rate in molecular clock units, if its is a """...
python
{ "resource": "" }
q273041
TreeTime._find_best_root
test
def _find_best_root(self, covariation=True, force_positive=True, slope=0, **kwarks): ''' Determine the node that, when the tree is rooted on this node, results in the best regression of temporal constraints and root to tip distances. Parameters ---------- infer_gtr : b...
python
{ "resource": "" }
q273042
assure_tree
test
def assure_tree(params, tmp_dir='treetime_tmp'): """ Function that attempts to load a tree and build it from the alignment if no tree is provided. """ if params.tree is None: params.tree = os.path.basename(params.aln)+'.nwk' print("No tree given: inferring tree") utils.tree_i...
python
{ "resource": "" }
q273043
create_gtr
test
def create_gtr(params): """ parse the arguments referring to the GTR model and return a GTR structure """ model = params.gtr gtr_params = params.gtr_params if model == 'infer': gtr = GTR.standard('jc', alphabet='aa' if params.aa else 'nuc') else: try: kwargs = {} ...
python
{ "resource": "" }
q273044
read_if_vcf
test
def read_if_vcf(params): """ Checks if input is VCF and reads in appropriately if it is """ ref = None aln = params.aln fixed_pi = None if hasattr(params, 'aln') and params.aln is not None: if any([params.aln.lower().endswith(x) for x in ['.vcf', '.vcf.gz']]): if not para...
python
{ "resource": "" }
q273045
ancestral_reconstruction
test
def ancestral_reconstruction(params): """ implementing treetime ancestral """ # set up if assure_tree(params, tmp_dir='ancestral_tmp'): return 1 outdir = get_outdir(params, '_ancestral') basename = get_basename(params, outdir) gtr = create_gtr(params) ####################...
python
{ "resource": "" }
q273046
Distribution.calc_fwhm
test
def calc_fwhm(distribution, is_neg_log=True): """ Assess the width of the probability distribution. This returns full-width-half-max """ if isinstance(distribution, interp1d): if is_neg_log: ymin = distribution.y.min() log_prob = dist...
python
{ "resource": "" }
q273047
Distribution.delta_function
test
def delta_function(cls, x_pos, weight=1., min_width=MIN_INTEGRATION_PEAK): """ Create delta function distribution. """ distribution = cls(x_pos,0.,is_log=True, min_width=min_width) distribution.weight = weight return distribution
python
{ "resource": "" }
q273048
Distribution.multiply
test
def multiply(dists): ''' multiplies a list of Distribution objects ''' if not all([isinstance(k, Distribution) for k in dists]): raise NotImplementedError("Can only multiply Distribution objects") n_delta = np.sum([k.is_delta for k in dists]) min_width = np....
python
{ "resource": "" }
q273049
ClockTree._assign_dates
test
def _assign_dates(self): """assign dates to nodes Returns ------- str success/error code """ if self.tree is None: self.logger("ClockTree._assign_dates: tree is not set, can't assign dates", 0) return ttconf.ERROR bad_branch_c...
python
{ "resource": "" }
q273050
ClockTree.setup_TreeRegression
test
def setup_TreeRegression(self, covariation=True): """instantiate a TreeRegression object and set its tip_value and branch_value function to defaults that are sensible for treetime instances. Parameters ---------- covariation : bool, optional account for phylogenetic ...
python
{ "resource": "" }
q273051
ClockTree.make_time_tree
test
def make_time_tree(self, time_marginal=False, clock_rate=None, **kwargs): ''' Use the date constraints to calculate the most likely positions of unconstrained nodes. Parameters ---------- time_marginal : bool If true, use marginal reconstruction for node po...
python
{ "resource": "" }
q273052
ClockTree.timetree_likelihood
test
def timetree_likelihood(self): ''' Return the likelihood of the data given the current branch length in the tree ''' LH = 0 for node in self.tree.find_clades(order='preorder'): # sum the likelihood contributions of all branches if node.up is None: # root node ...
python
{ "resource": "" }
q273053
ClockTree.convert_dates
test
def convert_dates(self): ''' This function converts the estimated "time_before_present" properties of all nodes to numerical dates stored in the "numdate" attribute. This date is further converted into a human readable date string in format %Y-%m-%d assuming the usual calendar. ...
python
{ "resource": "" }
q273054
ClockTree.date_uncertainty_due_to_rate
test
def date_uncertainty_due_to_rate(self, node, interval=(0.05, 0.095)): """use previously calculated variation of the rate to estimate the uncertainty in a particular numdate due to rate variation. Parameters ---------- node : PhyloTree.Clade node for which the confide...
python
{ "resource": "" }
q273055
ClockTree.get_max_posterior_region
test
def get_max_posterior_region(self, node, fraction = 0.9): ''' If temporal reconstruction was done using the marginal ML mode, the entire distribution of times is available. This function determines the interval around the highest posterior probability region that contains the specified f...
python
{ "resource": "" }
q273056
min_interp
test
def min_interp(interp_object): """ Find the global minimum of a function represented as an interpolation object. """ try: return interp_object.x[interp_object(interp_object.x).argmin()] except Exception as e: s = "Cannot find minimum of the interpolation object" + str(interp_object.x...
python
{ "resource": "" }
q273057
median_interp
test
def median_interp(interp_object): """ Find the median of the function represented as an interpolation object. """ new_grid = np.sort(np.concatenate([interp_object.x[:-1] + 0.1*ii*np.diff(interp_object.x) for ii in range(10)]).flatten()) tmp_prop = np.exp(-(int...
python
{ "resource": "" }
q273058
numeric_date
test
def numeric_date(dt=None): """ Convert datetime object to the numeric date. The numeric date format is YYYY.F, where F is the fraction of the year passed Parameters ---------- dt: datetime.datetime, None date of to be converted. if None, assume today """ if dt is None: ...
python
{ "resource": "" }
q273059
DateConversion.from_regression
test
def from_regression(cls, clock_model): """ Create the conversion object automatically from the tree Parameters ---------- clock_model : dict dictionary as returned from TreeRegression with fields intercept and slope """ dc = cls() dc.clock_...
python
{ "resource": "" }
q273060
GuacamoleClient.client
test
def client(self): """ Socket connection. """ if not self._client: self._client = socket.create_connection( (self.host, self.port), self.timeout) self.logger.debug('Client connected with guacd server (%s, %s, %s)' % (se...
python
{ "resource": "" }
q273061
GuacamoleClient.close
test
def close(self): """ Terminate connection with Guacamole guacd server. """ self.client.close() self._client = None self.connected = False self.logger.debug('Connection closed.')
python
{ "resource": "" }
q273062
GuacamoleClient.receive
test
def receive(self): """ Receive instructions from Guacamole guacd server. """ start = 0 while True: idx = self._buffer.find(INST_TERM.encode(), start) if idx != -1: # instruction was fully received! line = self._buffer[:idx ...
python
{ "resource": "" }
q273063
GuacamoleClient.send
test
def send(self, data): """ Send encoded instructions to Guacamole guacd server. """ self.logger.debug('Sending data: %s' % data) self.client.sendall(data.encode())
python
{ "resource": "" }
q273064
GuacamoleClient.send_instruction
test
def send_instruction(self, instruction): """ Send instruction after encoding. """ self.logger.debug('Sending instruction: %s' % str(instruction)) return self.send(instruction.encode())
python
{ "resource": "" }
q273065
GuacamoleClient.handshake
test
def handshake(self, protocol='vnc', width=1024, height=768, dpi=96, audio=None, video=None, image=None, **kwargs): """ Establish connection with Guacamole guacd server via handshake. """ if protocol not in PROTOCOLS: self.logger.debug('Invalid protocol: %s' ...
python
{ "resource": "" }
q273066
utf8
test
def utf8(unicode_str): """ Return a utf-8 encoded string from a valid unicode string. :param unicode_str: Unicode string. :return: str """ if six.PY2 and isinstance(unicode_str, __unicode__): return unicode_str.encode('utf-8') return unicode_str
python
{ "resource": "" }
q273067
GuacamoleInstruction.load
test
def load(cls, instruction): """ Loads a new GuacamoleInstruction from encoded instruction string. :param instruction: Instruction string. :return: GuacamoleInstruction() """ if not instruction.endswith(INST_TERM): raise InvalidInstruction('Instruction termin...
python
{ "resource": "" }
q273068
GuacamoleInstruction.encode_arg
test
def encode_arg(arg): """ Encode argument to be sent in a valid GuacamoleInstruction. example: >> arg = encode_arg('size') >> arg == '4.size' >> True :param arg: arg string. :return: str """ arg_utf8 = utf8(arg) return ELEM_SEP.j...
python
{ "resource": "" }
q273069
GuacamoleInstruction.encode
test
def encode(self): """ Prepare the instruction to be sent over the wire. :return: str """ instruction_iter = itertools.chain([self.opcode], self.args) elems = ARG_SEP.join(self.encode_arg(arg) for arg in instruction_iter) return elems + INST_TERM
python
{ "resource": "" }
q273070
APIResource.class_url
test
def class_url(cls): """Returns a versioned URI string for this class""" base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1')) return "/{0}/{1}".format(base, class_to_api_name(cls.class_name()))
python
{ "resource": "" }
q273071
APIResource.instance_url
test
def instance_url(self): """Get instance URL by ID""" id_ = self.get(self.ID_ATTR) base = self.class_url() if id_: return '/'.join([base, six.text_type(id_)]) else: raise Exception( 'Could not determine which URL to request: %s instance ' ...
python
{ "resource": "" }
q273072
SingletonAPIResource.class_url
test
def class_url(cls): """ Returns a versioned URI string for this class, and don't pluralize the class name. """ base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1')) return "/{0}/{1}".format(base, class_to_api_name( cls.class_name(), pluralize=False))
python
{ "resource": "" }
q273073
DownloadableAPIResource.download
test
def download(self, path=None, **kwargs): """ Download the file to the specified directory or file path. Downloads to a temporary directory if no path is specified. Returns the absolute path to the file. """ download_url = self.download_url(**kwargs) try: ...
python
{ "resource": "" }
q273074
DatasetCommit.parent_object
test
def parent_object(self): """ Get the commit objects parent Import or Migration """ from . import types parent_klass = types.get(self.parent_job_model.split('.')[1]) return parent_klass.retrieve(self.parent_job_id, client=self._client)
python
{ "resource": "" }
q273075
_ask_for_credentials
test
def _ask_for_credentials(): """ Asks the user for their email and password. """ _print_msg('Please enter your SolveBio credentials') domain = raw_input('Domain (e.g. <domain>.solvebio.com): ') # Check to see if this domain supports password authentication try: account = client.reques...
python
{ "resource": "" }
q273076
interactive_login
test
def interactive_login(): """ Force an interactive login via the command line. Sets the global API key and updates the client auth. """ solvebio.access_token = None solvebio.api_key = None client.set_token() domain, email, password = _ask_for_credentials() if not all([domain, email, ...
python
{ "resource": "" }
q273077
whoami
test
def whoami(*args, **kwargs): """ Prints information about the current user. Assumes the user is already logged-in. """ user = client.whoami() if user: print_user(user) else: print('You are not logged-in.')
python
{ "resource": "" }
q273078
print_user
test
def print_user(user): """ Prints information about the current user. """ email = user['email'] domain = user['account']['domain'] role = user['role'] print('You are logged-in to the "{0}" domain ' 'as {1} with role {2}.' .format(domain, email, role))
python
{ "resource": "" }
q273079
Query.filter
test
def filter(self, *filters, **kwargs): """ Returns this Query instance with the query args combined with existing set with AND. kwargs are simply passed to a new Filter object and combined to any other filters with AND. By default, everything is combined using AND. If yo...
python
{ "resource": "" }
q273080
Query.range
test
def range(self, chromosome, start, stop, exact=False): """ Shortcut to do range filters on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, start, stop, exact)])
python
{ "resource": "" }
q273081
Query.position
test
def position(self, chromosome, position, exact=False): """ Shortcut to do a single position filter on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, position, exact=exact)])
python
{ "resource": "" }
q273082
Query.facets
test
def facets(self, *args, **kwargs): """ Returns a dictionary with the requested facets. The facets function supports string args, and keyword args. q.facets('field_1', 'field_2') will return facets for field_1 and field_2. q.facets(field_1={'limit': 0}, field_2={...
python
{ "resource": "" }
q273083
Query._process_filters
test
def _process_filters(cls, filters): """Takes a list of filters and returns JSON :Parameters: - `filters`: List of Filters, (key, val) tuples, or dicts Returns: List of JSON API filters """ data = [] # Filters should always be a list for f in filters: ...
python
{ "resource": "" }
q273084
Query.next
test
def next(self): """ Allows the Query object to be an iterable. This method will iterate through a cached result set and fetch successive pages as required. A `StopIteration` exception will be raised when there aren't any more results available or when the requested resu...
python
{ "resource": "" }
q273085
Query.execute
test
def execute(self, offset=0, **query): """ Executes a query. Additional query parameters can be passed as keyword arguments. Returns: The request parameters and the raw query response. """ _params = self._build_query(**query) self._page_offset = offset _p...
python
{ "resource": "" }
q273086
Query.migrate
test
def migrate(self, target, follow=True, **kwargs): """ Migrate the data from the Query to a target dataset. Valid optional kwargs include: * target_fields * include_errors * validation_params * metadata * commit_mode """ from solvebio imp...
python
{ "resource": "" }
q273087
main
test
def main(argv=sys.argv[1:]): """ Main entry point for SolveBio CLI """ parser = SolveArgumentParser() args = parser.parse_solvebio_args(argv) if args.api_host: solvebio.api_host = args.api_host if args.api_key: solvebio.api_key = args.api_key if not solvebio.api_key: #...
python
{ "resource": "" }
q273088
download_vault_folder
test
def download_vault_folder(remote_path, local_path, dry_run=False, force=False): """Recursively downloads a folder in a vault to a local directory. Only downloads files, not datasets.""" local_path = os.path.normpath(os.path.expanduser(local_path)) if not os.access(local_path, os.W_OK): raise Ex...
python
{ "resource": "" }
q273089
SolveObject.construct_from
test
def construct_from(cls, values, **kwargs): """Used to create a new object from an HTTP response""" instance = cls(values.get(cls.ID_ATTR), **kwargs) instance.refresh_from(values) return instance
python
{ "resource": "" }
q273090
SolveBioAuth.logout
test
def logout(self): """Revoke the token and remove the cookie.""" if self._oauth_client_secret: try: oauth_token = flask.request.cookies[self.TOKEN_COOKIE_NAME] # Revoke the token requests.post( urljoin(self._api_host, self.OA...
python
{ "resource": "" }
q273091
SolveClient.request
test
def request(self, method, url, **kwargs): """ Issues an HTTP Request across the wire via the Python requests library. Parameters ---------- method : str an HTTP method: GET, PUT, POST, DELETE, ... url : str the place to connect to. If the ...
python
{ "resource": "" }
q273092
Task.child_object
test
def child_object(self): """ Get Task child object class """ from . import types child_klass = types.get(self.task_type.split('.')[1]) return child_klass.retrieve(self.task_id, client=self._client)
python
{ "resource": "" }
q273093
Task.cancel
test
def cancel(self): """ Cancel a task """ _status = self.status self.status = "canceled" try: self.save() except: # Reset status to what it was before # status update failure self.status = _status raise
python
{ "resource": "" }
q273094
ExpandingVCFParser._parse_info_snpeff
test
def _parse_info_snpeff(self, info): """ Specialized INFO field parser for SnpEff ANN fields. Requires self._snpeff_ann_fields to be set. """ ann = info.pop('ANN', []) or [] # Overwrite the existing ANN with something parsed # Split on '|', merge with the ANN keys ...
python
{ "resource": "" }
q273095
ExpandingVCFParser.row_to_dict
test
def row_to_dict(self, row, allele, alternate_alleles): """Return a parsed dictionary for JSON.""" def _variant_sbid(**kwargs): """Generates a SolveBio variant ID (SBID).""" return '{build}-{chromosome}-{start}-{stop}-{allele}'\ .format(**kwargs).upper() ...
python
{ "resource": "" }
q273096
get_credentials
test
def get_credentials(): """ Returns the user's stored API key if a valid credentials file is found. Raises CredentialsError if no valid credentials file is found. """ try: netrc_path = netrc.path() auths = netrc(netrc_path).authenticators( urlparse(solvebio.api_host).netlo...
python
{ "resource": "" }
q273097
netrc.save
test
def save(self, path): """Dump the class data in the format of a .netrc file.""" rep = "" for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + "machine " + host + "\n\tlogin " \ + six.text_type(attrs[0]) + "\n" if attrs[1]: ...
python
{ "resource": "" }
q273098
_format
test
def _format(val, valtype, floatfmt, missingval=""): """ Format a value accoding to its type. Unicode is supported: >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', \ '\u0446\u0438\u0444\u0440\u0430'] ; \ tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \ good...
python
{ "resource": "" }
q273099
_normalize_tabular_data
test
def _normalize_tabular_data(tabular_data, headers, sort=True): """ Transform a supported data type to a list of lists, and a list of headers. Supported tabular data types: * list-of-lists or another iterable of iterables * 2D NumPy arrays * dict of iterables (usually used with headers="keys"...
python
{ "resource": "" }