code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
logger.debug("download page: %r, %r", args, kwargs) return self.__clientDefer(downloadPage(*args, **kwargs))
def __doDownloadPage(self, *args, **kwargs)
Works like client.downloadPage(), but handle incoming headers
9.274728
8.634883
1.0741
"Verify a user's credentials." parser = txml.Users(delegate) return self.__downloadPage('/account/verify_credentials.xml', parser)
def verify_credentials(self, delegate=None)
Verify a user's credentials.
26.344419
26.810453
0.982617
"Update your status. Returns the ID of the new post." params = params.copy() params['status'] = status if source: params['source'] = source return self.__parsed_post(self.__post('/statuses/update.xml', params), txml.parseUpdateResponse)
def update(self, status, source=None, params={})
Update your status. Returns the ID of the new post.
9.848126
6.075469
1.620966
parser = txml.Statuses(delegate) return self.__postPage('/statuses/retweet/%s.xml' % (id), parser)
def retweet(self, id, delegate)
Retweet a post Returns the retweet status info back to the given delegate
16.201429
18.569172
0.872491
return self.__get('/statuses/friends_timeline.xml', delegate, params, txml.Statuses, extra_args=extra_args)
def friends(self, delegate, params={}, extra_args=None)
Get updates from friends. Calls the delgate once for each status object received.
10.582291
12.037911
0.87908
return self.__get('/statuses/home_timeline.xml', delegate, params, txml.Statuses, extra_args=extra_args)
def home_timeline(self, delegate, params={}, extra_args=None)
Get updates from friends. Calls the delgate once for each status object received.
7.569693
10.001319
0.756869
if user: params['id'] = user return self.__get('/statuses/user_timeline.xml', delegate, params, txml.Statuses, extra_args=extra_args)
def user_timeline(self, delegate, user=None, params={}, extra_args=None)
Get the most recent updates for a user. If no user is specified, the statuses for the authenticating user are returned. See search for example of how results are returned.
5.412481
7.040149
0.768802
"Get the most recent public timeline." return self.__get('/statuses/public_timeline.atom', delegate, params, extra_args=extra_args)
def public_timeline(self, delegate, params={}, extra_args=None)
Get the most recent public timeline.
9.748096
7.606725
1.28151
return self.__get('/direct_messages.xml', delegate, params, txml.Direct, extra_args=extra_args)
def direct_messages(self, delegate, params={}, extra_args=None)
Get direct messages for the authenticating user. Search results are returned one message at a time a DirectMessage objects
10.768832
14.484067
0.743495
params = params.copy() if user is not None: params['user'] = user if user_id is not None: params['user_id'] = user_id if screen_name is not None: params['screen_name'] = screen_name params['text'] = text parser = txml.Direct(de...
def send_direct_message(self, text, user=None, delegate=None, screen_name=None, user_id=None, params={})
Send a direct message
2.812298
2.934687
0.958296
return self.__get('/statuses/replies.atom', delegate, params, extra_args=extra_args)
def replies(self, delegate, params={}, extra_args=None)
Get the most recent replies for the authenticating user. See search for example of how results are returned.
10.013626
10.771002
0.929684
parser = txml.Users(delegate) return self.__postPage('/friendships/create/%s.xml' % (user), parser)
def follow_user(self, user, delegate)
Follow the given user. Returns the user info back to the given delegate
19.622629
25.458941
0.770756
parser = txml.Users(delegate) return self.__postPage('/friendships/destroy/%s.xml' % (user), parser)
def unfollow_user(self, user, delegate)
Unfollow the given user. Returns the user info back to the given delegate
18.616955
23.450497
0.793883
if user: url = '/statuses/friends/' + user + '.xml' else: url = '/statuses/friends.xml' return self.__get_maybe_paging(url, delegate, params, txml.PagedUserList, extra_args, page_delegate)
def list_friends(self, delegate, user=None, params={}, extra_args=None, page_delegate=None)
Get the list of friends for a user. Calls the delegate with each user object found.
5.968116
6.42521
0.928859
url = '/users/show/%s.xml' % (user) d = defer.Deferred() self.__downloadPage(url, txml.Users(lambda u: d.callback(u))) \ .addErrback(lambda e: d.errback(e)) return d
def show_user(self, user)
Get the info for a specific user. Returns a delegate that will receive the user in a callback.
7.751983
7.091542
1.093131
if args is None: args = {} args['q'] = query return self.__doDownloadPage(self.search_url + '?' + self._urlencode(args), txml.Feed(delegate, extra_args), agent=self.agent)
def search(self, query, delegate, args=None, extra_args=None)
Perform a search query. Results are given one at a time to the delegate. An example delegate may look like this: def exampleDelegate(entry): print entry.title
6.958767
8.503998
0.818294
service.Service.startService(self) self._toState('idle') try: self.connect() except NoConsumerError: pass
def startService(self)
Start the service. This causes a transition to the C{'idle'} state, and then calls L{connect} to attempt an initial conection.
11.356627
10.324114
1.10001
if self._state == 'stopped': raise Error("This service is not running. Not connecting.") if self._state == 'connected': if forceReconnect: self._toState('disconnecting') return True else: raise ConnectError("Alr...
def connect(self, forceReconnect=False)
Check current conditions and initiate connection if possible. This is called to check preconditions for starting a new connection, and initating the connection itself. If the service is not running, this will do nothing. @param forceReconnect: Drop an existing connection to reconnnect...
3.621999
3.377448
1.072407
self._errorState = None def cb(result): self.protocol = None if self._state == 'stopped': # Don't transition to any other state. We are stopped. pass else: if isinstance(result, failure.Failure): ...
def makeConnection(self, protocol)
Called when the connection has been established. This method is called when an HTTP 200 response has been received, with the protocol that decodes the individual Twitter stream elements. That protocol will call the consumer for all Twitter entries received. The protocol, stored in L{pr...
5.170686
4.950514
1.044475
def connect(): if self.noisy: log.msg("Reconnecting now.") self.connect() backOff = self.backOffs[errorState] if self._errorState != errorState or self._delay is None: self._errorState = errorState self._delay = backOff['...
def _reconnect(self, errorState)
Attempt to reconnect. If the current back-off delay is 0, L{connect} is called. Otherwise, it will cause a transition to the C{'waiting'} state, ultimately causing a call to L{connect} when the delay expires.
4.210004
3.713782
1.133616
try: method = getattr(self, '_state_%s' % state) except AttributeError: raise ValueError("No such state %r" % state) log.msg("%s: to state %r" % (self.__class__.__name__, state)) self._state = state method(*args, **kwargs)
def _toState(self, state, *args, **kwargs)
Transition to the next state. @param state: Name of the next state.
3.158419
3.390367
0.931586
if self._reconnectDelayedCall: self._reconnectDelayedCall.cancel() self._reconnectDelayedCall = None self.loseConnection()
def _state_stopped(self)
The service is not running. This is the initial state, and the state after L{stopService} was called. To get out of this state, call L{startService}. If there is a current connection, we disconnect.
8.07396
6.365485
1.268397
def responseReceived(protocol): self.makeConnection(protocol) if self._state == 'aborting': self._toState('disconnecting') else: self._toState('connected') def trapError(failure): self._toState('error', failure) ...
def _state_connecting(self)
A connection is being started. A succesful attempt results in the state C{'connected'} when the first response from Twitter has been received. Transitioning to the state C{'aborting'} will cause an immediate disconnect instead, by transitioning to C{'disconnecting'}. Errors wil...
4.84985
4.349496
1.115037
log.err(reason) def matchException(failure): for errorState, backOff in self.backOffs.iteritems(): if 'errorTypes' not in backOff: continue if failure.check(*backOff['errorTypes']): return errorState ...
def _state_error(self, reason)
The connection attempt resulted in an error. Attempt a reconnect with a back-off algorithm.
6.880278
6.338443
1.085484
if line and line.isdigit(): self._expectedLength = int(line) self._rawBuffer = [] self._rawBufferLength = 0 self.setRawMode() else: self.keepAliveReceived()
def lineReceived(self, line)
Called when a line is received. We expect a length in bytes or an empty line for keep-alive. If we got a length, switch to raw mode to receive that amount of bytes.
6.696274
4.021614
1.665071
self._rawBuffer.append(data) self._rawBufferLength += len(data) if self._rawBufferLength >= self._expectedLength: receivedData = ''.join(self._rawBuffer) expectedData = receivedData[:self._expectedLength] extraData = receivedData[self._expectedLength...
def rawDataReceived(self, data)
Called when raw data is received. Fill the raw buffer C{_rawBuffer} until we have received at least C{_expectedLength} bytes. Call C{datagramReceived} with the received byte string of the expected size. Then switch back to line mode with the remainder of the buffer.
2.641829
2.131545
1.239396
obj = cls() obj.raw = data for name, value in data.iteritems(): if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS: setattr(obj, name, value) elif cls.COMPLEX_PROPS and name in cls.COMPLEX_PROPS: value = cls.COMPLEX_PROPS[name].fromD...
def fromDict(cls, data)
Fill this objects attributes from a dict for known properties.
2.002048
1.936767
1.033707
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 ...
def datagramReceived(self, data)
Decode the JSON-encoded datagram and call the callback.
4.263481
3.911668
1.089939
self.setTimeout(None) if reason.check(ResponseDone, PotentialDataLoss): self.deferred.callback(None) else: self.deferred.errback(reason)
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.
4.145854
3.376323
1.22792
def create(delegate, extra_args=None): return listParser(list_type, delegate, extra_args) return create
def simpleListFactory(list_type)
Used for simple parsers that support only one type of object
10.231252
9.46826
1.080584
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)
def setSubDelegates(self, namelist, before=None, after=None)
Set a delegate for a sub-sub-item, according to a list of names
2.790969
2.566319
1.087538
path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, list_path, path
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.
5.380266
3.798178
1.416539
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 thing...
def path_dispatch_rename(rename_like_method)
decorator for rename-like function, that need dispatch on 2 arguments
4.517883
4.413498
1.023651
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',''): ...
def deactivate(profile='default')
should be a matter of just unsetting the above keys
5.706626
5.879306
0.970629
'''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): ...
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
3.815509
1.754184
2.175091
'''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...
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
5.556808
4.371573
1.271123
'''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 sequenc...
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, incl...
4.456177
3.300551
1.350131
print(filename) os.chdir(directory) subprocess.Popen(["ipython", "nbconvert", "--to", "rst", filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=directory)
def ipynb_to_rst(directory, filename)
Converts a given file in a directory to an rst in the same directory.
2.934473
3.115523
0.941888
# 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)
def convert_ipynbs(directory)
Recursively converts all ipynb files in a directory into rst files in the same directory.
3.938568
3.845685
1.024152
'''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 e...
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 win...
3.805051
2.917796
1.304084
'''Walk through the sequence of interest in windows of window_size, evaluate free (unbound) pair probabilities. :param window_size: Window size in base pairs. :type window_size: int :param context_len: The number of bases of context to use when analyz...
def windows(self, window_size=60, context_len=90, step=10)
Walk through the sequence of interest in windows of window_size, evaluate free (unbound) pair probabilities. :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 wi...
5.52363
2.147151
2.572539
'''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) ...
def plot(self)
Plot the results of the run method.
5.875856
5.378951
1.09238
'''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_unde...
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:...
2.637113
1.30226
2.025028
'''(5' or 3' region on reference sequence that uniquely matches the reverse complement of the associated (5' or 3') region of one sequence in a list of query sequences. :param reference: Reference sequence. :type reference: coral.DNA :param query_list: List of query sequences. :type query_l...
def bind_unique(reference, query_list, min_overlap=12, right=True)
(5' or 3' region on reference sequence that uniquely matches the reverse complement of the associated (5' or 3') region of one sequence in a list of query sequences. :param reference: Reference sequence. :type reference: coral.DNA :param query_list: List of query sequences. :type query_list: co...
4.892581
2.215205
2.208636
'''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
def nonmatches(self)
Report mismatches, indels, and coverage.
10.503677
6.897498
1.522824
'''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 # V...
def plot(self)
Make a summary plot of the alignment and highlight nonmatches.
3.375052
3.12481
1.080082
'''Report mistmatches and indels for a single (aligned) reference and result.''' # TODO: Recalculate coverage based on reference (e.g. sequencing result # longer than template reference_str = str(reference) result_str = str(result) report = {'mismatches': [], 'ins...
def _analyze_single(self, reference, result)
Report mistmatches and indels for a single (aligned) reference and result.
3.62034
2.835608
1.276742
'''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] = ...
def _remove_n(self)
Remove terminal Ns from sequencing results.
5.11028
3.932151
1.299615
'''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)]))
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
3.314126
2.221397
1.491911
'''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. ...
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. Frequen...
4.489327
1.787573
2.511409
'''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...
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 c...
3.192814
1.927658
1.656318
'''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 = 'loremipsum@gmail.com' Entrez.email = email print 'Downloading Genome...' han...
def fetch_genome(genome_id)
Acquire a genome from Entrez
6.813064
6.542125
1.041414
'''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 ...
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 ...
5.043592
3.250504
1.551634
'''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', '...
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
3.326115
2.776469
1.197966
'''Read .seq and .abi/.ab1 results files from a dir. :param directory: Path to directory containing sequencing files. :type directory: str :returns: A list of DNA sequences. :rtype: coral.DNA list ''' dirfiles = os.listdir(directory) seq_exts = ['.seq', '.abi', '.ab1'] # Exclude fi...
def read_sequencing(directory)
Read .seq and .abi/.ab1 results files from a dir. :param directory: Path to directory containing sequencing files. :type directory: str :returns: A list of DNA sequences. :rtype: coral.DNA list
3.799152
2.116369
1.795127
'''Write DNA to a file (genbank or fasta). :param dna: DNA sequence to write to file :type dna: coral.DNA :param path: file path to write. Has to be genbank or fasta file. :type path: str ''' # Check if path filetype is valid, remember for later ext = os.path.splitext(path)[1] if e...
def write_dna(dna, path)
Write DNA to a file (genbank or fasta). :param dna: DNA sequence to write to file :type dna: coral.DNA :param path: file path to write. Has to be genbank or fasta file. :type path: str
3.750541
3.299584
1.136671
'''Write a list of primers out to a csv file. The first three columns are compatible with the current IDT order form (name, sequence, notes). By default there are no notes, which is an optional parameter. :param primer_list: A list of primers. :type primer_list: coral.Primer list :param path: A...
def write_primers(primer_list, path, names=None, notes=None)
Write a list of primers out to a csv file. The first three columns are compatible with the current IDT order form (name, sequence, notes). By default there are no notes, which is an optional parameter. :param primer_list: A list of primers. :type primer_list: coral.Primer list :param path: A path t...
2.856694
1.650687
1.73061
'''Translate genbank feature types into usable ones (currently identical). The feature table is derived from the official genbank spec (gbrel.txt) available at http://www.insdc.org/documents/feature-table :param feature_type: feature to convert :type feature_type: str :param bio_to_coral: from ...
def _process_feature_type(feature_type, bio_to_coral=True)
Translate genbank feature types into usable ones (currently identical). The feature table is derived from the official genbank spec (gbrel.txt) available at http://www.insdc.org/documents/feature-table :param feature_type: feature to convert :type feature_type: str :param bio_to_coral: from coral t...
4.404928
1.618157
2.722188
'''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 incorpor...
def _seqfeature_to_coral(feature)
Convert a Biopython SeqFeature to a coral.Feature. :param feature: Biopython SeqFeature :type feature: Bio.SeqFeature
3.583013
3.567224
1.004426
'''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...
def _coral_to_seqfeature(feature)
Convert a coral.Feature to a Biopython SeqFeature. :param feature: coral Feature. :type feature: coral.Feature
3.572819
3.526821
1.013042
'''Given the SubstitutionMatrix input, generate an equivalent matrix that is indexed by the ASCII number of each residue (e.g. A -> 65).''' ords = [ord(c) for c in alphabet] ord_matrix = np.zeros((max(ords) + 1, max(ords) + 1), dtype=np.integer) for i, row_ord in enumerate(ords): for j, col_...
def as_ord_matrix(matrix, alphabet)
Given the SubstitutionMatrix input, generate an equivalent matrix that is indexed by the ASCII number of each residue (e.g. A -> 65).
3.562066
2.025381
1.758714
'''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 ...
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...
2.939344
1.947677
1.509154
os.chdir(directory) process = subprocess.Popen(["make", "html"], cwd=directory) process.communicate()
def build_docs(directory)
Builds sphinx docs from a given directory.
3.040383
3.111716
0.977076
'''Given string and multiplier n, find m**2 decomposition. :param string: input string :type string: str :param n: multiplier :type n: int :returns: generator that produces m**2 * string if m**2 is a factor of n :rtype: generator of 0 or 1 ''' binary = [int(x) for x in bin(n)[2:]] ...
def _decompose(string, n)
Given string and multiplier n, find m**2 decomposition. :param string: input string :type string: str :param n: multiplier :type n: int :returns: generator that produces m**2 * string if m**2 is a factor of n :rtype: generator of 0 or 1
4.374403
2.083943
2.099099
'''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 rever...
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
3.646435
2.953553
1.234593
'''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 :r...
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: ...
4.965397
2.842016
1.747139
'''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) se...
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
5.869313
1.927272
3.045399
'''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-ove...
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
3.416863
2.487017
1.37388
'''Create a copy of the current instance. :returns: A safely editable copy of the current sequence. ''' # Significant performance improvements by skipping alphabet check return type(self)(self.seq, self.material, run_checks=False)
def copy(self)
Create a copy of the current instance. :returns: A safely editable copy of the current sequence.
18.710615
10.981757
1.703791
'''Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints ''' if len(pattern) > len(self): raise ValueError('Search pattern longer than sear...
def locate(self, pattern)
Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints
4.261792
3.094833
1.377067
'''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, ...
def copy(self)
Return a copy of the Feature. :returns: A safely editable copy of the current feature. :rtype: coral.Feature
4.888325
3.044854
1.605438
'''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 ...
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 :pa...
3.821985
2.187514
1.747182
'''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
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.
8.987692
3.070693
2.926926
'''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 ...
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 ...
5.215931
1.690027
3.086299
'''Enumerates the total number of secondary structures over the structural ensemble Ω(π). Runs the \'count\' command. :param strand: Strand on which to run count. Strands must be either coral.DNA or coral.RNA). :type strand: list :param pseudo: Enable pseu...
def count(self, strand, pseudo=False)
Enumerates the total number of secondary structures over the structural ensemble Ω(π). Runs the \'count\' command. :param strand: Strand on which to run count. Strands must be either coral.DNA or coral.RNA). :type strand: list :param pseudo: Enable pseudoknots. ...
6.827022
2.173788
3.140611
'''Enumerates the total number of secondary structures over the structural ensemble Ω(π) with an ordered permutation of strands. Runs the \'count\' command. :param strands: List of strands to use as inputs to count -multi. :type strands: list :param permutation: The circ...
def count_multi(self, strands, permutation=None, pseudo=False)
Enumerates the total number of secondary structures over the structural ensemble Ω(π) with an ordered permutation of strands. Runs the \'count\' command. :param strands: List of strands to use as inputs to count -multi. :type strands: list :param permutation: The circular permut...
5.471445
1.505398
3.634551
'''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 d...
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 no...
4.645195
1.60419
2.895664
'''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.D...
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...
7.573513
2.125971
3.562378
'''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 ...
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
4.868887
1.907195
2.552905
'''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()
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
4.243796
2.439801
1.739402
'''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 ...
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 pr...
4.205786
1.639922
2.564625
'''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 =...
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
3.440274
2.559596
1.344069
'''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): exepa...
def ape(self, ape_path=None)
Open in ApE if `ApE` is in your command line path.
3.774205
3.172627
1.189615
'''Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA ''' # Significant performance improvements by skipping alphabet check features_copy = [feature.copy() for feature in self.features] copy = type(...
def copy(self)
Create a copy of the current instance. :returns: A safely-editable copy of the current sequence. :rtype: coral.DNA
9.064727
5.508536
1.645578
'''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 == '-' ...
def circularize(self)
Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA
4.232485
3.046294
1.389388
'''Display a visualization of the sequence in an IPython notebook.''' try: from IPython.display import HTML import uuid except ImportError: raise IPythonDisplayImportError sequence_json = self.json() d3cdn = '//d3js.org/d3.v3.min.js' ...
def display(self)
Display a visualization of the sequence in an IPython notebook.
3.175673
2.991995
1.06139
'''Removes feature from circular plasmid and linearizes. Automatically reorients at the base just after the feature. This operation is complementary to the .extract() method. :param feature_name: The feature to remove. :type feature_name: coral.Feature ''' rotat...
def excise(self, feature)
Removes feature from circular plasmid and linearizes. Automatically reorients at the base just after the feature. This operation is complementary to the .extract() method. :param feature_name: The feature to remove. :type feature_name: coral.Feature
14.336
2.964322
4.836183
'''Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence asid...
def extract(self, feature, remove_subfeatures=False)
Extract a feature from the sequence. This operation is complementary to the .excise() method. :param feature: Feature object. :type feature: coral.sequence.Feature :param remove_subfeatures: Remove all features in the extracted sequence aside from the ...
6.147841
2.952086
2.082542
'''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.fe...
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
5.763852
2.830133
2.036601
'''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: ...
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.
5.914723
2.810955
2.104169
'''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: ...
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 lis...
6.700916
1.499176
4.469734
'''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.DNA :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not...
def rotate(self, n)
Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.DNA :raises: ValueError if applied to linear sequence or `index` is negative.
4.118193
2.456951
1.67614
'''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 accu...
def reverse_complement(self)
Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA
10.033641
7.333435
1.368205
'''Select features from the features list based on feature name, gene, or locus tag. :param term: Search term. :type term: str :param by: Feature attribute to search by. Options are 'name', 'gene', and 'locus_tag'. :type by: str :param...
def select_features(self, term, by='name', fuzzy=False)
Select features from the features list based on feature name, gene, or locus tag. :param term: Search term. :type term: str :param by: Feature attribute to search by. Options are 'name', 'gene', and 'locus_tag'. :type by: str :param fuzzy: If ...
3.213151
1.382727
2.323778
'''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 ''...
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
5.389203
2.544533
2.117953
'''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(sel...
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
6.347384
2.640666
2.403706
'''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)
def copy(self)
Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA
10.951224
4.426711
2.473896
'''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 ...
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
3.556811
1.778643
1.999734
'''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 =...
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
3.182886
2.300911
1.383315
'''Sum corrections for SantaLucia '98 method (unified parameters). :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 ...
def santalucia98_corrections(seq, pars_error)
Sum corrections for SantaLucia '98 method (unified parameters). :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
2.92548
2.040009
1.434052