id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 51
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,100 | dustin/twitty-twister | twittytwister/streaming.py | TwitterStream.datagramReceived | 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 | def datagramReceived(self, data):
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) | [
"def",
"datagramReceived",
"(",
"self",
",",
"data",
")",
":",
"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",
")"
] | Decode the JSON-encoded datagram and call the callback. | [
"Decode",
"the",
"JSON",
"-",
"encoded",
"datagram",
"and",
"call",
"the",
"callback",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L306-L322 |
2,101 | dustin/twitty-twister | twittytwister/streaming.py | TwitterStream.connectionLost | 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 | def connectionLost(self, reason):
self.setTimeout(None)
if reason.check(ResponseDone, PotentialDataLoss):
self.deferred.callback(None)
else:
self.deferred.errback(reason) | [
"def",
"connectionLost",
"(",
"self",
",",
"reason",
")",
":",
"self",
".",
"setTimeout",
"(",
"None",
")",
"if",
"reason",
".",
"check",
"(",
"ResponseDone",
",",
"PotentialDataLoss",
")",
":",
"self",
".",
"deferred",
".",
"callback",
"(",
"None",
")",
"else",
":",
"self",
".",
"deferred",
".",
"errback",
"(",
"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. | [
"Called",
"when",
"the",
"body",
"is",
"complete",
"or",
"the",
"connection",
"was",
"lost",
"."
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/streaming.py#L325-L338 |
2,102 | dustin/twitty-twister | twittytwister/txml.py | simpleListFactory | 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 | def simpleListFactory(list_type):
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 | [
"def",
"simpleListFactory",
"(",
"list_type",
")",
":",
"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"
] | Used for simple parsers that support only one type of object | [
"Used",
"for",
"simple",
"parsers",
"that",
"support",
"only",
"one",
"type",
"of",
"object"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/txml.py#L305-L310 |
2,103 | dustin/twitty-twister | twittytwister/txml.py | BaseXMLHandler.setSubDelegates | 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 | def setSubDelegates(self, namelist, before=None, after=None):
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",
")",
":",
"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",
")"
] | Set a delegate for a sub-sub-item, according to a list of names | [
"Set",
"a",
"delegate",
"for",
"a",
"sub",
"-",
"sub",
"-",
"item",
"according",
"to",
"a",
"list",
"of",
"names"
] | 8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3 | https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/txml.py#L48-L55 |
2,104 | jupyter/jupyter-drive | jupyterdrive/mixednbmanager.py | _split_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.
"""
path = path.strip('/')
list_path = path.split('/')
sentinel = list_path.pop(0)
return sentinel, list_path, path | python | def _split_path(path):
path = path.strip('/')
list_path = path.split('/')
sentinel = list_path.pop(0)
return sentinel, list_path, path | [
"def",
"_split_path",
"(",
"path",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"list_path",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"sentinel",
"=",
"list_path",
".",
"pop",
"(",
"0",
")",
"return",
"sentinel",
",",
"list_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. | [
"split",
"a",
"path",
"return",
"by",
"the",
"api"
] | 545813377cb901235e8ea81f83b0ac7755dbd7a9 | https://github.com/jupyter/jupyter-drive/blob/545813377cb901235e8ea81f83b0ac7755dbd7a9/jupyterdrive/mixednbmanager.py#L21-L32 |
2,105 | jupyter/jupyter-drive | jupyterdrive/mixednbmanager.py | MixedContentsManager.path_dispatch_rename | 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 | def path_dispatch_rename(rename_like_method):
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 | [
"def",
"path_dispatch_rename",
"(",
"rename_like_method",
")",
":",
"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"
] | decorator for rename-like function, that need dispatch on 2 arguments | [
"decorator",
"for",
"rename",
"-",
"like",
"function",
"that",
"need",
"dispatch",
"on",
"2",
"arguments"
] | 545813377cb901235e8ea81f83b0ac7755dbd7a9 | https://github.com/jupyter/jupyter-drive/blob/545813377cb901235e8ea81f83b0ac7755dbd7a9/jupyterdrive/mixednbmanager.py#L186-L208 |
2,106 | jupyter/jupyter-drive | jupyterdrive/__init__.py | deactivate | 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 | def deactivate(profile='default'):
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'] | [
"def",
"deactivate",
"(",
"profile",
"=",
"'default'",
")",
":",
"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'",
"]"
] | should be a matter of just unsetting the above keys | [
"should",
"be",
"a",
"matter",
"of",
"just",
"unsetting",
"the",
"above",
"keys"
] | 545813377cb901235e8ea81f83b0ac7755dbd7a9 | https://github.com/jupyter/jupyter-drive/blob/545813377cb901235e8ea81f83b0ac7755dbd7a9/jupyterdrive/__init__.py#L111-L122 |
2,107 | klavinslab/coral | coral/analysis/utils.py | sequence_type | 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 | 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 | [
"def",
"sequence_type",
"(",
"seq",
")",
":",
"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"
] | 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 | [
"Validates",
"a",
"coral",
".",
"sequence",
"data",
"type",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/utils.py#L5-L23 |
2,108 | klavinslab/coral | coral/reaction/_restriction.py | digest | 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 | 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 | [
"def",
"digest",
"(",
"dna",
",",
"restriction_enzyme",
")",
":",
"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"
] | 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 | [
"Restriction",
"endonuclease",
"reaction",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_restriction.py#L5-L42 |
2,109 | klavinslab/coral | coral/reaction/_restriction.py | _cut | 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 | 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] | [
"def",
"_cut",
"(",
"dna",
",",
"index",
",",
"restriction_enzyme",
")",
":",
"# 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",
"]"
] | 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 | [
"Cuts",
"template",
"once",
"at",
"the",
"specified",
"index",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_restriction.py#L45-L86 |
2,110 | klavinslab/coral | bin/ipynb2rst.py | ipynb_to_rst | 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 | def ipynb_to_rst(directory, filename):
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",
")",
":",
"print",
"(",
"filename",
")",
"os",
".",
"chdir",
"(",
"directory",
")",
"subprocess",
".",
"Popen",
"(",
"[",
"\"ipython\"",
",",
"\"nbconvert\"",
",",
"\"--to\"",
",",
"\"rst\"",
",",
"filename",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"cwd",
"=",
"directory",
")"
] | Converts a given file in a directory to an rst in the same directory. | [
"Converts",
"a",
"given",
"file",
"in",
"a",
"directory",
"to",
"an",
"rst",
"in",
"the",
"same",
"directory",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/bin/ipynb2rst.py#L13-L21 |
2,111 | klavinslab/coral | bin/ipynb2rst.py | convert_ipynbs | 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 | def convert_ipynbs(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) | [
"def",
"convert_ipynbs",
"(",
"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",
")"
] | Recursively converts all ipynb files in a directory into rst files in
the same directory. | [
"Recursively",
"converts",
"all",
"ipynb",
"files",
"in",
"a",
"directory",
"into",
"rst",
"files",
"in",
"the",
"same",
"directory",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/bin/ipynb2rst.py#L24-L32 |
2,112 | klavinslab/coral | coral/analysis/_structure/structure_windows.py | _context_walk | 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 | 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 | [
"def",
"_context_walk",
"(",
"dna",
",",
"window_size",
",",
"context_len",
",",
"step",
")",
":",
"# 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"
] | 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",
"context",
"-",
"dependent",
"non",
"-",
"boundedness",
"scores",
"for",
"a",
"DNA",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/structure_windows.py#L56-L98 |
2,113 | klavinslab/coral | coral/analysis/_structure/structure_windows.py | StructureWindows.plot | 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 | 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!') | [
"def",
"plot",
"(",
"self",
")",
":",
"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!'",
")"
] | Plot the results of the run method. | [
"Plot",
"the",
"results",
"of",
"the",
"run",
"method",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/structure_windows.py#L38-L53 |
2,114 | klavinslab/coral | coral/design/_primers.py | primer | 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 | 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 | [
"def",
"primer",
"(",
"dna",
",",
"tm",
"=",
"65",
",",
"min_len",
"=",
"10",
",",
"tm_undershoot",
"=",
"1",
",",
"tm_overshoot",
"=",
"3",
",",
"end_gc",
"=",
"False",
",",
"tm_parameters",
"=",
"'cloning'",
",",
"overhang",
"=",
"None",
",",
"structure",
"=",
"False",
")",
":",
"# 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.\n\n :param primer: Primer for which to evaluate structure\n :type primer: sequence.Primer\n\n '''",
"# 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"
] | 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. | [
"Design",
"primer",
"to",
"a",
"nearest",
"-",
"neighbor",
"Tm",
"setpoint",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_primers.py#L6-L98 |
2,115 | klavinslab/coral | coral/design/_primers.py | primers | 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 | 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 | [
"def",
"primers",
"(",
"dna",
",",
"tm",
"=",
"65",
",",
"min_len",
"=",
"10",
",",
"tm_undershoot",
"=",
"1",
",",
"tm_overshoot",
"=",
"3",
",",
"end_gc",
"=",
"False",
",",
"tm_parameters",
"=",
"'cloning'",
",",
"overhangs",
"=",
"None",
",",
"structure",
"=",
"False",
")",
":",
"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"
] | 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 | [
"Design",
"primers",
"for",
"PCR",
"amplifying",
"any",
"arbitrary",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_primers.py#L101-L140 |
2,116 | klavinslab/coral | coral/analysis/_sequencing/sanger.py | Sanger.nonmatches | 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 | 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 | [
"def",
"nonmatches",
"(",
"self",
")",
":",
"# 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"
] | Report mismatches, indels, and coverage. | [
"Report",
"mismatches",
"indels",
"and",
"coverage",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/sanger.py#L72-L80 |
2,117 | klavinslab/coral | coral/analysis/_sequencing/sanger.py | Sanger.plot | 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 | 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() | [
"def",
"plot",
"(",
"self",
")",
":",
"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",
"(",
")"
] | Make a summary plot of the alignment and highlight nonmatches. | [
"Make",
"a",
"summary",
"plot",
"of",
"the",
"alignment",
"and",
"highlight",
"nonmatches",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/sanger.py#L82-L134 |
2,118 | klavinslab/coral | coral/analysis/_sequencing/sanger.py | Sanger._remove_n | 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 | 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] | [
"def",
"_remove_n",
"(",
"self",
")",
":",
"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",
"]"
] | Remove terminal Ns from sequencing results. | [
"Remove",
"terminal",
"Ns",
"from",
"sequencing",
"results",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/sanger.py#L160-L167 |
2,119 | klavinslab/coral | coral/design/_sequence_generation/random_sequences.py | random_dna | 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 | 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)])) | [
"def",
"random_dna",
"(",
"n",
")",
":",
"return",
"coral",
".",
"DNA",
"(",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"'ATGC'",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
")",
")"
] | Generate a random DNA sequence.
:param n: Output sequence length.
:type n: int
:returns: Random DNA sequence of length n.
:rtype: coral.DNA | [
"Generate",
"a",
"random",
"DNA",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_sequence_generation/random_sequences.py#L7-L16 |
2,120 | klavinslab/coral | coral/design/_sequence_generation/random_sequences.py | random_codons | 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 | 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) | [
"def",
"random_codons",
"(",
"peptide",
",",
"frequency_cutoff",
"=",
"0.0",
",",
"weighted",
"=",
"False",
",",
"table",
"=",
"None",
")",
":",
"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",
")"
] | 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. | [
"Generate",
"randomized",
"codons",
"given",
"a",
"peptide",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_sequence_generation/random_sequences.py#L19-L70 |
2,121 | klavinslab/coral | coral/design/_sequence_generation/random_sequences.py | _cutoff | 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 | 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 | [
"def",
"_cutoff",
"(",
"table",
",",
"frequency_cutoff",
")",
":",
"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"
] | 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 | [
"Generate",
"new",
"codon",
"frequency",
"table",
"given",
"a",
"mean",
"cutoff",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_sequence_generation/random_sequences.py#L73-L92 |
2,122 | klavinslab/coral | coral/database/_entrez.py | fetch_genome | 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 | 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 | [
"def",
"fetch_genome",
"(",
"genome_id",
")",
":",
"# 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"
] | Acquire a genome from Entrez | [
"Acquire",
"a",
"genome",
"from",
"Entrez"
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_entrez.py#L15-L34 |
2,123 | klavinslab/coral | coral/analysis/_structure/viennarna.py | ViennaRNA.fold | 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 | 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 | [
"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",
")",
":",
"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"
] | 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 | [
"Run",
"the",
"RNAfold",
"command",
"and",
"retrieve",
"the",
"result",
"in",
"a",
"dictionary",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/viennarna.py#L143-L248 |
2,124 | klavinslab/coral | coral/analysis/_structure/dimers.py | dimers | 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 | 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] | [
"def",
"dimers",
"(",
"primer1",
",",
"primer2",
",",
"concentrations",
"=",
"[",
"5e-7",
",",
"3e-11",
"]",
")",
":",
"# 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",
"]"
] | 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 | [
"Calculate",
"expected",
"fraction",
"of",
"primer",
"dimers",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/dimers.py#L5-L40 |
2,125 | klavinslab/coral | coral/seqio/_dna.py | read_dna | 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 | 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 | [
"def",
"read_dna",
"(",
"path",
")",
":",
"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"
] | 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 | [
"Read",
"DNA",
"from",
"file",
".",
"Uses",
"BioPython",
"and",
"coerces",
"to",
"coral",
"format",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/seqio/_dna.py#L22-L69 |
2,126 | klavinslab/coral | coral/seqio/_dna.py | _seqfeature_to_coral | 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 | 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 | [
"def",
"_seqfeature_to_coral",
"(",
"feature",
")",
":",
"# 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"
] | Convert a Biopython SeqFeature to a coral.Feature.
:param feature: Biopython SeqFeature
:type feature: Bio.SeqFeature | [
"Convert",
"a",
"Biopython",
"SeqFeature",
"to",
"a",
"coral",
".",
"Feature",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/seqio/_dna.py#L204-L265 |
2,127 | klavinslab/coral | coral/seqio/_dna.py | _coral_to_seqfeature | 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 | 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 | [
"def",
"_coral_to_seqfeature",
"(",
"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"
] | Convert a coral.Feature to a Biopython SeqFeature.
:param feature: coral Feature.
:type feature: coral.Feature | [
"Convert",
"a",
"coral",
".",
"Feature",
"to",
"a",
"Biopython",
"SeqFeature",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/seqio/_dna.py#L268-L307 |
2,128 | klavinslab/coral | coral/analysis/_sequencing/align.py | score_alignment | 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 | 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 | [
"def",
"score_alignment",
"(",
"a",
",",
"b",
",",
"gap_open",
",",
"gap_extend",
",",
"matrix",
")",
":",
"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"
] | 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. | [
"Calculate",
"the",
"alignment",
"score",
"from",
"two",
"aligned",
"sequences",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/align.py#L188-L219 |
2,129 | klavinslab/coral | bin/build_sphinx_docs.py | build_docs | def build_docs(directory):
"""Builds sphinx docs from a given directory."""
os.chdir(directory)
process = subprocess.Popen(["make", "html"], cwd=directory)
process.communicate() | python | def build_docs(directory):
os.chdir(directory)
process = subprocess.Popen(["make", "html"], cwd=directory)
process.communicate() | [
"def",
"build_docs",
"(",
"directory",
")",
":",
"os",
".",
"chdir",
"(",
"directory",
")",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"make\"",
",",
"\"html\"",
"]",
",",
"cwd",
"=",
"directory",
")",
"process",
".",
"communicate",
"(",
")"
] | Builds sphinx docs from a given directory. | [
"Builds",
"sphinx",
"docs",
"from",
"a",
"given",
"directory",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/bin/build_sphinx_docs.py#L11-L15 |
2,130 | klavinslab/coral | coral/design/_gibson.py | gibson | 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 | 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 | [
"def",
"gibson",
"(",
"seq_list",
",",
"circular",
"=",
"True",
",",
"overlaps",
"=",
"'mixed'",
",",
"overlap_tm",
"=",
"65",
",",
"maxlen",
"=",
"80",
",",
"terminal_primers",
"=",
"True",
",",
"primer_kwargs",
"=",
"None",
")",
":",
"# 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"
] | 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. | [
"Design",
"Gibson",
"primers",
"given",
"a",
"set",
"of",
"sequences"
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_gibson.py#L136-L214 |
2,131 | klavinslab/coral | coral/sequence/_sequence.py | reverse_complement | 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 | 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]) | [
"def",
"reverse_complement",
"(",
"sequence",
",",
"material",
")",
":",
"code",
"=",
"dict",
"(",
"COMPLEMENTS",
"[",
"material",
"]",
")",
"reverse_sequence",
"=",
"sequence",
"[",
":",
":",
"-",
"1",
"]",
"return",
"''",
".",
"join",
"(",
"[",
"code",
"[",
"str",
"(",
"base",
")",
"]",
"for",
"base",
"in",
"reverse_sequence",
"]",
")"
] | Reverse complement a sequence.
:param sequence: Sequence to reverse complement
:type sequence: str
:param material: dna, rna, or peptide.
:type material: str | [
"Reverse",
"complement",
"a",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_sequence.py#L386-L396 |
2,132 | klavinslab/coral | coral/sequence/_sequence.py | check_alphabet | 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 | 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) | [
"def",
"check_alphabet",
"(",
"seq",
",",
"material",
")",
":",
"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",
")"
] | 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. | [
"Verify",
"that",
"a",
"given",
"string",
"is",
"valid",
"DNA",
"RNA",
"or",
"peptide",
"characters",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_sequence.py#L399-L424 |
2,133 | klavinslab/coral | coral/sequence/_sequence.py | process_seq | 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 | 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 | [
"def",
"process_seq",
"(",
"seq",
",",
"material",
")",
":",
"check_alphabet",
"(",
"seq",
",",
"material",
")",
"seq",
"=",
"seq",
".",
"upper",
"(",
")",
"return",
"seq"
] | 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 | [
"Validate",
"and",
"process",
"sequence",
"inputs",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_sequence.py#L427-L441 |
2,134 | klavinslab/coral | coral/sequence/_sequence.py | palindrome | 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 | 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 | [
"def",
"palindrome",
"(",
"seq",
")",
":",
"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"
] | 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 | [
"Test",
"whether",
"a",
"sequence",
"is",
"palindrome",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_sequence.py#L444-L465 |
2,135 | klavinslab/coral | coral/sequence/_sequence.py | Feature.copy | 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 | 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) | [
"def",
"copy",
"(",
"self",
")",
":",
"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",
")"
] | Return a copy of the Feature.
:returns: A safely editable copy of the current feature.
:rtype: coral.Feature | [
"Return",
"a",
"copy",
"of",
"the",
"Feature",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_sequence.py#L334-L343 |
2,136 | klavinslab/coral | coral/analysis/_structure/nupack.py | nupack_multi | 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 | 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 | [
"def",
"nupack_multi",
"(",
"seqs",
",",
"material",
",",
"cmd",
",",
"arguments",
",",
"report",
"=",
"True",
")",
":",
"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"
] | 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 | [
"Split",
"Nupack",
"commands",
"over",
"processors",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1490-L1533 |
2,137 | klavinslab/coral | coral/analysis/_structure/nupack.py | run_nupack | 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 | 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 | [
"def",
"run_nupack",
"(",
"kwargs",
")",
":",
"run",
"=",
"NUPACK",
"(",
"kwargs",
"[",
"'seq'",
"]",
")",
"output",
"=",
"getattr",
"(",
"run",
",",
"kwargs",
"[",
"'cmd'",
"]",
")",
"(",
"*",
"*",
"kwargs",
"[",
"'arguments'",
"]",
")",
"return",
"output"
] | Run picklable Nupack command.
:param kwargs: keyword arguments to pass to Nupack as well as 'cmd'.
:returns: Variable - whatever `cmd` returns. | [
"Run",
"picklable",
"Nupack",
"command",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1536-L1545 |
2,138 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK.pfunc_multi | 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 | 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])) | [
"def",
"pfunc_multi",
"(",
"self",
",",
"strands",
",",
"permutation",
"=",
"None",
",",
"temp",
"=",
"37.0",
",",
"pseudo",
"=",
"False",
",",
"material",
"=",
"None",
",",
"dangles",
"=",
"'some'",
",",
"sodium",
"=",
"1.0",
",",
"magnesium",
"=",
"0.0",
")",
":",
"# 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",
"]",
")",
")"
] | 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 | [
"Compute",
"the",
"partition",
"function",
"for",
"an",
"ordered",
"complex",
"of",
"strands",
".",
"Runs",
"the",
"\\",
"pfunc",
"\\",
"command",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L97-L150 |
2,139 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK.subopt | 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 | 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 | [
"def",
"subopt",
"(",
"self",
",",
"strand",
",",
"gap",
",",
"temp",
"=",
"37.0",
",",
"pseudo",
"=",
"False",
",",
"material",
"=",
"None",
",",
"dangles",
"=",
"'some'",
",",
"sodium",
"=",
"1.0",
",",
"magnesium",
"=",
"0.0",
")",
":",
"# 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"
] | 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 | [
"Compute",
"the",
"suboptimal",
"structures",
"within",
"a",
"defined",
"energy",
"gap",
"of",
"the",
"MFE",
".",
"Runs",
"the",
"\\",
"subopt",
"\\",
"command",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L430-L481 |
2,140 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK.energy | 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 | 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]) | [
"def",
"energy",
"(",
"self",
",",
"strand",
",",
"dotparens",
",",
"temp",
"=",
"37.0",
",",
"pseudo",
"=",
"False",
",",
"material",
"=",
"None",
",",
"dangles",
"=",
"'some'",
",",
"sodium",
"=",
"1.0",
",",
"magnesium",
"=",
"0.0",
")",
":",
"# 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",
"]",
")"
] | 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 | [
"Calculate",
"the",
"free",
"energy",
"of",
"a",
"given",
"sequence",
"structure",
".",
"Runs",
"the",
"\\",
"energy",
"\\",
"command",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L618-L668 |
2,141 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK.complexes_timeonly | 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 | 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)) | [
"def",
"complexes_timeonly",
"(",
"self",
",",
"strands",
",",
"max_size",
")",
":",
"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",
")",
")"
] | 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 | [
"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",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1127-L1146 |
2,142 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK._multi_lines | 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 | 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 | [
"def",
"_multi_lines",
"(",
"self",
",",
"strands",
",",
"permutation",
")",
":",
"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"
] | 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 | [
"Prepares",
"lines",
"to",
"write",
"to",
"file",
"for",
"pfunc",
"command",
"input",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1346-L1363 |
2,143 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK._read_tempfile | 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 | 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() | [
"def",
"_read_tempfile",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_tempdir",
",",
"filename",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | Read in and return file that's in the tempdir.
:param filename: Name of the file to read.
:type filename: str | [
"Read",
"in",
"and",
"return",
"file",
"that",
"s",
"in",
"the",
"tempdir",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1366-L1374 |
2,144 | klavinslab/coral | coral/analysis/_structure/nupack.py | NUPACK._pairs_to_np | 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 | 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 | [
"def",
"_pairs_to_np",
"(",
"self",
",",
"pairlist",
",",
"dim",
")",
":",
"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"
] | 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 | [
"Given",
"a",
"set",
"of",
"pair",
"probability",
"lines",
"construct",
"a",
"numpy",
"array",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L1376-L1393 |
2,145 | klavinslab/coral | coral/sequence/_dna.py | _flip_feature | 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 | 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 | [
"def",
"_flip_feature",
"(",
"self",
",",
"feature",
",",
"parent_len",
")",
":",
"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"
] | 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 | [
"Adjust",
"a",
"feature",
"s",
"location",
"when",
"flipping",
"DNA",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L734-L753 |
2,146 | klavinslab/coral | coral/sequence/_dna.py | DNA.ape | 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 | 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) | [
"def",
"ape",
"(",
"self",
",",
"ape_path",
"=",
"None",
")",
":",
"# 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",
")"
] | Open in ApE if `ApE` is in your command line path. | [
"Open",
"in",
"ApE",
"if",
"ApE",
"is",
"in",
"your",
"command",
"line",
"path",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L84-L111 |
2,147 | klavinslab/coral | coral/sequence/_dna.py | DNA.circularize | 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 | 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 | [
"def",
"circularize",
"(",
"self",
")",
":",
"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"
] | Circularize linear DNA.
:returns: A circularized version of the current sequence.
:rtype: coral.DNA | [
"Circularize",
"linear",
"DNA",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L127-L143 |
2,148 | klavinslab/coral | coral/sequence/_dna.py | DNA.flip | 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 | 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 | [
"def",
"flip",
"(",
"self",
")",
":",
"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"
] | Flip the DNA - swap the top and bottom strands.
:returns: Flipped DNA (bottom strand is now top strand, etc.).
:rtype: coral.DNA | [
"Flip",
"the",
"DNA",
"-",
"swap",
"the",
"top",
"and",
"bottom",
"strands",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L242-L252 |
2,149 | klavinslab/coral | coral/sequence/_dna.py | DNA.linearize | 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 | 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 | [
"def",
"linearize",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"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"
] | 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. | [
"Linearize",
"circular",
"DNA",
"at",
"an",
"index",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L275-L295 |
2,150 | klavinslab/coral | coral/sequence/_dna.py | DNA.locate | 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 | 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] | [
"def",
"locate",
"(",
"self",
",",
"pattern",
")",
":",
"top_matches",
"=",
"self",
".",
"top",
".",
"locate",
"(",
"pattern",
")",
"bottom_matches",
"=",
"self",
".",
"bottom",
".",
"locate",
"(",
"pattern",
")",
"return",
"[",
"top_matches",
",",
"bottom_matches",
"]"
] | 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). | [
"Find",
"sequences",
"matching",
"a",
"pattern",
".",
"For",
"a",
"circular",
"sequence",
"the",
"search",
"extends",
"over",
"the",
"origin",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L297-L313 |
2,151 | klavinslab/coral | coral/sequence/_dna.py | DNA.reverse_complement | 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 | 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 | [
"def",
"reverse_complement",
"(",
"self",
")",
":",
"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"
] | Reverse complement the DNA.
:returns: A reverse-complemented instance of the current sequence.
:rtype: coral.DNA | [
"Reverse",
"complement",
"the",
"DNA",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L379-L395 |
2,152 | klavinslab/coral | coral/sequence/_dna.py | DNA.to_feature | 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 | 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) | [
"def",
"to_feature",
"(",
"self",
",",
"name",
"=",
"None",
",",
"feature_type",
"=",
"'misc_feature'",
")",
":",
"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",
")"
] | 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 | [
"Create",
"a",
"feature",
"from",
"the",
"current",
"object",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L436-L452 |
2,153 | klavinslab/coral | coral/sequence/_dna.py | RestrictionSite.cuts_outside | 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 | 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 | [
"def",
"cuts_outside",
"(",
"self",
")",
":",
"for",
"index",
"in",
"self",
".",
"cut_site",
":",
"if",
"index",
"<",
"0",
"or",
"index",
">",
"len",
"(",
"self",
".",
"recognition_site",
")",
"+",
"1",
":",
"return",
"True",
"return",
"False"
] | 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 | [
"Report",
"whether",
"the",
"enzyme",
"cuts",
"outside",
"its",
"recognition",
"site",
".",
"Cutting",
"at",
"the",
"very",
"end",
"of",
"the",
"site",
"returns",
"True",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L787-L798 |
2,154 | klavinslab/coral | coral/sequence/_dna.py | Primer.copy | 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 | 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) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"type",
"(",
"self",
")",
"(",
"self",
".",
"anneal",
",",
"self",
".",
"tm",
",",
"overhang",
"=",
"self",
".",
"overhang",
",",
"name",
"=",
"self",
".",
"name",
",",
"note",
"=",
"self",
".",
"note",
")"
] | Generate a Primer copy.
:returns: A safely-editable copy of the current primer.
:rtype: coral.DNA | [
"Generate",
"a",
"Primer",
"copy",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_dna.py#L886-L894 |
2,155 | klavinslab/coral | coral/analysis/_sequence/melting_temp.py | _pair_deltas | 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 | 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 | [
"def",
"_pair_deltas",
"(",
"seq",
",",
"pars",
")",
":",
"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"
] | 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 | [
"Add",
"up",
"nearest",
"-",
"neighbor",
"parameters",
"for",
"a",
"given",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L147-L164 |
2,156 | klavinslab/coral | coral/analysis/_sequence/melting_temp.py | breslauer_corrections | 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 | 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 | [
"def",
"breslauer_corrections",
"(",
"seq",
",",
"pars_error",
")",
":",
"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"
] | 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 | [
"Sum",
"corrections",
"for",
"Breslauer",
"84",
"method",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/melting_temp.py#L167-L193 |
2,157 | klavinslab/coral | coral/analysis/_sequencing/mafft.py | MAFFT | 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 | 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 | [
"def",
"MAFFT",
"(",
"sequences",
",",
"gap_open",
"=",
"1.53",
",",
"gap_extension",
"=",
"0.0",
",",
"retree",
"=",
"2",
")",
":",
"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"
] | 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 | [
"A",
"Coral",
"wrapper",
"for",
"the",
"MAFFT",
"command",
"line",
"multiple",
"sequence",
"aligner",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/mafft.py#L9-L55 |
2,158 | klavinslab/coral | coral/analysis/_sequence/repeats.py | repeats | 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 | 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 | [
"def",
"repeats",
"(",
"seq",
",",
"size",
")",
":",
"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"
] | 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 | [
"Count",
"times",
"that",
"a",
"sequence",
"of",
"a",
"certain",
"size",
"is",
"repeated",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequence/repeats.py#L5-L22 |
2,159 | klavinslab/coral | coral/reaction/_gibson.py | gibson | 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 | 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) | [
"def",
"gibson",
"(",
"seq_list",
",",
"linear",
"=",
"False",
",",
"homology",
"=",
"10",
",",
"tm",
"=",
"63.0",
")",
":",
"# 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",
")"
] | 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. | [
"Simulate",
"a",
"Gibson",
"reaction",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L21-L60 |
2,160 | klavinslab/coral | coral/reaction/_gibson.py | _fuse_last | 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 | 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 | [
"def",
"_fuse_last",
"(",
"working_list",
",",
"homology",
",",
"tm",
")",
":",
"# 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"
] | 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. | [
"With",
"one",
"sequence",
"left",
"attempt",
"to",
"fuse",
"it",
"to",
"itself",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_gibson.py#L153-L191 |
2,161 | klavinslab/coral | coral/database/_yeast.py | get_gene_id | 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 | 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 | [
"def",
"get_gene_id",
"(",
"gene_name",
")",
":",
"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"
] | 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 | [
"Retrieve",
"systematic",
"yeast",
"gene",
"name",
"from",
"the",
"common",
"name",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_yeast.py#L185-L219 |
2,162 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | _grow_overlaps | 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 | 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 | [
"def",
"_grow_overlaps",
"(",
"dna",
",",
"melting_temp",
",",
"require_even",
",",
"length_max",
",",
"overlap_min",
",",
"min_exception",
")",
":",
"# 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"
] | 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 | [
"Grows",
"equidistant",
"overlaps",
"until",
"they",
"meet",
"specified",
"constraints",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L215-L347 |
2,163 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | _recalculate_overlaps | 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 | 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 | [
"def",
"_recalculate_overlaps",
"(",
"dna",
",",
"overlaps",
",",
"oligo_indices",
")",
":",
"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"
] | 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 | [
"Recalculate",
"overlap",
"sequences",
"based",
"on",
"the",
"current",
"overlap",
"indices",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L350-L369 |
2,164 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | _expand_overlap | 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 | 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 | [
"def",
"_expand_overlap",
"(",
"dna",
",",
"oligo_indices",
",",
"index",
",",
"oligos",
",",
"length_max",
")",
":",
"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"
] | 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 | [
"Given",
"an",
"overlap",
"to",
"increase",
"increases",
"smaller",
"oligo",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L372-L409 |
2,165 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | _adjust_overlap | 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 | 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 | [
"def",
"_adjust_overlap",
"(",
"positions_list",
",",
"index",
",",
"direction",
")",
":",
"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"
] | 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\'. | [
"Increase",
"overlap",
"to",
"the",
"right",
"or",
"left",
"of",
"an",
"index",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L412-L432 |
2,166 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | OligoAssembly.design_assembly | 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 | 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 | [
"def",
"design_assembly",
"(",
"self",
")",
":",
"# 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"
] | Design the overlapping oligos.
:returns: Assembly oligos, and the sequences, Tms, and indices of their
overlapping regions.
:rtype: dict | [
"Design",
"the",
"overlapping",
"oligos",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L57-L145 |
2,167 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | OligoAssembly.primers | 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 | 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 | [
"def",
"primers",
"(",
"self",
",",
"tm",
"=",
"60",
")",
":",
"self",
".",
"primers",
"=",
"coral",
".",
"design",
".",
"primers",
"(",
"self",
".",
"template",
",",
"tm",
"=",
"tm",
")",
"return",
"self",
".",
"primers"
] | 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 | [
"Design",
"primers",
"for",
"amplifying",
"the",
"assembled",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L147-L157 |
2,168 | klavinslab/coral | coral/design/_oligo_synthesis/oligo_assembly.py | OligoAssembly.write_map | 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 | 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) | [
"def",
"write_map",
"(",
"self",
",",
"path",
")",
":",
"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",
")"
] | Write genbank map that highlights overlaps.
:param path: full path to .gb file to write.
:type path: str | [
"Write",
"genbank",
"map",
"that",
"highlights",
"overlaps",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/design/_oligo_synthesis/oligo_assembly.py#L186-L203 |
2,169 | klavinslab/coral | coral/reaction/_central_dogma.py | coding_sequence | 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 | 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 | [
"def",
"coding_sequence",
"(",
"rna",
")",
":",
"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"
] | 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. | [
"Extract",
"coding",
"sequence",
"from",
"an",
"RNA",
"template",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_central_dogma.py#L42-L86 |
2,170 | klavinslab/coral | coral/database/_rebase.py | Rebase.update | 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 | 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 | [
"def",
"update",
"(",
"self",
")",
":",
"# 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"
] | Update definitions. | [
"Update",
"definitions",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_rebase.py#L15-L51 |
2,171 | klavinslab/coral | coral/database/_rebase.py | Rebase._process_file | 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 | 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) | [
"def",
"_process_file",
"(",
"self",
")",
":",
"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",
")"
] | Process rebase file into dict with name and cut site information. | [
"Process",
"rebase",
"file",
"into",
"dict",
"with",
"name",
"and",
"cut",
"site",
"information",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/database/_rebase.py#L69-L102 |
2,172 | klavinslab/coral | coral/utils/tempdirs.py | tempdir | 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 | 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 | [
"def",
"tempdir",
"(",
"fun",
")",
":",
"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"
] | 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 | [
"For",
"use",
"as",
"a",
"decorator",
"of",
"instance",
"methods",
"-",
"creates",
"a",
"temporary",
"dir",
"named",
"self",
".",
"_tempdir",
"and",
"then",
"deletes",
"it",
"after",
"the",
"method",
"runs",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/utils/tempdirs.py#L9-L30 |
2,173 | klavinslab/coral | coral/reaction/utils.py | convert_sequence | 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 | 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 | [
"def",
"convert_sequence",
"(",
"seq",
",",
"to_material",
")",
":",
"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"
] | 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] | [
"Translate",
"a",
"DNA",
"sequence",
"into",
"peptide",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/utils.py#L6-L70 |
2,174 | klavinslab/coral | coral/sequence/_nucleicacid.py | NucleicAcid.gc | 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 | 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) | [
"def",
"gc",
"(",
"self",
")",
":",
"gc",
"=",
"len",
"(",
"[",
"base",
"for",
"base",
"in",
"self",
".",
"seq",
"if",
"base",
"==",
"'C'",
"or",
"base",
"==",
"'G'",
"]",
")",
"return",
"float",
"(",
"gc",
")",
"/",
"len",
"(",
"self",
")"
] | Find the frequency of G and C in the current sequence. | [
"Find",
"the",
"frequency",
"of",
"G",
"and",
"C",
"in",
"the",
"current",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L58-L61 |
2,175 | klavinslab/coral | coral/sequence/_nucleicacid.py | NucleicAcid.is_rotation | 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 | 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 | [
"def",
"is_rotation",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
")",
"!=",
"len",
"(",
"other",
")",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"if",
"self",
".",
"rotate",
"(",
"i",
")",
"==",
"other",
":",
"return",
"True",
"return",
"False"
] | 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 | [
"Determine",
"whether",
"two",
"sequences",
"are",
"the",
"same",
"just",
"at",
"different",
"rotations",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L78-L93 |
2,176 | klavinslab/coral | coral/sequence/_nucleicacid.py | NucleicAcid.linearize | 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 | 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 | [
"def",
"linearize",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"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"
] | 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. | [
"Linearize",
"the",
"Sequence",
"at",
"an",
"index",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L95-L113 |
2,177 | klavinslab/coral | coral/sequence/_nucleicacid.py | NucleicAcid.mw | 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 | 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 | [
"def",
"mw",
"(",
"self",
")",
":",
"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"
] | Calculate the molecular weight.
:returns: The molecular weight of the current sequence in amu.
:rtype: float | [
"Calculate",
"the",
"molecular",
"weight",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/sequence/_nucleicacid.py#L133-L150 |
2,178 | klavinslab/coral | coral/reaction/_resect.py | five_resect | 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 | 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 | [
"def",
"five_resect",
"(",
"dna",
",",
"n_bases",
")",
":",
"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"
] | 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 | [
"Remove",
"bases",
"from",
"5",
"end",
"of",
"top",
"strand",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_resect.py#L5-L24 |
2,179 | klavinslab/coral | coral/reaction/_resect.py | _remove_end_gaps | 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 | 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] | [
"def",
"_remove_end_gaps",
"(",
"sequence",
")",
":",
"# 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",
"]"
] | Removes double-stranded gaps from ends of the sequence.
:returns: The current sequence with terminal double-strand gaps ('-')
removed.
:rtype: coral.DNA | [
"Removes",
"double",
"-",
"stranded",
"gaps",
"from",
"ends",
"of",
"the",
"sequence",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_resect.py#L49-L78 |
2,180 | klavinslab/coral | coral/analysis/_sequencing/needle.py | needle | 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 | 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 | [
"def",
"needle",
"(",
"reference",
",",
"query",
",",
"gap_open",
"=",
"-",
"15",
",",
"gap_extend",
"=",
"0",
",",
"matrix",
"=",
"submat",
".",
"DNA_SIMPLE",
")",
":",
"# 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"
] | 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 | [
"Do",
"a",
"Needleman",
"-",
"Wunsch",
"alignment",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L16-L48 |
2,181 | klavinslab/coral | coral/analysis/_sequencing/needle.py | needle_msa | 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 | 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 | [
"def",
"needle_msa",
"(",
"reference",
",",
"results",
",",
"gap_open",
"=",
"-",
"15",
",",
"gap_extend",
"=",
"0",
",",
"matrix",
"=",
"submat",
".",
"DNA_SIMPLE",
")",
":",
"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"
] | Create a multiple sequence alignment based on aligning every result
sequence against the reference, then inserting gaps until every aligned
reference is identical | [
"Create",
"a",
"multiple",
"sequence",
"alignment",
"based",
"on",
"aligning",
"every",
"result",
"sequence",
"against",
"the",
"reference",
"then",
"inserting",
"gaps",
"until",
"every",
"aligned",
"reference",
"is",
"identical"
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L58-L113 |
2,182 | klavinslab/coral | coral/analysis/_sequencing/needle.py | needle_multi | 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 | 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 | [
"def",
"needle_multi",
"(",
"references",
",",
"queries",
",",
"gap_open",
"=",
"-",
"15",
",",
"gap_extend",
"=",
"0",
",",
"matrix",
"=",
"submat",
".",
"DNA_SIMPLE",
")",
":",
"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"
] | 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 | [
"Batch",
"process",
"of",
"sequencing",
"split",
"over",
"several",
"cores",
".",
"Acts",
"just",
"like",
"needle",
"but",
"sequence",
"inputs",
"are",
"lists",
"."
] | 17f59591211562a59a051f474cd6cecba4829df9 | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_sequencing/needle.py#L116-L147 |
2,183 | WoLpH/python-utils | python_utils/import_.py | import_global | 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 | 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 | [
"def",
"import_global",
"(",
"name",
",",
"modules",
"=",
"None",
",",
"exceptions",
"=",
"DummyException",
",",
"locals_",
"=",
"None",
",",
"globals_",
"=",
"None",
",",
"level",
"=",
"-",
"1",
")",
":",
"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"
] | 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 | [
"Import",
"the",
"requested",
"items",
"into",
"the",
"global",
"scope"
] | 6bbe13bab33bd9965b0edd379f26261b31a3e427 | https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/import_.py#L6-L78 |
2,184 | WoLpH/python-utils | python_utils/formatters.py | camel_to_underscore | 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 | 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) | [
"def",
"camel_to_underscore",
"(",
"name",
")",
":",
"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",
")"
] | 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__' | [
"Convert",
"camel",
"case",
"style",
"naming",
"to",
"underscore",
"style",
"naming"
] | 6bbe13bab33bd9965b0edd379f26261b31a3e427 | https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/formatters.py#L4-L39 |
2,185 | WoLpH/python-utils | python_utils/time.py | timedelta_to_seconds | 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 | 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 | [
"def",
"timedelta_to_seconds",
"(",
"delta",
")",
":",
"# 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"
] | 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' | [
"Convert",
"a",
"timedelta",
"to",
"seconds",
"with",
"the",
"microseconds",
"as",
"fraction"
] | 6bbe13bab33bd9965b0edd379f26261b31a3e427 | https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/time.py#L10-L33 |
2,186 | WoLpH/python-utils | python_utils/terminal.py | get_terminal_size | 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 | 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 | [
"def",
"get_terminal_size",
"(",
")",
":",
"# pragma: no cover",
"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"
] | 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 | [
"Get",
"the",
"current",
"size",
"of",
"your",
"terminal"
] | 6bbe13bab33bd9965b0edd379f26261b31a3e427 | https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/terminal.py#L4-L78 |
2,187 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.AsyncSearchUsers | 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 | def AsyncSearchUsers(self, Target):
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 | [
"def",
"AsyncSearchUsers",
"(",
"self",
",",
"Target",
")",
":",
"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"
] | 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 | [
"Asynchronously",
"searches",
"for",
"Skype",
"users",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L376-L394 |
2,188 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Attach | 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 | def Attach(self, Protocol=5, Wait=True):
try:
self._Api.protocol = Protocol
self._Api.attach(self.Timeout, Wait)
except SkypeAPIError:
self.ResetCache()
raise | [
"def",
"Attach",
"(",
"self",
",",
"Protocol",
"=",
"5",
",",
"Wait",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"_Api",
".",
"protocol",
"=",
"Protocol",
"self",
".",
"_Api",
".",
"attach",
"(",
"self",
".",
"Timeout",
",",
"Wait",
")",
"except",
"SkypeAPIError",
":",
"self",
".",
"ResetCache",
"(",
")",
"raise"
] | 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`. | [
"Establishes",
"a",
"connection",
"to",
"Skype",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L396-L411 |
2,189 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Call | 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 | def Call(self, Id=0):
o = Call(self, Id)
o.Status # Test if such a call exists.
return o | [
"def",
"Call",
"(",
"self",
",",
"Id",
"=",
"0",
")",
":",
"o",
"=",
"Call",
"(",
"self",
",",
"Id",
")",
"o",
".",
"Status",
"# Test if such a call exists.",
"return",
"o"
] | Queries a call object.
:Parameters:
Id : int
Call identifier.
:return: Call object.
:rtype: `call.Call` | [
"Queries",
"a",
"call",
"object",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L413-L425 |
2,190 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.ChangeUserStatus | 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 | def ChangeUserStatus(self, 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 | [
"def",
"ChangeUserStatus",
"(",
"self",
",",
"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"
] | 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. | [
"Changes",
"the",
"online",
"status",
"for",
"the",
"current",
"user",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L443-L461 |
2,191 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Chat | 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 | def Chat(self, Name=''):
o = Chat(self, Name)
o.Status # Tests if such a chat really exists.
return o | [
"def",
"Chat",
"(",
"self",
",",
"Name",
"=",
"''",
")",
":",
"o",
"=",
"Chat",
"(",
"self",
",",
"Name",
")",
"o",
".",
"Status",
"# Tests if such a chat really exists.",
"return",
"o"
] | Queries a chat object.
:Parameters:
Name : str
Chat name.
:return: A chat object.
:rtype: `chat.Chat` | [
"Queries",
"a",
"chat",
"object",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L463-L475 |
2,192 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.ClearCallHistory | 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 | def ClearCallHistory(self, Username='ALL', Type=chsAllCalls):
cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username)
self._DoCommand(cmd, cmd) | [
"def",
"ClearCallHistory",
"(",
"self",
",",
"Username",
"=",
"'ALL'",
",",
"Type",
"=",
"chsAllCalls",
")",
":",
"cmd",
"=",
"'CLEAR CALLHISTORY %s %s'",
"%",
"(",
"str",
"(",
"Type",
")",
",",
"Username",
")",
"self",
".",
"_DoCommand",
"(",
"cmd",
",",
"cmd",
")"
] | 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. | [
"Clears",
"the",
"call",
"history",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L477-L488 |
2,193 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Command | 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 | def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1):
from api import Command as CommandClass
return CommandClass(Command, Reply, Block, Timeout, Id) | [
"def",
"Command",
"(",
"self",
",",
"Command",
",",
"Reply",
"=",
"u''",
",",
"Block",
"=",
"False",
",",
"Timeout",
"=",
"30000",
",",
"Id",
"=",
"-",
"1",
")",
":",
"from",
"api",
"import",
"Command",
"as",
"CommandClass",
"return",
"CommandClass",
"(",
"Command",
",",
"Reply",
",",
"Block",
",",
"Timeout",
",",
"Id",
")"
] | 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` | [
"Creates",
"an",
"API",
"command",
"object",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L501-L526 |
2,194 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Conference | 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 | def Conference(self, Id=0):
o = Conference(self, Id)
if Id <= 0 or not o.Calls:
raise SkypeError(0, 'Unknown conference')
return o | [
"def",
"Conference",
"(",
"self",
",",
"Id",
"=",
"0",
")",
":",
"o",
"=",
"Conference",
"(",
"self",
",",
"Id",
")",
"if",
"Id",
"<=",
"0",
"or",
"not",
"o",
".",
"Calls",
":",
"raise",
"SkypeError",
"(",
"0",
",",
"'Unknown conference'",
")",
"return",
"o"
] | Queries a call conference object.
:Parameters:
Id : int
Conference Id.
:return: A conference object.
:rtype: `Conference` | [
"Queries",
"a",
"call",
"conference",
"object",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L528-L541 |
2,195 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.CreateChatWith | 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 | def CreateChatWith(self, *Usernames):
return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1]) | [
"def",
"CreateChatWith",
"(",
"self",
",",
"*",
"Usernames",
")",
":",
"return",
"Chat",
"(",
"self",
",",
"chop",
"(",
"self",
".",
"_DoCommand",
"(",
"'CHAT CREATE %s'",
"%",
"', '",
".",
"join",
"(",
"Usernames",
")",
")",
",",
"2",
")",
"[",
"1",
"]",
")"
] | 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` | [
"Creates",
"a",
"chat",
"with",
"one",
"or",
"more",
"users",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L555-L567 |
2,196 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.CreateGroup | 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 | def CreateGroup(self, GroupName):
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') | [
"def",
"CreateGroup",
"(",
"self",
",",
"GroupName",
")",
":",
"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'",
")"
] | Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup` | [
"Creates",
"a",
"custom",
"contact",
"group",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L569-L586 |
2,197 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.CreateSms | 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 | def CreateSms(self, MessageType, *TargetNumbers):
return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1]) | [
"def",
"CreateSms",
"(",
"self",
",",
"MessageType",
",",
"*",
"TargetNumbers",
")",
":",
"return",
"SmsMessage",
"(",
"self",
",",
"chop",
"(",
"self",
".",
"_DoCommand",
"(",
"'CREATE SMS %s %s'",
"%",
"(",
"MessageType",
",",
"', '",
".",
"join",
"(",
"TargetNumbers",
")",
")",
")",
",",
"2",
")",
"[",
"1",
"]",
")"
] | 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` | [
"Creates",
"an",
"SMS",
"message",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L588-L600 |
2,198 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Greeting | 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 | def Greeting(self, Username=''):
for v in self.Voicemails:
if Username and v.PartnerHandle != Username:
continue
if v.Type in (vmtDefaultGreeting, vmtCustomGreeting):
return v | [
"def",
"Greeting",
"(",
"self",
",",
"Username",
"=",
"''",
")",
":",
"for",
"v",
"in",
"self",
".",
"Voicemails",
":",
"if",
"Username",
"and",
"v",
".",
"PartnerHandle",
"!=",
"Username",
":",
"continue",
"if",
"v",
".",
"Type",
"in",
"(",
"vmtDefaultGreeting",
",",
"vmtCustomGreeting",
")",
":",
"return",
"v"
] | Queries the greeting used as voicemail.
:Parameters:
Username : str
Skypename of the user.
:return: A voicemail object.
:rtype: `Voicemail` | [
"Queries",
"the",
"greeting",
"used",
"as",
"voicemail",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L638-L652 |
2,199 | Skype4Py/Skype4Py | Skype4Py/skype.py | Skype.Message | 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 | def Message(self, Id=0):
o = ChatMessage(self, Id)
o.Status # Test if such an id is known.
return o | [
"def",
"Message",
"(",
"self",
",",
"Id",
"=",
"0",
")",
":",
"o",
"=",
"ChatMessage",
"(",
"self",
",",
"Id",
")",
"o",
".",
"Status",
"# Test if such an id is known.",
"return",
"o"
] | Queries a chat message object.
:Parameters:
Id : int
Message Id.
:return: A chat message object.
:rtype: `ChatMessage` | [
"Queries",
"a",
"chat",
"message",
"object",
"."
] | c48d83f7034109fe46315d45a066126002c6e0d4 | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L654-L666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.