sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def load_multiple(filters="*.*", text='Select some files, FACEFACE!', default_directory='default_directory'): """ Pops up a dialog for opening more than one file. Returns a list of string paths or None. """ # make sure the filters contains "*.*" as an option! if not '*' in filters.split(';'): filter...
Pops up a dialog for opening more than one file. Returns a list of string paths or None.
entailment
def Dump(self): """ Dumps the current prefs to the preferences.txt file """ prefs_file = open(self.prefs_path, 'w') for n in range(0,len(self.prefs)): if len(list(self.prefs.items())[n]) > 1: prefs_file.write(str(list(self.prefs.items())[n][0]) + ' = '...
Dumps the current prefs to the preferences.txt file
entailment
def link(self): """Resolve and link all types in the scope.""" type_specs = {} types = [] for name, type_spec in self.scope.type_specs.items(): type_spec = type_spec.link(self.scope) type_specs[name] = type_spec if type_spec.surface is not None: ...
Resolve and link all types in the scope.
entailment
def install(path, name=None): """Compiles a Thrift file and installs it as a submodule of the caller. Given a tree organized like so:: foo/ __init__.py bar.py my_service.thrift You would do, .. code-block:: python my_service = thriftrw.install('my...
Compiles a Thrift file and installs it as a submodule of the caller. Given a tree organized like so:: foo/ __init__.py bar.py my_service.thrift You would do, .. code-block:: python my_service = thriftrw.install('my_service.thrift') To install ``m...
entailment
def loads(self, name, document): """Parse and compile the given Thrift document. :param str name: Name of the Thrift document. :param str document: The Thrift IDL as a string. """ return self.compiler.compile(name, document).link().surface
Parse and compile the given Thrift document. :param str name: Name of the Thrift document. :param str document: The Thrift IDL as a string.
entailment
def load(self, path, name=None): """Load and compile the given Thrift file. :param str path: Path to the ``.thrift`` file. :param str name: Name of the generated module. Defaults to the base name of the file. :returns: The compiled module....
Load and compile the given Thrift file. :param str path: Path to the ``.thrift`` file. :param str name: Name of the generated module. Defaults to the base name of the file. :returns: The compiled module.
entailment
def get_url_implicit_flow_user(client_id, scope, redirect_uri='https://oauth.vk.com/blank.html', display='page', response_type='token', version=None, state=None, revoke=1): """ https://vk.com/dev/implicit_flow_user :return: url """ url =...
https://vk.com/dev/implicit_flow_user :return: url
entailment
def get_url_authcode_flow_user(client_id, redirect_uri, display="page", scope=None, state=None): """Authorization Code Flow for User Access Token Use Authorization Code Flow to run VK API methods from the server side of an application. Access token received this way is not bound to an ip address but set of...
Authorization Code Flow for User Access Token Use Authorization Code Flow to run VK API methods from the server side of an application. Access token received this way is not bound to an ip address but set of permissions that can be granted is limited for security reasons. Args: client_id (int): Ap...
entailment
def get_fake_data(*a): """ Called whenever someone presses the "fire" button. """ # add columns of data to the databox d['x'] = _n.linspace(0,10,100) d['y'] = _n.cos(d['x']) + 0.1*_n.random.rand(100) # update the curve c.setData(d['x'], d['y'])
Called whenever someone presses the "fire" button.
entailment
def setOpts(self, **opts): """ Changes the behavior of the SpinBox. Accepts most of the arguments allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`. """ #print opts for k in opts: if k == 'bounds': #print opts[k] ...
Changes the behavior of the SpinBox. Accepts most of the arguments allowed in :func:`__init__ <pyqtgraph.SpinBox.__init__>`.
entailment
def setMaximum(self, m, update=True): """Set the maximum allowed value (or None for no limit)""" if m is not None: m = D(asUnicode(m)) self.opts['bounds'][1] = m if update: self.setValue()
Set the maximum allowed value (or None for no limit)
entailment
def selectNumber(self): """ Select the numerical portion of the text to allow quick editing by the user. """ le = self.lineEdit() text = asUnicode(le.text()) if self.opts['suffix'] == '': le.setSelection(0, len(text)) else: try: ...
Select the numerical portion of the text to allow quick editing by the user.
entailment
def value(self): """ Return the value of this SpinBox. """ if self.opts['int']: return int(self.val) else: return float(self.val)
Return the value of this SpinBox.
entailment
def setValue(self, value=None, update=True, delaySignal=False): """ Set the value of this spin. If the value is out of bounds, it will be clipped to the nearest boundary. If the spin is integer type, the value will be coerced to int. Returns the actual value set. ...
Set the value of this spin. If the value is out of bounds, it will be clipped to the nearest boundary. If the spin is integer type, the value will be coerced to int. Returns the actual value set. If value is None, then the current value is used (this is for resetting th...
entailment
def interpret(self): """Return value of text. Return False if text is invalid, raise exception if text is intermediate""" strn = self.lineEdit().text() suf = self.opts['suffix'] if len(suf) > 0: if strn[-len(suf):] != suf: return False #raise Excep...
Return value of text. Return False if text is invalid, raise exception if text is intermediate
entailment
def editingFinishedEvent(self): """Edit has finished; set value.""" #print "Edit finished." if asUnicode(self.lineEdit().text()) == self.lastText: #print "no text change." return try: val = self.interpret() except: return ...
Edit has finished; set value.
entailment
def make_factory(self, cls, count): """ Get the generators from the Scaffolding class within the model. """ field_names = cls._meta.get_all_field_names() fields = {} text = [] finalizer = None scaffold = scaffolding.scaffold_for_model(cls) for field_name ...
Get the generators from the Scaffolding class within the model.
entailment
def compute_indel_length(fs_df): """Computes the indel length accounting for wether it is an insertion or deletion. Parameters ---------- fs_df : pd.DataFrame mutation input as dataframe only containing indel mutations Returns ------- indel_len : pd.Series length of ind...
Computes the indel length accounting for wether it is an insertion or deletion. Parameters ---------- fs_df : pd.DataFrame mutation input as dataframe only containing indel mutations Returns ------- indel_len : pd.Series length of indels
entailment
def keep_indels(mut_df, indel_len_col=True, indel_type_col=True): """Filters out all mutations that are not indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, resp...
Filters out all mutations that are not indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, respectively. Parameters ---------- mut_df : pd.DataFrame mutation input file as a dataf...
entailment
def keep_frameshifts(mut_df, indel_len_col=True): """Filters out all mutations that are not frameshift indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, respectively. P...
Filters out all mutations that are not frameshift indels. Requires that one of the alleles have '-' indicating either an insertion or deletion depending if found in reference allele or somatic allele columns, respectively. Parameters ---------- mut_df : pd.DataFrame mutation input file...
entailment
def is_frameshift_len(mut_df): """Simply returns a series indicating whether each corresponding mutation is a frameshift. This is based on the length of the indel. Thus may be fooled by frameshifts at exon-intron boundaries or other odd cases. Parameters ---------- mut_df : pd.DataFrame ...
Simply returns a series indicating whether each corresponding mutation is a frameshift. This is based on the length of the indel. Thus may be fooled by frameshifts at exon-intron boundaries or other odd cases. Parameters ---------- mut_df : pd.DataFrame mutation input file as a datafra...
entailment
def get_frameshift_lengths(num_bins): """Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested. """ fs_len = [] i = 1 tmp_bins = 0 while(tmp_bins<num_bins): if i%3: fs_len.append(i) tm...
Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested.
entailment
def _init_context(self, gene_seq): """Initializes attributes defining mutation contexts and their position. The self.context2pos and self.pos2context dictionaries map from sequence context to sequence position and sequence position to sequence context, respectively. These attributes all...
Initializes attributes defining mutation contexts and their position. The self.context2pos and self.pos2context dictionaries map from sequence context to sequence position and sequence position to sequence context, respectively. These attributes allow for randomly sampling of mutation p...
entailment
def random_context_pos(self, num, num_permutations, context): """Samples with replacement available positions matching the sequence context. Note: this method does random sampling only for an individual sequence context. Parameters ---------- num : int ...
Samples with replacement available positions matching the sequence context. Note: this method does random sampling only for an individual sequence context. Parameters ---------- num : int Number of positions to sample for each permutation. This i...
entailment
def random_pos(self, context_iterable, num_permutations): """Obtains random positions w/ replacement which match sequence context. Parameters ---------- context_iterable: iterable containing two element tuple Records number of mutations in each context. context_iterable ...
Obtains random positions w/ replacement which match sequence context. Parameters ---------- context_iterable: iterable containing two element tuple Records number of mutations in each context. context_iterable should be something like [('AA', 5), ...]. num_permut...
entailment
def multiprocess_permutation(bed_dict, mut_df, opts, indel_df=None): """Handles parallelization of permutations by splitting work by chromosome. """ chroms = sorted(bed_dict.keys(), key=lambda x: len(bed_dict[x]), reverse=True) multiprocess_flag = opts['processes']>0 if multiprocess_flag: ...
Handles parallelization of permutations by splitting work by chromosome.
entailment
def multiprocess_permutation(bed_dict, mut_df, opts): """Handles parallelization of permutations by splitting work by chromosome. """ chroms = sorted(bed_dict.keys()) multiprocess_flag = opts['processes']>0 if multiprocess_flag: num_processes = opts['processes'] else: num_pro...
Handles parallelization of permutations by splitting work by chromosome.
entailment
def retrieve_scores(gname, sdir, codon_pos, germ_aa, somatic_aa, default_mga=5., default_vest=0, no_file_flag=-1): """Retrieves scores from pickle files. Used by summary script. """ # get variant types #var_class = cutils.get_variant_clas...
Retrieves scores from pickle files. Used by summary script.
entailment
def read_vest_pickle(gname, score_dir): """Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns ...
Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns None if not found.
entailment
def compute_vest_stat(vest_dict, ref_aa, somatic_aa, codon_pos, stat_func=np.mean, default_val=0.0): """Compute missense VEST score statistic. Note: non-missense mutations are intentially not filtered out and will take a default value of zero. Parameters ...
Compute missense VEST score statistic. Note: non-missense mutations are intentially not filtered out and will take a default value of zero. Parameters ---------- vest_dict : dict dictionary containing vest scores across the gene of interest ref_aa: list of str list of reference...
entailment
def compute_mga_entropy_stat(mga_vec, codon_pos, stat_func=np.mean, default_val=0.0): """Compute MGA entropy conservation statistic Parameters ---------- mga_vec : np.array numpy vector containing MGA Entropy conservation scores for resi...
Compute MGA entropy conservation statistic Parameters ---------- mga_vec : np.array numpy vector containing MGA Entropy conservation scores for residues codon_pos : list of int position of codon in protein sequence stat_func : function, default=np.mean function that calculat...
entailment
def fetch_vest_scores(vest_dict, ref_aa, somatic_aa, codon_pos, default_vest=0.0): """Get VEST scores from pre-computed scores in dictionary. Note: either all mutations should be missense or non-missense intended to have value equal to default. Parameters ...
Get VEST scores from pre-computed scores in dictionary. Note: either all mutations should be missense or non-missense intended to have value equal to default. Parameters ---------- vest_dict : dict dictionary containing vest scores across the gene of interest ref_aa: list of str ...
entailment
def fetch_mga_scores(mga_vec, codon_pos, default_mga=None): """Get MGAEntropy scores from pre-computed scores in array. Parameters ---------- mga_vec : np.array numpy vector containing MGA Entropy conservation scores for residues codon_pos: list of ...
Get MGAEntropy scores from pre-computed scores in array. Parameters ---------- mga_vec : np.array numpy vector containing MGA Entropy conservation scores for residues codon_pos: list of int position of codon in protein sequence default_mga: float or None, default=None value ...
entailment
def read_neighbor_graph_pickle(gname, graph_dir): """Read in neighbor graph for given gene. Parameters ---------- gname : str name of gene graph_dir : str directory containing gene graphs Returns ------- gene_graph : dict or None neighbor graph as dict for gene....
Read in neighbor graph for given gene. Parameters ---------- gname : str name of gene graph_dir : str directory containing gene graphs Returns ------- gene_graph : dict or None neighbor graph as dict for gene. Returns None if not found.
entailment
def compute_ng_stat(gene_graph, pos_ct, alpha=.5): """Compute the clustering score for the gene on its neighbor graph. Parameters ---------- gene_graph : dict Graph of spatially near codons. keys = nodes, edges = key -> value. pos_ct : dict missense mutation count for each codon ...
Compute the clustering score for the gene on its neighbor graph. Parameters ---------- gene_graph : dict Graph of spatially near codons. keys = nodes, edges = key -> value. pos_ct : dict missense mutation count for each codon alpha : float smoothing factor Returns -...
entailment
def count_frameshift_total(mut_df, bed_path, use_unmapped=False, to_zero_based=False): """Count frameshifts for each gene. Parameters ---------- mut_df : pd.DataFrame mutation input bed_path : str path ...
Count frameshifts for each gene. Parameters ---------- mut_df : pd.DataFrame mutation input bed_path : str path to BED file containing reference tx for genes use_unmapped : Bool flag indicating whether to include frameshifts not mapping to reference tx to_zero_ba...
entailment
def _fetch_3ss_fasta(fasta, gene_name, exon_num, chrom, strand, start, end): """Retreives the 3' SS sequence flanking the specified exon. Returns a string in fasta format with the first line containing a ">" and the second line contains the two base pairs of 3' SS. Parameters ...
Retreives the 3' SS sequence flanking the specified exon. Returns a string in fasta format with the first line containing a ">" and the second line contains the two base pairs of 3' SS. Parameters ---------- fasta : pysam.Fastafile fasta object from pysam gene_name : str gene n...
entailment
def fetch_gene_fasta(gene_bed, fasta_obj): """Retreive gene sequences in FASTA format. Parameters ---------- gene_bed : BedLine BedLine object representing a single gene fasta_obj : pysam.Fastafile fasta object for index retreival of sequence Returns ------- gene_fasta ...
Retreive gene sequences in FASTA format. Parameters ---------- gene_bed : BedLine BedLine object representing a single gene fasta_obj : pysam.Fastafile fasta object for index retreival of sequence Returns ------- gene_fasta : str sequence of gene in FASTA format
entailment
def _reset_seq(self): """Updates attributes for gene represented in the self.bed attribute. Sequences are always upper case. """ exon_seq_list, five_ss_seq_list, three_ss_seq_list = self._fetch_seq() self.exon_seq = ''.join(exon_seq_list) self.three_prime_seq = three_ss_...
Updates attributes for gene represented in the self.bed attribute. Sequences are always upper case.
entailment
def add_germline_variants(self, germline_nucs, coding_pos): """Add potential germline variants into the nucleotide sequence. Sequenced individuals may potentially have a SNP at a somatic mutation position. Therefore they may differ from the reference genome. This method updates the gene ...
Add potential germline variants into the nucleotide sequence. Sequenced individuals may potentially have a SNP at a somatic mutation position. Therefore they may differ from the reference genome. This method updates the gene germline gene sequence to match the actual individual. Parame...
entailment
def _to_upper(self): """Convert sequences to upper case.""" self.exon_seq = self.exon_seq.upper() self.three_prime_seq = [s.upper() for s in self.three_prime_seq] self.five_prime_seq = [s.upper() for s in self.five_prime_seq]
Convert sequences to upper case.
entailment
def _fetch_seq(self): """Fetches gene sequence from PySAM fasta object. Returns ------- exons : list of str list of exon nucleotide sequences five_prime_ss : list of str list of 5' splice site sequences three_prime_ss : list of str lis...
Fetches gene sequence from PySAM fasta object. Returns ------- exons : list of str list of exon nucleotide sequences five_prime_ss : list of str list of 5' splice site sequences three_prime_ss : list of str list of 3' splice site sequences
entailment
def correct_chrom_names(chroms): """Make sure chromosome names follow UCSC chr convention.""" chrom_list = [] for chrom in chroms: # fix chrom numbering chrom = str(chrom) chrom = chrom.replace('23', 'X') chrom = chrom.replace('24', 'Y') chrom = chrom.replace('25', 'M...
Make sure chromosome names follow UCSC chr convention.
entailment
def fishers_method(pvals): """Fisher's method for combining independent p-values.""" pvals = np.asarray(pvals) degrees_of_freedom = 2 * pvals.size chisq_stat = np.sum(-2*np.log(pvals)) fishers_pval = stats.chi2.sf(chisq_stat, degrees_of_freedom) return fishers_pval
Fisher's method for combining independent p-values.
entailment
def cummin(x): """A python implementation of the cummin function in R""" for i in range(1, len(x)): if x[i-1] < x[i]: x[i] = x[i-1] return x
A python implementation of the cummin function in R
entailment
def bh_fdr(pval): """A python implementation of the Benjamani-Hochberg FDR method. This code should always give precisely the same answer as using p.adjust(pval, method="BH") in R. Parameters ---------- pval : list or array list/array of p-values Returns ------- pval_adj :...
A python implementation of the Benjamani-Hochberg FDR method. This code should always give precisely the same answer as using p.adjust(pval, method="BH") in R. Parameters ---------- pval : list or array list/array of p-values Returns ------- pval_adj : np.array adjuste...
entailment
def calc_deleterious_p_value(mut_info, unmapped_mut_info, sc, gs, bed, num_permutations, stop_thresh, del_threshold, ...
Calculates the p-value for the number of inactivating SNV mutations. Calculates p-value based on how many simulations exceed the observed value. Parameters ---------- mut_info : dict contains codon and amino acid residue information for mutations mappable to provided reference tx. ...
entailment
def calc_protein_p_value(mut_info, unmapped_mut_info, sc, gs, bed, graph_dir, num_permutations, stop_thresh, min_recurre...
Computes the p-value for clustering on a neighbor graph composed of codons connected with edges if they are spatially near in 3D protein structure. Parameters ---------- Returns -------
entailment
def shannon_entropy(p): """Calculates shannon entropy in bits. Parameters ---------- p : np.array array of probabilities Returns ------- shannon entropy in bits """ return -np.sum(np.where(p!=0, p * np.log2(p), 0))
Calculates shannon entropy in bits. Parameters ---------- p : np.array array of probabilities Returns ------- shannon entropy in bits
entailment
def normalized_mutation_entropy(counts, total_cts=None): """Calculate the normalized mutation entropy based on a list/array of mutation counts. Note: Any grouping of mutation counts together should be done before hand Parameters ---------- counts : np.array_like array/list of mutation ...
Calculate the normalized mutation entropy based on a list/array of mutation counts. Note: Any grouping of mutation counts together should be done before hand Parameters ---------- counts : np.array_like array/list of mutation counts Returns ------- norm_ent : float nor...
entailment
def kl_divergence(p, q): """Compute the Kullback-Leibler (KL) divergence for discrete distributions. Parameters ---------- p : np.array "Ideal"/"true" Probability distribution q : np.array Approximation of probability distribution p Returns ------- kl : float KL...
Compute the Kullback-Leibler (KL) divergence for discrete distributions. Parameters ---------- p : np.array "Ideal"/"true" Probability distribution q : np.array Approximation of probability distribution p Returns ------- kl : float KL divergence of approximating p w...
entailment
def js_divergence(p, q): """Compute the Jensen-Shannon Divergence between two discrete distributions. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability mass array (sums to 1) Returns ------- js_div : float js divergen...
Compute the Jensen-Shannon Divergence between two discrete distributions. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability mass array (sums to 1) Returns ------- js_div : float js divergence between the two distrubtions
entailment
def js_distance(p, q): """Compute the Jensen-Shannon distance between two discrete distributions. NOTE: JS divergence is not a metric but the sqrt of JS divergence is a metric and is called the JS distance. Parameters ---------- p : np.array probability mass array (sums to 1) q : n...
Compute the Jensen-Shannon distance between two discrete distributions. NOTE: JS divergence is not a metric but the sqrt of JS divergence is a metric and is called the JS distance. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability ma...
entailment
def _filter_utr(self, ex): """Filter out UTR regions from the exon list (ie retain only coding regions). Coding regions are defined by the thickStart and thickEnd attributes. Parameters ---------- ex : list of tuples list of exon positions, [(ex1_start, ex1_end), .....
Filter out UTR regions from the exon list (ie retain only coding regions). Coding regions are defined by the thickStart and thickEnd attributes. Parameters ---------- ex : list of tuples list of exon positions, [(ex1_start, ex1_end), ...] Returns ------- ...
entailment
def _init_exons(self): """Sets a list of position intervals for each exon. Only coding regions as defined by thickStart and thickEnd are kept. Exons are stored in the self.exons attribute. """ exon_starts = [self.chrom_start + int(s) for s in self.bed_tupl...
Sets a list of position intervals for each exon. Only coding regions as defined by thickStart and thickEnd are kept. Exons are stored in the self.exons attribute.
entailment
def init_genome_coordinates(self) : """Creates the self.seqpos2genome dictionary that converts positions relative to the sequence to genome coordinates.""" self.seqpos2genome = {} # record genome positions for each sequence position seq_pos = 0 for estart, eend in self.e...
Creates the self.seqpos2genome dictionary that converts positions relative to the sequence to genome coordinates.
entailment
def query_position(self, strand, chr, genome_coord): """Provides the relative position on the coding sequence for a given genomic position. Parameters ---------- chr : str chromosome, provided to check validity of query genome_coord : int 0-based ...
Provides the relative position on the coding sequence for a given genomic position. Parameters ---------- chr : str chromosome, provided to check validity of query genome_coord : int 0-based position for mutation, actually used to get relative coding pos ...
entailment
def start_logging(log_file='', log_level='INFO', verbose=False): """Start logging information into the log directory. If os.devnull is specified as the log_file then the log file will not actually be written to a file. """ if not log_file: # create log directory if it doesn't exist ...
Start logging information into the log directory. If os.devnull is specified as the log_file then the log file will not actually be written to a file.
entailment
def log_error_decorator(f): """Writes exception to log file if occured in decorated function. This decorator wrapper is needed for multiprocess logging since otherwise the python multiprocessing module will obscure the actual line of the error. """ @wraps(f) def wrapper(*args, **kwds): ...
Writes exception to log file if occured in decorated function. This decorator wrapper is needed for multiprocess logging since otherwise the python multiprocessing module will obscure the actual line of the error.
entailment
def filter_list(mylist, bad_ixs): """Removes indices from a list. All elements in bad_ixs will be removed from the list. Parameters ---------- mylist : list list to filter out specific indices bad_ixs : list of ints indices to remove from list Returns ------- mylis...
Removes indices from a list. All elements in bad_ixs will be removed from the list. Parameters ---------- mylist : list list to filter out specific indices bad_ixs : list of ints indices to remove from list Returns ------- mylist : list list with elements filte...
entailment
def rev_comp(seq): """Get reverse complement of sequence. rev_comp will maintain the case of the sequence. Parameters ---------- seq : str nucleotide sequence. valid {a, c, t, g, n} Returns ------- rev_comp_seq : str reverse complement of sequence """ rev_seq =...
Get reverse complement of sequence. rev_comp will maintain the case of the sequence. Parameters ---------- seq : str nucleotide sequence. valid {a, c, t, g, n} Returns ------- rev_comp_seq : str reverse complement of sequence
entailment
def bed_generator(bed_path): """Iterates through a BED file yielding parsed BED lines. Parameters ---------- bed_path : str path to BED file Yields ------ BedLine(line) : BedLine A BedLine object which has parsed the individual line in a BED file. """ with o...
Iterates through a BED file yielding parsed BED lines. Parameters ---------- bed_path : str path to BED file Yields ------ BedLine(line) : BedLine A BedLine object which has parsed the individual line in a BED file.
entailment
def read_bed(file_path, restricted_genes=None): """Reads BED file and populates a dictionary separating genes by chromosome. Parameters ---------- file_path : str path to BED file filtered_genes: list list of gene names to not use Returns ------- bed_dict: dict ...
Reads BED file and populates a dictionary separating genes by chromosome. Parameters ---------- file_path : str path to BED file filtered_genes: list list of gene names to not use Returns ------- bed_dict: dict dictionary mapping chromosome keys to a list of BED...
entailment
def _fix_mutation_df(mutation_df, only_unique=False): """Drops invalid mutations and corrects for 1-based coordinates. TODO: Be smarter about what coordinate system is put in the provided mutations. Parameters ---------- mutation_df : pd.DataFrame user provided mutations only_uniqu...
Drops invalid mutations and corrects for 1-based coordinates. TODO: Be smarter about what coordinate system is put in the provided mutations. Parameters ---------- mutation_df : pd.DataFrame user provided mutations only_unique : bool flag indicating whether only unique mutation...
entailment
def calc_windowed_sum(aa_mut_pos, germ_aa, somatic_aa, window=[3]): """Calculate the sum of mutations within a window around a particular mutated codon. Parameters ---------- aa_mut_pos : list list of mutated amino acid posit...
Calculate the sum of mutations within a window around a particular mutated codon. Parameters ---------- aa_mut_pos : list list of mutated amino acid positions germ_aa : list Reference amino acid somatic_aa : list Somatic amino acid (if missense) window : list ...
entailment
def get_all_context_names(context_num): """Based on the nucleotide base context number, return a list of strings representing each context. Parameters ---------- context_num : int number representing the amount of nucleotide base context to use. Returns ------- a list of st...
Based on the nucleotide base context number, return a list of strings representing each context. Parameters ---------- context_num : int number representing the amount of nucleotide base context to use. Returns ------- a list of strings containing the names of the base contexts
entailment
def get_chasm_context(tri_nuc): """Returns the mutation context acording to CHASM. For more information about CHASM's mutation context, look at http://wiki.chasmsoftware.org/index.php/CHASM_Overview. Essentially CHASM uses a few specified di-nucleotide contexts followed by single nucleotide context...
Returns the mutation context acording to CHASM. For more information about CHASM's mutation context, look at http://wiki.chasmsoftware.org/index.php/CHASM_Overview. Essentially CHASM uses a few specified di-nucleotide contexts followed by single nucleotide context. Parameters ---------- tr...
entailment
def get_aa_mut_info(coding_pos, somatic_base, gene_seq): """Retrieves relevant information about the effect of a somatic SNV on the amino acid of a gene. Information includes the germline codon, somatic codon, codon position, germline AA, and somatic AA. Parameters ---------- coding_pos : ...
Retrieves relevant information about the effect of a somatic SNV on the amino acid of a gene. Information includes the germline codon, somatic codon, codon position, germline AA, and somatic AA. Parameters ---------- coding_pos : iterable of ints Contains the base position (0-based) of...
entailment
def handle_tsg_results(permutation_result): """Handles result from TSG results. Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ---...
Handles result from TSG results. Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame form...
entailment
def handle_oncogene_results(permutation_result, num_permutations): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permut...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
entailment
def handle_hotmaps_results(permutation_result): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataF...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
entailment
def handle_protein_results(permutation_result): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataF...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
entailment
def handle_effect_results(permutation_result): """Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFr...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
entailment
def get_frameshift_info(fs_df, bins): """Counts frameshifts stratified by a given length. Parameters ---------- fs_df : pd.DataFrame indel mutations from non-coding portion bins : int number of different length categories for frameshifts Returns ------- indel_len : list...
Counts frameshifts stratified by a given length. Parameters ---------- fs_df : pd.DataFrame indel mutations from non-coding portion bins : int number of different length categories for frameshifts Returns ------- indel_len : list length of specific frameshift length...
entailment
def set_mutation_type(self, mut_type=''): """Sets the mutation type attribute to a single label based on attribute flags. Kwargs: mut_type (str): value to set self.mut_type """ if mut_type: # user specifies a mutation type self.mutation_type =...
Sets the mutation type attribute to a single label based on attribute flags. Kwargs: mut_type (str): value to set self.mut_type
entailment
def set_amino_acid(self, aa): """Set amino acid change and position.""" aa = aa.upper() # make sure it is upper case aa = aa[2:] if aa.startswith('P.') else aa # strip "p." self.__set_mutation_status() # set flags detailing the type of mutation self.__parse_hgvs_syntax(aa)
Set amino acid change and position.
entailment
def __set_mutation_type(self, hgvs_string): """Interpret the mutation type (missense, etc.) and set appropriate flags. Args: hgvs_string (str): hgvs syntax with "p." removed """ self.__set_lost_stop_status(hgvs_string) self.__set_lost_start_status(hgvs_string) ...
Interpret the mutation type (missense, etc.) and set appropriate flags. Args: hgvs_string (str): hgvs syntax with "p." removed
entailment
def __set_missense_status(self, hgvs_string): """Sets the self.is_missense flag.""" # set missense status if re.search('^[A-Z?]\d+[A-Z?]$', hgvs_string): self.is_missense = True self.is_non_silent = True else: self.is_missense = False
Sets the self.is_missense flag.
entailment
def __set_lost_start_status(self, hgvs_string): """Sets the self.is_lost_start flag.""" # set is lost start status mymatch = re.search('^([A-Z?])(\d+)([A-Z?])$', hgvs_string) if mymatch: grps = mymatch.groups() if int(grps[1]) == 1 and grps[0] != grps[2]: ...
Sets the self.is_lost_start flag.
entailment
def __set_frame_shift_status(self): """Check for frame shift and set the self.is_frame_shift flag.""" if 'fs' in self.hgvs_original: self.is_frame_shift = True self.is_non_silent = True elif re.search('[A-Z]\d+[A-Z]+\*', self.hgvs_original): # it looks like so...
Check for frame shift and set the self.is_frame_shift flag.
entailment
def __set_lost_stop_status(self, hgvs_string): """Check if the stop codon was mutated to something other than a stop codon.""" lost_stop_pattern = '^\*\d+[A-Z?]+\*?$' if re.search(lost_stop_pattern, hgvs_string): self.is_lost_stop = True self.is_non_silent = True ...
Check if the stop codon was mutated to something other than a stop codon.
entailment
def __set_premature_stop_codon_status(self, hgvs_string): """Set whether there is a premature stop codon.""" if re.search('.+\*(\d+)?$', hgvs_string): self.is_premature_stop_codon = True self.is_non_silent = True # check if it is also a nonsense mutation ...
Set whether there is a premature stop codon.
entailment
def __set_indel_status(self): """Sets flags related to the mutation being an indel.""" # set indel status if "ins" in self.hgvs_original: # mutation is insertion self.is_insertion = True self.is_deletion = False self.is_indel = True sel...
Sets flags related to the mutation being an indel.
entailment
def __set_unkown_effect(self, hgvs_string): """Sets a flag for unkown effect according to HGVS syntax. The COSMIC database also uses unconventional questionmarks to denote missing information. Args: hgvs_string (str): hgvs syntax with "p." removed """ # Stand...
Sets a flag for unkown effect according to HGVS syntax. The COSMIC database also uses unconventional questionmarks to denote missing information. Args: hgvs_string (str): hgvs syntax with "p." removed
entailment
def __set_no_protein(self, hgvs_string): """Set a flag for no protein expected. ("p.0" or "p.0?") Args: hgvs_string (str): hgvs syntax with "p." removed """ no_protein_list = ['0', '0?'] # no protein symbols if hgvs_string in no_protein_list: self.is_no_...
Set a flag for no protein expected. ("p.0" or "p.0?") Args: hgvs_string (str): hgvs syntax with "p." removed
entailment
def __parse_hgvs_syntax(self, aa_hgvs): """Convert HGVS syntax for amino acid change into attributes. Specific details of the mutation are stored in attributes like self.intial (prior to mutation), sel.pos (mutation position), self.mutated (mutation), and self.stop_pos (position of stop...
Convert HGVS syntax for amino acid change into attributes. Specific details of the mutation are stored in attributes like self.intial (prior to mutation), sel.pos (mutation position), self.mutated (mutation), and self.stop_pos (position of stop codon, if any). Args: ...
entailment
def deleterious_permutation(obs_del, context_counts, context_to_mut, seq_context, gene_seq, num_permutations=10000, stop_criteria=100, ...
Performs null-permutations for deleterious mutation statistics in a single gene. Parameters ---------- context_counts : pd.Series number of mutations for each context context_to_mut : dict dictionary mapping nucleotide context to a list of observed somatic base changes. ...
entailment
def position_permutation(obs_stat, context_counts, context_to_mut, seq_context, gene_seq, gene_vest=None, num_permutations=10000, stop_criteria=1...
Performs null-permutations for position-based mutation statistics in a single gene. Parameters ---------- obs_stat : tuple, (recur ct, entropy, delta entropy, mean vest) tuple containing the observed statistics context_counts : pd.Series number of mutations for each context cont...
entailment
def hotmaps_permutation(obs_stat, context_counts, context_to_mut, seq_context, gene_seq, window, num_permutations=10000, stop_criteria=100, ...
Performs null-permutations for position-based mutation statistics in a single gene. Parameters ---------- obs_stat : dict dictionary mapping codons to the sum of mutations in a window context_counts : pd.Series number of mutations for each context context_to_mut : dict d...
entailment
def protein_permutation(graph_score, num_codons_obs, context_counts, context_to_mut, seq_context, gene_seq, gene_graph, num_permutations=10000, ...
Performs null-simulations for position-based mutation statistics in a single gene. Parameters ---------- graph_score : float clustering score for observed data num_codons_obs : int number of codons with missense mutation in observed data context_counts : pd.Series number...
entailment
def effect_permutation(context_counts, context_to_mut, seq_context, gene_seq, num_permutations=10000, pseudo_count=0): """Performs null-permutations for effect-based mutation statistics in a single...
Performs null-permutations for effect-based mutation statistics in a single gene. Parameters ---------- context_counts : pd.Series number of mutations for each context context_to_mut : dict dictionary mapping nucleotide context to a list of observed somatic base changes. ...
entailment
def non_silent_ratio_permutation(context_counts, context_to_mut, seq_context, gene_seq, num_permutations=10000): """Performs null-permutations for non-silent ratio across all genes. ...
Performs null-permutations for non-silent ratio across all genes. Parameters ---------- context_counts : pd.Series number of mutations for each context context_to_mut : dict dictionary mapping nucleotide context to a list of observed somatic base changes. seq_context : Seque...
entailment
def summary_permutation(context_counts, context_to_mut, seq_context, gene_seq, score_dir, num_permutations=10000, min_frac=0.0, min_recur=2, ...
Performs null-permutations and summarizes the results as features over the gene. Parameters ---------- context_counts : pd.Series number of mutations for each context context_to_mut : dict dictionary mapping nucleotide context to a list of observed somatic base changes. ...
entailment
def maf_permutation(context_counts, context_to_mut, seq_context, gene_seq, num_permutations=10000, drop_silent=False): """Performs null-permutations across all genes and records the results in a format like a MAF...
Performs null-permutations across all genes and records the results in a format like a MAF file. This could be useful for examining the null permutations because the alternative approaches always summarize the results. With the simulated null-permutations, novel metrics can be applied to create an empir...
entailment
def markdown(value, extensions=settings.MARKDOWN_EXTENSIONS, extension_configs=settings.MARKDOWN_EXTENSION_CONFIGS, safe=False): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. :retu...
Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. :returns: A rendered markdown
entailment
def editor_js_initialization(selector, **extra_settings): """ Return script tag with initialization code. """ init_template = loader.get_template( settings.MARKDOWN_EDITOR_INIT_TEMPLATE) options = dict( previewParserPath=reverse('django_markdown_preview'), **settings.MARKDOWN_EDITO...
Return script tag with initialization code.
entailment
def preview(request): """ Render preview page. :returns: A rendered preview """ if settings.MARKDOWN_PROTECT_PREVIEW: user = getattr(request, 'user', None) if not user or not user.is_staff: from django.contrib.auth.views import redirect_to_login return redirect_...
Render preview page. :returns: A rendered preview
entailment
def register(): """ Register markdown for flatpages. """ admin.site.unregister(FlatPage) admin.site.register(FlatPage, LocalFlatPageAdmin)
Register markdown for flatpages.
entailment
def main(argv=None): """Command line options.""" program_name = __programm_name__ program_version = "v%s" % __version__ program_descrption = __programm_description__ try: # Setup argument parser parser = ArgumentParser(prog=program_name, description=program_descrption) p...
Command line options.
entailment
def markdown(value, arg=None): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. Syntax: :: {{value|markdown}} {{value|markdown:"tables,codehilite"}} :returns: A rendered markdown ""...
Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. Syntax: :: {{value|markdown}} {{value|markdown:"tables,codehilite"}} :returns: A rendered markdown
entailment