code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return self._call_endpoint(INVOKE_SCRIPT, params=[script], id=id, endpoint=endpoint)
def invoke_script(self, script, id=None, endpoint=None)
Invokes a script that has been assembled Args: script: (str) a hexlified string of a contract invocation script, example '00c10b746f74616c537570706c796754a64cac1b1073e662933ef3e30b007cd98d67d7' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, option...
6.021935
7.306885
0.824145
return self._call_endpoint(SEND_TX, params=[serialized_tx], id=id, endpoint=endpoint)
def send_raw_tx(self, serialized_tx, id=None, endpoint=None)
Submits a serialized tx to the network Args: serialized_tx: (str) a hexlified string of a transaction id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: bool: whether the tx was accepte...
5.242824
7.11699
0.736663
return self._call_endpoint(VALIDATE_ADDR, params=[address], id=id, endpoint=endpoint)
def validate_addr(self, address, id=None, endpoint=None)
returns whether or not addr string is valid Args: address: (str) address to lookup ( in format 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK') id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: ...
6.057385
7.448137
0.813275
return self._call_endpoint(GET_PEERS, id=id, endpoint=endpoint)
def get_peers(self, id=None, endpoint=None)
Get the current peers of a remote node Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
5.258243
7.402877
0.710297
return self._call_endpoint(GET_VALIDATORS, id=id, endpoint=endpoint)
def get_validators(self, id=None, endpoint=None)
Returns the current NEO consensus nodes information and voting status. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
5.379333
7.605227
0.707321
return self._call_endpoint(GET_VERSION, id=id, endpoint=endpoint)
def get_version(self, id=None, endpoint=None)
Get the current version of the endpoint. Note: Not all endpoints currently implement this method Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the e...
5.983408
6.938131
0.862395
return self._call_endpoint(GET_NEW_ADDRESS, id=id, endpoint=endpoint)
def get_new_address(self, id=None, endpoint=None)
Create new address Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
4.84234
6.338957
0.763902
return self._call_endpoint(GET_WALLET_HEIGHT, id=id, endpoint=endpoint)
def get_wallet_height(self, id=None, endpoint=None)
Get the current wallet index height. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
4.323581
5.754502
0.751339
return self._call_endpoint(LIST_ADDRESS, id=id, endpoint=endpoint)
def list_address(self, id=None, endpoint=None)
Lists all the addresses in the current wallet. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
5.909866
9.327844
0.633573
params = [asset_id, addr_from, to_addr, value] if fee: params.append(fee) if fee and change_addr: params.append(change_addr) elif not fee and change_addr: params.append(0) params.append(change_addr) return self._call_endpoi...
def send_from(self, asset_id, addr_from, to_addr, value, fee=None, change_addr=None, id=None, endpoint=None)
Transfer from the specified address to the destination address. Args: asset_id: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7') addr_from: (str) transfering a...
2.149117
2.674231
0.803639
params = [asset_id, to_addr, value] if fee: params.append(fee) if fee and change_addr: params.append(change_addr) elif not fee and change_addr: params.append(0) params.append(change_addr) return self._call_endpoint(SEND_TO_...
def send_to_address(self, asset_id, to_addr, value, fee=None, change_addr=None, id=None, endpoint=None)
Args: asset_id: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7') to_addr: (str) destination address value: (int/decimal) transfer amount fee: (...
2.185006
2.696913
0.810188
params = [outputs_array] if fee: params.append(fee) if fee and change_addr: params.append(change_addr) elif not fee and change_addr: params.append(0) params.append(change_addr) return self._call_endpoint(SEND_MANY, params=p...
def send_many(self, outputs_array, fee=None, change_addr=None, id=None, endpoint=None)
Args: outputs_array: (dict) array, the data structure of each element in the array is as follows: {"asset": <asset>,"value": <value>,"address": <address>} asset: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602...
2.440302
2.88868
0.844781
if mpi: if not MPIPool.enabled(): raise SystemError("Tried to run with MPI but MPIPool not enabled.") pool = MPIPool(**kwargs) if not pool.is_master(): pool.wait() sys.exit(0) log.info("Running with MPI on {0} cores".format(pool.size)) ...
def choose_pool(mpi=False, processes=1, **kwargs)
Choose between the different pools given options from, e.g., argparse. Parameters ---------- mpi : bool, optional Use the MPI processing pool, :class:`~schwimmbad.mpi.MPIPool`. By default, ``False``, will use the :class:`~schwimmbad.serial.SerialPool`. processes : int, optional ...
2.761187
2.766969
0.99791
if self.is_master(): return worker = self.comm.rank status = MPI.Status() while True: log.log(_VERBOSE, "Worker {0} waiting for task".format(worker)) task = self.comm.recv(source=self.master, tag=MPI.ANY_TAG, ...
def wait(self, callback=None)
Tell the workers to wait and listen for the master process. This is called automatically when using :meth:`MPIPool.map` and doesn't need to be called by the user.
2.732618
2.624491
1.041199
# If not the master just wait for instructions. if not self.is_master(): self.wait() return if callback is None: callback = _dummy_callback workerset = self.workers.copy() tasklist = [(tid, (worker, arg)) for tid, arg in enumerate(t...
def map(self, worker, tasks, callback=None)
Evaluate a function or callable on each task in parallel using MPI. The callable, ``worker``, is called on each element of the ``tasks`` iterable. The results are returned in the expected order (symmetric with ``tasks``). Parameters ---------- worker : callable ...
2.730429
2.799983
0.975159
if self.is_worker(): return for worker in self.workers: self.comm.send(None, worker, 0)
def close(self)
Tell all the workers to quit.
8.136889
5.83849
1.393663
try: # Quick way to determine if we're in git or not - returns '' if not devstr = get_git_devstr(sha=True, show_warning=False, path=path) except OSError: return version if not devstr: # Probably not in git so just pass silently return version if 'dev' in v...
def update_git_devstr(version, path=None)
Updates the git revision string if and only if the path is being imported directly from a git working copy. This ensures that the revision number in the version string is accurate.
5.147092
5.087465
1.01172
if path is None: path = os.getcwd() if not _get_repo_path(path, levels=0): return '' if not os.path.isdir(path): path = os.path.abspath(os.path.dirname(path)) if sha: # Faster for getting just the hash of HEAD cmd = ['rev-parse', 'HEAD'] else: ...
def get_git_devstr(sha=False, show_warning=True, path=None)
Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits in the repository will be used as a "revision number". show_warning : bool If True, issue a warnin...
3.055162
2.985267
1.023413
if os.path.isfile(pathname): current_dir = os.path.abspath(os.path.dirname(pathname)) elif os.path.isdir(pathname): current_dir = os.path.abspath(pathname) else: return None current_level = 0 while levels is None or current_level <= levels: if os.path.exists(o...
def _get_repo_path(pathname, levels=None)
Given a file or directory name, determine the root of the git repository this path is under. If given, this won't look any higher than ``levels`` (that is, if ``levels=0`` then the given path must be the root of the git repository and is returned if so. Returns `None` if the given path could not be de...
1.790442
1.764688
1.014594
return self._call_callback(callback, map(func, iterable))
def map(self, func, iterable, callback=None)
A wrapper around the built-in ``map()`` function to provide a consistent interface with the other ``Pool`` classes. Parameters ---------- worker : callable A function or callable object that is executed on each element of the specified ``tasks`` iterable. This ob...
8.549017
30.698589
0.278482
# not handling rare Leucine or Valine starts! if aa_pos == 0 and codon in START_CODONS: return "M" elif codon in STOP_CODONS: return "*" else: return DNA_CODON_TABLE[codon]
def translate_codon(codon, aa_pos)
Translate a single codon into a single amino acid or stop '*' Parameters ---------- codon : str Expected to be of length 3 aa_pos : int Codon/amino acid offset into the protein (starting from 0)
6.199459
6.96658
0.889886
if not isinstance(nucleotide_sequence, Seq): nucleotide_sequence = Seq(nucleotide_sequence) if truncate: # if sequence isn't a multiple of 3, truncate it so BioPython # doesn't complain n_nucleotides = int(len(nucleotide_sequence) / 3) * 3 nucleotide_sequence = nucl...
def translate( nucleotide_sequence, first_codon_is_start=True, to_stop=True, truncate=False)
Translates cDNA coding sequence into amino acid protein sequence. Should typically start with a start codon but allowing non-methionine first residues since the CDS we're translating might have been affected by a start loss mutation. The sequence may include the 3' UTR but will stop translation at the...
3.333416
3.302676
1.009307
n_mutant_codons = len(nucleotide_sequence) // 3 for i in range(n_mutant_codons): codon = nucleotide_sequence[3 * i:3 * i + 3] if codon in STOP_CODONS: return i return -1
def find_first_stop_codon(nucleotide_sequence)
Given a sequence of codons (expected to have length multiple of three), return index of first stop codon, or -1 if none is in the sequence.
2.209617
2.129264
1.037737
mutant_stop_codon_index = find_first_stop_codon(mutant_codons) using_three_prime_utr = False if mutant_stop_codon_index != -1: mutant_codons = mutant_codons[:3 * mutant_stop_codon_index] elif ref_codon_end_offset > len(transcript.protein_sequence): # if the mutant codons didn't co...
def translate_in_frame_mutation( transcript, ref_codon_start_offset, ref_codon_end_offset, mutant_codons)
Returns: - mutant amino acid sequence - offset of first stop codon in the mutant sequence (or -1 if there was none) - boolean flag indicating whether any codons from the 3' UTR were used Parameters ---------- transcript : pyensembl.Transcript Reference transcript to which a ...
2.605725
2.560998
1.017465
print_version_info() if args_list is None: args_list = sys.argv[1:] args = arg_parser.parse_args(args_list) variants = variant_collection_from_args(args) variants_dataframe = variants.to_dataframe() logger.info('\n%s', variants_dataframe) if args.output_csv: variants_dat...
def main(args_list=None)
Script which loads variants and annotates them with overlapping genes. Example usage: varcode-genes --vcf mutect.vcf \ --vcf strelka.vcf \ --maf tcga_brca.maf \ --variant chr1 498584 C G \ --json-variants more_variants.json
2.633858
2.894401
0.909984
require_string(path, "Path to MAF") n_basic_columns = len(MAF_COLUMN_NAMES) # pylint: disable=no-member # pylint gets confused by read_csv df = pandas.read_csv( path, comment="#", sep="\t", low_memory=False, skip_blank_lines=True, header=0, ...
def load_maf_dataframe(path, nrows=None, raise_on_error=True, encoding=None)
Load the guaranteed columns of a TCGA MAF file into a DataFrame Parameters ---------- path : str Path to MAF file nrows : int Optional limit to number of rows loaded raise_on_error : bool Raise an exception upon encountering an error or log an error encoding : str, op...
3.297721
3.50163
0.941768
# pylint: disable=no-member # pylint gets confused by read_csv inside load_maf_dataframe maf_df = load_maf_dataframe(path, raise_on_error=raise_on_error, encoding=encoding) if len(maf_df) == 0 and raise_on_error: raise ValueError("Empty MAF file %s" % path) ensembl_objects = {} va...
def load_maf( path, optional_cols=[], sort_key=variant_ascending_position_sort_key, distinct=True, raise_on_error=True, encoding=None)
Load reference name and Variant objects from MAF filename. Parameters ---------- path : str Path to MAF (*.maf). optional_cols : list, optional A list of MAF columns to include as metadata if they are present in the MAF. Does not result in an error if those columns are not pre...
2.351243
2.396702
0.981033
value = getattr(effect, field_name, None) if value is None: return default else: return fn(value)
def apply_to_field_if_exists(effect, field_name, fn, default)
Apply function to specified field of effect if it is not None, otherwise return default.
2.583436
2.501711
1.032668
return apply_to_field_if_exists( effect=effect, field_name="transcript", fn=fn, default=default)
def apply_to_transcript_if_exists(effect, fn, default)
Apply function to transcript associated with effect, if it exists, otherwise return default.
3.579295
4.313913
0.82971
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: len(t.exons), default=0)
def number_exons_in_associated_transcript(effect)
Number of exons on transcript associated with effect, if there is one (otherwise return 0).
5.733887
6.167634
0.929674
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: len(t.coding_sequence) if (t.complete and t.coding_sequence) else 0, default=0)
def cds_length_of_associated_transcript(effect)
Length of coding sequence of transcript associated with effect, if there is one (otherwise return 0).
5.517717
5.65778
0.975244
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: len(t.sequence), default=0)
def length_of_associated_transcript(effect)
Length of spliced mRNA sequence of transcript associated with effect, if there is one (otherwise return 0).
6.775761
7.311142
0.926772
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: t.name, default="")
def name_of_associated_transcript(effect)
Name of transcript associated with effect, if there is one (otherwise return "").
7.811821
8.554767
0.913154
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: t.gene_id, default=None)
def gene_id_of_associated_transcript(effect)
Ensembl gene ID of transcript associated with effect, returns None if effect does not have transcript.
5.855022
6.39141
0.916077
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: t.complete, default=False)
def effect_has_complete_transcript(effect)
Parameters ---------- effect : subclass of MutationEffect Returns True if effect has transcript and that transcript has complete CDS
6.930968
9.548182
0.725894
return apply_to_gene_if_exists( effect=effect, fn=lambda g: g.biotype == "protein_coding", default=False)
def effect_associated_with_protein_coding_gene(effect)
Parameters ---------- effect : subclass of MutationEffect Returns True if effect is associated with a gene and that gene has a protein_coding biotype.
6.528742
7.009925
0.931357
return apply_to_transcript_if_exists( effect=effect, fn=lambda t: t.biotype == "protein_coding", default=False)
def effect_associated_with_protein_coding_transcript(effect)
Parameters ---------- effect : subclass of MutationEffect Returns True if effect is associated with a transcript and that transcript has a protein_coding biotype.
6.24845
6.791874
0.919989
name = name_of_associated_transcript(effect) if "-" not in name: return 0 parts = name.split("-") last_part = parts[-1] if last_part.isdigit(): return int(last_part) else: return 0
def parse_transcript_number(effect)
Try to parse the number at the end of a transcript name associated with an effect. e.g. TP53-001 returns the integer 1. Parameters ---------- effect : subclass of MutationEffect Returns int
3.331384
3.297862
1.010165
return tuple([ effect_priority(effect), effect_associated_with_protein_coding_gene(effect), effect_associated_with_protein_coding_transcript(effect), effect_has_complete_transcript(effect), cds_length_of_associated_transcript(effect), length_of_associated_transc...
def multi_gene_effect_sort_key(effect)
This function acts as a sort key for choosing the highest priority effect across multiple genes (so does not assume that effects might involve the same start/stop codons). Returns tuple with the following elements: 1) Integer priority of the effect type. 2) Does the associated gene have a "...
5.159819
2.756986
1.871543
if effect.__class__ is not ExonicSpliceSite: return effect if effect.alternate_effect is None: return effect splice_priority = effect_priority(effect) alternate_priority = effect_priority(effect.alternate_effect) if splice_priority > alternate_priority: return effect ...
def select_between_exonic_splice_site_and_alternate_effect(effect)
If the given effect is an ExonicSpliceSite then it might contain an alternate effect of higher priority. In that case, return the alternate effect. Otherwise, this acts as an identity function.
2.660768
2.431139
1.094453
priority_values = map(effect_priority, effects) max_priority = max(priority_values) return [e for (e, p) in zip(effects, priority_values) if p == max_priority]
def keep_max_priority_effects(effects)
Given a list of effects, only keep the ones with the maximum priority effect type. Parameters ---------- effects : list of MutationEffect subclasses Returns list of same length or shorter
2.632735
3.525689
0.746729
for filter_fn in filters: filtered_effects = filter_fn(effects) if len(effects) == 1: return effects elif len(filtered_effects) > 1: effects = filtered_effects return effects
def filter_pipeline(effects, filters)
Apply each filter to the effect list sequentially. If any filter returns zero values then ignore it. As soon as only one effect is left, return it. Parameters ---------- effects : list of MutationEffect subclass instances filters : list of functions Each function takes a list of effect...
2.765945
2.750121
1.005754
# first filter effects to keep those on # 1) maximum priority effects # 2) protein coding genes # 3) protein coding transcripts # 4) complete transcripts # # If any of these filters drop all the effects then we move on to the next # filtering step. effects = filter_pipeline( ...
def top_priority_effect_for_single_gene(effects)
For effects which are from the same gene, check to see if there is a canonical transcript with both the maximum length CDS and maximum length full transcript sequence. If not, then use number of exons and transcript name as tie-breaking features. Parameters ---------- effects : list of Mut...
3.642184
3.412594
1.067278
if len(effects) == 0: raise ValueError("List of effects cannot be empty") effects = map( select_between_exonic_splice_site_and_alternate_effect, effects) effects_grouped_by_gene = apply_groupby( effects, fn=gene_id_of_associated_transcript, skip_none=False) if Non...
def top_priority_effect(effects)
Given a collection of variant transcript effects, return the top priority object. ExonicSpliceSite variants require special treatment since they actually represent two effects -- the splicing modification and whatever else would happen to the exonic sequence if nothing else gets changed. In cases where ...
3.612969
3.386329
1.066928
return dict( variants=self.variants, distinct=self.distinct, sort_key=self.sort_key, sources=self.sources, source_to_metadata_dict=self.source_to_metadata_dict)
def to_dict(self)
Since Collection.to_dict() returns a state dictionary with an 'elements' field we have to rename it to 'variants'.
5.157603
4.087605
1.261766
kwargs = self.to_dict() kwargs["variants"] = new_elements return self.from_dict(kwargs)
def clone_with_new_elements(self, new_elements)
Create another VariantCollection of the same class and with same state (including metadata) but possibly different entries. Warning: metadata is a dictionary keyed by variants. This method leaves that dictionary as-is, which may result in extraneous entries or missing entries.
5.693569
4.734573
1.202552
return EffectCollection([ effect for variant in self for effect in variant.effects(raise_on_error=raise_on_error) ])
def effects(self, raise_on_error=True)
Parameters ---------- raise_on_error : bool, optional If exception is raised while determining effect of variant on a transcript, should it be raised? This default is True, meaning errors result in raised exceptions, otherwise they are only logged.
4.703227
4.593598
1.023866
return { gene_name: len(group) for (gene_name, group) in self.groupby_gene_name().items() }
def gene_counts(self)
Returns number of elements overlapping each gene name. Expects the derived class (VariantCollection or EffectCollection) to have an implementation of groupby_gene_name.
5.124761
2.955449
1.734004
return self.filter_any_above_threshold( multi_key_fn=lambda variant: variant.transcript_ids, value_dict=transcript_expression_dict, threshold=min_expression_value)
def filter_by_transcript_expression( self, transcript_expression_dict, min_expression_value=0.0)
Filters variants down to those which have overlap a transcript whose expression value in the transcript_expression_dict argument is greater than min_expression_value. Parameters ---------- transcript_expression_dict : dict Dictionary mapping Ensembl transcript IDs to...
6.211822
6.676188
0.930444
return self.filter_any_above_threshold( multi_key_fn=lambda effect: effect.gene_ids, value_dict=gene_expression_dict, threshold=min_expression_value)
def filter_by_gene_expression( self, gene_expression_dict, min_expression_value=0.0)
Filters variants down to those which have overlap a gene whose expression value in the transcript_expression_dict argument is greater than min_expression_value. Parameters ---------- gene_expression_dict : dict Dictionary mapping Ensembl gene IDs to expression estima...
6.403246
7.025393
0.911443
''' Comparison between VariantCollection instances that takes into account the info field of Variant instances. Returns ---------- True if the variants in this collection equal the variants in the other collection. The Variant.info fields are included in the comp...
def exactly_equal(self, other)
Comparison between VariantCollection instances that takes into account the info field of Variant instances. Returns ---------- True if the variants in this collection equal the variants in the other collection. The Variant.info fields are included in the comparison.
5.13644
1.998442
2.570222
# three levels of nested dictionaries! # {source name: {variant: {attribute: value}}} combined_dictionary = {} for source_to_metadata_dict in dictionaries: for source_name, variant_to_metadata_dict in source_to_metadata_dict.items(): combined_dictio...
def _merge_metadata_dictionaries(cls, dictionaries)
Helper function for combining variant collections: given multiple dictionaries mapping: source name -> (variant -> (attribute -> value)) Returns dictionary with union of all variants and sources.
2.623741
2.322685
1.129615
kwargs["variants"] = combine_fn(*[set(vc) for vc in variant_collections]) kwargs["source_to_metadata_dict"] = cls._merge_metadata_dictionaries( [vc.source_to_metadata_dict for vc in variant_collections]) kwargs["sources"] = set.union(*([vc.sources for vc in variant_collectio...
def _combine_variant_collections(cls, combine_fn, variant_collections, kwargs)
Create a single VariantCollection from multiple different collections. Parameters ---------- cls : class Should be VariantCollection combine_fn : function Function which takes any number of sets of variants and returns some combination of them (typi...
4.757102
4.782184
0.994755
return self._combine_variant_collections( combine_fn=set.union, variant_collections=(self,) + others, kwargs=kwargs)
def union(self, *others, **kwargs)
Returns the union of variants in a several VariantCollection objects.
8.685221
5.589685
1.553794
return self._combine_variant_collections( combine_fn=set.intersection, variant_collections=(self,) + others, kwargs=kwargs)
def intersection(self, *others, **kwargs)
Returns the intersection of variants in several VariantCollection objects.
9.143491
5.694417
1.605694
def row_from_variant(variant): return OrderedDict([ ("chr", variant.contig), ("start", variant.original_start), ("ref", variant.original_ref), ("alt", variant.original_alt), ("gene_name", ";".join(variant.gene_n...
def to_dataframe(self)
Build a DataFrame from this variant collection
2.711717
2.502161
1.08375
n_ref = len(ref) n_alt = len(alt) n_min = min(n_ref, n_alt) i = 0 while i < n_min and ref[i] == alt[i]: i += 1 # guaranteed that ref and alt agree on all the characters # up to i'th position, so it doesn't matter which one we pull # the prefix out of prefix = ref[:i] ...
def trim_shared_prefix(ref, alt)
Sometimes mutations are given with a shared prefix between the reference and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids). This function trims the common prefix and returns the disjoint ref and alt strings, along with the shared prefix.
3.077936
3.118914
0.986861
n_ref = len(ref) n_alt = len(alt) n_min = min(n_ref, n_alt) i = 0 while i < n_min and ref[-i - 1] == alt[-i - 1]: i += 1 # i is length of shared suffix. if i == 0: return (ref, alt, '') return (ref[:-i], alt[:-i], ref[-i:])
def trim_shared_suffix(ref, alt)
Reuse the `trim_shared_prefix` function above to implement similar functionality for string suffixes. Given ref='ABC' and alt='BC', we first revese both strings: reverse_ref = 'CBA' reverse_alt = 'CB' and then the result of calling trim_shared_prefix will be: ('A', '', 'CB') We ...
2.275031
2.457232
0.925851
ref, alt, prefix = trim_shared_prefix(ref, alt) ref, alt, suffix = trim_shared_suffix(ref, alt) return ref, alt, prefix, suffix
def trim_shared_flanking_strings(ref, alt)
Given two nucleotide or amino acid strings, identify if they have a common prefix, a common suffix, and return their unique components along with the prefix and suffix. For example, if the input ref = "SYFFQGR" and alt = "SYMLLFIFQGR" then the result will be: ("F", "MLLFI", "SY", "FQGR")
2.343848
2.82276
0.830339
print_version_info() if args_list is None: args_list = sys.argv[1:] args = arg_parser.parse_args(args_list) variants = variant_collection_from_args(args) effects = variants.effects() if args.only_coding: effects = effects.drop_silent_and_noncoding() if args.one_per_vari...
def main(args_list=None)
Script which loads variants and annotates them with overlapping genes and predicted coding effects. Example usage: varcode --vcf mutect.vcf \ --vcf strelka.vcf \ --maf tcga_brca.maf \ --variant chr1 498584 C G \ --json-variants more_variants.j...
3.590238
3.740912
0.959723
# index (starting from 0) of first affected reference codon ref_codon_start_offset = cds_offset // 3 # which nucleotide of the first codon got changed? nucleotide_offset_into_first_ref_codon = cds_offset % 3 n_ref_nucleotides = len(trimmed_cdna_ref) if n_ref_nucleotides == 0: if nu...
def get_codons( variant, trimmed_cdna_ref, trimmed_cdna_alt, sequence_from_start_codon, cds_offset)
Returns indices of first and last reference codons affected by the variant, as well as the actual sequence of the mutated codons which replace those reference codons. Parameters ---------- variant : Variant trimmed_cdna_ref : str Trimmed reference cDNA nucleotides affected by the varia...
2.51836
2.488416
1.012033
variant_arg_group = arg_parser.add_argument_group( title="Variants", description="Genomic variant files") variant_arg_group.add_argument( "--vcf", default=[], action="append", help="Genomic variants in VCF format") variant_arg_group.add_argument( ...
def add_variant_args(arg_parser)
Extends an ArgumentParser instance with the following commandline arguments: --vcf --genome --maf --variant --json-variants
4.347223
4.177251
1.04069
assert 0 < offset <= len(sequence), \ "Invalid position %d for sequence of length %d" % ( offset, len(sequence)) prefix = sequence[:offset] suffix = sequence[offset:] return prefix + new_residues + suffix
def insert_before(sequence, offset, new_residues)
Mutate the given sequence by inserting the string `new_residues` before `offset`. Parameters ---------- sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of sequence, after which we should insert `new_residues`. new_residues :...
2.673968
3.819971
0.699997
assert 0 <= offset < len(sequence), \ "Invalid position %d for sequence of length %d" % ( offset, len(sequence)) prefix = sequence[:offset + 1] suffix = sequence[offset + 1:] return prefix + new_residues + suffix
def insert_after(sequence, offset, new_residues)
Mutate the given sequence by inserting the string `new_residues` after `offset`. Parameters ---------- sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of sequence, after which we should insert `new_residues`. new_residues : ...
2.501841
3.3636
0.743799
n_ref = len(ref) sequence_ref = sequence[offset:offset + n_ref] assert str(sequence_ref) == str(ref), \ "Reference %s at offset %d != expected reference %s" % \ (sequence_ref, offset, ref) prefix = sequence[:offset] suffix = sequence[offset + n_ref:] return prefix + alt + su...
def substitute(sequence, offset, ref, alt)
Mutate a sequence by substituting given `alt` at instead of `ref` at the given `position`. Parameters ---------- sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of `sequence` ref : sequence or str What do we expect to find a...
2.811156
3.62152
0.776236
match_recency = [ int(re.search('\d+', assembly_name).group()) for assembly_name in assembly_names ] most_recent = [ x for (y, x) in sorted(zip(match_recency, assembly_names), reverse=True)][0] return most_recent
def _most_recent_assembly(assembly_names)
Given list of (in this case, matched) assemblies, identify the most recent ("recency" here is determined by sorting based on the numeric element of the assembly name)
3.134605
2.593793
1.208502
# identify all cases where reference name or path matches candidate aliases reference_file_name = os.path.basename(reference_name_or_path) matches = {'file_name': list(), 'full_path': list()} for assembly_name in reference_alias_dict.keys(): candidate_list = [assembly_name] + reference_alia...
def infer_reference_name(reference_name_or_path)
Given a string containing a reference name (such as a path to that reference's FASTA file), return its canonical name as used by Ensembl.
3.500279
3.528256
0.992071
if isinstance(genome_object_string_or_int, Genome): return genome_object_string_or_int if is_integer(genome_object_string_or_int): return cached_release(genome_object_string_or_int) elif is_string(genome_object_string_or_int): # first infer the canonical reference name, e.g. map...
def infer_genome(genome_object_string_or_int)
If given an integer, return associated human EnsemblRelease for that Ensembl version. If given a string, return latest EnsemblRelease which has a reference of the same name. If given a PyEnsembl Genome, simply return it.
2.875619
2.618043
1.098385
return dict( contig=self.original_contig, start=self.original_start, ref=self.original_ref, alt=self.original_alt, ensembl=self.ensembl, allow_extended_nucleotides=self.allow_extended_nucleotides, normalize_contig_name=...
def to_dict(self)
We want the original values (un-normalized) field values while serializing since normalization will happen in __init__.
3.446173
3.162999
1.089527
if self.is_insertion: return "chr%s g.%d_%dins%s" % ( self.contig, self.start, self.start + 1, self.alt) elif self.is_deletion: return "chr%s g.%d_%ddel%s" % ( self.contig, se...
def short_description(self)
HGVS nomenclature for genomic variants More info: http://www.hgvs.org/mutnomen/
2.217043
1.869974
1.185601
if self._genes is None: self._genes = self.ensembl.genes_at_locus( self.contig, self.start, self.end) return self._genes
def genes(self)
Return Gene object for all genes which overlap this variant.
3.663118
3.098627
1.182175
return self.ensembl.gene_ids_at_locus( self.contig, self.start, self.end)
def gene_ids(self)
Return IDs of all genes which overlap this variant. Calling this method is significantly cheaper than calling `Variant.genes()`, which has to issue many more queries to construct each Gene object.
6.782856
5.683954
1.193334
return self.ensembl.gene_names_at_locus( self.contig, self.start, self.end)
def gene_names(self)
Return names of all genes which overlap this variant. Calling this method is significantly cheaper than calling `Variant.genes()`, which has to issue many more queries to construct each Gene object.
6.710006
5.841373
1.148704
# An insertion would appear in a VCF like C>CT, so that the # alternate allele starts with the reference nucleotides. # Since the nucleotide strings may be normalized in the constructor, # it's worth noting that the normalized form of this variant would be # ''>'T', so t...
def is_insertion(self)
Does this variant represent the insertion of nucleotides into the reference genome?
12.624583
10.387208
1.215397
# A deletion would appear in a VCF like CT>C, so that the # reference allele starts with the alternate nucleotides. # This is true even in the normalized case, where the alternate # nucleotides are an empty string. return (len(self.ref) > len(self.alt)) and self.ref.star...
def is_deletion(self)
Does this variant represent the deletion of nucleotides from the reference genome?
9.683304
7.895689
1.226404
return (len(self.ref) == len(self.alt) == 1) and (self.ref != self.alt)
def is_snv(self)
Is the variant a single nucleotide variant
3.489986
2.959089
1.179412
return self.is_snv and is_purine(self.ref) == is_purine(self.alt)
def is_transition(self)
Is this variant and pyrimidine to pyrimidine change or purine to purine change
11.084412
4.763504
2.326945
return self.is_snv and is_purine(self.ref) != is_purine(self.alt)
def is_transversion(self)
Is this variant a pyrimidine to purine change or vice versa
7.166682
4.452477
1.609595
if n_ref_bases == 0: # insertions only overlap intervals which start before and # end after the insertion point, they must be fully contained # by the other interval return interval_start <= variant_start and interval_end >= variant_start variant_end = variant_start + n_ref...
def variant_overlaps_interval( variant_start, n_ref_bases, interval_start, interval_end)
Does a variant overlap a given interval on the same chromosome? Parameters ---------- variant_start : int Inclusive base-1 position of variant's starting location (or location before an insertion) n_ref_bases : int Number of reference bases affect by variant (used to compute ...
4.116658
4.417597
0.931877
# first we're going to make sure the variant doesn't disrupt the # splicing sequences we got from Divina et. al's # Ab initio prediction of mutation-induced cryptic # splice-site activation and exon skipping # (http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2947103/) # # 5' splice site...
def changes_exonic_splice_site( transcript_offset, transcript, transcript_ref, transcript_alt, exon_start_offset, exon_end_offset, exon_number)
Does the given exonic mutation of a particular transcript change a splice site? Parameters ---------- transcript_offset : int Offset from start of transcript of first reference nucleotide (or the last nucleotide before an insertion) transcript : pyensembl.Transcript transcript...
5.240089
5.268132
0.994677
if not allow_extended_nucleotides and nucleotide not in STANDARD_NUCLEOTIDES: raise ValueError( "{} is a non-standard nucleotide, neither purine or pyrimidine".format(nucleotide)) return nucleotide in PURINE_NUCLEOTIDES
def is_purine(nucleotide, allow_extended_nucleotides=False)
Is the nucleotide a purine
3.180152
3.051248
1.042247
if nucleotides in empty_chars: return "" elif treat_nan_as_empty and isinstance(nucleotides, float) and np.isnan(nucleotides): return "" require_string(nucleotides, name="nucleotide string") nucleotides = nucleotides.upper() if allow_extended_nucleotides: valid_nucleo...
def normalize_nucleotide_string( nucleotides, allow_extended_nucleotides=False, empty_chars=".-", treat_nan_as_empty=True)
Normalizes a nucleotide string by converting various ways of encoding empty strings into "", making all letters upper case, and checking to make sure all letters in the string are actually nucleotides. Parameters ---------- nucleotides : str Sequence of nucleotides, e.g. "ACCTG" extend...
2.073395
2.661783
0.77895
return OrderedDict( (call.sample, call.data._asdict()) for call in calls)
def pyvcf_calls_to_sample_info_list(calls)
Given pyvcf.model._Call instances, return a dict mapping each sample name to its per-sample info: sample name -> field -> value
7.782516
9.313284
0.835636
expected_columns = ( ["CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER"] + (["INFO"] if info_parser else [])) if info_parser and sample_names: if sample_info_parser is None: raise TypeError( "Must specify sample_info_parser if specifying sample_names...
def dataframes_to_variant_collection( dataframes, source_path, info_parser=None, only_passing=True, max_variants=None, sample_names=None, sample_info_parser=None, variant_kwargs={}, variant_collection_kwargs={})
Load a VariantCollection from an iterable of pandas dataframes. This takes an iterable of dataframes instead of a single dataframe to avoid having to load huge dataframes at once into memory. If you have a single dataframe, just pass it in a single-element list. Parameters ---------- dataframe...
2.838182
2.702109
1.050358
vcf_field_types = OrderedDict() vcf_field_types['CHROM'] = str vcf_field_types['POS'] = int vcf_field_types['ID'] = str vcf_field_types['REF'] = str vcf_field_types['ALT'] = str vcf_field_types['QUAL'] = str vcf_field_types['FILTER'] = str if include_info: vcf_field_type...
def read_vcf_into_dataframe( path, include_info=False, sample_names=None, chunk_size=None)
Load the data of a VCF into a pandas dataframe. All headers are ignored. Parameters ---------- path : str Path to local file. HTTP and other protocols are not implemented. include_info : boolean, default False If true, the INFO field is not parsed, but is included as a string in ...
1.804107
1.86092
0.96947
dec = zlib.decompressobj(zlib.MAX_WBITS | 16) previous = "" for compressed_chunk in stream: chunk = dec.decompress(compressed_chunk).decode() if chunk: lines = (previous + chunk).split("\n") previous = lines.pop() for line in lines: yi...
def stream_gzip_decompress_lines(stream)
Uncompress a gzip stream into lines of text. Parameters ---------- Generator of chunks of gzip compressed text. Returns ------- Generator of uncompressed lines.
2.756079
2.9537
0.933094
if genome: return infer_genome(genome) elif reference_vcf_key not in vcf_reader.metadata: raise ValueError("Unable to infer reference genome for %s" % ( vcf_reader.filename,)) else: reference_path = vcf_reader.metadata[reference_vcf_key] return infer_genome(r...
def infer_genome_from_vcf(genome, vcf_reader, reference_vcf_key)
Helper function to make a pyensembl.Genome instance.
2.653653
2.676615
0.991421
assert transcript.protein_sequence is not None, \ "Expect transcript %s to have protein sequence" % transcript original_protein_sequence = transcript.protein_sequence original_protein_length = len(original_protein_sequence) mutant_protein_suffix = translate( nucleotide_sequence=s...
def create_frameshift_effect( mutated_codon_index, sequence_from_mutated_codon, variant, transcript)
Determine frameshift effect within a coding sequence (possibly affecting either the start or stop codons, or anythign in between) Parameters ---------- mutated_codon_index : int Codon offset (starting from 0 = start codon) of first non-reference amino acid in the variant protein se...
3.621545
3.554702
1.018804
# special logic for insertions coding_sequence_after_insertion = \ sequence_from_start_codon[cds_offset_before_insertion + 1:] if cds_offset_before_insertion % 3 == 2: # insertion happens after last nucleotide in a codon, # doesn't disrupt the existing codon from cds_offset-2 t...
def cdna_codon_sequence_after_insertion_frameshift( sequence_from_start_codon, cds_offset_before_insertion, inserted_nucleotides)
Returns index of mutated codon and nucleotide sequence starting at the first mutated codon.
2.424917
2.337307
1.037483
mutated_codon_index = cds_offset // 3 # get the sequence starting from the first modified codon until the end # of the transcript. sequence_after_mutated_codon = \ sequence_from_start_codon[mutated_codon_index * 3:] # the variant's ref nucleotides should start either 0, 1, or 2 nucleot...
def cdna_codon_sequence_after_deletion_or_substitution_frameshift( sequence_from_start_codon, cds_offset, trimmed_cdna_ref, trimmed_cdna_alt)
Logic for any frameshift which isn't an insertion. We have insertions as a special case since our base-inclusive indexing means something different for insertions: cds_offset = base before insertion Whereas in this case: cds_offset = first reference base affected by a variant Returns inde...
3.259797
3.076562
1.059558
if len(trimmed_cdna_ref) != 0: mutated_codon_index, sequence_from_mutated_codon = \ cdna_codon_sequence_after_deletion_or_substitution_frameshift( sequence_from_start_codon=sequence_from_start_codon, cds_offset=cds_offset, trimmed_cdna_ref=tri...
def predict_frameshift_coding_effect( variant, transcript, trimmed_cdna_ref, trimmed_cdna_alt, cds_offset, sequence_from_start_codon)
Coding effect of a frameshift mutation. Parameters ---------- variant : Variant transcript : Transcript trimmed_cdna_ref : nucleotide sequence Reference nucleotides in the coding sequence of the given transcript. trimmed_cdna_alt : nucleotide sequence Alternate nucleotides in...
1.929478
2.010917
0.959502
# if this variant isn't overlapping any genes, return a # Intergenic effect # TODO: look for nearby genes and mark those as Upstream and Downstream # effects if len(variant.gene_ids) == 0: effects = [Intergenic(variant)] else: # list of all MutationEffects for all genes & tr...
def predict_variant_effects(variant, raise_on_error=False)
Determine the effects of a variant on any transcripts it overlaps. Returns an EffectCollection object. Parameters ---------- variant : Variant raise_on_error : bool Raise an exception if we encounter an error while trying to determine the effect of this variant on a transcript, or ...
4.034931
3.89439
1.036088
try: return predict_variant_effect_on_transcript( variant=variant, transcript=transcript) except (AssertionError, ValueError) as error: logger.warn( "Encountered error annotating %s for %s: %s", variant, transcript, err...
def predict_variant_effect_on_transcript_or_failure(variant, transcript)
Try predicting the effect of a variant on a particular transcript but suppress raised exceptions by converting them into `Failure` effect values.
3.410405
3.186476
1.070275
assert distance_to_exon > 0, \ "Expected intronic effect to have distance_to_exon > 0, got %d" % ( distance_to_exon,) if nearest_exon.strand == "+": # if exon on positive strand start_before = variant.trimmed_base1_start < nearest_exon.start start_same = variant...
def choose_intronic_effect_class( variant, nearest_exon, distance_to_exon)
Infer effect of variant which does not overlap any exon of the given transcript.
4.50369
4.599055
0.979264
# create an empty list for every new key groups = defaultdict(list) for record in records: value = fn(record) if value is not None or not skip_none: groups[value].append(record) return dict(groups)
def apply_groupby(records, fn, skip_none=False)
Given a list of objects, group them into a dictionary by applying fn to each one and using returned values as a dictionary key. Parameters ---------- records : list fn : function skip_none : bool If False, then None can be a key in the returned dictionary, otherwise record...
3.408764
3.423527
0.995688
return apply_groupby( records, lambda obj: getattr(obj, field_name), skip_none=skip_none)
def groupby_field(records, field_name, skip_none=True)
Given a list of objects, group them into a dictionary by the unique values of a given field name.
4.24786
5.460448
0.777932
memoized_values = {} @wraps(fn) def wrapped_fn(*args, **kwargs): key = (args, tuple(sorted(kwargs.items()))) try: return memoized_values[key] except KeyError: memoized_values[key] = fn(*args, **kwargs) return memoized_values[key] return ...
def memoize(fn)
Simple memoization decorator for functions and methods, assumes that all arguments to the function can be hashed and compared.
1.830761
2.070088
0.884388
# ensure that start_pos:end_pos overlap with transcript positions if start > end: raise ValueError( "start_pos %d shouldn't be greater than end_pos %d" % ( start, end)) if start > transcript.end: raise ValueError( "Range %d:%d starts after transcr...
def interval_offset_on_transcript(start, end, transcript)
Given an interval [start:end] and a particular transcript, return the start offset of the interval relative to the chromosomal positions of the transcript.
2.423134
2.445152
0.990995
return self.filter_above_threshold( key_fn=lambda effect: effect.transcript_id, value_dict=transcript_expression_dict, threshold=min_expression_value)
def filter_by_transcript_expression( self, transcript_expression_dict, min_expression_value=0.0)
Filters effects to those which have an associated transcript whose expression value in the transcript_expression_dict argument is greater than min_expression_value. Parameters ---------- transcript_expression_dict : dict Dictionary mapping Ensembl transcript IDs to e...
5.512553
5.794988
0.951262
return self.filter_above_threshold( key_fn=lambda effect: effect.gene_id, value_dict=gene_expression_dict, threshold=min_expression_value)
def filter_by_gene_expression( self, gene_expression_dict, min_expression_value=0.0)
Filters effects to those which have an associated gene whose expression value in the gene_expression_dict argument is greater than min_expression_value. Parameters ---------- gene_expression_dict : dict Dictionary mapping Ensembl gene IDs to expression estimates ...
5.17275
5.7394
0.90127