_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q2100
TwitterStream.datagramReceived
train
def datagramReceived(self, data): """ Decode the JSON-encoded datagram and call the callback. """ try: obj = json.loads(data) except ValueError, e: log.err(e, 'Invalid JSON in stream: %r' % data) return if u'text' in obj: obj = Status.fromDict(obj) else: log.msg('Unsupported object %r' % obj) return self.callback(obj)
python
{ "resource": "" }
q2101
TwitterStream.connectionLost
train
def connectionLost(self, reason): """ Called when the body is complete or the connection was lost. @note: As the body length is usually not known at the beginning of the response we expect a L{PotentialDataLoss} when Twitter closes the stream, instead of L{ResponseDone}. Other exceptions are treated as error conditions. """ self.setTimeout(None) if reason.check(ResponseDone, PotentialDataLoss): self.deferred.callback(None) else: self.deferred.errback(reason)
python
{ "resource": "" }
q2102
simpleListFactory
train
def simpleListFactory(list_type): """Used for simple parsers that support only one type of object""" def create(delegate, extra_args=None): """Create a Parser object for the specific tag type, on the fly""" return listParser(list_type, delegate, extra_args) return create
python
{ "resource": "" }
q2103
BaseXMLHandler.setSubDelegates
train
def setSubDelegates(self, namelist, before=None, after=None): """Set a delegate for a sub-sub-item, according to a list of names""" if len(namelist) > 1: def set_sub(i): i.setSubDelegates(namelist[1:], before, after) self.setBeforeDelegate(namelist[0], set_sub) elif len(namelist) == 1: self.setDelegate(namelist[0], before, after)
python
{ "resource": "" }
q2104
_split_path
train
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, list_path, path
python
{ "resource": "" }
q2105
MixedContentsManager.path_dispatch_rename
train
def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrapper_method(self, old_path, new_path): old_path, _old_path, old_sentinel = _split_path(old_path); new_path, _new_path, new_sentinel = _split_path(new_path); if old_sentinel != new_sentinel: raise ValueError('Does not know how to move things across contents manager mountpoints') else: sentinel = new_sentinel man = self.managers.get(sentinel, None) if man is not None: rename_meth = getattr(man, rename_like_method.__name__) sub = rename_meth('/'.join(_old_path), '/'.join(_new_path)) return sub else : return rename_meth(self, old_path, new_path) return _wrapper_method
python
{ "resource": "" }
q2106
deactivate
train
def deactivate(profile='default'): """should be a matter of just unsetting the above keys """ with jconfig(profile) as config: deact = True; if not getattr(config.NotebookApp.contents_manager_class, 'startswith',lambda x:False)('jupyterdrive'): deact=False if 'gdrive' not in getattr(config.NotebookApp.tornado_settings,'get', lambda _,__:'')('contents_js_source',''): deact=False if deact: del config['NotebookApp']['tornado_settings']['contents_js_source'] del config['NotebookApp']['contents_manager_class']
python
{ "resource": "" }
q2107
sequence_type
train
def sequence_type(seq): '''Validates a coral.sequence data type. :param sequence_in: input DNA sequence. :type sequence_in: any :returns: The material - 'dna', 'rna', or 'peptide'. :rtype: str :raises: ValueError ''' if isinstance(seq, coral.DNA): material = 'dna' elif isinstance(seq, coral.RNA): material = 'rna' elif isinstance(seq, coral.Peptide): material = 'peptide' else: raise ValueError('Input was not a recognized coral.sequence object.') return material
python
{ "resource": "" }
q2108
digest
train
def digest(dna, restriction_enzyme): '''Restriction endonuclease reaction. :param dna: DNA template to digest. :type dna: coral.DNA :param restriction_site: Restriction site to use. :type restriction_site: RestrictionSite :returns: list of digested DNA fragments. :rtype: coral.DNA list ''' pattern = restriction_enzyme.recognition_site located = dna.locate(pattern) if not located[0] and not located[1]: return [dna] # Bottom strand indices are relative to the bottom strand 5' end. # Convert to same type as top strand pattern_len = len(pattern) r_indices = [len(dna) - index - pattern_len for index in located[1]] # If sequence is palindrome, remove redundant results if pattern.is_palindrome(): r_indices = [index for index in r_indices if index not in located[0]] # Flatten cut site indices cut_sites = sorted(located[0] + r_indices) # Go through each cut site starting at highest one # Cut remaining template once, generating remaining + new current = [dna] for cut_site in cut_sites[::-1]: new = _cut(current, cut_site, restriction_enzyme) current.append(new[1]) current.append(new[0]) current.reverse() # Combine first and last back together if digest was circular if dna.circular: current[0] = current.pop() + current[0] return current
python
{ "resource": "" }
q2109
_cut
train
def _cut(dna, index, restriction_enzyme): '''Cuts template once at the specified index. :param dna: DNA to cut :type dna: coral.DNA :param index: index at which to cut :type index: int :param restriction_enzyme: Enzyme with which to cut :type restriction_enzyme: coral.RestrictionSite :returns: 2-element list of digested sequence, including any overhangs. :rtype: list ''' # TODO: handle case where cut site is outside of recognition sequence, # for both circular and linear cases where site is at index 0 # Find absolute indices at which to cut cut_site = restriction_enzyme.cut_site top_cut = index + cut_site[0] bottom_cut = index + cut_site[1] # Isolate left and ride sequences to_cut = dna.pop() max_cut = max(top_cut, bottom_cut) min_cut = min(top_cut, bottom_cut) left = to_cut[:max_cut] right = to_cut[min_cut:] # If applicable, leave overhangs diff = top_cut - bottom_cut if not diff: # Blunt-end cutter, no adjustment necessary pass elif diff > 0: # 3' overhangs left = coral.reaction.five_resect(left.flip(), diff).flip() right = coral.reaction.five_resect(right, diff) else: # 5' overhangs left = coral.reaction.three_resect(left, abs(diff)) right = coral.reaction.three_resect(right.flip(), abs(diff)).flip() return [left, right]
python
{ "resource": "" }
q2110
ipynb_to_rst
train
def ipynb_to_rst(directory, filename): """Converts a given file in a directory to an rst in the same directory.""" print(filename) os.chdir(directory) subprocess.Popen(["ipython", "nbconvert", "--to", "rst", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=directory)
python
{ "resource": "" }
q2111
convert_ipynbs
train
def convert_ipynbs(directory): """Recursively converts all ipynb files in a directory into rst files in the same directory.""" # The ipython_examples dir has to be in the same dir as this script for root, subfolders, files in os.walk(os.path.abspath(directory)): for f in files: if ".ipynb_checkpoints" not in root: if f.endswith("ipynb"): ipynb_to_rst(root, f)
python
{ "resource": "" }
q2112
_context_walk
train
def _context_walk(dna, window_size, context_len, step): '''Generate context-dependent 'non-boundedness' scores for a DNA sequence. :param dna: Sequence to score. :type dna: coral.DNA :param window_size: Window size in base pairs. :type window_size: int :param context_len: The number of bases of context to use when analyzing each window. :type context_len: int :param step: The number of base pairs to move for each new window. :type step: int ''' # Generate window indices window_start_ceiling = len(dna) - context_len - window_size window_starts = range(context_len - 1, window_start_ceiling, step) window_ends = [start + window_size for start in window_starts] # Generate left and right in-context subsequences l_starts = [step * i for i in range(len(window_starts))] l_seqs = [dna[start:end] for start, end in zip(l_starts, window_ends)] r_ends = [x + window_size + context_len for x in window_starts] r_seqs = [dna[start:end].reverse_complement() for start, end in zip(window_starts, r_ends)] # Combine and calculate nupack pair probabilities seqs = l_seqs + r_seqs pairs_run = coral.analysis.nupack_multi(seqs, 'dna', 'pairs', {'index': 0}) # Focus on pair probabilities that matter - those in the window pairs = [run[-window_size:] for run in pairs_run] # Score by average pair probability lr_scores = [sum(pair) / len(pair) for pair in pairs] # Split into left-right contexts again and sum for each window l_scores = lr_scores[0:len(seqs) / 2] r_scores = lr_scores[len(seqs) / 2:] scores = [(l + r) / 2 for l, r in zip(l_scores, r_scores)] # Summarize and return window indices and score summary = zip(window_starts, window_ends, scores) return summary
python
{ "resource": "" }
q2113
StructureWindows.plot
train
def plot(self): '''Plot the results of the run method.''' try: from matplotlib import pylab except ImportError: raise ImportError('Optional dependency matplotlib not installed.') if self.walked: fig = pylab.figure() ax1 = fig.add_subplot(111) ax1.plot(self.core_starts, self.scores, 'bo-') pylab.xlabel('Core sequence start position (base pairs).') pylab.ylabel('Score - Probability of being unbound.') pylab.show() else: raise Exception('Run calculate() first so there\'s data to plot!')
python
{ "resource": "" }
q2114
primer
train
def primer(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3, end_gc=False, tm_parameters='cloning', overhang=None, structure=False): '''Design primer to a nearest-neighbor Tm setpoint. :param dna: Sequence for which to design a primer. :type dna: coral.DNA :param tm: Ideal primer Tm in degrees C. :type tm: float :param min_len: Minimum primer length. :type min_len: int :param tm_undershoot: Allowed Tm undershoot. :type tm_undershoot: float :param tm_overshoot: Allowed Tm overshoot. :type tm_overshoot: float :param end_gc: Obey the 'end on G or C' rule. :type end_gc: bool :param tm_parameters: Melting temp calculator method to use. :type tm_parameters: string :param overhang: Append the primer to this overhang sequence. :type overhang: str :param structure: Evaluate primer for structure, with warning for high structure. :type structure: bool :returns: A primer. :rtype: coral.Primer :raises: ValueError if the input sequence is lower than the Tm settings allow. ValueError if a primer ending with G or C can't be found given the Tm settings. ''' # Check Tm of input sequence to see if it's already too low seq_tm = coral.analysis.tm(dna, parameters=tm_parameters) if seq_tm < (tm - tm_undershoot): msg = 'Input sequence Tm is lower than primer Tm setting' raise ValueError(msg) # Focus on first 90 bases - shouldn't need more than 90bp to anneal dna = dna[0:90] # Generate primers from min_len to 'tm' + tm_overshoot # TODO: this is a good place for optimization. Only calculate as many # primers as are needed. Use binary search. primers_tms = [] last_tm = 0 bases = min_len while last_tm <= tm + tm_overshoot and bases != len(dna): next_primer = dna[0:bases] last_tm = coral.analysis.tm(next_primer, parameters=tm_parameters) primers_tms.append((next_primer, last_tm)) bases += 1 # Trim primer list based on tm_undershoot and end_gc primers_tms = [(primer, melt) for primer, melt in primers_tms if melt >= tm - tm_undershoot] if end_gc: primers_tms = [pair for pair in primers_tms if pair[0][-1] == coral.DNA('C') or pair[0][-1] == coral.DNA('G')] if not primers_tms: raise ValueError('No primers could be generated using these settings') # Find the primer closest to the set Tm, make it single stranded tm_diffs = [abs(melt - tm) for primer, melt in primers_tms] best_index = tm_diffs.index(min(tm_diffs)) best_primer, best_tm = primers_tms[best_index] best_primer = best_primer.top # Apply overhang if overhang: overhang = overhang.top output_primer = coral.Primer(best_primer, best_tm, overhang=overhang) def _structure(primer): '''Check annealing sequence for structure. :param primer: Primer for which to evaluate structure :type primer: sequence.Primer ''' # Check whole primer for high-probability structure, focus in on # annealing sequence, report average nupack = coral.analysis.Nupack(primer.primer()) pairs = nupack.pairs(0) anneal_len = len(primer.anneal) pairs_mean = sum(pairs[-anneal_len:]) / anneal_len if pairs_mean < 0.5: warnings.warn('High probability structure', Warning) return pairs_mean if structure: _structure(output_primer) return output_primer
python
{ "resource": "" }
q2115
primers
train
def primers(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3, end_gc=False, tm_parameters='cloning', overhangs=None, structure=False): '''Design primers for PCR amplifying any arbitrary sequence. :param dna: Input sequence. :type dna: coral.DNA :param tm: Ideal primer Tm in degrees C. :type tm: float :param min_len: Minimum primer length. :type min_len: int :param tm_undershoot: Allowed Tm undershoot. :type tm_undershoot: float :param tm_overshoot: Allowed Tm overshoot. :type tm_overshoot: float :param end_gc: Obey the 'end on G or C' rule. :type end_gc: bool :param tm_parameters: Melting temp calculator method to use. :type tm_parameters: string :param overhangs: 2-tuple of overhang sequences. :type overhangs: tuple :param structure: Evaluate each primer for structure, with warning for high structure. :type structure: bool :returns: A list primers (the output of primer). :rtype: list ''' if not overhangs: overhangs = [None, None] templates = [dna, dna.reverse_complement()] primer_list = [] for template, overhang in zip(templates, overhangs): primer_i = primer(template, tm=tm, min_len=min_len, tm_undershoot=tm_undershoot, tm_overshoot=tm_overshoot, end_gc=end_gc, tm_parameters=tm_parameters, overhang=overhang, structure=structure) primer_list.append(primer_i) return primer_list
python
{ "resource": "" }
q2116
Sanger.nonmatches
train
def nonmatches(self): '''Report mismatches, indels, and coverage.''' # For every result, keep a dictionary of mismatches, insertions, and # deletions report = [] for result in self.aligned_results: report.append(self._analyze_single(self.aligned_reference, result)) return report
python
{ "resource": "" }
q2117
Sanger.plot
train
def plot(self): '''Make a summary plot of the alignment and highlight nonmatches.''' import matplotlib.pyplot as plt import matplotlib.patches as patches # Constants to use throughout drawing n = len(self.results) nbases = len(self.aligned_reference) barheight = 0.4 # Vary height of figure based on number of results figheight = 3 + 3 * (n - 1) fig = plt.figure(figsize=(9, figheight)) ax1 = fig.add_subplot(111) # Plot bars to represent coverage area # Reference sequence ax1.add_patch(patches.Rectangle((0, 0), nbases, barheight, facecolor='black')) # Results for i, report in enumerate(self.nonmatches()): j = i + 1 start, stop = report['coverage'] patch = patches.Rectangle((start, j), stop - start, barheight, facecolor='darkgray') ax1.add_patch(patch) # Draw a vertical line for each type of result plt.vlines(report['mismatches'], j, j + barheight, colors='b') plt.vlines(report['insertions'], j, j + barheight, colors='r') # Terminal trailing deletions shouldn't be added deletions = [] crange = range(*report['coverage']) deletions = [idx for idx in report['deletions'] if idx in crange] plt.vlines(deletions, j, j + barheight, colors='g') ax1.set_xlim((0, nbases)) ax1.set_ylim((-0.3, n + 1)) ax1.set_yticks([i + barheight / 2 for i in range(n + 1)]) ax1.set_yticklabels(['Reference'] + self.names) # Add legend mismatch_patch = patches.Patch(color='blue', label='Mismatch') insertion_patch = patches.Patch(color='red', label='Insertion') deletion_patch = patches.Patch(color='green', label='Deletion') plt.legend(handles=[mismatch_patch, insertion_patch, deletion_patch], loc=1, ncol=3, mode='expand', borderaxespad=0.) plt.show()
python
{ "resource": "" }
q2118
Sanger._remove_n
train
def _remove_n(self): '''Remove terminal Ns from sequencing results.''' for i, result in enumerate(self.results): largest = max(str(result).split('N'), key=len) start = result.locate(largest)[0][0] stop = start + len(largest) if start != stop: self.results[i] = self.results[i][start:stop]
python
{ "resource": "" }
q2119
random_dna
train
def random_dna(n): '''Generate a random DNA sequence. :param n: Output sequence length. :type n: int :returns: Random DNA sequence of length n. :rtype: coral.DNA ''' return coral.DNA(''.join([random.choice('ATGC') for i in range(n)]))
python
{ "resource": "" }
q2120
random_codons
train
def random_codons(peptide, frequency_cutoff=0.0, weighted=False, table=None): '''Generate randomized codons given a peptide sequence. :param peptide: Peptide sequence for which to generate randomized codons. :type peptide: coral.Peptide :param frequency_cutoff: Relative codon usage cutoff - codons that are rarer will not be used. Frequency is relative to average over all codons for a given amino acid. :param frequency_cutoff: Codon frequency table to use. :param weighted: Use codon table :type weighted: bool :param table: Codon frequency table to use. Table should be organized by amino acid, then be a dict of codon: frequency. Only relevant if weighted=True or frequency_cutoff > 0. Tables available: constants.molecular_bio.CODON_FREQ_BY_AA['sc'] (default) :type table: dict :returns: Randomized sequence of codons (DNA) that code for the input peptide. :rtype: coral.DNA :raises: ValueError if frequency_cutoff is set so high that there are no codons available for an amino acid in the input peptide. ''' if table is None: table = CODON_FREQ_BY_AA['sc'] # Process codon table using frequency_cutoff new_table = _cutoff(table, frequency_cutoff) # Select codons randomly or using weighted distribution rna = '' for amino_acid in str(peptide): codons = new_table[amino_acid.upper()] if not codons: raise ValueError('No {} codons at freq cutoff'.format(amino_acid)) if weighted: cumsum = [] running_sum = 0 for codon, frequency in codons.iteritems(): running_sum += frequency cumsum.append(running_sum) random_num = random.uniform(0, max(cumsum)) for codon, value in zip(codons, cumsum): if value > random_num: selection = codon break else: selection = random.choice(codons.keys()) rna += selection return coral.RNA(rna)
python
{ "resource": "" }
q2121
_cutoff
train
def _cutoff(table, frequency_cutoff): '''Generate new codon frequency table given a mean cutoff. :param table: codon frequency table of form {amino acid: codon: frequency} :type table: dict :param frequency_cutoff: value between 0 and 1.0 for mean frequency cutoff :type frequency_cutoff: float :returns: A codon frequency table with some codons removed. :rtype: dict ''' new_table = {} # IDEA: cutoff should be relative to most-frequent codon, not average? for amino_acid, codons in table.iteritems(): average_cutoff = frequency_cutoff * sum(codons.values()) / len(codons) new_table[amino_acid] = {} for codon, frequency in codons.iteritems(): if frequency > average_cutoff: new_table[amino_acid][codon] = frequency return new_table
python
{ "resource": "" }
q2122
fetch_genome
train
def fetch_genome(genome_id): '''Acquire a genome from Entrez ''' # TODO: Can strandedness by found in fetched genome attributes? # TODO: skip read/write step? # Using a dummy email for now - does this violate NCBI guidelines? email = '[email protected]' Entrez.email = email print 'Downloading Genome...' handle = Entrez.efetch(db='nucleotide', id=str(genome_id), rettype='gb', retmode='text') print 'Genome Downloaded...' tmpfile = os.path.join(mkdtemp(), 'tmp.gb') with open(tmpfile, 'w') as f: f.write(handle.read()) genome = coral.seqio.read_dna(tmpfile) return genome
python
{ "resource": "" }
q2123
ViennaRNA.fold
train
def fold(self, strand, temp=37.0, dangles=2, nolp=False, nogu=False, noclosinggu=False, constraints=None, canonicalbponly=False, partition=False, pfscale=None, imfeelinglucky=False, gquad=False): '''Run the RNAfold command and retrieve the result in a dictionary. :param strand: The DNA or RNA sequence on which to run RNAfold. :type strand: coral.DNA or coral.RNA :param temp: Temperature at which to run the calculations. :type temp: float :param dangles: How to treat dangling end energies. Set to 0 to ignore dangling ends. Set to 1 to limit unpaired bases to at most one dangling end (default for MFE calc). Set to 2 (the default) to remove the limit in 1. Set to 3 to allow coaxial stacking of adjacent helices in .multi-loops :type dangles: int :param nolp: Produce structures without lonely pairs (isolated single base pairs). :type nolp: bool :param nogu: Do not allow GU pairs. :type nogu: bool :param noclosinggu: Do not allow GU pairs at the end of helices. :type noclosinggu: bool :param constraints: Any structural constraints to use. Format is defined at http://www.tbi.univie.ac.at/RNA/RNAfold.1.html :type constraints: str :param canonicalbponly: Remove non-canonical base pairs from the structure constraint (if applicable). :type canonicalbponly: bool :param partition: Generates the partition function, generating a coarse grain structure ('coarse') in the format described at http://www.itc.univie.ac.at/~ivo/RNA/RNAlib/PF-Fold.h tml, the ensemble free energy ('ensemble'), the centroid structure ('centroid'), the free energy of the centroid structure ('centroid_fe'), and its distance from the ensemble ('centroid_d'). :type partition: int :param pfscale: Scaling factor for the partition function. :type pfScale: float :param imfeelinglucky: Returns the one secondary structure from the Boltzmann equilibrium according to its probability in the ensemble. :type imfeelinglucky: bool :param gquad: Incorporate G-Quadruplex formation into the structure prediction. :type gquad: bool :returns: Dictionary of calculated values, defaulting to values of MFE ('mfe': float) and dotbracket structure ('dotbracket': str). More keys are added depending on keyword arguments. :rtype: dict ''' cmd_args = [] cmd_kwargs = {'--temp=': str(temp)} cmd_kwargs['--dangles='] = dangles if nolp: cmd_args.append('--noLP') if nogu: cmd_args.append('--noGU') if noclosinggu: cmd_args.append('--noClosingGU') if constraints is not None: cmd_args.append('--constraint') if canonicalbponly: cmd_args.append('--canonicalBPonly') if partition: cmd_args.append('--partfunc') if pfscale is not None: cmd_kwargs['pfScale'] = float(pfscale) if gquad: cmd_args.append('--gquad') inputs = [str(strand)] if constraints is not None: inputs.append(constraints) if strand.circular: cmd_args.append('--circ') rnafold_output = self._run('RNAfold', inputs, cmd_args, cmd_kwargs) # Process the output output = {} lines = rnafold_output.splitlines() # Line 1 is the sequence as RNA lines.pop(0) # Line 2 is the dotbracket + mfe line2 = lines.pop(0) output['dotbracket'] = self._lparse(line2, '^(.*) \(') output['mfe'] = float(self._lparse(line2, ' \((.*)\)$')) # Optional outputs if partition: # Line 3 is 'a coarse representation of the pair probabilities' and # the ensemble free energy line3 = lines.pop(0) output['coarse'] = self._lparse(line3, '^(.*) \[') output['ensemble'] = float(self._lparse(line3, ' \[(.*)\]$')) # Line 4 is the centroid structure, its free energy, and distance # to the ensemble line4 = lines.pop(0) output['centroid'] = self._lparse(line4, '^(.*) \{') output['centroid_fe'] = float(self._lparse(line4, '^.*{(.*) d')) output['centroid_d'] = float(self._lparse(line4, 'd=(.*)}$')) return output
python
{ "resource": "" }
q2124
dimers
train
def dimers(primer1, primer2, concentrations=[5e-7, 3e-11]): '''Calculate expected fraction of primer dimers. :param primer1: Forward primer. :type primer1: coral.DNA :param primer2: Reverse primer. :type primer2: coral.DNA :param template: DNA template. :type template: coral.DNA :param concentrations: list of concentrations for primers and the template. Defaults are those for PCR with 1kb template. :type concentrations: list :returns: Fraction of dimers versus the total amount of primer added. :rtype: float ''' # It is not reasonable (yet) to use a long template for doing these # computations directly, as NUPACK does an exhaustive calculation and # would take too long without a cluster. # Instead, this function compares primer-primer binding to # primer-complement binding # Simulate binding of template vs. primers nupack = coral.analysis.NUPACK([primer1.primer(), primer2.primer(), primer1.primer().reverse_complement(), primer2.primer().reverse_complement()]) # Include reverse complement concentration primer_concs = [concentrations[0]] * 2 template_concs = [concentrations[1]] * 2 concs = primer_concs + template_concs nupack_concs = nupack.concentrations(2, conc=concs) dimer_conc = nupack_concs['concentrations'][5] #primer1_template = nupack_concs['concentrations'][6] #primer2_template = nupack_concs['concentrations'][10] return dimer_conc / concs[0]
python
{ "resource": "" }
q2125
read_dna
train
def read_dna(path): '''Read DNA from file. Uses BioPython and coerces to coral format. :param path: Full path to input file. :type path: str :returns: DNA sequence. :rtype: coral.DNA ''' filename, ext = os.path.splitext(os.path.split(path)[-1]) genbank_exts = ['.gb', '.ape'] fasta_exts = ['.fasta', '.fa', '.fsa', '.seq'] abi_exts = ['.abi', '.ab1'] if any([ext == extension for extension in genbank_exts]): file_format = 'genbank' elif any([ext == extension for extension in fasta_exts]): file_format = 'fasta' elif any([ext == extension for extension in abi_exts]): file_format = 'abi' else: raise ValueError('File format not recognized.') seq = SeqIO.read(path, file_format) dna = coral.DNA(str(seq.seq)) if seq.name == '.': dna.name = filename else: dna.name = seq.name # Features for feature in seq.features: try: dna.features.append(_seqfeature_to_coral(feature)) except FeatureNameError: pass dna.features = sorted(dna.features, key=lambda feature: feature.start) # Used to use data_file_division, but it's inconsistent (not always the # molecule type) dna.circular = False with open(path) as f: first_line = f.read().split() for word in first_line: if word == 'circular': dna.circular = True return dna
python
{ "resource": "" }
q2126
_seqfeature_to_coral
train
def _seqfeature_to_coral(feature): '''Convert a Biopython SeqFeature to a coral.Feature. :param feature: Biopython SeqFeature :type feature: Bio.SeqFeature ''' # Some genomic sequences don't have a label attribute # TODO: handle genomic cases differently than others. Some features lack # a label but should still be incorporated somehow. qualifiers = feature.qualifiers if 'label' in qualifiers: feature_name = qualifiers['label'][0] elif 'locus_tag' in qualifiers: feature_name = qualifiers['locus_tag'][0] else: raise FeatureNameError('Unrecognized feature name') # Features with gaps are special, require looking at subfeatures # Assumption: subfeatures are never more than one level deep if feature.location_operator == 'join': # Feature has gaps. Have to figure out start/stop from subfeatures, # calculate gap indices. A nested feature model may be required # eventually. # Reorder the sub_feature list by start location # Assumption: none of the subfeatures overlap so the last entry in # the reordered list also has the final stop point of the feature. # FIXME: Getting a deprecation warning about using sub_features # instead of feature.location being a CompoundFeatureLocation reordered = sorted(feature.location.parts, key=lambda location: location.start) starts = [int(location.start) for location in reordered] stops = [int(location.end) for location in reordered] feature_start = starts.pop(0) feature_stop = stops.pop(-1) starts = [start - feature_start for start in starts] stops = [stop - feature_start for stop in stops] feature_gaps = list(zip(stops, starts)) else: # Feature doesn't have gaps. Ignore subfeatures. feature_start = int(feature.location.start) feature_stop = int(feature.location.end) feature_gaps = [] feature_type = _process_feature_type(feature.type) if feature.location.strand == -1: feature_strand = 1 else: feature_strand = 0 if 'gene' in qualifiers: gene = qualifiers['gene'] else: gene = [] if 'locus_tag' in qualifiers: locus_tag = qualifiers['locus_tag'] else: locus_tag = [] coral_feature = coral.Feature(feature_name, feature_start, feature_stop, feature_type, gene=gene, locus_tag=locus_tag, qualifiers=qualifiers, strand=feature_strand, gaps=feature_gaps) return coral_feature
python
{ "resource": "" }
q2127
_coral_to_seqfeature
train
def _coral_to_seqfeature(feature): '''Convert a coral.Feature to a Biopython SeqFeature. :param feature: coral Feature. :type feature: coral.Feature ''' bio_strand = 1 if feature.strand == 1 else -1 ftype = _process_feature_type(feature.feature_type, bio_to_coral=False) sublocations = [] if feature.gaps: # There are gaps. Have to define location_operator and add subfeatures location_operator = 'join' # Feature location means nothing for 'join' sequences? # TODO: verify location = FeatureLocation(ExactPosition(0), ExactPosition(1), strand=bio_strand) # Reconstruct start/stop indices for each subfeature stops, starts = zip(*feature.gaps) starts = [feature.start] + [start + feature.start for start in starts] stops = [stop + feature.start for stop in stops] + [feature.stop] # Build subfeatures for start, stop in zip(starts, stops): sublocation = FeatureLocation(ExactPosition(start), ExactPosition(stop), strand=bio_strand) sublocations.append(sublocation) location = CompoundLocation(sublocations, operator='join') else: # No gaps, feature is simple location_operator = '' location = FeatureLocation(ExactPosition(feature.start), ExactPosition(feature.stop), strand=bio_strand) qualifiers = feature.qualifiers qualifiers['label'] = [feature.name] seqfeature = SeqFeature(location, type=ftype, qualifiers=qualifiers, location_operator=location_operator) return seqfeature
python
{ "resource": "" }
q2128
score_alignment
train
def score_alignment(a, b, gap_open, gap_extend, matrix): '''Calculate the alignment score from two aligned sequences. :param a: The first aligned sequence. :type a: str :param b: The second aligned sequence. :type b: str :param gap_open: The cost of opening a gap (negative number). :type gap_open: int :param gap_extend: The cost of extending an open gap (negative number). :type gap_extend: int. :param matrix: A score matrix dictionary name. Examples can be found in the substitution_matrices module. ''' al = a bl = b l = len(al) score = 0 assert len(bl) == l, 'Alignment lengths must be the same' mat = as_ord_matrix(matrix) gap_started = 0 for i in range(l): if al[i] == '-' or bl[i] == '-': score += gap_extend if gap_started else gap_open gap_started = 1 else: score += mat[ord(al[i]), ord(bl[i])] gap_started = 0 return score
python
{ "resource": "" }
q2129
build_docs
train
def build_docs(directory): """Builds sphinx docs from a given directory.""" os.chdir(directory) process = subprocess.Popen(["make", "html"], cwd=directory) process.communicate()
python
{ "resource": "" }
q2130
gibson
train
def gibson(seq_list, circular=True, overlaps='mixed', overlap_tm=65, maxlen=80, terminal_primers=True, primer_kwargs=None): '''Design Gibson primers given a set of sequences :param seq_list: List of DNA sequences to stitch together :type seq_list: list containing coral.DNA :param circular: If true, designs primers for making a circular construct. If false, designs primers for a linear construct. :type circular: bool :param splits: Specifies locations of overlap. Must be either a single entry of the same type as the 'split' parameter in gibson_primers or a list of those types of the appropriate length (for circular construct, len(seq_list), for linear construct, len(seq_list) - 1) :type splits: str or list of str :param overlap_tm: Minimum Tm of overlap :type overlap_tm: float :param maxlen: Maximum length of each primer. :type maxlen: int :param terminal_primers: If the output is not circular, will design non-Gibson primers for amplifying the first and last fragments sans homology. If False, there will be one less set of primers returned. :type terminal_primers: bool :param primer_kwargs: keyword arguments to pass to design.primer :type primer_kwargs: dict :returns: Forward and reverse primers for amplifying every fragment. :rtype: a list of sequence.Primer tuples :raises: ValueError if split parameter is an invalid string or wrong size. ''' # Input checking if circular: n_overlaps = len(seq_list) else: n_overlaps = len(seq_list) - 1 if type(overlaps) is str: overlaps = [overlaps] * n_overlaps else: if len(overlaps) != n_overlaps: raise ValueError('Incorrect number of \'overlaps\' entries.') else: for overlap in overlaps: if overlap not in ['left', 'right', 'mixed']: raise ValueError('Invalid \'overlaps\' setting.') if primer_kwargs is None: primer_kwargs = {} # If here, inputs were good # Design primers for linear constructs: primers_list = [] for i, (left, right) in enumerate(zip(seq_list[:-1], seq_list[1:])): primers_list.append(gibson_primers(left, right, overlaps[i], overlap_tm=overlap_tm, primer_kwargs=primer_kwargs)) if circular: primers_list.append(gibson_primers(seq_list[-1], seq_list[0], overlaps[-1], overlap_tm=overlap_tm, primer_kwargs=primer_kwargs)) else: if terminal_primers: primer_f = coral.design.primer(seq_list[0], **primer_kwargs) primer_r = coral.design.primer(seq_list[-1].reverse_complement(), **primer_kwargs) primers_list.append((primer_r, primer_f)) # Primers are now in order of 'reverse for seq1, forward for seq2' config # Should be in 'forward and reverse primers for seq1, then seq2', etc # Just need to rotate one to the right flat = [y for x in primers_list for y in x] flat = [flat[-1]] + flat[:-1] grouped_primers = [(flat[2 * i], flat[2 * i + 1]) for i in range(len(flat) / 2)] return grouped_primers
python
{ "resource": "" }
q2131
reverse_complement
train
def reverse_complement(sequence, material): '''Reverse complement a sequence. :param sequence: Sequence to reverse complement :type sequence: str :param material: dna, rna, or peptide. :type material: str ''' code = dict(COMPLEMENTS[material]) reverse_sequence = sequence[::-1] return ''.join([code[str(base)] for base in reverse_sequence])
python
{ "resource": "" }
q2132
check_alphabet
train
def check_alphabet(seq, material): '''Verify that a given string is valid DNA, RNA, or peptide characters. :param seq: DNA, RNA, or peptide sequence. :type seq: str :param material: Input material - 'dna', 'rna', or 'pepide'. :type sequence: str :returns: Whether the `seq` is a valid string of `material`. :rtype: bool :raises: ValueError if `material` isn't \'dna\', \'rna\', or \'peptide\'. ValueError if `seq` contains invalid characters for its material type. ''' errs = {'dna': 'DNA', 'rna': 'RNA', 'peptide': 'peptide'} if material == 'dna' or material == 'rna' or material == 'peptide': alphabet = ALPHABETS[material] err_msg = errs[material] else: msg = 'Input material must be \'dna\', \'rna\', or \'peptide\'.' raise ValueError(msg) # This is a bottleneck when modifying sequence - hence the run_checks # optional parameter in sequence objects.. # First attempt with cython was slower. Could also try pypy. if re.search('[^' + alphabet + ']', seq): raise ValueError('Encountered a non-%s character' % err_msg)
python
{ "resource": "" }
q2133
process_seq
train
def process_seq(seq, material): '''Validate and process sequence inputs. :param seq: input sequence :type seq: str :param material: DNA, RNA, or peptide :type: str :returns: Uppercase version of `seq` with the alphabet checked by check_alphabet(). :rtype: str ''' check_alphabet(seq, material) seq = seq.upper() return seq
python
{ "resource": "" }
q2134
palindrome
train
def palindrome(seq): '''Test whether a sequence is palindrome. :param seq: Sequence to analyze (DNA or RNA). :type seq: coral.DNA or coral.RNA :returns: Whether a sequence is a palindrome. :rtype: bool ''' seq_len = len(seq) if seq_len % 2 == 0: # Sequence has even number of bases, can test non-overlapping seqs wing = seq_len / 2 l_wing = seq[0: wing] r_wing = seq[wing:] if l_wing == r_wing.reverse_complement(): return True else: return False else: # Sequence has odd number of bases and cannot be a palindrome return False
python
{ "resource": "" }
q2135
Feature.copy
train
def copy(self): '''Return a copy of the Feature. :returns: A safely editable copy of the current feature. :rtype: coral.Feature ''' return type(self)(self.name, self.start, self.stop, self.feature_type, gene=self.gene, locus_tag=self.locus_tag, qualifiers=self.qualifiers, strand=self.strand)
python
{ "resource": "" }
q2136
nupack_multi
train
def nupack_multi(seqs, material, cmd, arguments, report=True): '''Split Nupack commands over processors. :param inputs: List of sequences, same format as for coral.analysis.Nupack. :type inpus: list :param material: Input material: 'dna' or 'rna'. :type material: str :param cmd: Command: 'mfe', 'pairs', 'complexes', or 'concentrations'. :type cmd: str :param arguments: Arguments for the command. :type arguments: str :returns: A list of the same return value you would get from `cmd`. :rtype: list ''' nupack_pool = multiprocessing.Pool() try: args = [{'seq': seq, 'cmd': cmd, 'material': material, 'arguments': arguments} for seq in seqs] nupack_iterator = nupack_pool.imap(run_nupack, args) total = len(seqs) msg = ' calculations complete.' passed = 4 while report: completed = nupack_iterator._index if (completed == total): break else: if passed >= 4: print '({0}/{1}) '.format(completed, total) + msg passed = 0 passed += 1 time.sleep(1) multi_output = [x for x in nupack_iterator] nupack_pool.close() nupack_pool.join() except KeyboardInterrupt: nupack_pool.terminate() nupack_pool.close() raise KeyboardInterrupt return multi_output
python
{ "resource": "" }
q2137
run_nupack
train
def run_nupack(kwargs): '''Run picklable Nupack command. :param kwargs: keyword arguments to pass to Nupack as well as 'cmd'. :returns: Variable - whatever `cmd` returns. ''' run = NUPACK(kwargs['seq']) output = getattr(run, kwargs['cmd'])(**kwargs['arguments']) return output
python
{ "resource": "" }
q2138
NUPACK.pfunc_multi
train
def pfunc_multi(self, strands, permutation=None, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the partition function for an ordered complex of strands. Runs the \'pfunc\' command. :param strands: List of strands to use as inputs to pfunc -multi. :type strands: list :param permutation: The circular permutation of strands to test in complex. e.g. to test in the order that was input for 4 strands, the permutation would be [1,2,3,4]. If set to None, defaults to the order of the input strands. :type permutation: list :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and 'rna1999' for the RNA 1999 parameters. :type material: str :param dangles: How to treat dangles in the computation. From the user guide: For \'none\': Dangle energies are ignored. For \'some\': \'A dangle energy is incorporated for each unpaired base flanking a duplex\'. For 'all': all dangle energy is considered. :type dangles: str :param sodium: Sodium concentration in solution (molar), only applies to DNA. :type sodium: float :param magnesium: Magnesium concentration in solution (molar), only applies to DNA> :type magnesium: float :returns: A 2-tuple of the free energy of the ordered complex (float) and the partition function (float). :rtype: tuple ''' # Set the material (will be used to set command material flag) material = self._set_material(strands, material, multi=True) # Set up command flags cmd_args = self._prep_cmd_args(temp, dangles, material, pseudo, sodium, magnesium, multi=True) # Set up the input file and run the command if permutation is None: permutation = range(1, len(strands) + 1) lines = self._multi_lines(strands, permutation) stdout = self._run('pfunc', cmd_args, lines).split('\n') return (float(stdout[-3]), float(stdout[-2]))
python
{ "resource": "" }
q2139
NUPACK.subopt
train
def subopt(self, strand, gap, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the suboptimal structures within a defined energy gap of the MFE. Runs the \'subopt\' command. :param strand: Strand on which to run subopt. Strands must be either coral.DNA or coral.RNA). :type strand: coral.DNA or coral.RNA :param gap: Energy gap within to restrict results, e.g. 0.1. :type gap: float :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and 'rna1999' for the RNA 1999 parameters. :type material: str :param dangles: How to treat dangles in the computation. From the user guide: For \'none\': Dangle energies are ignored. For \'some\': \'A dangle energy is incorporated for each unpaired base flanking a duplex\'. For 'all': all dangle energy is considered. :type dangles: str :param sodium: Sodium concentration in solution (molar), only applies to DNA. :type sodium: float :param magnesium: Magnesium concentration in solution (molar), only applies to DNA> :type magnesium: float :returns: A list of dictionaries of the type returned by .mfe(). :rtype: list ''' # Set the material (will be used to set command material flag) material = self._set_material(strand, material) # Set up command flags cmd_args = self._prep_cmd_args(temp, dangles, material, pseudo, sodium, magnesium, multi=False) # Set up the input file and run the command. Note: no STDOUT lines = [str(strand), str(gap)] self._run('subopt', cmd_args, lines) # Read the output from file structures = self._process_mfe(self._read_tempfile('subopt.subopt')) return structures
python
{ "resource": "" }
q2140
NUPACK.energy
train
def energy(self, strand, dotparens, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Calculate the free energy of a given sequence structure. Runs the \'energy\' command. :param strand: Strand on which to run energy. Strands must be either coral.DNA or coral.RNA). :type strand: coral.DNA or coral.RNA :param dotparens: The structure in dotparens notation. :type dotparens: str :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and 'rna1999' for the RNA 1999 parameters. :type material: str :param dangles: How to treat dangles in the computation. From the user guide: For \'none\': Dangle energies are ignored. For \'some\': \'A dangle energy is incorporated for each unpaired base flanking a duplex\'. For 'all': all dangle energy is considered. :type dangles: str :param sodium: Sodium concentration in solution (molar), only applies to DNA. :type sodium: float :param magnesium: Magnesium concentration in solution (molar), only applies to DNA> :type magnesium: float :returns: The free energy of the sequence with the specified secondary structure. :rtype: float ''' # Set the material (will be used to set command material flag) material = self._set_material(strand, material) # Set up command flags cmd_args = self._prep_cmd_args(temp, dangles, material, pseudo, sodium, magnesium, multi=False) # Set up the input file and run the command. Note: no STDOUT lines = [str(strand), dotparens] stdout = self._run('energy', cmd_args, lines).split('\n') # Return the energy return float(stdout[-2])
python
{ "resource": "" }
q2141
NUPACK.complexes_timeonly
train
def complexes_timeonly(self, strands, max_size): '''Estimate the amount of time it will take to calculate all the partition functions for each circular permutation - estimate the time the actual \'complexes\' command will take to run. :param strands: Strands on which to run energy. Strands must be either coral.DNA or coral.RNA). :type strands: list of coral.DNA or coral.RNA :param max_size: Maximum complex size to consider (maximum number of strand species in complex). :type max_size: int :returns: The estimated time to run complexes' partition functions, in seconds. :rtype: float ''' cmd_args = ['-quiet', '-timeonly'] lines = self._multi_lines(strands, [max_size]) stdout = self._run('complexes', cmd_args, lines) return float(re.search('calculation\: (.*) seconds', stdout).group(1))
python
{ "resource": "" }
q2142
NUPACK._multi_lines
train
def _multi_lines(self, strands, permutation): '''Prepares lines to write to file for pfunc command input. :param strand: Strand input (cr.DNA or cr.RNA). :type strand: cr.DNA or cr.DNA :param permutation: Permutation (e.g. [1, 2, 3, 4]) of the type used by pfunc_multi. :type permutation: list ''' lines = [] # Write the total number of distinct strands lines.append(str(len(strands))) # Write the distinct strands lines += [str(strand) for strand in strands] # Write the permutation lines.append(' '.join(str(p) for p in permutation)) return lines
python
{ "resource": "" }
q2143
NUPACK._read_tempfile
train
def _read_tempfile(self, filename): '''Read in and return file that's in the tempdir. :param filename: Name of the file to read. :type filename: str ''' with open(os.path.join(self._tempdir, filename)) as f: return f.read()
python
{ "resource": "" }
q2144
NUPACK._pairs_to_np
train
def _pairs_to_np(self, pairlist, dim): '''Given a set of pair probability lines, construct a numpy array. :param pairlist: a list of pair probability triples :type pairlist: list :returns: An upper triangular matrix of pair probabilities augmented with one extra column that represents the unpaired probabilities. :rtype: numpy.array ''' mat = np.zeros((dim, dim + 1)) for line in pairlist: i = int(line[0]) - 1 j = int(line[1]) - 1 prob = float(line[2]) mat[i, j] = prob return mat
python
{ "resource": "" }
q2145
_flip_feature
train
def _flip_feature(self, feature, parent_len): '''Adjust a feature's location when flipping DNA. :param feature: The feature to flip. :type feature: coral.Feature :param parent_len: The length of the sequence to which the feature belongs. :type parent_len: int ''' copy = feature.copy() # Put on the other strand if copy.strand == 0: copy.strand = 1 else: copy.strand = 0 # Adjust locations - guarantee that start is always less than end copy.start = parent_len - copy.start copy.stop = parent_len - copy.stop copy.start, copy.stop = copy.stop, copy.start return copy
python
{ "resource": "" }
q2146
DNA.ape
train
def ape(self, ape_path=None): '''Open in ApE if `ApE` is in your command line path.''' # TODO: simplify - make ApE look in PATH only cmd = 'ApE' if ape_path is None: # Check for ApE in PATH ape_executables = [] for path in os.environ['PATH'].split(os.pathsep): exepath = os.path.join(path, cmd) ape_executables.append(os.access(exepath, os.X_OK)) if not any(ape_executables): raise Exception('Ape not in PATH. Use ape_path kwarg.') else: cmd = ape_path # Check whether ApE exists in PATH tmp = tempfile.mkdtemp() if self.name is not None and self.name: filename = os.path.join(tmp, '{}.ape'.format(self.name)) else: filename = os.path.join(tmp, 'tmp.ape') coral.seqio.write_dna(self, filename) process = subprocess.Popen([cmd, filename]) # Block until window is closed try: process.wait() shutil.rmtree(tmp) except KeyboardInterrupt: shutil.rmtree(tmp)
python
{ "resource": "" }
q2147
DNA.circularize
train
def circularize(self): '''Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA ''' if self.top[-1].seq == '-' and self.bottom[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') if self.bottom[-1].seq == '-' and self.top[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') copy = self.copy() copy.circular = True copy.top.circular = True copy.bottom.circular = True return copy
python
{ "resource": "" }
q2148
DNA.flip
train
def flip(self): '''Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ''' copy = self.copy() copy.top, copy.bottom = copy.bottom, copy.top copy.features = [_flip_feature(f, len(self)) for f in copy.features] return copy
python
{ "resource": "" }
q2149
DNA.linearize
train
def linearize(self, index=0): '''Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input is linear DNA. ''' if not self.circular: raise ValueError('Cannot relinearize linear DNA.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False copy.top.circular = False copy.bottom.circular = False return copy
python
{ "resource": "" }
q2150
DNA.locate
train
def locate(self, pattern): '''Find sequences matching a pattern. For a circular sequence, the search extends over the origin. :param pattern: str or NucleicAcidSequence for which to find matches. :type pattern: str or coral.DNA :returns: A list of top and bottom strand indices of matches. :rtype: list of lists of indices (ints) :raises: ValueError if the pattern is longer than either the input sequence (for linear DNA) or twice as long as the input sequence (for circular DNA). ''' top_matches = self.top.locate(pattern) bottom_matches = self.bottom.locate(pattern) return [top_matches, bottom_matches]
python
{ "resource": "" }
q2151
DNA.reverse_complement
train
def reverse_complement(self): '''Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA ''' copy = self.copy() # Note: if sequence is double-stranded, swapping strand is basically # (but not entirely) the same thing - gaps affect accuracy. copy.top = self.top.reverse_complement() copy.bottom = self.bottom.reverse_complement() # Remove all features - the reverse complement isn't flip! copy.features = [] return copy
python
{ "resource": "" }
q2152
DNA.to_feature
train
def to_feature(self, name=None, feature_type='misc_feature'): '''Create a feature from the current object. :param name: Name for the new feature. Must be specified if the DNA instance has no .name attribute. :type name: str :param feature_type: The type of feature (genbank standard). :type feature_type: str ''' if name is None: if not self.name: raise ValueError('name attribute missing from DNA instance' ' and arguments') name = self.name return Feature(name, start=0, stop=len(self), feature_type=feature_type)
python
{ "resource": "" }
q2153
RestrictionSite.cuts_outside
train
def cuts_outside(self): '''Report whether the enzyme cuts outside its recognition site. Cutting at the very end of the site returns True. :returns: Whether the enzyme will cut outside its recognition site. :rtype: bool ''' for index in self.cut_site: if index < 0 or index > len(self.recognition_site) + 1: return True return False
python
{ "resource": "" }
q2154
Primer.copy
train
def copy(self): '''Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA ''' return type(self)(self.anneal, self.tm, overhang=self.overhang, name=self.name, note=self.note)
python
{ "resource": "" }
q2155
_pair_deltas
train
def _pair_deltas(seq, pars): '''Add up nearest-neighbor parameters for a given sequence. :param seq: DNA sequence for which to sum nearest neighbors :type seq: str :param pars: parameter set to use :type pars: dict :returns: nearest-neighbor delta_H and delta_S sums. :rtype: tuple of floats ''' delta0 = 0 delta1 = 0 for i in range(len(seq) - 1): curchar = seq[i:i + 2] delta0 += pars['delta_h'][curchar] delta1 += pars['delta_s'][curchar] return delta0, delta1
python
{ "resource": "" }
q2156
breslauer_corrections
train
def breslauer_corrections(seq, pars_error): '''Sum corrections for Breslauer '84 method. :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] contains_gc = 'G' in str(seq) or 'C' in str(seq) only_at = str(seq).count('A') + str(seq).count('T') == len(seq) symmetric = seq == seq.reverse_complement() terminal_t = str(seq)[0] == 'T' + str(seq)[-1] == 'T' for i, delta in enumerate(['delta_h', 'delta_s']): if contains_gc: deltas_corr[i] += pars_error[delta]['anyGC'] if only_at: deltas_corr[i] += pars_error[delta]['onlyAT'] if symmetric: deltas_corr[i] += pars_error[delta]['symmetry'] if terminal_t and delta == 'delta_h': deltas_corr[i] += pars_error[delta]['terminalT'] * terminal_t return deltas_corr
python
{ "resource": "" }
q2157
MAFFT
train
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2): '''A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --op (gap open) penalty in MAFFT cli. :type gap_open: float :param gap_extension: --ep (gap extension) penalty in MAFFT cli. :type gap_extension: float :param retree: Number of times to build the guide tree. :type retree: int ''' arguments = ['mafft'] arguments += ['--op', str(gap_open)] arguments += ['--ep', str(gap_extension)] arguments += ['--retree', str(retree)] arguments.append('input.fasta') tempdir = tempfile.mkdtemp() try: with open(os.path.join(tempdir, 'input.fasta'), 'w') as f: for i, sequence in enumerate(sequences): if hasattr(sequence, 'name'): name = sequence.name else: name = 'sequence{}'.format(i) f.write('>{}\n'.format(name)) f.write(str(sequence) + '\n') process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=tempdir) stdout = process.communicate()[0] finally: shutil.rmtree(tempdir) # Process stdout into something downstream process can use records = stdout.split('>') # First line is now blank records.pop(0) aligned_list = [] for record in records: lines = record.split('\n') name = lines.pop(0) aligned_list.append(coral.DNA(''.join(lines))) return aligned_list
python
{ "resource": "" }
q2158
repeats
train
def repeats(seq, size): '''Count times that a sequence of a certain size is repeated. :param seq: Input sequence. :type seq: coral.DNA or coral.RNA :param size: Size of the repeat to count. :type size: int :returns: Occurrences of repeats and how many :rtype: tuple of the matched sequence and how many times it occurs ''' seq = str(seq) n_mers = [seq[i:i + size] for i in range(len(seq) - size + 1)] counted = Counter(n_mers) # No one cares about patterns that appear once, so exclude them found_repeats = [(key, value) for key, value in counted.iteritems() if value > 1] return found_repeats
python
{ "resource": "" }
q2159
gibson
train
def gibson(seq_list, linear=False, homology=10, tm=63.0): '''Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear: bool :param homology_min: minimum bp of homology allowed :type homology_min: int :param tm: Minimum tm of overlaps :type tm: float :returns: coral.reaction.Gibson instance. :raises: ValueError if any input sequences are circular DNA. ''' # FIXME: Preserve features in overlap # TODO: set a max length? # TODO: add 'expected' keyword argument somewhere to automate # validation # Remove any redundant (identical) sequences seq_list = list(set(seq_list)) for seq in seq_list: if seq.circular: raise ValueError('Input sequences must be linear.') # Copy input list working_list = [s.copy() for s in seq_list] # Attempt to fuse fragments together until only one is left while len(working_list) > 1: working_list = _find_fuse_next(working_list, homology, tm) if not linear: # Fuse the final fragment to itself working_list = _fuse_last(working_list, homology, tm) # Clear features working_list[0].features = [] return _annotate_features(working_list[0], seq_list)
python
{ "resource": "" }
q2160
_fuse_last
train
def _fuse_last(working_list, homology, tm): '''With one sequence left, attempt to fuse it to itself. :param homology: length of terminal homology in bp. :type homology: int :raises: AmbiguousGibsonError if either of the termini are palindromic (would bind self-self). ValueError if the ends are not compatible. ''' # 1. Construct graph on self-self # (destination, size, strand1, strand2) pattern = working_list[0] def graph_strands(strand1, strand2): matchlen = homology_report(pattern, pattern, strand1, strand2, cutoff=homology, min_tm=tm, top_two=True) if matchlen: # Ignore full-sequence matches # HACK: modified homology_report to accept top_two. It should # really just ignore full-length matches for length in matchlen: if length != len(pattern): return (0, length, strand1, strand2) else: return [] # cw is redundant with wc graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cc = graph_strands('c', 'c') if graph_ww + graph_cc: raise AmbiguousGibsonError('Self-self binding during circularization.') if not graph_wc: raise ValueError('Failed to find compatible ends for circularization.') working_list[0] = working_list[0][:-graph_wc[1]].circularize() return working_list
python
{ "resource": "" }
q2161
get_gene_id
train
def get_gene_id(gene_name): '''Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'crossReferences.identifier', 'crossReferences.source.name') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') for row in query.rows(): gid = row['secondaryIdentifier'] return gid
python
{ "resource": "" }
q2162
_grow_overlaps
train
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min, min_exception): '''Grows equidistant overlaps until they meet specified constraints. :param dna: Input sequence. :type dna: coral.DNA :param melting_temp: Ideal Tm of the overlaps, in degrees C. :type melting_temp: float :param require_even: Require that the number of oligonucleotides is even. :type require_even: bool :param length_max: Maximum oligo size (e.g. 60bp price point cutoff) range. :type length_range: int :param overlap_min: Minimum overlap size. :type overlap_min: int :param min_exception: In order to meet melting_temp and overlap_min settings, allow overlaps less than overlap_min to continue growing above melting_temp. :type min_exception: bool :returns: Oligos, their overlapping regions, overlap Tms, and overlap indices. :rtype: tuple ''' # TODO: prevent growing overlaps from bumping into each other - # should halt when it happens, give warning, let user decide if they still # want the current construct # Another option would be to start over, moving the starting positions # near the problem region a little farther from each other - this would # put the AT-rich region in the middle of the spanning oligo # Try bare minimum number of oligos oligo_n = len(dna) // length_max + 1 # Adjust number of oligos if even number required if require_even: oligo_increment = 2 if oligo_n % 2 == 1: oligo_n += 1 else: oligo_increment = 1 # Increase oligo number until the minimum oligo_len is less than length_max while float(len(dna)) / oligo_n > length_max: oligo_n += oligo_increment # Loop until all overlaps meet minimum Tm and length tm_met = False len_met = False while(not tm_met or not len_met): # Calculate initial number of overlaps overlap_n = oligo_n - 1 # Place overlaps approximately equidistant over sequence length overlap_interval = float(len(dna)) / oligo_n starts = [int(overlap_interval * (i + 1)) for i in range(overlap_n)] ends = [index + 1 for index in starts] # Fencepost for while loop # Initial overlaps (1 base) and their tms overlaps = [dna[start:end] for start, end in zip(starts, ends)] overlap_tms = [coral.analysis.tm(overlap) for overlap in overlaps] index = overlap_tms.index(min(overlap_tms)) # Initial oligos - includes the 1 base overlaps. # All the oligos are in the same direction - reverse # complementation of every other one happens later oligo_starts = [0] + starts oligo_ends = ends + [len(dna)] oligo_indices = [oligo_starts, oligo_ends] oligos = [dna[start:end] for start, end in zip(*oligo_indices)] # Oligo won't be maxed in first pass. tm_met and len_met will be false maxed = False while not (tm_met and len_met) and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Tm calculation is bottleneck - only recalculate changed overlap overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Find lowest-Tm overlap and its index. index = overlap_tms.index(min(overlap_tms)) # Move overlap at that index oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Regenerate conditions maxed = any([len(x) == length_max for x in oligos]) tm_met = all([x >= melting_temp for x in overlap_tms]) if min_exception: len_met = True else: len_met = all([len(x) >= overlap_min for x in overlaps]) # TODO: add test for min_exception case (use rob's sequence from # 20130624 with 65C Tm) if min_exception: len_met = all([len(x) >= overlap_min for x in overlaps]) # See if len_met is true - if so do nothing if len_met: break else: while not len_met and not maxed: # Recalculate overlaps and their Tms overlaps = _recalculate_overlaps(dna, overlaps, oligo_indices) # Overlap to increase is the shortest one overlap_lens = [len(overlap) for overlap in overlaps] index = overlap_lens.index(min(overlap_lens)) # Increase left or right oligo oligos = _expand_overlap(dna, oligo_indices, index, oligos, length_max) # Recalculate conditions maxed = any([len(x) == length_max for x in oligos]) len_met = all([len(x) >= overlap_min for x in overlaps]) # Recalculate tms to reflect any changes (some are redundant) overlap_tms[index] = coral.analysis.tm(overlaps[index]) # Outcome could be that len_met happened *or* maxed out # length of one of the oligos. If len_met happened, should be # done so long as tm_met has been satisfied. If maxed happened, # len_met will not have been met, even if tm_met is satisfied, # and script will reattempt with more oligos oligo_n += oligo_increment # Calculate location of overlaps overlap_indices = [(oligo_indices[0][x + 1], oligo_indices[1][x]) for x in range(overlap_n)] return oligos, overlaps, overlap_tms, overlap_indices
python
{ "resource": "" }
q2163
_recalculate_overlaps
train
def _recalculate_overlaps(dna, overlaps, oligo_indices): '''Recalculate overlap sequences based on the current overlap indices. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param overlaps: Current overlaps - a list of DNA sequences. :type overlaps: coral.DNA list :param oligo_indices: List of oligo indices (starts and stops). :type oligo_indices: list :returns: Overlap sequences. :rtype: coral.DNA list ''' for i, overlap in enumerate(overlaps): first_index = oligo_indices[0][i + 1] second_index = oligo_indices[1][i] overlap = dna[first_index:second_index] overlaps[i] = overlap return overlaps
python
{ "resource": "" }
q2164
_expand_overlap
train
def _expand_overlap(dna, oligo_indices, index, oligos, length_max): '''Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo :type left_len: int :param right_len: length of right oligo :type right_len: int :param length_max: length ceiling :type length_max: int :returns: New oligo list with one expanded. :rtype: list ''' left_len = len(oligos[index]) right_len = len(oligos[index + 1]) # If one of the oligos is max size, increase the other one if right_len == length_max: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') elif left_len == length_max: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: if left_len > right_len: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') # Recalculate oligos from start and end indices oligos = [dna[start:end] for start, end in zip(*oligo_indices)] return oligos
python
{ "resource": "" }
q2165
_adjust_overlap
train
def _adjust_overlap(positions_list, index, direction): '''Increase overlap to the right or left of an index. :param positions_list: list of overlap positions :type positions_list: list :param index: index of the overlap to increase. :type index: int :param direction: which side of the overlap to increase - left or right. :type direction: str :returns: A list of overlap positions (2-element lists) :rtype: list :raises: ValueError if direction isn't \'left\' or \'right\'. ''' if direction == 'left': positions_list[index + 1] -= 1 elif direction == 'right': positions_list[index] += 1 else: raise ValueError('direction must be \'left\' or \'right\'.') return positions_list
python
{ "resource": "" }
q2166
OligoAssembly.design_assembly
train
def design_assembly(self): '''Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict ''' # Input parameters needed to design the oligos length_range = self.kwargs['length_range'] oligo_number = self.kwargs['oligo_number'] require_even = self.kwargs['require_even'] melting_temp = self.kwargs['tm'] overlap_min = self.kwargs['overlap_min'] min_exception = self.kwargs['min_exception'] start_5 = self.kwargs['start_5'] if len(self.template) < length_range[0]: # If sequence can be built with just two oligos, do that oligos = [self.template, self.template.reverse_complement()] overlaps = [self.template] overlap_tms = [coral.analysis.tm(self.template)] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] return assembly_dict if oligo_number: # Make first attempt using length_range[1] and see what happens step = 3 # Decrease max range by this amount each iteration length_max = length_range[1] current_oligo_n = oligo_number + 1 oligo_n_met = False above_min_len = length_max > length_range[0] if oligo_n_met or not above_min_len: raise Exception('Failed to design assembly.') while not oligo_n_met and above_min_len: # Starting with low range and going up doesnt work for longer # sequence (overlaps become longer than 80) assembly = _grow_overlaps(self.template, melting_temp, require_even, length_max, overlap_min, min_exception) current_oligo_n = len(assembly[0]) if current_oligo_n > oligo_number: break length_max -= step oligo_n_met = current_oligo_n == oligo_number else: assembly = _grow_overlaps(self.template, melting_temp, require_even, length_range[1], overlap_min, min_exception) oligos, overlaps, overlap_tms, overlap_indices = assembly if start_5: for i in [x for x in range(len(oligos)) if x % 2 == 1]: oligos[i] = oligos[i].reverse_complement() else: for i in [x for x in range(len(oligos)) if x % 2 == 0]: oligos[i] = oligos[i].reverse_complement() # Make single-stranded oligos = [oligo.top for oligo in oligos] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms, 'overlap_indices': overlap_indices} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] self.overlap_indices = assembly_dict['overlap_indices'] for i in range(len(self.overlap_indices) - 1): # TODO: either raise an exception or prevent this from happening # at all current_start = self.overlap_indices[i + 1][0] current_end = self.overlap_indices[i][1] if current_start <= current_end: self.warning = 'warning: overlapping overlaps!' print self.warning self._has_run = True return assembly_dict
python
{ "resource": "" }
q2167
OligoAssembly.primers
train
def primers(self, tm=60): '''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list ''' self.primers = coral.design.primers(self.template, tm=tm) return self.primers
python
{ "resource": "" }
q2168
OligoAssembly.write_map
train
def write_map(self, path): '''Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str ''' starts = [index[0] for index in self.overlap_indices] features = [] for i, start in enumerate(starts): stop = start + len(self.overlaps[i]) name = 'overlap {}'.format(i + 1) feature_type = 'misc' strand = 0 features.append(coral.Feature(name, start, stop, feature_type, strand=strand)) seq_map = coral.DNA(self.template, features=features) coral.seqio.write_dna(seq_map, path)
python
{ "resource": "" }
q2169
coding_sequence
train
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'. :rtype: coral.RNA :raises: ValueError if rna argument has no start codon. ValueError if rna argument has no stop codon in-frame with the first start codon. ''' if isinstance(rna, coral.DNA): rna = transcribe(rna) codons_left = len(rna) // 3 start_codon = coral.RNA('aug') stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')] start = None stop = None valid = [None, None] index = 0 while codons_left: codon = rna[index:index + 3] if valid[0] is None: if codon in start_codon: start = index valid[0] = True else: if codon in stop_codons: stop = index + 3 valid[1] = True break index += 3 codons_left -= 1 if valid[0] is None: raise ValueError('Sequence has no start codon.') elif stop is None: raise ValueError('Sequence has no stop codon.') coding_rna = rna[start:stop] return coding_rna
python
{ "resource": "" }
q2170
Rebase.update
train
def update(self): '''Update definitions.''' # Download http://rebase.neb.com/rebase/link_withref to tmp self._tmpdir = tempfile.mkdtemp() try: self._rebase_file = self._tmpdir + '/rebase_file' print 'Downloading latest enzyme definitions' url = 'http://rebase.neb.com/rebase/link_withref' header = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(url, headers=header) con = urllib2.urlopen(req) with open(self._rebase_file, 'wb') as rebase_file: rebase_file.write(con.read()) # Process into self._enzyme_dict self._process_file() except urllib2.HTTPError, e: print 'HTTP Error: {} {}'.format(e.code, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes except urllib2.URLError, e: print 'URL Error: {} {}'.format(e.reason, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes # Process into RestrictionSite objects? (depends on speed) print 'Processing into RestrictionSite instances.' self.restriction_sites = {} # TODO: make sure all names are unique for key, (site, cuts) in self._enzyme_dict.iteritems(): # Make a site try: r = coral.RestrictionSite(coral.DNA(site), cuts, name=key) # Add it to dict with name as key self.restriction_sites[key] = r except ValueError: # Encountered ambiguous sequence, have to ignore it until # coral.DNA can handle ambiguous DNA pass
python
{ "resource": "" }
q2171
Rebase._process_file
train
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')] if len(names) != len(seqs): raise Exception('Found different number of enzyme names and ' 'sequences.') self._enzyme_dict = {} for name, seq in zip(names, seqs): if '?' in seq: # Is unknown sequence, don't keep it pass elif seq.startswith('(') and seq.endswith(')'): # Has four+ cut sites, don't keep it pass elif '^' in seq: # Has reasonable internal cut sites, keep it top_cut = seq.index('^') bottom_cut = len(seq) - top_cut - 1 site = seq.replace('^', '') self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) elif seq.endswith(')'): # Has reasonable external cut sites, keep it # (4-cutter also starts with '(') # separate site and cut locations site, cuts = seq.split('(') cuts = cuts.replace(')', '') top_cut, bottom_cut = [int(x) + len(site) for x in cuts.split('/')] self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) shutil.rmtree(self._tmpdir)
python
{ "resource": "" }
q2172
tempdir
train
def tempdir(fun): '''For use as a decorator of instance methods - creates a temporary dir named self._tempdir and then deletes it after the method runs. :param fun: function to decorate :type fun: instance method ''' def wrapper(*args, **kwargs): self = args[0] if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) self._tempdir = tempfile.mkdtemp() # If the method raises an exception, delete the temporary dir try: retval = fun(*args, **kwargs) finally: shutil.rmtree(self._tempdir) if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) return retval return wrapper
python
{ "resource": "" }
q2173
convert_sequence
train
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :type seq: coral.DNA or coral.RNA :param to_material: material to which to convert ('rna', 'dna', or 'peptide'). :type to_material: str :returns: sequence of type coral.sequence.[material type] ''' if isinstance(seq, coral.DNA) and to_material == 'rna': # Transcribe # Can't transcribe a gap if '-' in seq: raise ValueError('Cannot transcribe gapped DNA') # Convert DNA chars to RNA chars origin = ALPHABETS['dna'][:-1] destination = ALPHABETS['rna'] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate RNA object converted = coral.RNA(converted) elif isinstance(seq, coral.RNA): if to_material == 'dna': # Reverse transcribe origin = ALPHABETS['rna'] destination = ALPHABETS['dna'][:-1] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate DNA object converted = coral.DNA(converted) elif to_material == 'peptide': # Translate seq_list = list(str(seq)) # Convert to peptide until stop codon is found. converted = [] while True: if len(seq_list) >= 3: base_1 = seq_list.pop(0) base_2 = seq_list.pop(0) base_3 = seq_list.pop(0) codon = ''.join(base_1 + base_2 + base_3).upper() amino_acid = CODONS[codon] # Stop when stop codon is found if amino_acid == '*': break converted.append(amino_acid) else: break converted = ''.join(converted) converted = coral.Peptide(converted) else: msg1 = 'Conversion from ' msg2 = '{0} to {1} is not supported.'.format(seq.__class__.__name__, to_material) raise ValueError(msg1 + msg2) return converted
python
{ "resource": "" }
q2174
NucleicAcid.gc
train
def gc(self): '''Find the frequency of G and C in the current sequence.''' gc = len([base for base in self.seq if base == 'C' or base == 'G']) return float(gc) / len(self)
python
{ "resource": "" }
q2175
NucleicAcid.is_rotation
train
def is_rotation(self, other): '''Determine whether two sequences are the same, just at different rotations. :param other: The sequence to check for rotational equality. :type other: coral.sequence._sequence.Sequence ''' if len(self) != len(other): return False for i in range(len(self)): if self.rotate(i) == other: return True return False
python
{ "resource": "" }
q2176
NucleicAcid.linearize
train
def linearize(self, index=0): '''Linearize the Sequence at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if the input is a linear sequence. ''' if not self.circular and index != 0: raise ValueError('Cannot relinearize a linear sequence.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False return copy
python
{ "resource": "" }
q2177
NucleicAcid.mw
train
def mw(self): '''Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float ''' counter = collections.Counter(self.seq.lower()) mw_a = counter['a'] * 313.2 mw_t = counter['t'] * 304.2 mw_g = counter['g'] * 289.2 mw_c = counter['c'] * 329.2 mw_u = counter['u'] * 306.2 if self.material == 'dna': return mw_a + mw_t + mw_g + mw_c + 79.0 else: return mw_a + mw_u + mw_g + mw_c + 159.0
python
{ "resource": "" }
q2178
five_resect
train
def five_resect(dna, n_bases): '''Remove bases from 5' end of top strand. :param dna: Sequence to resect. :type dna: coral.DNA :param n_bases: Number of bases cut back. :type n_bases: int :returns: DNA sequence resected at the 5' end by n_bases. :rtype: coral.DNA ''' new_instance = dna.copy() if n_bases >= len(dna): new_instance.top.seq = ''.join(['-' for i in range(len(dna))]) else: new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:] new_instance = _remove_end_gaps(new_instance) return new_instance
python
{ "resource": "" }
q2179
_remove_end_gaps
train
def _remove_end_gaps(sequence): '''Removes double-stranded gaps from ends of the sequence. :returns: The current sequence with terminal double-strand gaps ('-') removed. :rtype: coral.DNA ''' # Count terminal blank sequences def count_end_gaps(seq): gap = coral.DNA('-') count = 0 for base in seq: if base == gap: count += 1 else: break return count top_left = count_end_gaps(sequence.top) top_right = count_end_gaps(reversed(sequence.top)) bottom_left = count_end_gaps(reversed(sequence.bottom)) bottom_right = count_end_gaps(sequence.bottom) # Trim sequence left_index = min(top_left, bottom_left) right_index = len(sequence) - min(top_right, bottom_right) return sequence[left_index:right_index]
python
{ "resource": "" }
q2180
needle
train
def needle(reference, query, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. :type gapextend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: (aligned reference, aligned query, score) :rtype: tuple of two coral.DNA instances and a float ''' # Align using cython Needleman-Wunsch aligned_ref, aligned_res = aligner(str(reference), str(query), gap_open=gap_open, gap_extend=gap_extend, method='global_cfe', matrix=matrix.matrix, alphabet=matrix.alphabet) # Score the alignment score = score_alignment(aligned_ref, aligned_res, gap_open, gap_extend, matrix.matrix, matrix.alphabet) return cr.DNA(aligned_ref), cr.DNA(aligned_res), score
python
{ "resource": "" }
q2181
needle_msa
train
def needle_msa(reference, results, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Create a multiple sequence alignment based on aligning every result sequence against the reference, then inserting gaps until every aligned reference is identical ''' gap = '-' # Convert alignments to list of strings alignments = [] for result in results: ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open, gap_extend=gap_extend, matrix=matrix) alignments.append([str(ref_dna), str(res_dna), score]) def insert_gap(sequence, position): return sequence[:position] + gap + sequence[position:] i = 0 while True: # Iterate over 'columns' in every reference refs = [alignment[0][i] for alignment in alignments] # If there's a non-unanimous gap, insert gap into alignments gaps = [ref == gap for ref in refs] if any(gaps) and not all(gaps): for alignment in alignments: if alignment[0][i] != gap: alignment[0] = insert_gap(alignment[0], i) alignment[1] = insert_gap(alignment[1], i) # If all references match, we're all done alignment_set = set(alignment[0] for alignment in alignments) if len(alignment_set) == 1: break # If we've reach the end of some, but not all sequences, add end gap lens = [len(alignment[0]) for alignment in alignments] if i + 1 in lens: for alignment in alignments: if len(alignment[0]) == i + 1: alignment[0] = alignment[0] + gap alignment[1] = alignment[1] + gap i += 1 if i > 20: break # Convert into MSA format output_alignment = [cr.DNA(alignments[0][0])] for alignment in alignments: output_alignment.append(cr.DNA(alignment[1])) return output_alignment
python
{ "resource": "" }
q2182
needle_multi
train
def needle_multi(references, queries, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Batch process of sequencing split over several cores. Acts just like needle but sequence inputs are lists. :param references: References sequence. :type references: coral.DNA list :param queries: Sequences to align against the reference. :type queries: coral.DNA list :param gap_open: Penalty for opening a gap. :type gap_open: float :param gap_extend: Penalty for extending a gap. :type gap_extend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: a list of the same output as coral.sequence.needle :rtype: list ''' pool = multiprocessing.Pool() try: args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in zip(references, queries)] aligned = pool.map(run_needle, args_list) except KeyboardInterrupt: print('Caught KeyboardInterrupt, terminating workers') pool.terminate() pool.join() raise KeyboardInterrupt return aligned
python
{ "resource": "" }
q2183
import_global
train
def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports ''' frame = None try: # If locals_ or globals_ are not given, autodetect them by inspecting # the current stack if locals_ is None or globals_ is None: import inspect frame = inspect.stack()[1][0] if locals_ is None: locals_ = frame.f_locals if globals_ is None: globals_ = frame.f_globals try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.', globals=globals_, locals=locals_, fromlist=name[1:], level=max(level, 0), ) # Make sure we get the right part of a dotted import (i.e. # spam.eggs should return eggs, not spam) try: for attr in name[1:]: module = getattr(module, attr) except AttributeError: raise ImportError('No module named ' + '.'.join(name)) # If no list of modules is given, autodetect from either __all__ # or a dir() of the module if not modules: modules = getattr(module, '__all__', dir(module)) else: modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules): if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
python
{ "resource": "" }
q2184
camel_to_underscore
train
def camel_to_underscore(name): '''Convert camel case style naming to underscore style naming If there are existing underscores they will be collapsed with the to-be-added underscores. Multiple consecutive capital letters will not be split except for the last one. >>> camel_to_underscore('SpamEggsAndBacon') 'spam_eggs_and_bacon' >>> camel_to_underscore('Spam_and_bacon') 'spam_and_bacon' >>> camel_to_underscore('Spam_And_Bacon') 'spam_and_bacon' >>> camel_to_underscore('__SpamAndBacon__') '__spam_and_bacon__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__' ''' output = [] for i, c in enumerate(name): if i > 0: pc = name[i - 1] if c.isupper() and not pc.isupper() and pc != '_': # Uppercase and the previous character isn't upper/underscore? # Add the underscore output.append('_') elif i > 3 and not c.isupper(): # Will return the last 3 letters to check if we are changing # case previous = name[i - 3:i] if previous.isalpha() and previous.isupper(): output.insert(len(output) - 1, '_') output.append(c.lower()) return ''.join(output)
python
{ "resource": "" }
q2185
timedelta_to_seconds
train
def timedelta_to_seconds(delta): '''Convert a timedelta to seconds with the microseconds as fraction Note that this method has become largely obsolete with the `timedelta.total_seconds()` method introduced in Python 2.7. >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001' ''' # Only convert to float if needed if delta.microseconds: total = delta.microseconds * 1e-6 else: total = 0 total += delta.seconds total += delta.days * 60 * 60 * 24 return total
python
{ "resource": "" }
q2186
get_terminal_size
train
def get_terminal_size(): # pragma: no cover '''Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height ''' try: # Default to 79 characters for IPython notebooks from IPython import get_ipython ipython = get_ipython() from ipykernel import zmqshell if isinstance(ipython, zmqshell.ZMQInteractiveShell): return 79, 24 except Exception: # pragma: no cover pass try: # This works for Python 3, but not Pypy3. Probably the best method if # it's supported so let's always try import shutil w, h = shutil.get_terminal_size() if w and h: # The off by one is needed due to progressbars in some cases, for # safety we'll always substract it. return w - 1, h except Exception: # pragma: no cover pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if w and h: return w, h except Exception: # pragma: no cover pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if w and h: return w, h except Exception: # pragma: no cover pass try: w, h = _get_terminal_size_linux() if w and h: return w, h except Exception: # pragma: no cover pass try: # Windows detection doesn't always work, let's try anyhow w, h = _get_terminal_size_windows() if w and h: return w, h except Exception: # pragma: no cover pass try: # needed for window's python in cygwin's xterm! w, h = _get_terminal_size_tput() if w and h: return w, h except Exception: # pragma: no cover pass return 79, 24
python
{ "resource": "" }
q2187
Skype.AsyncSearchUsers
train
def AsyncSearchUsers(self, Target): """Asynchronously searches for Skype users. :Parameters: Target : unicode Search target (name or email address). :return: A search identifier. It will be passed along with the results to the `SkypeEvents.AsyncSearchUsersFinished` event after the search is completed. :rtype: int """ if not hasattr(self, '_AsyncSearchUsersCommands'): self._AsyncSearchUsersCommands = [] self.RegisterEventHandler('Reply', self._AsyncSearchUsersReplyHandler) command = Command('SEARCH USERS %s' % tounicode(Target), 'USERS', False, self.Timeout) self._AsyncSearchUsersCommands.append(command) self.SendCommand(command) # return pCookie - search identifier return command.Id
python
{ "resource": "" }
q2188
Skype.Attach
train
def Attach(self, Protocol=5, Wait=True): """Establishes a connection to Skype. :Parameters: Protocol : int Minimal Skype protocol version. Wait : bool If set to False, blocks forever until the connection is established. Otherwise, timeouts after the `Timeout`. """ try: self._Api.protocol = Protocol self._Api.attach(self.Timeout, Wait) except SkypeAPIError: self.ResetCache() raise
python
{ "resource": "" }
q2189
Skype.Call
train
def Call(self, Id=0): """Queries a call object. :Parameters: Id : int Call identifier. :return: Call object. :rtype: `call.Call` """ o = Call(self, Id) o.Status # Test if such a call exists. return o
python
{ "resource": "" }
q2190
Skype.ChangeUserStatus
train
def ChangeUserStatus(self, Status): """Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` property to perform an immediate change of status. """ if self.CurrentUserStatus.upper() == Status.upper(): return self._ChangeUserStatus_Event = threading.Event() self._ChangeUserStatus_Status = Status.upper() self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) self.CurrentUserStatus = Status self._ChangeUserStatus_Event.wait() self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status
python
{ "resource": "" }
q2191
Skype.Chat
train
def Chat(self, Name=''): """Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat` """ o = Chat(self, Name) o.Status # Tests if such a chat really exists. return o
python
{ "resource": "" }
q2192
Skype.ClearCallHistory
train
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls): """Clears the call history. :Parameters: Username : str Skypename of the user. A special value of 'ALL' means that entries of all users should be removed. Type : `enums`.clt* Call type. """ cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username) self._DoCommand(cmd, cmd)
python
{ "resource": "" }
q2193
Skype.Command
train
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1): """Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an `SkypeError` exception). Block : bool If set to True, `SendCommand` method waits for a response from Skype API before returning. Timeout : float, int or long Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type is int or long or in seconds (or fractions thereof) if the type is float. Id : int Command Id. The default (-1) means it will be assigned automatically as soon as the command is sent. :return: A command object. :rtype: `Command` :see: `SendCommand` """ from api import Command as CommandClass return CommandClass(Command, Reply, Block, Timeout, Id)
python
{ "resource": "" }
q2194
Skype.Conference
train
def Conference(self, Id=0): """Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference` """ o = Conference(self, Id) if Id <= 0 or not o.Calls: raise SkypeError(0, 'Unknown conference') return o
python
{ "resource": "" }
q2195
Skype.CreateChatWith
train
def CreateChatWith(self, *Usernames): """Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat` :see: `Chat.AddMembers` """ return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])
python
{ "resource": "" }
q2196
Skype.CreateGroup
train
def CreateGroup(self, GroupName): """Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup` """ groups = self.CustomGroups self._DoCommand('CREATE GROUP %s' % tounicode(GroupName)) for g in self.CustomGroups: if g not in groups and g.DisplayName == GroupName: return g raise SkypeError(0, 'Group creating failed')
python
{ "resource": "" }
q2197
Skype.CreateSms
train
def CreateSms(self, MessageType, *TargetNumbers): """Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage` """ return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1])
python
{ "resource": "" }
q2198
Skype.Greeting
train
def Greeting(self, Username=''): """Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail` """ for v in self.Voicemails: if Username and v.PartnerHandle != Username: continue if v.Type in (vmtDefaultGreeting, vmtCustomGreeting): return v
python
{ "resource": "" }
q2199
Skype.Message
train
def Message(self, Id=0): """Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage` """ o = ChatMessage(self, Id) o.Status # Test if such an id is known. return o
python
{ "resource": "" }