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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
alvinwan/TexSoup | examples/resolve_imports.py | resolve | def resolve(tex):
"""Resolve all imports and update the parse tree.
Reads from a tex file and once finished, writes to a tex file.
"""
# soupify
soup = TexSoup(tex)
# resolve subimports
for subimport in soup.find_all('subimport'):
path = subimport.args[0] + subimport.args[1]
subimport.replace_with(*resolve(open(path)).contents)
# resolve imports
for _import in soup.find_all('import'):
_import.replace_with(*resolve(open(_import.args[0])).contents)
# resolve includes
for include in soup.find_all('include'):
include.replace_with(*resolve(open(include.args[0])).contents)
return soup | python | def resolve(tex):
"""Resolve all imports and update the parse tree.
Reads from a tex file and once finished, writes to a tex file.
"""
# soupify
soup = TexSoup(tex)
# resolve subimports
for subimport in soup.find_all('subimport'):
path = subimport.args[0] + subimport.args[1]
subimport.replace_with(*resolve(open(path)).contents)
# resolve imports
for _import in soup.find_all('import'):
_import.replace_with(*resolve(open(_import.args[0])).contents)
# resolve includes
for include in soup.find_all('include'):
include.replace_with(*resolve(open(include.args[0])).contents)
return soup | [
"def",
"resolve",
"(",
"tex",
")",
":",
"# soupify",
"soup",
"=",
"TexSoup",
"(",
"tex",
")",
"# resolve subimports",
"for",
"subimport",
"in",
"soup",
".",
"find_all",
"(",
"'subimport'",
")",
":",
"path",
"=",
"subimport",
".",
"args",
"[",
"0",
"]",
... | Resolve all imports and update the parse tree.
Reads from a tex file and once finished, writes to a tex file. | [
"Resolve",
"all",
"imports",
"and",
"update",
"the",
"parse",
"tree",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/examples/resolve_imports.py#L19-L41 | train | 212,700 |
alvinwan/TexSoup | examples/solution_length.py | sollen | def sollen(tex, command):
r"""Measure solution length
:param Union[str,buffer] tex: the LaTeX source as a string or file buffer
:param str command: the command denoting a solution i.e., if the tex file
uses '\answer{<answer here>}', then the command is 'answer'.
:return int: the solution length
"""
return sum(len(a.string) for a in TexSoup(tex).find_all(command)) | python | def sollen(tex, command):
r"""Measure solution length
:param Union[str,buffer] tex: the LaTeX source as a string or file buffer
:param str command: the command denoting a solution i.e., if the tex file
uses '\answer{<answer here>}', then the command is 'answer'.
:return int: the solution length
"""
return sum(len(a.string) for a in TexSoup(tex).find_all(command)) | [
"def",
"sollen",
"(",
"tex",
",",
"command",
")",
":",
"return",
"sum",
"(",
"len",
"(",
"a",
".",
"string",
")",
"for",
"a",
"in",
"TexSoup",
"(",
"tex",
")",
".",
"find_all",
"(",
"command",
")",
")"
] | r"""Measure solution length
:param Union[str,buffer] tex: the LaTeX source as a string or file buffer
:param str command: the command denoting a solution i.e., if the tex file
uses '\answer{<answer here>}', then the command is 'answer'.
:return int: the solution length | [
"r",
"Measure",
"solution",
"length"
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/examples/solution_length.py#L19-L27 | train | 212,701 |
alvinwan/TexSoup | examples/count_references.py | count | def count(tex):
"""Extract all labels, then count the number of times each is referenced in
the provided file. Does not follow \includes.
"""
# soupify
soup = TexSoup(tex)
# extract all unique labels
labels = set(label.string for label in soup.find_all('label'))
# create dictionary mapping label to number of references
return dict((label, soup.find_all('\ref{%s}' % label)) for label in labels) | python | def count(tex):
"""Extract all labels, then count the number of times each is referenced in
the provided file. Does not follow \includes.
"""
# soupify
soup = TexSoup(tex)
# extract all unique labels
labels = set(label.string for label in soup.find_all('label'))
# create dictionary mapping label to number of references
return dict((label, soup.find_all('\ref{%s}' % label)) for label in labels) | [
"def",
"count",
"(",
"tex",
")",
":",
"# soupify",
"soup",
"=",
"TexSoup",
"(",
"tex",
")",
"# extract all unique labels",
"labels",
"=",
"set",
"(",
"label",
".",
"string",
"for",
"label",
"in",
"soup",
".",
"find_all",
"(",
"'label'",
")",
")",
"# crea... | Extract all labels, then count the number of times each is referenced in
the provided file. Does not follow \includes. | [
"Extract",
"all",
"labels",
"then",
"count",
"the",
"number",
"of",
"times",
"each",
"is",
"referenced",
"in",
"the",
"provided",
"file",
".",
"Does",
"not",
"follow",
"\\",
"includes",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/examples/count_references.py#L19-L31 | train | 212,702 |
alvinwan/TexSoup | TexSoup/reader.py | next_token | def next_token(text):
r"""Returns the next possible token, advancing the iterator to the next
position to start processing from.
:param Union[str,iterator,Buffer] text: LaTeX to process
:return str: the token
>>> b = Buffer(r'\textbf{Do play\textit{nice}.} $$\min_w \|w\|_2^2$$')
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
\textbf { Do play \textit
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
{ nice } .
>>> print(next_token(b))
}
>>> print(next_token(Buffer('.}')))
.
>>> next_token(b)
' '
>>> next_token(b)
'$$'
>>> b2 = Buffer(r'\gamma = \beta')
>>> print(next_token(b2), next_token(b2), next_token(b2))
\gamma = \beta
"""
while text.hasNext():
for name, f in tokenizers:
current_token = f(text)
if current_token is not None:
return current_token | python | def next_token(text):
r"""Returns the next possible token, advancing the iterator to the next
position to start processing from.
:param Union[str,iterator,Buffer] text: LaTeX to process
:return str: the token
>>> b = Buffer(r'\textbf{Do play\textit{nice}.} $$\min_w \|w\|_2^2$$')
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
\textbf { Do play \textit
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
{ nice } .
>>> print(next_token(b))
}
>>> print(next_token(Buffer('.}')))
.
>>> next_token(b)
' '
>>> next_token(b)
'$$'
>>> b2 = Buffer(r'\gamma = \beta')
>>> print(next_token(b2), next_token(b2), next_token(b2))
\gamma = \beta
"""
while text.hasNext():
for name, f in tokenizers:
current_token = f(text)
if current_token is not None:
return current_token | [
"def",
"next_token",
"(",
"text",
")",
":",
"while",
"text",
".",
"hasNext",
"(",
")",
":",
"for",
"name",
",",
"f",
"in",
"tokenizers",
":",
"current_token",
"=",
"f",
"(",
"text",
")",
"if",
"current_token",
"is",
"not",
"None",
":",
"return",
"cur... | r"""Returns the next possible token, advancing the iterator to the next
position to start processing from.
:param Union[str,iterator,Buffer] text: LaTeX to process
:return str: the token
>>> b = Buffer(r'\textbf{Do play\textit{nice}.} $$\min_w \|w\|_2^2$$')
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
\textbf { Do play \textit
>>> print(next_token(b), next_token(b), next_token(b), next_token(b))
{ nice } .
>>> print(next_token(b))
}
>>> print(next_token(Buffer('.}')))
.
>>> next_token(b)
' '
>>> next_token(b)
'$$'
>>> b2 = Buffer(r'\gamma = \beta')
>>> print(next_token(b2), next_token(b2), next_token(b2))
\gamma = \beta | [
"r",
"Returns",
"the",
"next",
"possible",
"token",
"advancing",
"the",
"iterator",
"to",
"the",
"next",
"position",
"to",
"start",
"processing",
"from",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L40-L68 | train | 212,703 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize | def tokenize(text):
r"""Generator for LaTeX tokens on text, ignoring comments.
:param Union[str,iterator,Buffer] text: LaTeX to process
>>> print(*tokenize(r'\textbf{Do play \textit{nice}.}'))
\textbf { Do play \textit { nice } . }
>>> print(*tokenize(r'\begin{tabular} 0 & 1 \\ 2 & 0 \end{tabular}'))
\begin { tabular } 0 & 1 \\ 2 & 0 \end { tabular }
"""
current_token = next_token(text)
while current_token is not None:
yield current_token
current_token = next_token(text) | python | def tokenize(text):
r"""Generator for LaTeX tokens on text, ignoring comments.
:param Union[str,iterator,Buffer] text: LaTeX to process
>>> print(*tokenize(r'\textbf{Do play \textit{nice}.}'))
\textbf { Do play \textit { nice } . }
>>> print(*tokenize(r'\begin{tabular} 0 & 1 \\ 2 & 0 \end{tabular}'))
\begin { tabular } 0 & 1 \\ 2 & 0 \end { tabular }
"""
current_token = next_token(text)
while current_token is not None:
yield current_token
current_token = next_token(text) | [
"def",
"tokenize",
"(",
"text",
")",
":",
"current_token",
"=",
"next_token",
"(",
"text",
")",
"while",
"current_token",
"is",
"not",
"None",
":",
"yield",
"current_token",
"current_token",
"=",
"next_token",
"(",
"text",
")"
] | r"""Generator for LaTeX tokens on text, ignoring comments.
:param Union[str,iterator,Buffer] text: LaTeX to process
>>> print(*tokenize(r'\textbf{Do play \textit{nice}.}'))
\textbf { Do play \textit { nice } . }
>>> print(*tokenize(r'\begin{tabular} 0 & 1 \\ 2 & 0 \end{tabular}'))
\begin { tabular } 0 & 1 \\ 2 & 0 \end { tabular } | [
"r",
"Generator",
"for",
"LaTeX",
"tokens",
"on",
"text",
"ignoring",
"comments",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L72-L85 | train | 212,704 |
alvinwan/TexSoup | TexSoup/reader.py | token | def token(name):
"""Marker for a token
:param str name: Name of tokenizer
"""
def wrap(f):
tokenizers.append((name, f))
return f
return wrap | python | def token(name):
"""Marker for a token
:param str name: Name of tokenizer
"""
def wrap(f):
tokenizers.append((name, f))
return f
return wrap | [
"def",
"token",
"(",
"name",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"tokenizers",
".",
"append",
"(",
"(",
"name",
",",
"f",
")",
")",
"return",
"f",
"return",
"wrap"
] | Marker for a token
:param str name: Name of tokenizer | [
"Marker",
"for",
"a",
"token"
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L95-L105 | train | 212,705 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize_punctuation_command | def tokenize_punctuation_command(text):
"""Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position
"""
if text.peek() == '\\':
for point in PUNCTUATION_COMMANDS:
if text.peek((1, len(point) + 1)) == point:
return text.forward(len(point) + 1) | python | def tokenize_punctuation_command(text):
"""Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position
"""
if text.peek() == '\\':
for point in PUNCTUATION_COMMANDS:
if text.peek((1, len(point) + 1)) == point:
return text.forward(len(point) + 1) | [
"def",
"tokenize_punctuation_command",
"(",
"text",
")",
":",
"if",
"text",
".",
"peek",
"(",
")",
"==",
"'\\\\'",
":",
"for",
"point",
"in",
"PUNCTUATION_COMMANDS",
":",
"if",
"text",
".",
"peek",
"(",
"(",
"1",
",",
"len",
"(",
"point",
")",
"+",
"... | Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position | [
"Process",
"command",
"that",
"augments",
"or",
"modifies",
"punctuation",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L109-L120 | train | 212,706 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize_line_comment | def tokenize_line_comment(text):
r"""Process a line comment
:param Buffer text: iterator over line, with current position
>>> tokenize_line_comment(Buffer('hello %world'))
>>> tokenize_line_comment(Buffer('%hello world'))
'%hello world'
>>> tokenize_line_comment(Buffer('%hello\n world'))
'%hello'
"""
result = TokenWithPosition('', text.position)
if text.peek() == '%' and text.peek(-1) != '\\':
result += text.forward(1)
while text.peek() != '\n' and text.hasNext():
result += text.forward(1)
return result | python | def tokenize_line_comment(text):
r"""Process a line comment
:param Buffer text: iterator over line, with current position
>>> tokenize_line_comment(Buffer('hello %world'))
>>> tokenize_line_comment(Buffer('%hello world'))
'%hello world'
>>> tokenize_line_comment(Buffer('%hello\n world'))
'%hello'
"""
result = TokenWithPosition('', text.position)
if text.peek() == '%' and text.peek(-1) != '\\':
result += text.forward(1)
while text.peek() != '\n' and text.hasNext():
result += text.forward(1)
return result | [
"def",
"tokenize_line_comment",
"(",
"text",
")",
":",
"result",
"=",
"TokenWithPosition",
"(",
"''",
",",
"text",
".",
"position",
")",
"if",
"text",
".",
"peek",
"(",
")",
"==",
"'%'",
"and",
"text",
".",
"peek",
"(",
"-",
"1",
")",
"!=",
"'\\\\'",... | r"""Process a line comment
:param Buffer text: iterator over line, with current position
>>> tokenize_line_comment(Buffer('hello %world'))
>>> tokenize_line_comment(Buffer('%hello world'))
'%hello world'
>>> tokenize_line_comment(Buffer('%hello\n world'))
'%hello' | [
"r",
"Process",
"a",
"line",
"comment"
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L138-L154 | train | 212,707 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize_argument | def tokenize_argument(text):
"""Process both optional and required arguments.
:param Buffer text: iterator over line, with current position
"""
for delim in ARG_TOKENS:
if text.startswith(delim):
return text.forward(len(delim)) | python | def tokenize_argument(text):
"""Process both optional and required arguments.
:param Buffer text: iterator over line, with current position
"""
for delim in ARG_TOKENS:
if text.startswith(delim):
return text.forward(len(delim)) | [
"def",
"tokenize_argument",
"(",
"text",
")",
":",
"for",
"delim",
"in",
"ARG_TOKENS",
":",
"if",
"text",
".",
"startswith",
"(",
"delim",
")",
":",
"return",
"text",
".",
"forward",
"(",
"len",
"(",
"delim",
")",
")"
] | Process both optional and required arguments.
:param Buffer text: iterator over line, with current position | [
"Process",
"both",
"optional",
"and",
"required",
"arguments",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L158-L165 | train | 212,708 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize_math | def tokenize_math(text):
r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$'
"""
if text.startswith('$') and (
text.position == 0 or text.peek(-1) != '\\' or text.endswith(r'\\')):
starter = '$$' if text.startswith('$$') else '$'
return TokenWithPosition(text.forward(len(starter)), text.position) | python | def tokenize_math(text):
r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$'
"""
if text.startswith('$') and (
text.position == 0 or text.peek(-1) != '\\' or text.endswith(r'\\')):
starter = '$$' if text.startswith('$$') else '$'
return TokenWithPosition(text.forward(len(starter)), text.position) | [
"def",
"tokenize_math",
"(",
"text",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"'$'",
")",
"and",
"(",
"text",
".",
"position",
"==",
"0",
"or",
"text",
".",
"peek",
"(",
"-",
"1",
")",
"!=",
"'\\\\'",
"or",
"text",
".",
"endswith",
"(",
"r... | r"""Prevents math from being tokenized.
:param Buffer text: iterator over line, with current position
>>> b = Buffer(r'$\min_x$ \command')
>>> tokenize_math(b)
'$'
>>> b = Buffer(r'$$\min_x$$ \command')
>>> tokenize_math(b)
'$$' | [
"r",
"Prevents",
"math",
"from",
"being",
"tokenized",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L169-L184 | train | 212,709 |
alvinwan/TexSoup | TexSoup/reader.py | tokenize_string | def tokenize_string(text, delimiters=None):
r"""Process a string of text
:param Buffer text: iterator over line, with current position
:param Union[None,iterable,str] delimiters: defines the delimiters
>>> tokenize_string(Buffer('hello'))
'hello'
>>> b = Buffer(r'hello again\command')
>>> tokenize_string(b)
'hello again'
>>> print(b.peek())
\
>>> print(tokenize_string(Buffer(r'0 & 1 \\\command')))
0 & 1 \\
"""
if delimiters is None:
delimiters = ALL_TOKENS
result = TokenWithPosition('', text.position)
for c in text:
if c == '\\' and str(text.peek()) in delimiters and str(c + text.peek()) not in delimiters:
c += next(text)
elif str(c) in delimiters: # assumes all tokens are single characters
text.backward(1)
return result
result += c
if text.peek((0, 2)) == '\\\\':
result += text.forward(2)
if text.peek((0, 2)) == '\n\n':
result += text.forward(2)
return result
return result | python | def tokenize_string(text, delimiters=None):
r"""Process a string of text
:param Buffer text: iterator over line, with current position
:param Union[None,iterable,str] delimiters: defines the delimiters
>>> tokenize_string(Buffer('hello'))
'hello'
>>> b = Buffer(r'hello again\command')
>>> tokenize_string(b)
'hello again'
>>> print(b.peek())
\
>>> print(tokenize_string(Buffer(r'0 & 1 \\\command')))
0 & 1 \\
"""
if delimiters is None:
delimiters = ALL_TOKENS
result = TokenWithPosition('', text.position)
for c in text:
if c == '\\' and str(text.peek()) in delimiters and str(c + text.peek()) not in delimiters:
c += next(text)
elif str(c) in delimiters: # assumes all tokens are single characters
text.backward(1)
return result
result += c
if text.peek((0, 2)) == '\\\\':
result += text.forward(2)
if text.peek((0, 2)) == '\n\n':
result += text.forward(2)
return result
return result | [
"def",
"tokenize_string",
"(",
"text",
",",
"delimiters",
"=",
"None",
")",
":",
"if",
"delimiters",
"is",
"None",
":",
"delimiters",
"=",
"ALL_TOKENS",
"result",
"=",
"TokenWithPosition",
"(",
"''",
",",
"text",
".",
"position",
")",
"for",
"c",
"in",
"... | r"""Process a string of text
:param Buffer text: iterator over line, with current position
:param Union[None,iterable,str] delimiters: defines the delimiters
>>> tokenize_string(Buffer('hello'))
'hello'
>>> b = Buffer(r'hello again\command')
>>> tokenize_string(b)
'hello again'
>>> print(b.peek())
\
>>> print(tokenize_string(Buffer(r'0 & 1 \\\command')))
0 & 1 \\ | [
"r",
"Process",
"a",
"string",
"of",
"text"
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L188-L219 | train | 212,710 |
alvinwan/TexSoup | TexSoup/reader.py | read_tex | def read_tex(src):
r"""Read next expression from buffer
:param Buffer src: a buffer of tokens
"""
c = next(src)
if c.startswith('%'):
return c
elif c.startswith('$'):
name = '$$' if c.startswith('$$') else '$'
expr = TexEnv(name, [], nobegin=True)
return read_math_env(src, expr)
elif c.startswith('\[') or c.startswith("\("):
if c.startswith('\['):
name = 'displaymath'
begin = '\['
end = '\]'
else:
name = "math"
begin = "\("
end = "\)"
expr = TexEnv(name, [], nobegin=True, begin=begin, end=end)
return read_math_env(src, expr)
elif c.startswith('\\'):
command = TokenWithPosition(c[1:], src.position)
if command == 'item':
contents, arg = read_item(src)
mode, expr = 'command', TexCmd(command, contents, arg)
elif command == 'begin':
mode, expr, _ = 'begin', TexEnv(src.peek(1)), src.forward(3)
else:
mode, expr = 'command', TexCmd(command)
expr.args = read_args(src, expr.args)
if mode == 'begin':
read_env(src, expr)
return expr
if c in ARG_START_TOKENS:
return read_arg(src, c)
return c | python | def read_tex(src):
r"""Read next expression from buffer
:param Buffer src: a buffer of tokens
"""
c = next(src)
if c.startswith('%'):
return c
elif c.startswith('$'):
name = '$$' if c.startswith('$$') else '$'
expr = TexEnv(name, [], nobegin=True)
return read_math_env(src, expr)
elif c.startswith('\[') or c.startswith("\("):
if c.startswith('\['):
name = 'displaymath'
begin = '\['
end = '\]'
else:
name = "math"
begin = "\("
end = "\)"
expr = TexEnv(name, [], nobegin=True, begin=begin, end=end)
return read_math_env(src, expr)
elif c.startswith('\\'):
command = TokenWithPosition(c[1:], src.position)
if command == 'item':
contents, arg = read_item(src)
mode, expr = 'command', TexCmd(command, contents, arg)
elif command == 'begin':
mode, expr, _ = 'begin', TexEnv(src.peek(1)), src.forward(3)
else:
mode, expr = 'command', TexCmd(command)
expr.args = read_args(src, expr.args)
if mode == 'begin':
read_env(src, expr)
return expr
if c in ARG_START_TOKENS:
return read_arg(src, c)
return c | [
"def",
"read_tex",
"(",
"src",
")",
":",
"c",
"=",
"next",
"(",
"src",
")",
"if",
"c",
".",
"startswith",
"(",
"'%'",
")",
":",
"return",
"c",
"elif",
"c",
".",
"startswith",
"(",
"'$'",
")",
":",
"name",
"=",
"'$$'",
"if",
"c",
".",
"startswit... | r"""Read next expression from buffer
:param Buffer src: a buffer of tokens | [
"r",
"Read",
"next",
"expression",
"from",
"buffer"
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L227-L268 | train | 212,711 |
alvinwan/TexSoup | TexSoup/reader.py | read_item | def read_item(src):
r"""Read the item content.
There can be any number of whitespace characters between \item and the first
non-whitespace character. However, after that first non-whitespace
character, the item can only tolerate one successive line break at a time.
\item can also take an argument.
:param Buffer src: a buffer of tokens
:return: contents of the item and any item arguments
"""
def stringify(s):
return TokenWithPosition.join(s.split(' '), glue=' ')
def forward_until_new(s):
"""Catch the first non-whitespace character"""
t = TokenWithPosition('', s.peek().position)
while (s.hasNext() and
any([s.peek().startswith(substr) for substr in string.whitespace]) and
not t.strip(" ").endswith('\n')):
t += s.forward(1)
return t
# Item argument such as in description environment
arg = []
extra = []
if src.peek() in ARG_START_TOKENS:
c = next(src)
a = read_arg(src, c)
arg.append(a)
if not src.hasNext():
return extra, arg
last = stringify(forward_until_new(src))
extra.append(last.lstrip(" "))
while (src.hasNext() and not str(src).strip(" ").startswith('\n\n') and
not src.startswith('\item') and
not src.startswith('\end') and
not (isinstance(last, TokenWithPosition) and last.strip(" ").endswith('\n\n') and len(extra) > 1)):
last = read_tex(src)
extra.append(last)
return extra, arg | python | def read_item(src):
r"""Read the item content.
There can be any number of whitespace characters between \item and the first
non-whitespace character. However, after that first non-whitespace
character, the item can only tolerate one successive line break at a time.
\item can also take an argument.
:param Buffer src: a buffer of tokens
:return: contents of the item and any item arguments
"""
def stringify(s):
return TokenWithPosition.join(s.split(' '), glue=' ')
def forward_until_new(s):
"""Catch the first non-whitespace character"""
t = TokenWithPosition('', s.peek().position)
while (s.hasNext() and
any([s.peek().startswith(substr) for substr in string.whitespace]) and
not t.strip(" ").endswith('\n')):
t += s.forward(1)
return t
# Item argument such as in description environment
arg = []
extra = []
if src.peek() in ARG_START_TOKENS:
c = next(src)
a = read_arg(src, c)
arg.append(a)
if not src.hasNext():
return extra, arg
last = stringify(forward_until_new(src))
extra.append(last.lstrip(" "))
while (src.hasNext() and not str(src).strip(" ").startswith('\n\n') and
not src.startswith('\item') and
not src.startswith('\end') and
not (isinstance(last, TokenWithPosition) and last.strip(" ").endswith('\n\n') and len(extra) > 1)):
last = read_tex(src)
extra.append(last)
return extra, arg | [
"def",
"read_item",
"(",
"src",
")",
":",
"def",
"stringify",
"(",
"s",
")",
":",
"return",
"TokenWithPosition",
".",
"join",
"(",
"s",
".",
"split",
"(",
"' '",
")",
",",
"glue",
"=",
"' '",
")",
"def",
"forward_until_new",
"(",
"s",
")",
":",
"\"... | r"""Read the item content.
There can be any number of whitespace characters between \item and the first
non-whitespace character. However, after that first non-whitespace
character, the item can only tolerate one successive line break at a time.
\item can also take an argument.
:param Buffer src: a buffer of tokens
:return: contents of the item and any item arguments | [
"r",
"Read",
"the",
"item",
"content",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L271-L316 | train | 212,712 |
alvinwan/TexSoup | TexSoup/reader.py | read_args | def read_args(src, args=None):
r"""Read all arguments from buffer.
Advances buffer until end of last valid arguments. There can be any number
of whitespace characters between command and the first argument.
However, after that first argument, the command can only tolerate one
successive line break, before discontinuing the chain of arguments.
:param TexArgs args: existing arguments to extend
:return: parsed arguments
:rtype: TexArgs
"""
args = args or TexArgs()
# Unlimited whitespace before first argument
candidate_index = src.num_forward_until(lambda s: not s.isspace())
while src.peek().isspace():
args.append(read_tex(src))
# Restricted to only one line break after first argument
line_breaks = 0
while src.peek() in ARG_START_TOKENS or \
(src.peek().isspace() and line_breaks == 0):
space_index = src.num_forward_until(lambda s: not s.isspace())
if space_index > 0:
line_breaks += 1
if src.peek((0, space_index)).count("\n") <= 1 and src.peek(space_index) in ARG_START_TOKENS:
args.append(read_tex(src))
else:
line_breaks = 0
tex_text = read_tex(src)
args.append(tex_text)
if not args:
src.backward(candidate_index)
return args | python | def read_args(src, args=None):
r"""Read all arguments from buffer.
Advances buffer until end of last valid arguments. There can be any number
of whitespace characters between command and the first argument.
However, after that first argument, the command can only tolerate one
successive line break, before discontinuing the chain of arguments.
:param TexArgs args: existing arguments to extend
:return: parsed arguments
:rtype: TexArgs
"""
args = args or TexArgs()
# Unlimited whitespace before first argument
candidate_index = src.num_forward_until(lambda s: not s.isspace())
while src.peek().isspace():
args.append(read_tex(src))
# Restricted to only one line break after first argument
line_breaks = 0
while src.peek() in ARG_START_TOKENS or \
(src.peek().isspace() and line_breaks == 0):
space_index = src.num_forward_until(lambda s: not s.isspace())
if space_index > 0:
line_breaks += 1
if src.peek((0, space_index)).count("\n") <= 1 and src.peek(space_index) in ARG_START_TOKENS:
args.append(read_tex(src))
else:
line_breaks = 0
tex_text = read_tex(src)
args.append(tex_text)
if not args:
src.backward(candidate_index)
return args | [
"def",
"read_args",
"(",
"src",
",",
"args",
"=",
"None",
")",
":",
"args",
"=",
"args",
"or",
"TexArgs",
"(",
")",
"# Unlimited whitespace before first argument",
"candidate_index",
"=",
"src",
".",
"num_forward_until",
"(",
"lambda",
"s",
":",
"not",
"s",
... | r"""Read all arguments from buffer.
Advances buffer until end of last valid arguments. There can be any number
of whitespace characters between command and the first argument.
However, after that first argument, the command can only tolerate one
successive line break, before discontinuing the chain of arguments.
:param TexArgs args: existing arguments to extend
:return: parsed arguments
:rtype: TexArgs | [
"r",
"Read",
"all",
"arguments",
"from",
"buffer",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L365-L401 | train | 212,713 |
alvinwan/TexSoup | TexSoup/reader.py | read_arg | def read_arg(src, c):
"""Read the argument from buffer.
Advances buffer until right before the end of the argument.
:param Buffer src: a buffer of tokens
:param str c: argument token (starting token)
:return: the parsed argument
:rtype: Arg
"""
content = [c]
while src.hasNext():
if src.peek() in ARG_END_TOKENS:
content.append(next(src))
break
else:
content.append(read_tex(src))
return Arg.parse(content) | python | def read_arg(src, c):
"""Read the argument from buffer.
Advances buffer until right before the end of the argument.
:param Buffer src: a buffer of tokens
:param str c: argument token (starting token)
:return: the parsed argument
:rtype: Arg
"""
content = [c]
while src.hasNext():
if src.peek() in ARG_END_TOKENS:
content.append(next(src))
break
else:
content.append(read_tex(src))
return Arg.parse(content) | [
"def",
"read_arg",
"(",
"src",
",",
"c",
")",
":",
"content",
"=",
"[",
"c",
"]",
"while",
"src",
".",
"hasNext",
"(",
")",
":",
"if",
"src",
".",
"peek",
"(",
")",
"in",
"ARG_END_TOKENS",
":",
"content",
".",
"append",
"(",
"next",
"(",
"src",
... | Read the argument from buffer.
Advances buffer until right before the end of the argument.
:param Buffer src: a buffer of tokens
:param str c: argument token (starting token)
:return: the parsed argument
:rtype: Arg | [
"Read",
"the",
"argument",
"from",
"buffer",
"."
] | 63323ed71510fd2351102b8c36660a3b7703cead | https://github.com/alvinwan/TexSoup/blob/63323ed71510fd2351102b8c36660a3b7703cead/TexSoup/reader.py#L404-L421 | train | 212,714 |
msmbuilder/msmbuilder | msmbuilder/tpt/hub.py | hub_scores | def hub_scores(msm, waypoints=None):
"""
Calculate the hub score for one or more waypoints
The "hub score" is a measure of how well traveled a certain state or
set of states is in a network. Specifically, it is the fraction of
times that a walker visits a state en route from some state A to another
state B, averaged over all combinations of A and B.
Parameters
----------
msm : msmbuilder.MarkovStateModel
MSM to analyze
waypoints : array_like, int, optional
The index of the intermediate state (or more than one).
If None, then all waypoints will be used
Returns
-------
hub_score : float
The hub score for the waypoint
References
----------
.. [1] Dickson & Brooks (2012), J. Chem. Theory Comput., 8, 3044-3052.
"""
n_states = msm.n_states_
if isinstance(waypoints, int):
waypoints = [waypoints]
elif waypoints is None:
waypoints = xrange(n_states)
elif not (isinstance(waypoints, list) or
isinstance(waypoints, np.ndarray)):
raise ValueError("waypoints (%s) must be an int, a list, or None" %
str(waypoints))
hub_scores = []
for waypoint in waypoints:
other_states = (i for i in xrange(n_states) if i != waypoint)
# calculate the hub score for this waypoint
hub_score = 0.0
for (source, sink) in itertools.permutations(other_states, 2):
hub_score += fraction_visited(source, sink, waypoint, msm)
hub_score /= float((n_states - 1) * (n_states - 2))
hub_scores.append(hub_score)
return np.array(hub_scores) | python | def hub_scores(msm, waypoints=None):
"""
Calculate the hub score for one or more waypoints
The "hub score" is a measure of how well traveled a certain state or
set of states is in a network. Specifically, it is the fraction of
times that a walker visits a state en route from some state A to another
state B, averaged over all combinations of A and B.
Parameters
----------
msm : msmbuilder.MarkovStateModel
MSM to analyze
waypoints : array_like, int, optional
The index of the intermediate state (or more than one).
If None, then all waypoints will be used
Returns
-------
hub_score : float
The hub score for the waypoint
References
----------
.. [1] Dickson & Brooks (2012), J. Chem. Theory Comput., 8, 3044-3052.
"""
n_states = msm.n_states_
if isinstance(waypoints, int):
waypoints = [waypoints]
elif waypoints is None:
waypoints = xrange(n_states)
elif not (isinstance(waypoints, list) or
isinstance(waypoints, np.ndarray)):
raise ValueError("waypoints (%s) must be an int, a list, or None" %
str(waypoints))
hub_scores = []
for waypoint in waypoints:
other_states = (i for i in xrange(n_states) if i != waypoint)
# calculate the hub score for this waypoint
hub_score = 0.0
for (source, sink) in itertools.permutations(other_states, 2):
hub_score += fraction_visited(source, sink, waypoint, msm)
hub_score /= float((n_states - 1) * (n_states - 2))
hub_scores.append(hub_score)
return np.array(hub_scores) | [
"def",
"hub_scores",
"(",
"msm",
",",
"waypoints",
"=",
"None",
")",
":",
"n_states",
"=",
"msm",
".",
"n_states_",
"if",
"isinstance",
"(",
"waypoints",
",",
"int",
")",
":",
"waypoints",
"=",
"[",
"waypoints",
"]",
"elif",
"waypoints",
"is",
"None",
... | Calculate the hub score for one or more waypoints
The "hub score" is a measure of how well traveled a certain state or
set of states is in a network. Specifically, it is the fraction of
times that a walker visits a state en route from some state A to another
state B, averaged over all combinations of A and B.
Parameters
----------
msm : msmbuilder.MarkovStateModel
MSM to analyze
waypoints : array_like, int, optional
The index of the intermediate state (or more than one).
If None, then all waypoints will be used
Returns
-------
hub_score : float
The hub score for the waypoint
References
----------
.. [1] Dickson & Brooks (2012), J. Chem. Theory Comput., 8, 3044-3052. | [
"Calculate",
"the",
"hub",
"score",
"for",
"one",
"or",
"more",
"waypoints"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/hub.py#L86-L136 | train | 212,715 |
msmbuilder/msmbuilder | msmbuilder/lumping/bace.py | BACE.fit | def fit(self, sequences, y=None):
"""Fit a BACE lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self
"""
super(BACE, self).fit(sequences, y=y)
if self.n_macrostates is not None:
self._do_lumping()
else:
raise RuntimeError('n_macrostates must not be None to fit')
return self | python | def fit(self, sequences, y=None):
"""Fit a BACE lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self
"""
super(BACE, self).fit(sequences, y=y)
if self.n_macrostates is not None:
self._do_lumping()
else:
raise RuntimeError('n_macrostates must not be None to fit')
return self | [
"def",
"fit",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"super",
"(",
"BACE",
",",
"self",
")",
".",
"fit",
"(",
"sequences",
",",
"y",
"=",
"y",
")",
"if",
"self",
".",
"n_macrostates",
"is",
"not",
"None",
":",
"self",
"... | Fit a BACE lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self | [
"Fit",
"a",
"BACE",
"lumping",
"model",
"using",
"a",
"sequence",
"of",
"cluster",
"assignments",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/bace.py#L91-L111 | train | 212,716 |
msmbuilder/msmbuilder | msmbuilder/lumping/bace.py | BACE._do_lumping | def _do_lumping(self):
"""Do the BACE lumping.
"""
c = copy.deepcopy(self.countsmat_)
if self.sliding_window:
c *= self.lag_time
c, macro_map, statesKeep = self._filterFunc(c)
w = np.array(c.sum(axis=1)).flatten()
w[statesKeep] += 1
unmerged = np.zeros(w.shape[0], dtype=np.int8)
unmerged[statesKeep] = 1
# get nonzero indices in upper triangle
indRecalc = self._getInds(c, statesKeep)
dMat = np.zeros(c.shape, dtype=np.float32)
i = 0
nCurrentStates = statesKeep.shape[0]
self.bayesFactors = {}
dMat, minX, minY = self._calcDMat(c, w, indRecalc, dMat,
statesKeep, unmerged)
while nCurrentStates > self.n_macrostates:
c, w, indRecalc, dMat, macro_map, statesKeep, unmerged, minX, minY = self._mergeTwoClosestStates(
c, w, indRecalc, dMat, macro_map,
statesKeep, minX, minY, unmerged)
nCurrentStates -= 1
if self.save_all_maps:
saved_map = copy.deepcopy(macro_map)
self.map_dict[nCurrentStates] = saved_map
if nCurrentStates - 1 == self.n_macrostates:
self.microstate_mapping_ = macro_map | python | def _do_lumping(self):
"""Do the BACE lumping.
"""
c = copy.deepcopy(self.countsmat_)
if self.sliding_window:
c *= self.lag_time
c, macro_map, statesKeep = self._filterFunc(c)
w = np.array(c.sum(axis=1)).flatten()
w[statesKeep] += 1
unmerged = np.zeros(w.shape[0], dtype=np.int8)
unmerged[statesKeep] = 1
# get nonzero indices in upper triangle
indRecalc = self._getInds(c, statesKeep)
dMat = np.zeros(c.shape, dtype=np.float32)
i = 0
nCurrentStates = statesKeep.shape[0]
self.bayesFactors = {}
dMat, minX, minY = self._calcDMat(c, w, indRecalc, dMat,
statesKeep, unmerged)
while nCurrentStates > self.n_macrostates:
c, w, indRecalc, dMat, macro_map, statesKeep, unmerged, minX, minY = self._mergeTwoClosestStates(
c, w, indRecalc, dMat, macro_map,
statesKeep, minX, minY, unmerged)
nCurrentStates -= 1
if self.save_all_maps:
saved_map = copy.deepcopy(macro_map)
self.map_dict[nCurrentStates] = saved_map
if nCurrentStates - 1 == self.n_macrostates:
self.microstate_mapping_ = macro_map | [
"def",
"_do_lumping",
"(",
"self",
")",
":",
"c",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"countsmat_",
")",
"if",
"self",
".",
"sliding_window",
":",
"c",
"*=",
"self",
".",
"lag_time",
"c",
",",
"macro_map",
",",
"statesKeep",
"=",
"self",
... | Do the BACE lumping. | [
"Do",
"the",
"BACE",
"lumping",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/bace.py#L113-L152 | train | 212,717 |
msmbuilder/msmbuilder | msmbuilder/utils/progressbar/progressbar.py | ProgressBar.percentage | def percentage(self):
"""Returns the progress as a percentage."""
if self.currval >= self.maxval:
return 100.0
return self.currval * 100.0 / self.maxval | python | def percentage(self):
"""Returns the progress as a percentage."""
if self.currval >= self.maxval:
return 100.0
return self.currval * 100.0 / self.maxval | [
"def",
"percentage",
"(",
"self",
")",
":",
"if",
"self",
".",
"currval",
">=",
"self",
".",
"maxval",
":",
"return",
"100.0",
"return",
"self",
".",
"currval",
"*",
"100.0",
"/",
"self",
".",
"maxval"
] | Returns the progress as a percentage. | [
"Returns",
"the",
"progress",
"as",
"a",
"percentage",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/progressbar/progressbar.py#L185-L189 | train | 212,718 |
msmbuilder/msmbuilder | basesetup.py | find_packages | def find_packages():
"""Find all of mdtraj's python packages.
Adapted from IPython's setupbase.py. Copyright IPython
contributors, licensed under the BSD license.
"""
packages = ['mdtraj.scripts']
for dir,subdirs,files in os.walk('MDTraj'):
package = dir.replace(os.path.sep, '.')
if '__init__.py' not in files:
# not a package
continue
packages.append(package.replace('MDTraj', 'mdtraj'))
return packages | python | def find_packages():
"""Find all of mdtraj's python packages.
Adapted from IPython's setupbase.py. Copyright IPython
contributors, licensed under the BSD license.
"""
packages = ['mdtraj.scripts']
for dir,subdirs,files in os.walk('MDTraj'):
package = dir.replace(os.path.sep, '.')
if '__init__.py' not in files:
# not a package
continue
packages.append(package.replace('MDTraj', 'mdtraj'))
return packages | [
"def",
"find_packages",
"(",
")",
":",
"packages",
"=",
"[",
"'mdtraj.scripts'",
"]",
"for",
"dir",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"'MDTraj'",
")",
":",
"package",
"=",
"dir",
".",
"replace",
"(",
"os",
".",
"path",
".",
... | Find all of mdtraj's python packages.
Adapted from IPython's setupbase.py. Copyright IPython
contributors, licensed under the BSD license. | [
"Find",
"all",
"of",
"mdtraj",
"s",
"python",
"packages",
".",
"Adapted",
"from",
"IPython",
"s",
"setupbase",
".",
"py",
".",
"Copyright",
"IPython",
"contributors",
"licensed",
"under",
"the",
"BSD",
"license",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/basesetup.py#L18-L30 | train | 212,719 |
msmbuilder/msmbuilder | basesetup.py | CompilerDetection._detect_sse3 | def _detect_sse3(self):
"Does this compiler support SSE3 intrinsics?"
self._print_support_start('SSE3')
result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)',
include='<pmmintrin.h>',
extra_postargs=['-msse3'])
self._print_support_end('SSE3', result)
return result | python | def _detect_sse3(self):
"Does this compiler support SSE3 intrinsics?"
self._print_support_start('SSE3')
result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)',
include='<pmmintrin.h>',
extra_postargs=['-msse3'])
self._print_support_end('SSE3', result)
return result | [
"def",
"_detect_sse3",
"(",
"self",
")",
":",
"self",
".",
"_print_support_start",
"(",
"'SSE3'",
")",
"result",
"=",
"self",
".",
"hasfunction",
"(",
"'__m128 v; _mm_hadd_ps(v,v)'",
",",
"include",
"=",
"'<pmmintrin.h>'",
",",
"extra_postargs",
"=",
"[",
"'-mss... | Does this compiler support SSE3 intrinsics? | [
"Does",
"this",
"compiler",
"support",
"SSE3",
"intrinsics?"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/basesetup.py#L210-L217 | train | 212,720 |
msmbuilder/msmbuilder | basesetup.py | CompilerDetection._detect_sse41 | def _detect_sse41(self):
"Does this compiler support SSE4.1 intrinsics?"
self._print_support_start('SSE4.1')
result = self.hasfunction( '__m128 v; _mm_round_ps(v,0x00)',
include='<smmintrin.h>',
extra_postargs=['-msse4'])
self._print_support_end('SSE4.1', result)
return result | python | def _detect_sse41(self):
"Does this compiler support SSE4.1 intrinsics?"
self._print_support_start('SSE4.1')
result = self.hasfunction( '__m128 v; _mm_round_ps(v,0x00)',
include='<smmintrin.h>',
extra_postargs=['-msse4'])
self._print_support_end('SSE4.1', result)
return result | [
"def",
"_detect_sse41",
"(",
"self",
")",
":",
"self",
".",
"_print_support_start",
"(",
"'SSE4.1'",
")",
"result",
"=",
"self",
".",
"hasfunction",
"(",
"'__m128 v; _mm_round_ps(v,0x00)'",
",",
"include",
"=",
"'<smmintrin.h>'",
",",
"extra_postargs",
"=",
"[",
... | Does this compiler support SSE4.1 intrinsics? | [
"Does",
"this",
"compiler",
"support",
"SSE4",
".",
"1",
"intrinsics?"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/basesetup.py#L219-L226 | train | 212,721 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM.uncertainty_K | def uncertainty_K(self):
"""Estimate of the element-wise asymptotic standard deviation
in the rate matrix
"""
if self.information_ is None:
self._build_information()
sigma_K = _ratematrix.sigma_K(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_K | python | def uncertainty_K(self):
"""Estimate of the element-wise asymptotic standard deviation
in the rate matrix
"""
if self.information_ is None:
self._build_information()
sigma_K = _ratematrix.sigma_K(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_K | [
"def",
"uncertainty_K",
"(",
"self",
")",
":",
"if",
"self",
".",
"information_",
"is",
"None",
":",
"self",
".",
"_build_information",
"(",
")",
"sigma_K",
"=",
"_ratematrix",
".",
"sigma_K",
"(",
"self",
".",
"information_",
",",
"theta",
"=",
"self",
... | Estimate of the element-wise asymptotic standard deviation
in the rate matrix | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"rate",
"matrix"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L221-L230 | train | 212,722 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM.uncertainty_pi | def uncertainty_pi(self):
"""Estimate of the element-wise asymptotic standard deviation
in the stationary distribution.
"""
if self.information_ is None:
self._build_information()
sigma_pi = _ratematrix.sigma_pi(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_pi | python | def uncertainty_pi(self):
"""Estimate of the element-wise asymptotic standard deviation
in the stationary distribution.
"""
if self.information_ is None:
self._build_information()
sigma_pi = _ratematrix.sigma_pi(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_pi | [
"def",
"uncertainty_pi",
"(",
"self",
")",
":",
"if",
"self",
".",
"information_",
"is",
"None",
":",
"self",
".",
"_build_information",
"(",
")",
"sigma_pi",
"=",
"_ratematrix",
".",
"sigma_pi",
"(",
"self",
".",
"information_",
",",
"theta",
"=",
"self",... | Estimate of the element-wise asymptotic standard deviation
in the stationary distribution. | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"stationary",
"distribution",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L232-L241 | train | 212,723 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM.uncertainty_eigenvalues | def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues
"""
if self.information_ is None:
self._build_information()
sigma_eigenvalues = _ratematrix.sigma_eigenvalues(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_eigenvalues
return np.nan_to_num(sigma_eigenvalues[:self.n_timescales+1]) | python | def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues
"""
if self.information_ is None:
self._build_information()
sigma_eigenvalues = _ratematrix.sigma_eigenvalues(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_eigenvalues
return np.nan_to_num(sigma_eigenvalues[:self.n_timescales+1]) | [
"def",
"uncertainty_eigenvalues",
"(",
"self",
")",
":",
"if",
"self",
".",
"information_",
"is",
"None",
":",
"self",
".",
"_build_information",
"(",
")",
"sigma_eigenvalues",
"=",
"_ratematrix",
".",
"sigma_eigenvalues",
"(",
"self",
".",
"information_",
",",
... | Estimate of the element-wise asymptotic standard deviation
in the model eigenvalues | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"model",
"eigenvalues"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L243-L255 | train | 212,724 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM.uncertainty_timescales | def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model relaxation timescales.
"""
if self.information_ is None:
self._build_information()
sigma_timescales = _ratematrix.sigma_timescales(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_timescales
return sigma_timescales[:self.n_timescales] | python | def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation
in the model relaxation timescales.
"""
if self.information_ is None:
self._build_information()
sigma_timescales = _ratematrix.sigma_timescales(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_timescales
return sigma_timescales[:self.n_timescales] | [
"def",
"uncertainty_timescales",
"(",
"self",
")",
":",
"if",
"self",
".",
"information_",
"is",
"None",
":",
"self",
".",
"_build_information",
"(",
")",
"sigma_timescales",
"=",
"_ratematrix",
".",
"sigma_timescales",
"(",
"self",
".",
"information_",
",",
"... | Estimate of the element-wise asymptotic standard deviation
in the model relaxation timescales. | [
"Estimate",
"of",
"the",
"element",
"-",
"wise",
"asymptotic",
"standard",
"deviation",
"in",
"the",
"model",
"relaxation",
"timescales",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L257-L269 | train | 212,725 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM._initial_guess | def _initial_guess(self, countsmat):
"""Generate an initial guess for \theta.
"""
if self.theta_ is not None:
return self.theta_
if self.guess == 'log':
transmat, pi = _transmat_mle_prinz(countsmat)
K = np.real(scipy.linalg.logm(transmat)) / self.lag_time
elif self.guess == 'pseudo':
transmat, pi = _transmat_mle_prinz(countsmat)
K = (transmat - np.eye(self.n_states_)) / self.lag_time
elif isinstance(self.guess, np.ndarray):
pi = _solve_ratemat_eigensystem(self.guess)[1][:, 0]
K = self.guess
S = np.multiply(np.sqrt(np.outer(pi, 1/pi)), K)
sflat = np.maximum(S[np.triu_indices_from(countsmat, k=1)], 0)
theta0 = np.concatenate((sflat, np.log(pi)))
return theta0 | python | def _initial_guess(self, countsmat):
"""Generate an initial guess for \theta.
"""
if self.theta_ is not None:
return self.theta_
if self.guess == 'log':
transmat, pi = _transmat_mle_prinz(countsmat)
K = np.real(scipy.linalg.logm(transmat)) / self.lag_time
elif self.guess == 'pseudo':
transmat, pi = _transmat_mle_prinz(countsmat)
K = (transmat - np.eye(self.n_states_)) / self.lag_time
elif isinstance(self.guess, np.ndarray):
pi = _solve_ratemat_eigensystem(self.guess)[1][:, 0]
K = self.guess
S = np.multiply(np.sqrt(np.outer(pi, 1/pi)), K)
sflat = np.maximum(S[np.triu_indices_from(countsmat, k=1)], 0)
theta0 = np.concatenate((sflat, np.log(pi)))
return theta0 | [
"def",
"_initial_guess",
"(",
"self",
",",
"countsmat",
")",
":",
"if",
"self",
".",
"theta_",
"is",
"not",
"None",
":",
"return",
"self",
".",
"theta_",
"if",
"self",
".",
"guess",
"==",
"'log'",
":",
"transmat",
",",
"pi",
"=",
"_transmat_mle_prinz",
... | Generate an initial guess for \theta. | [
"Generate",
"an",
"initial",
"guess",
"for",
"\\",
"theta",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L271-L293 | train | 212,726 |
msmbuilder/msmbuilder | msmbuilder/msm/ratematrix.py | ContinuousTimeMSM._build_information | def _build_information(self):
"""Build the inverse of hessian of the log likelihood at theta_
"""
lag_time = float(self.lag_time)
# only the "active set" of variables not at the bounds of the
# feasible set.
inds = np.where(self.theta_ != 0)[0]
hessian = _ratematrix.hessian(
self.theta_, self.countsmat_, t=lag_time, inds=inds)
self.information_ = np.zeros((len(self.theta_), len(self.theta_)))
self.information_[np.ix_(inds, inds)] = scipy.linalg.pinv(-hessian) | python | def _build_information(self):
"""Build the inverse of hessian of the log likelihood at theta_
"""
lag_time = float(self.lag_time)
# only the "active set" of variables not at the bounds of the
# feasible set.
inds = np.where(self.theta_ != 0)[0]
hessian = _ratematrix.hessian(
self.theta_, self.countsmat_, t=lag_time, inds=inds)
self.information_ = np.zeros((len(self.theta_), len(self.theta_)))
self.information_[np.ix_(inds, inds)] = scipy.linalg.pinv(-hessian) | [
"def",
"_build_information",
"(",
"self",
")",
":",
"lag_time",
"=",
"float",
"(",
"self",
".",
"lag_time",
")",
"# only the \"active set\" of variables not at the bounds of the",
"# feasible set.",
"inds",
"=",
"np",
".",
"where",
"(",
"self",
".",
"theta_",
"!=",
... | Build the inverse of hessian of the log likelihood at theta_ | [
"Build",
"the",
"inverse",
"of",
"hessian",
"of",
"the",
"log",
"likelihood",
"at",
"theta_"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/ratematrix.py#L295-L308 | train | 212,727 |
msmbuilder/msmbuilder | msmbuilder/msm/bayes_ratematrix.py | _log_posterior | def _log_posterior(theta, counts, alpha, beta, n):
"""Log of the posterior probability and gradient
Parameters
----------
theta : ndarray, shape=(n_params,)
The free parameters of the reversible rate matrix
counts : ndarray, shape=(n, n)
The count matrix (sufficient statistics for the likielihood)
alpha : ndarray, shape=(n,)
Dirichlet concentration parameters
beta : ndarray, shape=(n_params-n,)
Scale parameter for the exponential prior on the symmetric rate
matrix.
"""
# likelihood + grad
logp1, grad = loglikelihood(theta, counts)
# exponential prior on s_{ij}
logp2 = lexponential(theta[:-n], beta, grad=grad[:-n])
# dirichlet prior on \pi
logp3 = ldirichlet_softmax(theta[-n:], alpha=alpha, grad=grad[-n:])
logp = logp1 + logp2 + logp3
return logp, grad | python | def _log_posterior(theta, counts, alpha, beta, n):
"""Log of the posterior probability and gradient
Parameters
----------
theta : ndarray, shape=(n_params,)
The free parameters of the reversible rate matrix
counts : ndarray, shape=(n, n)
The count matrix (sufficient statistics for the likielihood)
alpha : ndarray, shape=(n,)
Dirichlet concentration parameters
beta : ndarray, shape=(n_params-n,)
Scale parameter for the exponential prior on the symmetric rate
matrix.
"""
# likelihood + grad
logp1, grad = loglikelihood(theta, counts)
# exponential prior on s_{ij}
logp2 = lexponential(theta[:-n], beta, grad=grad[:-n])
# dirichlet prior on \pi
logp3 = ldirichlet_softmax(theta[-n:], alpha=alpha, grad=grad[-n:])
logp = logp1 + logp2 + logp3
return logp, grad | [
"def",
"_log_posterior",
"(",
"theta",
",",
"counts",
",",
"alpha",
",",
"beta",
",",
"n",
")",
":",
"# likelihood + grad",
"logp1",
",",
"grad",
"=",
"loglikelihood",
"(",
"theta",
",",
"counts",
")",
"# exponential prior on s_{ij}",
"logp2",
"=",
"lexponenti... | Log of the posterior probability and gradient
Parameters
----------
theta : ndarray, shape=(n_params,)
The free parameters of the reversible rate matrix
counts : ndarray, shape=(n, n)
The count matrix (sufficient statistics for the likielihood)
alpha : ndarray, shape=(n,)
Dirichlet concentration parameters
beta : ndarray, shape=(n_params-n,)
Scale parameter for the exponential prior on the symmetric rate
matrix. | [
"Log",
"of",
"the",
"posterior",
"probability",
"and",
"gradient"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/bayes_ratematrix.py#L253-L275 | train | 212,728 |
msmbuilder/msmbuilder | msmbuilder/utils/probability.py | categorical | def categorical(pvals, size=None, random_state=None):
"""Return random integer from a categorical distribution
Parameters
----------
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
should sum to 1.
size : int or tuple of ints, optional
Defines the shape of the returned array of random integers. If None
(the default), returns a single float.
random_state: RandomState or an int seed, optional
A random number generator instance.
"""
cumsum = np.cumsum(pvals)
if size is None:
size = (1,)
axis = 0
elif isinstance(size, tuple):
size = size + (1,)
axis = len(size) - 1
else:
raise TypeError('size must be an int or tuple of ints')
random_state = check_random_state(random_state)
return np.sum(cumsum < random_state.random_sample(size), axis=axis) | python | def categorical(pvals, size=None, random_state=None):
"""Return random integer from a categorical distribution
Parameters
----------
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
should sum to 1.
size : int or tuple of ints, optional
Defines the shape of the returned array of random integers. If None
(the default), returns a single float.
random_state: RandomState or an int seed, optional
A random number generator instance.
"""
cumsum = np.cumsum(pvals)
if size is None:
size = (1,)
axis = 0
elif isinstance(size, tuple):
size = size + (1,)
axis = len(size) - 1
else:
raise TypeError('size must be an int or tuple of ints')
random_state = check_random_state(random_state)
return np.sum(cumsum < random_state.random_sample(size), axis=axis) | [
"def",
"categorical",
"(",
"pvals",
",",
"size",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"cumsum",
"=",
"np",
".",
"cumsum",
"(",
"pvals",
")",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"(",
"1",
",",
")",
"axis",
"=",
"0",
... | Return random integer from a categorical distribution
Parameters
----------
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
should sum to 1.
size : int or tuple of ints, optional
Defines the shape of the returned array of random integers. If None
(the default), returns a single float.
random_state: RandomState or an int seed, optional
A random number generator instance. | [
"Return",
"random",
"integer",
"from",
"a",
"categorical",
"distribution"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/probability.py#L8-L33 | train | 212,729 |
msmbuilder/msmbuilder | msmbuilder/msm/_metzner_mcmc_slow.py | metzner_mcmc_slow | def metzner_mcmc_slow(Z, n_samples, n_thin=1, random_state=None):
"""Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between states plus the number of prior counts
n_samples : int
Number of steps to iterate the chain for
n_thin : int
Yield every ``n_thin``-th sample from the MCMC chain
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Notes
-----
The transition matrix posterior distribution is ::
P(T | Z) \propto \Prod_{ij} T_{ij}^{Z_{ij}}
and constrained to be reversible, such that there exists a \pi s.t. ::
\pi_i T_{ij} = \pi_j T_{ji}
Yields
------
T : np.array, shape=(n_states, n_states)
This generator yields samples from the transition matrix posterior
References
----------
.. [1] P. Metzner, F. Noe and C. Schutte, "Estimating the sampling error:
Distribution of transition matrices and functions of transition
matrices for given trajectory data." Phys. Rev. E 80 021106 (2009)
See Also
--------
metzner_mcmc_fast
"""
# Upper and lower bounds on the sum of the K matrix, to ensure proper
# proposal weights. See Eq. 17 of [1].
K_MINUS = 0.9
K_PLUS = 1.1
Z = np.asarray(Z)
n_states = Z.shape[0]
if not Z.ndim == 2 and Z.shape[1] == n_states:
raise ValueError("Z must be square. Z.shape=%s" % str(Z.shape))
K = 0.5 * (Z + Z.T) / np.sum(Z, dtype=float)
random = check_random_state(random_state)
n_accept = 0
for t in range(n_samples):
# proposal
# Select two indices in [0...n_states). We draw them by drawing a
# random floats in [0,1) and then rounding to int so that this method
# is exactly analogous to `metzner_mcmc_fast`, which, for each MCMC
# iteration, draws 4 random floats in [0,1) from the same numpy PSRNG,
# and then inside the C step kernel (src/metzner_mcmc.c) uses two of
# them like this. This ensures that this function and
# `metzner_mcmc_fast` give _exactly_ the same sequence of transition
# matricies, given the same random seed.
i, j = (random.rand(2) * n_states).astype(np.int)
sc = np.sum(K)
if i == j:
a, b = max(-K[i,j], K_MINUS - sc), K_PLUS - sc
else:
a, b = max(-K[i,j], 0.5*(K_MINUS - sc)), 0.5*(K_PLUS - sc)
epsilon = random.uniform(a, b)
K_proposal = np.copy(K)
K_proposal[i, j] += epsilon
if i != j:
K_proposal[j, i] += epsilon
# acceptance?
cutoff = np.exp(_logprob_T(_K_to_T(K_proposal), Z) -
_logprob_T(_K_to_T(K), Z))
r = random.rand()
# print 'i', i, 'j', j
# print 'a', a, 'b', b
# print 'cutoff', cutoff
# print 'r', r
# print 'sc', sc
if r < cutoff:
n_accept += 1
K = K_proposal
if (t+1) % n_thin == 0:
yield _K_to_T(K) | python | def metzner_mcmc_slow(Z, n_samples, n_thin=1, random_state=None):
"""Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between states plus the number of prior counts
n_samples : int
Number of steps to iterate the chain for
n_thin : int
Yield every ``n_thin``-th sample from the MCMC chain
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Notes
-----
The transition matrix posterior distribution is ::
P(T | Z) \propto \Prod_{ij} T_{ij}^{Z_{ij}}
and constrained to be reversible, such that there exists a \pi s.t. ::
\pi_i T_{ij} = \pi_j T_{ji}
Yields
------
T : np.array, shape=(n_states, n_states)
This generator yields samples from the transition matrix posterior
References
----------
.. [1] P. Metzner, F. Noe and C. Schutte, "Estimating the sampling error:
Distribution of transition matrices and functions of transition
matrices for given trajectory data." Phys. Rev. E 80 021106 (2009)
See Also
--------
metzner_mcmc_fast
"""
# Upper and lower bounds on the sum of the K matrix, to ensure proper
# proposal weights. See Eq. 17 of [1].
K_MINUS = 0.9
K_PLUS = 1.1
Z = np.asarray(Z)
n_states = Z.shape[0]
if not Z.ndim == 2 and Z.shape[1] == n_states:
raise ValueError("Z must be square. Z.shape=%s" % str(Z.shape))
K = 0.5 * (Z + Z.T) / np.sum(Z, dtype=float)
random = check_random_state(random_state)
n_accept = 0
for t in range(n_samples):
# proposal
# Select two indices in [0...n_states). We draw them by drawing a
# random floats in [0,1) and then rounding to int so that this method
# is exactly analogous to `metzner_mcmc_fast`, which, for each MCMC
# iteration, draws 4 random floats in [0,1) from the same numpy PSRNG,
# and then inside the C step kernel (src/metzner_mcmc.c) uses two of
# them like this. This ensures that this function and
# `metzner_mcmc_fast` give _exactly_ the same sequence of transition
# matricies, given the same random seed.
i, j = (random.rand(2) * n_states).astype(np.int)
sc = np.sum(K)
if i == j:
a, b = max(-K[i,j], K_MINUS - sc), K_PLUS - sc
else:
a, b = max(-K[i,j], 0.5*(K_MINUS - sc)), 0.5*(K_PLUS - sc)
epsilon = random.uniform(a, b)
K_proposal = np.copy(K)
K_proposal[i, j] += epsilon
if i != j:
K_proposal[j, i] += epsilon
# acceptance?
cutoff = np.exp(_logprob_T(_K_to_T(K_proposal), Z) -
_logprob_T(_K_to_T(K), Z))
r = random.rand()
# print 'i', i, 'j', j
# print 'a', a, 'b', b
# print 'cutoff', cutoff
# print 'r', r
# print 'sc', sc
if r < cutoff:
n_accept += 1
K = K_proposal
if (t+1) % n_thin == 0:
yield _K_to_T(K) | [
"def",
"metzner_mcmc_slow",
"(",
"Z",
",",
"n_samples",
",",
"n_thin",
"=",
"1",
",",
"random_state",
"=",
"None",
")",
":",
"# Upper and lower bounds on the sum of the K matrix, to ensure proper",
"# proposal weights. See Eq. 17 of [1].",
"K_MINUS",
"=",
"0.9",
"K_PLUS",
... | Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between states plus the number of prior counts
n_samples : int
Number of steps to iterate the chain for
n_thin : int
Yield every ``n_thin``-th sample from the MCMC chain
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Notes
-----
The transition matrix posterior distribution is ::
P(T | Z) \propto \Prod_{ij} T_{ij}^{Z_{ij}}
and constrained to be reversible, such that there exists a \pi s.t. ::
\pi_i T_{ij} = \pi_j T_{ji}
Yields
------
T : np.array, shape=(n_states, n_states)
This generator yields samples from the transition matrix posterior
References
----------
.. [1] P. Metzner, F. Noe and C. Schutte, "Estimating the sampling error:
Distribution of transition matrices and functions of transition
matrices for given trajectory data." Phys. Rev. E 80 021106 (2009)
See Also
--------
metzner_mcmc_fast | [
"Metropolis",
"Markov",
"chain",
"Monte",
"Carlo",
"sampler",
"for",
"reversible",
"transition",
"matrices"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/_metzner_mcmc_slow.py#L5-L99 | train | 212,730 |
msmbuilder/msmbuilder | msmbuilder/io/project_template.py | get_layout | def get_layout():
"""Specify a hierarchy of our templates."""
tica_msm = TemplateDir(
'tica',
[
'tica/tica.py',
'tica/tica-plot.py',
'tica/tica-sample-coordinate.py',
'tica/tica-sample-coordinate-plot.py',
],
[
TemplateDir(
'cluster',
[
'cluster/cluster.py',
'cluster/cluster-plot.py',
'cluster/sample-clusters.py',
'cluster/sample-clusters-plot.py',
],
[
TemplateDir(
'msm',
[
'msm/timescales.py',
'msm/timescales-plot.py',
'msm/microstate.py',
'msm/microstate-plot.py',
'msm/microstate-traj.py',
],
[],
)
]
)
]
)
layout = TemplateDir(
'',
[
'0-test-install.py',
'1-get-example-data.py',
'README.md',
],
[
TemplateDir(
'analysis',
[
'analysis/gather-metadata.py',
'analysis/gather-metadata-plot.py',
],
[
TemplateDir(
'rmsd',
[
'rmsd/rmsd.py',
'rmsd/rmsd-plot.py',
],
[],
),
TemplateDir(
'landmarks',
[
'landmarks/find-landmarks.py',
'landmarks/featurize.py',
'landmarks/featurize-plot.py',
],
[tica_msm],
),
TemplateDir(
'dihedrals',
[
'dihedrals/featurize.py',
'dihedrals/featurize-plot.py',
],
[tica_msm],
)
]
)
]
)
return layout | python | def get_layout():
"""Specify a hierarchy of our templates."""
tica_msm = TemplateDir(
'tica',
[
'tica/tica.py',
'tica/tica-plot.py',
'tica/tica-sample-coordinate.py',
'tica/tica-sample-coordinate-plot.py',
],
[
TemplateDir(
'cluster',
[
'cluster/cluster.py',
'cluster/cluster-plot.py',
'cluster/sample-clusters.py',
'cluster/sample-clusters-plot.py',
],
[
TemplateDir(
'msm',
[
'msm/timescales.py',
'msm/timescales-plot.py',
'msm/microstate.py',
'msm/microstate-plot.py',
'msm/microstate-traj.py',
],
[],
)
]
)
]
)
layout = TemplateDir(
'',
[
'0-test-install.py',
'1-get-example-data.py',
'README.md',
],
[
TemplateDir(
'analysis',
[
'analysis/gather-metadata.py',
'analysis/gather-metadata-plot.py',
],
[
TemplateDir(
'rmsd',
[
'rmsd/rmsd.py',
'rmsd/rmsd-plot.py',
],
[],
),
TemplateDir(
'landmarks',
[
'landmarks/find-landmarks.py',
'landmarks/featurize.py',
'landmarks/featurize-plot.py',
],
[tica_msm],
),
TemplateDir(
'dihedrals',
[
'dihedrals/featurize.py',
'dihedrals/featurize-plot.py',
],
[tica_msm],
)
]
)
]
)
return layout | [
"def",
"get_layout",
"(",
")",
":",
"tica_msm",
"=",
"TemplateDir",
"(",
"'tica'",
",",
"[",
"'tica/tica.py'",
",",
"'tica/tica-plot.py'",
",",
"'tica/tica-sample-coordinate.py'",
",",
"'tica/tica-sample-coordinate-plot.py'",
",",
"]",
",",
"[",
"TemplateDir",
"(",
... | Specify a hierarchy of our templates. | [
"Specify",
"a",
"hierarchy",
"of",
"our",
"templates",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/project_template.py#L17-L96 | train | 212,731 |
msmbuilder/msmbuilder | msmbuilder/io/project_template.py | TemplateDir.find | def find(self, name, limit=None):
"""Find the named TemplateDir in the hierarchy"""
if name == self.name:
if limit is not None:
assert limit == 1
self.subdirs = []
return self
for subdir in self.subdirs:
res = subdir.find(name, limit)
if res is not None:
return res
return None | python | def find(self, name, limit=None):
"""Find the named TemplateDir in the hierarchy"""
if name == self.name:
if limit is not None:
assert limit == 1
self.subdirs = []
return self
for subdir in self.subdirs:
res = subdir.find(name, limit)
if res is not None:
return res
return None | [
"def",
"find",
"(",
"self",
",",
"name",
",",
"limit",
"=",
"None",
")",
":",
"if",
"name",
"==",
"self",
".",
"name",
":",
"if",
"limit",
"is",
"not",
"None",
":",
"assert",
"limit",
"==",
"1",
"self",
".",
"subdirs",
"=",
"[",
"]",
"return",
... | Find the named TemplateDir in the hierarchy | [
"Find",
"the",
"named",
"TemplateDir",
"in",
"the",
"hierarchy"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/project_template.py#L283-L294 | train | 212,732 |
msmbuilder/msmbuilder | msmbuilder/msm/implied_timescales.py | implied_timescales | def implied_timescales(sequences, lag_times, n_timescales=10,
msm=None, n_jobs=1, verbose=0):
"""
Calculate the implied timescales for a given MSM.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
lag_times : array-like
Lag times to calculate implied timescales at.
n_timescales : int, optional
Number of timescales to calculate.
msm : msmbuilder.msm.MarkovStateModel, optional
Instance of an MSM to specify parameters other
than the lag time. If None, then the default
parameters (as implemented by msmbuilder.msm.MarkovStateModel)
will be used.
n_jobs : int, optional
Number of jobs to run in parallel
Returns
-------
timescales : np.ndarray, shape = [n_models, n_timescales]
The slowest timescales (in units of lag times) for each
model.
"""
if msm is None:
msm = MarkovStateModel()
param_grid = {'lag_time' : lag_times}
models = param_sweep(msm, sequences, param_grid, n_jobs=n_jobs,
verbose=verbose)
timescales = [m.timescales_ for m in models]
n_timescales = min(n_timescales, min(len(ts) for ts in timescales))
timescales = np.array([ts[:n_timescales] for ts in timescales])
return timescales | python | def implied_timescales(sequences, lag_times, n_timescales=10,
msm=None, n_jobs=1, verbose=0):
"""
Calculate the implied timescales for a given MSM.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
lag_times : array-like
Lag times to calculate implied timescales at.
n_timescales : int, optional
Number of timescales to calculate.
msm : msmbuilder.msm.MarkovStateModel, optional
Instance of an MSM to specify parameters other
than the lag time. If None, then the default
parameters (as implemented by msmbuilder.msm.MarkovStateModel)
will be used.
n_jobs : int, optional
Number of jobs to run in parallel
Returns
-------
timescales : np.ndarray, shape = [n_models, n_timescales]
The slowest timescales (in units of lag times) for each
model.
"""
if msm is None:
msm = MarkovStateModel()
param_grid = {'lag_time' : lag_times}
models = param_sweep(msm, sequences, param_grid, n_jobs=n_jobs,
verbose=verbose)
timescales = [m.timescales_ for m in models]
n_timescales = min(n_timescales, min(len(ts) for ts in timescales))
timescales = np.array([ts[:n_timescales] for ts in timescales])
return timescales | [
"def",
"implied_timescales",
"(",
"sequences",
",",
"lag_times",
",",
"n_timescales",
"=",
"10",
",",
"msm",
"=",
"None",
",",
"n_jobs",
"=",
"1",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"msm",
"is",
"None",
":",
"msm",
"=",
"MarkovStateModel",
"(",
... | Calculate the implied timescales for a given MSM.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
lag_times : array-like
Lag times to calculate implied timescales at.
n_timescales : int, optional
Number of timescales to calculate.
msm : msmbuilder.msm.MarkovStateModel, optional
Instance of an MSM to specify parameters other
than the lag time. If None, then the default
parameters (as implemented by msmbuilder.msm.MarkovStateModel)
will be used.
n_jobs : int, optional
Number of jobs to run in parallel
Returns
-------
timescales : np.ndarray, shape = [n_models, n_timescales]
The slowest timescales (in units of lag times) for each
model. | [
"Calculate",
"the",
"implied",
"timescales",
"for",
"a",
"given",
"MSM",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/implied_timescales.py#L12-L52 | train | 212,733 |
msmbuilder/msmbuilder | msmbuilder/utils/compat.py | experimental | def experimental(name=None):
"""A simple decorator to mark functions and methods as experimental."""
def inner(func):
@functools.wraps(func)
def wrapper(*fargs, **kw):
fname = name
if name is None:
fname = func.__name__
warnings.warn("%s" % fname, category=ExperimentalWarning,
stacklevel=2)
return func(*fargs, **kw)
return wrapper
return inner | python | def experimental(name=None):
"""A simple decorator to mark functions and methods as experimental."""
def inner(func):
@functools.wraps(func)
def wrapper(*fargs, **kw):
fname = name
if name is None:
fname = func.__name__
warnings.warn("%s" % fname, category=ExperimentalWarning,
stacklevel=2)
return func(*fargs, **kw)
return wrapper
return inner | [
"def",
"experimental",
"(",
"name",
"=",
"None",
")",
":",
"def",
"inner",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"fargs",
",",
"*",
"*",
"kw",
")",
":",
"fname",
"=",
"name",
"if",
... | A simple decorator to mark functions and methods as experimental. | [
"A",
"simple",
"decorator",
"to",
"mark",
"functions",
"and",
"methods",
"as",
"experimental",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/compat.py#L46-L58 | train | 212,734 |
msmbuilder/msmbuilder | msmbuilder/cluster/__init__.py | _replace_labels | def _replace_labels(doc):
"""Really hacky find-and-replace method that modifies one of the sklearn
docstrings to change the semantics of labels_ for the subclasses"""
lines = doc.splitlines()
labelstart, labelend = None, None
foundattributes = False
for i, line in enumerate(lines):
stripped = line.strip()
if stripped == 'Attributes':
foundattributes = True
if foundattributes and not labelstart and stripped.startswith('labels_'):
labelstart = len('\n'.join(lines[:i])) + 1
if labelstart and not labelend and stripped == '':
labelend = len('\n'.join(lines[:i + 1]))
if labelstart is None or labelend is None:
return doc
replace = '\n'.join([
' labels_ : list of arrays, each of shape [sequence_length, ]',
' The label of each point is an integer in [0, n_clusters).',
'',
])
return doc[:labelstart] + replace + doc[labelend:] | python | def _replace_labels(doc):
"""Really hacky find-and-replace method that modifies one of the sklearn
docstrings to change the semantics of labels_ for the subclasses"""
lines = doc.splitlines()
labelstart, labelend = None, None
foundattributes = False
for i, line in enumerate(lines):
stripped = line.strip()
if stripped == 'Attributes':
foundattributes = True
if foundattributes and not labelstart and stripped.startswith('labels_'):
labelstart = len('\n'.join(lines[:i])) + 1
if labelstart and not labelend and stripped == '':
labelend = len('\n'.join(lines[:i + 1]))
if labelstart is None or labelend is None:
return doc
replace = '\n'.join([
' labels_ : list of arrays, each of shape [sequence_length, ]',
' The label of each point is an integer in [0, n_clusters).',
'',
])
return doc[:labelstart] + replace + doc[labelend:] | [
"def",
"_replace_labels",
"(",
"doc",
")",
":",
"lines",
"=",
"doc",
".",
"splitlines",
"(",
")",
"labelstart",
",",
"labelend",
"=",
"None",
",",
"None",
"foundattributes",
"=",
"False",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
"... | Really hacky find-and-replace method that modifies one of the sklearn
docstrings to change the semantics of labels_ for the subclasses | [
"Really",
"hacky",
"find",
"-",
"and",
"-",
"replace",
"method",
"that",
"modifies",
"one",
"of",
"the",
"sklearn",
"docstrings",
"to",
"change",
"the",
"semantics",
"of",
"labels_",
"for",
"the",
"subclasses"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/__init__.py#L37-L60 | train | 212,735 |
msmbuilder/msmbuilder | msmbuilder/utils/io.py | dump | def dump(value, filename, compress=None, cache_size=None):
"""Save an arbitrary python object using pickle.
Parameters
-----------
value : any Python object
The object to store to disk using pickle.
filename : string
The name of the file in which it is to be stored
compress : None
No longer used
cache_size : positive number, optional
No longer used
See Also
--------
load : corresponding loader
"""
if compress is not None or cache_size is not None:
warnings.warn("compress and cache_size are no longer valid options")
with open(filename, 'wb') as f:
pickle.dump(value, f) | python | def dump(value, filename, compress=None, cache_size=None):
"""Save an arbitrary python object using pickle.
Parameters
-----------
value : any Python object
The object to store to disk using pickle.
filename : string
The name of the file in which it is to be stored
compress : None
No longer used
cache_size : positive number, optional
No longer used
See Also
--------
load : corresponding loader
"""
if compress is not None or cache_size is not None:
warnings.warn("compress and cache_size are no longer valid options")
with open(filename, 'wb') as f:
pickle.dump(value, f) | [
"def",
"dump",
"(",
"value",
",",
"filename",
",",
"compress",
"=",
"None",
",",
"cache_size",
"=",
"None",
")",
":",
"if",
"compress",
"is",
"not",
"None",
"or",
"cache_size",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"compress and cache... | Save an arbitrary python object using pickle.
Parameters
-----------
value : any Python object
The object to store to disk using pickle.
filename : string
The name of the file in which it is to be stored
compress : None
No longer used
cache_size : positive number, optional
No longer used
See Also
--------
load : corresponding loader | [
"Save",
"an",
"arbitrary",
"python",
"object",
"using",
"pickle",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/io.py#L24-L46 | train | 212,736 |
msmbuilder/msmbuilder | msmbuilder/utils/io.py | load | def load(filename):
"""Load an object that has been saved with dump.
We try to open it using the pickle protocol. As a fallback, we
use joblib.load. Joblib was the default prior to msmbuilder v3.2
Parameters
----------
filename : string
The name of the file to load.
"""
try:
with open(filename, 'rb') as f:
return pickle.load(f)
except Exception as e1:
try:
return jl_load(filename)
except Exception as e2:
raise IOError(
"Unable to load {} using the pickle or joblib protocol.\n"
"Pickle: {}\n"
"Joblib: {}".format(filename, e1, e2)
) | python | def load(filename):
"""Load an object that has been saved with dump.
We try to open it using the pickle protocol. As a fallback, we
use joblib.load. Joblib was the default prior to msmbuilder v3.2
Parameters
----------
filename : string
The name of the file to load.
"""
try:
with open(filename, 'rb') as f:
return pickle.load(f)
except Exception as e1:
try:
return jl_load(filename)
except Exception as e2:
raise IOError(
"Unable to load {} using the pickle or joblib protocol.\n"
"Pickle: {}\n"
"Joblib: {}".format(filename, e1, e2)
) | [
"def",
"load",
"(",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"pickle",
".",
"load",
"(",
"f",
")",
"except",
"Exception",
"as",
"e1",
":",
"try",
":",
"return",
"jl_load",
"(",
... | Load an object that has been saved with dump.
We try to open it using the pickle protocol. As a fallback, we
use joblib.load. Joblib was the default prior to msmbuilder v3.2
Parameters
----------
filename : string
The name of the file to load. | [
"Load",
"an",
"object",
"that",
"has",
"been",
"saved",
"with",
"dump",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/io.py#L49-L71 | train | 212,737 |
msmbuilder/msmbuilder | msmbuilder/utils/io.py | verbosedump | def verbosedump(value, fn, compress=None):
"""Verbose wrapper around dump"""
print('Saving "%s"... (%s)' % (fn, type(value)))
dump(value, fn, compress=compress) | python | def verbosedump(value, fn, compress=None):
"""Verbose wrapper around dump"""
print('Saving "%s"... (%s)' % (fn, type(value)))
dump(value, fn, compress=compress) | [
"def",
"verbosedump",
"(",
"value",
",",
"fn",
",",
"compress",
"=",
"None",
")",
":",
"print",
"(",
"'Saving \"%s\"... (%s)'",
"%",
"(",
"fn",
",",
"type",
"(",
"value",
")",
")",
")",
"dump",
"(",
"value",
",",
"fn",
",",
"compress",
"=",
"compress... | Verbose wrapper around dump | [
"Verbose",
"wrapper",
"around",
"dump"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/io.py#L74-L77 | train | 212,738 |
msmbuilder/msmbuilder | msmbuilder/tpt/flux.py | net_fluxes | def net_fluxes(sources, sinks, msm, for_committors=None):
"""
Computes the transition path theory net flux matrix.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateModel
MSM fit to data.
for_committors : np.ndarray, optional
The forward committors associated with `sources`, `sinks`, and `tprob`.
If not provided, is calculated from scratch. If provided, `sources`
and `sinks` are ignored.
Returns
-------
net_flux : np.ndarray
The net flux matrix
See Also
--------
fluxes
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
flux_matrix = fluxes(sources, sinks, msm, for_committors=for_committors)
net_flux = flux_matrix - flux_matrix.T
net_flux[np.where(net_flux < 0)] = 0.0
return net_flux | python | def net_fluxes(sources, sinks, msm, for_committors=None):
"""
Computes the transition path theory net flux matrix.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateModel
MSM fit to data.
for_committors : np.ndarray, optional
The forward committors associated with `sources`, `sinks`, and `tprob`.
If not provided, is calculated from scratch. If provided, `sources`
and `sinks` are ignored.
Returns
-------
net_flux : np.ndarray
The net flux matrix
See Also
--------
fluxes
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
flux_matrix = fluxes(sources, sinks, msm, for_committors=for_committors)
net_flux = flux_matrix - flux_matrix.T
net_flux[np.where(net_flux < 0)] = 0.0
return net_flux | [
"def",
"net_fluxes",
"(",
"sources",
",",
"sinks",
",",
"msm",
",",
"for_committors",
"=",
"None",
")",
":",
"flux_matrix",
"=",
"fluxes",
"(",
"sources",
",",
"sinks",
",",
"msm",
",",
"for_committors",
"=",
"for_committors",
")",
"net_flux",
"=",
"flux_m... | Computes the transition path theory net flux matrix.
Parameters
----------
sources : array_like, int
The set of unfolded/reactant states.
sinks : array_like, int
The set of folded/product states.
msm : msmbuilder.MarkovStateModel
MSM fit to data.
for_committors : np.ndarray, optional
The forward committors associated with `sources`, `sinks`, and `tprob`.
If not provided, is calculated from scratch. If provided, `sources`
and `sinks` are ignored.
Returns
-------
net_flux : np.ndarray
The net flux matrix
See Also
--------
fluxes
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. | [
"Computes",
"the",
"transition",
"path",
"theory",
"net",
"flux",
"matrix",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/flux.py#L96-L143 | train | 212,739 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | featurize_all | def featurize_all(filenames, featurizer, topology, chunk=1000, stride=1):
"""Load and featurize many trajectory files.
Parameters
----------
filenames : list of strings
List of paths to MD trajectory files
featurizer : Featurizer
The featurizer to be invoked on each trajectory trajectory as
it is loaded
topology : str, Topology, Trajectory
Topology or path to a topology file, used to load trajectories with
MDTraj
chunk : {int, None}
If chunk is an int, load the trajectories up in chunks using
md.iterload for better memory efficiency (less trajectory data needs
to be in memory at once)
stride : int, default=1
Only read every stride-th frame.
Returns
-------
data : np.ndarray, shape=(total_length_of_all_trajectories, n_features)
indices : np.ndarray, shape=(total_length_of_all_trajectories)
fns : np.ndarray shape=(total_length_of_all_trajectories)
These three arrays all share the same indexing, such that data[i] is
the featurized version of indices[i]-th frame in the MD trajectory
with filename fns[i].
"""
data = []
indices = []
fns = []
for file in filenames:
kwargs = {} if file.endswith('.h5') else {'top': topology}
count = 0
for t in md.iterload(file, chunk=chunk, stride=stride, **kwargs):
x = featurizer.partial_transform(t)
n_frames = len(x)
data.append(x)
indices.append(count + (stride * np.arange(n_frames)))
fns.extend([file] * n_frames)
count += (stride * n_frames)
if len(data) == 0:
raise ValueError("None!")
return np.concatenate(data), np.concatenate(indices), np.array(fns) | python | def featurize_all(filenames, featurizer, topology, chunk=1000, stride=1):
"""Load and featurize many trajectory files.
Parameters
----------
filenames : list of strings
List of paths to MD trajectory files
featurizer : Featurizer
The featurizer to be invoked on each trajectory trajectory as
it is loaded
topology : str, Topology, Trajectory
Topology or path to a topology file, used to load trajectories with
MDTraj
chunk : {int, None}
If chunk is an int, load the trajectories up in chunks using
md.iterload for better memory efficiency (less trajectory data needs
to be in memory at once)
stride : int, default=1
Only read every stride-th frame.
Returns
-------
data : np.ndarray, shape=(total_length_of_all_trajectories, n_features)
indices : np.ndarray, shape=(total_length_of_all_trajectories)
fns : np.ndarray shape=(total_length_of_all_trajectories)
These three arrays all share the same indexing, such that data[i] is
the featurized version of indices[i]-th frame in the MD trajectory
with filename fns[i].
"""
data = []
indices = []
fns = []
for file in filenames:
kwargs = {} if file.endswith('.h5') else {'top': topology}
count = 0
for t in md.iterload(file, chunk=chunk, stride=stride, **kwargs):
x = featurizer.partial_transform(t)
n_frames = len(x)
data.append(x)
indices.append(count + (stride * np.arange(n_frames)))
fns.extend([file] * n_frames)
count += (stride * n_frames)
if len(data) == 0:
raise ValueError("None!")
return np.concatenate(data), np.concatenate(indices), np.array(fns) | [
"def",
"featurize_all",
"(",
"filenames",
",",
"featurizer",
",",
"topology",
",",
"chunk",
"=",
"1000",
",",
"stride",
"=",
"1",
")",
":",
"data",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"fns",
"=",
"[",
"]",
"for",
"file",
"in",
"filenames",
":"... | Load and featurize many trajectory files.
Parameters
----------
filenames : list of strings
List of paths to MD trajectory files
featurizer : Featurizer
The featurizer to be invoked on each trajectory trajectory as
it is loaded
topology : str, Topology, Trajectory
Topology or path to a topology file, used to load trajectories with
MDTraj
chunk : {int, None}
If chunk is an int, load the trajectories up in chunks using
md.iterload for better memory efficiency (less trajectory data needs
to be in memory at once)
stride : int, default=1
Only read every stride-th frame.
Returns
-------
data : np.ndarray, shape=(total_length_of_all_trajectories, n_features)
indices : np.ndarray, shape=(total_length_of_all_trajectories)
fns : np.ndarray shape=(total_length_of_all_trajectories)
These three arrays all share the same indexing, such that data[i] is
the featurized version of indices[i]-th frame in the MD trajectory
with filename fns[i]. | [
"Load",
"and",
"featurize",
"many",
"trajectory",
"files",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L54-L101 | train | 212,740 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | Featurizer.describe_features | def describe_features(self, traj):
"""Generic method for describing features.
Parameters
----------
traj : mdtraj.Trajectory
Trajectory to use
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Featurizer name
- featuregroup: Other information
Notes
-------
Method resorts to returning N/A for everything if describe_features in not
implemented in the sub_class
"""
n_f = self.partial_transform(traj).shape[1]
zippy=zip(itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat(("N/A","N/A","N/A","N/A"), n_f))
return dict_maker(zippy) | python | def describe_features(self, traj):
"""Generic method for describing features.
Parameters
----------
traj : mdtraj.Trajectory
Trajectory to use
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Featurizer name
- featuregroup: Other information
Notes
-------
Method resorts to returning N/A for everything if describe_features in not
implemented in the sub_class
"""
n_f = self.partial_transform(traj).shape[1]
zippy=zip(itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat(("N/A","N/A","N/A","N/A"), n_f))
return dict_maker(zippy) | [
"def",
"describe_features",
"(",
"self",
",",
"traj",
")",
":",
"n_f",
"=",
"self",
".",
"partial_transform",
"(",
"traj",
")",
".",
"shape",
"[",
"1",
"]",
"zippy",
"=",
"zip",
"(",
"itertools",
".",
"repeat",
"(",
"\"N/A\"",
",",
"n_f",
")",
",",
... | Generic method for describing features.
Parameters
----------
traj : mdtraj.Trajectory
Trajectory to use
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Featurizer name
- featuregroup: Other information
Notes
-------
Method resorts to returning N/A for everything if describe_features in not
implemented in the sub_class | [
"Generic",
"method",
"for",
"describing",
"features",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L163-L195 | train | 212,741 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | LandMarkRMSDFeaturizer.describe_features | def describe_features(self, traj):
"""Return a list of dictionaries describing the LandmarkRMSD features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Alpha Angle
- featuregroup: the type of dihedral angle and whether sin or
cos has been applied.
"""
feature_descs = []
# fill in the atom indices using just the first frame
self.partial_transform(traj[0])
top = traj.topology
aind_tuples = [self.atom_indices for _ in range(self.sliced_reference_traj.n_frames)]
zippy = zippy_maker(aind_tuples, top)
zippy = itertools.product(["LandMarkFeaturizer"], ["RMSD"], [self.sigma], zippy)
feature_descs.extend(dict_maker(zippy))
return feature_descs | python | def describe_features(self, traj):
"""Return a list of dictionaries describing the LandmarkRMSD features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Alpha Angle
- featuregroup: the type of dihedral angle and whether sin or
cos has been applied.
"""
feature_descs = []
# fill in the atom indices using just the first frame
self.partial_transform(traj[0])
top = traj.topology
aind_tuples = [self.atom_indices for _ in range(self.sliced_reference_traj.n_frames)]
zippy = zippy_maker(aind_tuples, top)
zippy = itertools.product(["LandMarkFeaturizer"], ["RMSD"], [self.sigma], zippy)
feature_descs.extend(dict_maker(zippy))
return feature_descs | [
"def",
"describe_features",
"(",
"self",
",",
"traj",
")",
":",
"feature_descs",
"=",
"[",
"]",
"# fill in the atom indices using just the first frame",
"self",
".",
"partial_transform",
"(",
"traj",
"[",
"0",
"]",
")",
"top",
"=",
"traj",
".",
"topology",
"aind... | Return a list of dictionaries describing the LandmarkRMSD features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each feature
- resnames: unique names of residues
- atominds: the four atom indicies
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: Alpha Angle
- featuregroup: the type of dihedral angle and whether sin or
cos has been applied. | [
"Return",
"a",
"list",
"of",
"dictionaries",
"describing",
"the",
"LandmarkRMSD",
"features",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L352-L386 | train | 212,742 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | AtomPairsFeaturizer.partial_transform | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via pairwise
atom-atom distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
d = md.geometry.compute_distances(traj, self.pair_indices,
periodic=self.periodic)
return d ** self.exponent | python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via pairwise
atom-atom distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
d = md.geometry.compute_distances(traj, self.pair_indices,
periodic=self.periodic)
return d ** self.exponent | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"d",
"=",
"md",
".",
"geometry",
".",
"compute_distances",
"(",
"traj",
",",
"self",
".",
"pair_indices",
",",
"periodic",
"=",
"self",
".",
"periodic",
")",
"return",
"d",
"**",
"self",
"... | Featurize an MD trajectory into a vector space via pairwise
atom-atom distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"via",
"pairwise",
"atom",
"-",
"atom",
"distances"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L416-L439 | train | 212,743 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | AtomPairsFeaturizer.describe_features | def describe_features(self, traj):
"""Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each dihedral
- resnames: unique names of residues
- atominds: the two atom inds
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: AtomPairsFeaturizer
- featuregroup: Distance.
- other info : Value of the exponent
"""
feature_descs = []
top = traj.topology
residue_indices = [[top.atom(i[0]).residue.index, top.atom(i[1]).residue.index] \
for i in self.atom_indices]
aind = []
resseqs = []
resnames = []
for ind,resid_ids in enumerate(residue_indices):
aind += [[i for i in self.atom_indices[ind]]]
resseqs += [[top.residue(ri).resSeq for ri in resid_ids]]
resnames += [[top.residue(ri).name for ri in resid_ids]]
zippy = itertools.product(["AtomPairs"], ["Distance"],
["Exponent {}".format(self.exponent)],
zip(aind, resseqs, residue_indices, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs | python | def describe_features(self, traj):
"""Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each dihedral
- resnames: unique names of residues
- atominds: the two atom inds
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: AtomPairsFeaturizer
- featuregroup: Distance.
- other info : Value of the exponent
"""
feature_descs = []
top = traj.topology
residue_indices = [[top.atom(i[0]).residue.index, top.atom(i[1]).residue.index] \
for i in self.atom_indices]
aind = []
resseqs = []
resnames = []
for ind,resid_ids in enumerate(residue_indices):
aind += [[i for i in self.atom_indices[ind]]]
resseqs += [[top.residue(ri).resSeq for ri in resid_ids]]
resnames += [[top.residue(ri).name for ri in resid_ids]]
zippy = itertools.product(["AtomPairs"], ["Distance"],
["Exponent {}".format(self.exponent)],
zip(aind, resseqs, residue_indices, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs | [
"def",
"describe_features",
"(",
"self",
",",
"traj",
")",
":",
"feature_descs",
"=",
"[",
"]",
"top",
"=",
"traj",
".",
"topology",
"residue_indices",
"=",
"[",
"[",
"top",
".",
"atom",
"(",
"i",
"[",
"0",
"]",
")",
".",
"residue",
".",
"index",
"... | Return a list of dictionaries describing the atom pair features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each dihedral
- resnames: unique names of residues
- atominds: the two atom inds
- resseqs: unique residue sequence ids (not necessarily
0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: AtomPairsFeaturizer
- featuregroup: Distance.
- other info : Value of the exponent | [
"Return",
"a",
"list",
"of",
"dictionaries",
"describing",
"the",
"atom",
"pair",
"features",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L441-L482 | train | 212,744 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | VonMisesFeaturizer.partial_transform | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of soft-bins over dihdral angle space.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
x = []
for a in self.types:
func = getattr(md, 'compute_%s' % a)
_, y = func(traj)
res = vm.pdf(y[..., np.newaxis],
loc=self.loc, kappa=self.kappa)
#we reshape the results using a Fortran-like index order,
#so that it goes over the columns first. This should put the results
#phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1)
x.extend(np.reshape(res, (1, -1, self.n_bins*y.shape[1]), order='F'))
return np.hstack(x) | python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of soft-bins over dihdral angle space.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
x = []
for a in self.types:
func = getattr(md, 'compute_%s' % a)
_, y = func(traj)
res = vm.pdf(y[..., np.newaxis],
loc=self.loc, kappa=self.kappa)
#we reshape the results using a Fortran-like index order,
#so that it goes over the columns first. This should put the results
#phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1)
x.extend(np.reshape(res, (1, -1, self.n_bins*y.shape[1]), order='F'))
return np.hstack(x) | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"x",
"=",
"[",
"]",
"for",
"a",
"in",
"self",
".",
"types",
":",
"func",
"=",
"getattr",
"(",
"md",
",",
"'compute_%s'",
"%",
"a",
")",
"_",
",",
"y",
"=",
"func",
"(",
"traj",
")"... | Featurize an MD trajectory into a vector space via calculation
of soft-bins over dihdral angle space.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"via",
"calculation",
"of",
"soft",
"-",
"bins",
"over",
"dihdral",
"angle",
"space",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L768-L799 | train | 212,745 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | SASAFeaturizer.describe_features | def describe_features(self, traj):
"""Return a list of dictionaries describing the SASA features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each SASA feature
- resnames: names of residues
- atominds: atom index or atom indices in mode="residue"
- resseqs: residue ids (not necessarily 0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: SASA
- featuregroup: atom or residue
"""
feature_descs = []
_, mapping = md.geometry.sasa.shrake_rupley(traj, mode=self.mode, get_mapping=True)
top = traj.topology
if self.mode == "residue":
resids = np.unique(mapping)
resseqs = [top.residue(ri).resSeq for ri in resids]
resnames = [top.residue(ri).name for ri in resids]
atoms_in_res = [res.atoms for res in top.residues]
aind_tuples = []
# For each resdiue...
for i,x in enumerate(atoms_in_res):
# For each atom in the residues, append it's index
aind_tuples.append([atom.index for atom in x])
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(aind_tuples, resseqs, resids, resnames))
else:
resids = [top.atom(ai).residue.index for ai in mapping]
resseqs = [top.atom(ai).residue.resSeq for ai in mapping]
resnames = [top.atom(ai).residue.name for ai in mapping]
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(mapping, resseqs, resids, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs | python | def describe_features(self, traj):
"""Return a list of dictionaries describing the SASA features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each SASA feature
- resnames: names of residues
- atominds: atom index or atom indices in mode="residue"
- resseqs: residue ids (not necessarily 0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: SASA
- featuregroup: atom or residue
"""
feature_descs = []
_, mapping = md.geometry.sasa.shrake_rupley(traj, mode=self.mode, get_mapping=True)
top = traj.topology
if self.mode == "residue":
resids = np.unique(mapping)
resseqs = [top.residue(ri).resSeq for ri in resids]
resnames = [top.residue(ri).name for ri in resids]
atoms_in_res = [res.atoms for res in top.residues]
aind_tuples = []
# For each resdiue...
for i,x in enumerate(atoms_in_res):
# For each atom in the residues, append it's index
aind_tuples.append([atom.index for atom in x])
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(aind_tuples, resseqs, resids, resnames))
else:
resids = [top.atom(ai).residue.index for ai in mapping]
resseqs = [top.atom(ai).residue.resSeq for ai in mapping]
resnames = [top.atom(ai).residue.name for ai in mapping]
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(mapping, resseqs, resids, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs | [
"def",
"describe_features",
"(",
"self",
",",
"traj",
")",
":",
"feature_descs",
"=",
"[",
"]",
"_",
",",
"mapping",
"=",
"md",
".",
"geometry",
".",
"sasa",
".",
"shrake_rupley",
"(",
"traj",
",",
"mode",
"=",
"self",
".",
"mode",
",",
"get_mapping",
... | Return a list of dictionaries describing the SASA features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following information
about the atoms participating in each SASA feature
- resnames: names of residues
- atominds: atom index or atom indices in mode="residue"
- resseqs: residue ids (not necessarily 0-indexed)
- resids: unique residue ids (0-indexed)
- featurizer: SASA
- featuregroup: atom or residue | [
"Return",
"a",
"list",
"of",
"dictionaries",
"describing",
"the",
"SASA",
"features",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L1086-L1130 | train | 212,746 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | GaussianSolventFeaturizer.partial_transform | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of solvent fingerprints
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
# The result vector
fingerprints = np.zeros((traj.n_frames, self.n_features))
atom_pairs = np.zeros((len(self.solvent_indices), 2))
sigma = self.sigma
for i, solute_i in enumerate(self.solute_indices):
# For each solute atom, calculate distance to all solvent
# molecules
atom_pairs[:, 0] = solute_i
atom_pairs[:, 1] = self.solvent_indices
distances = md.compute_distances(traj, atom_pairs, periodic=True)
distances = np.exp(-distances / (2 * sigma * sigma))
# Sum over water atoms for all frames
fingerprints[:, i] = np.sum(distances, axis=1)
return fingerprints | python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of solvent fingerprints
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
# The result vector
fingerprints = np.zeros((traj.n_frames, self.n_features))
atom_pairs = np.zeros((len(self.solvent_indices), 2))
sigma = self.sigma
for i, solute_i in enumerate(self.solute_indices):
# For each solute atom, calculate distance to all solvent
# molecules
atom_pairs[:, 0] = solute_i
atom_pairs[:, 1] = self.solvent_indices
distances = md.compute_distances(traj, atom_pairs, periodic=True)
distances = np.exp(-distances / (2 * sigma * sigma))
# Sum over water atoms for all frames
fingerprints[:, i] = np.sum(distances, axis=1)
return fingerprints | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"# The result vector",
"fingerprints",
"=",
"np",
".",
"zeros",
"(",
"(",
"traj",
".",
"n_frames",
",",
"self",
".",
"n_features",
")",
")",
"atom_pairs",
"=",
"np",
".",
"zeros",
"(",
"(",
... | Featurize an MD trajectory into a vector space via calculation
of solvent fingerprints
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"via",
"calculation",
"of",
"solvent",
"fingerprints"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L1440-L1478 | train | 212,747 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | RawPositionsFeaturizer.partial_transform | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space with the raw
cartesian coordinates.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
Notes
-----
If you requested superposition (gave `ref_traj` in __init__) the
input trajectory will be modified.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
# Optionally take only certain atoms
if self.atom_indices is not None:
p_traj = traj.atom_slice(self.atom_indices)
else:
p_traj = traj
# Optionally superpose to a reference trajectory.
if self.ref_traj is not None:
p_traj.superpose(self.ref_traj, parallel=False)
# Get the positions and reshape.
value = p_traj.xyz.reshape(len(p_traj), -1)
return value | python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space with the raw
cartesian coordinates.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
Notes
-----
If you requested superposition (gave `ref_traj` in __init__) the
input trajectory will be modified.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories
"""
# Optionally take only certain atoms
if self.atom_indices is not None:
p_traj = traj.atom_slice(self.atom_indices)
else:
p_traj = traj
# Optionally superpose to a reference trajectory.
if self.ref_traj is not None:
p_traj.superpose(self.ref_traj, parallel=False)
# Get the positions and reshape.
value = p_traj.xyz.reshape(len(p_traj), -1)
return value | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"# Optionally take only certain atoms",
"if",
"self",
".",
"atom_indices",
"is",
"not",
"None",
":",
"p_traj",
"=",
"traj",
".",
"atom_slice",
"(",
"self",
".",
"atom_indices",
")",
"else",
":",
... | Featurize an MD trajectory into a vector space with the raw
cartesian coordinates.
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, dtype=float, shape=(n_samples, n_features)
A featurized trajectory is a 2D array of shape
`(length_of_trajectory x n_features)` where each `features[i]`
vector is computed by applying the featurization function
to the `i`th snapshot of the input trajectory.
Notes
-----
If you requested superposition (gave `ref_traj` in __init__) the
input trajectory will be modified.
See Also
--------
transform : simultaneously featurize a collection of MD trajectories | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"with",
"the",
"raw",
"cartesian",
"coordinates",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L1508-L1546 | train | 212,748 |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | Slicer.partial_transform | def partial_transform(self, traj):
"""Slice a single input array along to select a subset of features.
Parameters
----------
traj : np.ndarray, shape=(n_samples, n_features)
A sample to slice.
Returns
-------
sliced_traj : np.ndarray shape=(n_samples, n_feature_subset)
Slice of traj
"""
if self.index is not None:
return traj[:, self.index]
else:
return traj[:, :self.first] | python | def partial_transform(self, traj):
"""Slice a single input array along to select a subset of features.
Parameters
----------
traj : np.ndarray, shape=(n_samples, n_features)
A sample to slice.
Returns
-------
sliced_traj : np.ndarray shape=(n_samples, n_feature_subset)
Slice of traj
"""
if self.index is not None:
return traj[:, self.index]
else:
return traj[:, :self.first] | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"if",
"self",
".",
"index",
"is",
"not",
"None",
":",
"return",
"traj",
"[",
":",
",",
"self",
".",
"index",
"]",
"else",
":",
"return",
"traj",
"[",
":",
",",
":",
"self",
".",
"fir... | Slice a single input array along to select a subset of features.
Parameters
----------
traj : np.ndarray, shape=(n_samples, n_features)
A sample to slice.
Returns
-------
sliced_traj : np.ndarray shape=(n_samples, n_feature_subset)
Slice of traj | [
"Slice",
"a",
"single",
"input",
"array",
"along",
"to",
"select",
"a",
"subset",
"of",
"features",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L1627-L1643 | train | 212,749 |
msmbuilder/msmbuilder | msmbuilder/utils/param_sweep.py | param_sweep | def param_sweep(model, sequences, param_grid, n_jobs=1, verbose=0):
"""Fit a series of models over a range of parameters.
Parameters
----------
model : msmbuilder.BaseEstimator
An *instance* of an estimator to be used
to fit data.
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
param_grid : dict or sklearn.grid_search.ParameterGrid
Parameter grid to specify models to fit. See
sklearn.grid_search.ParameterGrid for an explanation
n_jobs : int, optional
Number of jobs to run in parallel using joblib.Parallel
Returns
-------
models : list
List of models fit to the data according to
param_grid
"""
if isinstance(param_grid, dict):
param_grid = ParameterGrid(param_grid)
elif not isinstance(param_grid, ParameterGrid):
raise ValueError("param_grid must be a dict or ParamaterGrid instance")
# iterable with (model, sequence) as items
iter_args = ((clone(model).set_params(**params), sequences)
for params in param_grid)
models = Parallel(n_jobs=n_jobs, verbose=verbose)(
delayed(_param_sweep_helper)(args) for args in iter_args)
return models | python | def param_sweep(model, sequences, param_grid, n_jobs=1, verbose=0):
"""Fit a series of models over a range of parameters.
Parameters
----------
model : msmbuilder.BaseEstimator
An *instance* of an estimator to be used
to fit data.
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
param_grid : dict or sklearn.grid_search.ParameterGrid
Parameter grid to specify models to fit. See
sklearn.grid_search.ParameterGrid for an explanation
n_jobs : int, optional
Number of jobs to run in parallel using joblib.Parallel
Returns
-------
models : list
List of models fit to the data according to
param_grid
"""
if isinstance(param_grid, dict):
param_grid = ParameterGrid(param_grid)
elif not isinstance(param_grid, ParameterGrid):
raise ValueError("param_grid must be a dict or ParamaterGrid instance")
# iterable with (model, sequence) as items
iter_args = ((clone(model).set_params(**params), sequences)
for params in param_grid)
models = Parallel(n_jobs=n_jobs, verbose=verbose)(
delayed(_param_sweep_helper)(args) for args in iter_args)
return models | [
"def",
"param_sweep",
"(",
"model",
",",
"sequences",
",",
"param_grid",
",",
"n_jobs",
"=",
"1",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"param_grid",
",",
"dict",
")",
":",
"param_grid",
"=",
"ParameterGrid",
"(",
"param_grid",
")"... | Fit a series of models over a range of parameters.
Parameters
----------
model : msmbuilder.BaseEstimator
An *instance* of an estimator to be used
to fit data.
sequences : list of array-like
List of sequences, or a single sequence. Each
sequence should be a 1D iterable of state
labels. Labels can be integers, strings, or
other orderable objects.
param_grid : dict or sklearn.grid_search.ParameterGrid
Parameter grid to specify models to fit. See
sklearn.grid_search.ParameterGrid for an explanation
n_jobs : int, optional
Number of jobs to run in parallel using joblib.Parallel
Returns
-------
models : list
List of models fit to the data according to
param_grid | [
"Fit",
"a",
"series",
"of",
"models",
"over",
"a",
"range",
"of",
"parameters",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/param_sweep.py#L13-L51 | train | 212,750 |
msmbuilder/msmbuilder | msmbuilder/dataset.py | dataset | def dataset(path, mode='r', fmt=None, verbose=False, **kwargs):
"""Open a dataset object
MSMBuilder supports several dataset 'formats' for storing
lists of sequences on disk.
This function can also be used as a context manager.
Parameters
----------
path : str
The path to the dataset on the filesystem
mode : {'r', 'w', 'a'}
Open a dataset for reading, writing, or appending. Note that
some formats only support a subset of these modes.
fmt : {'dir-npy', 'hdf5', 'mdtraj'}
The format of the data on disk
``dir-npy``
A directory of binary numpy files, one file per sequence
``hdf5``
A single hdf5 file with each sequence as an array node
``mdtraj``
A read-only set of trajectory files that can be loaded
with mdtraj
verbose : bool
Whether to print information about the dataset
"""
if mode == 'r' and fmt is None:
fmt = _guess_format(path)
elif mode in 'wa' and fmt is None:
raise ValueError('mode="%s", but no fmt. fmt=%s' % (mode, fmt))
if fmt == 'dir-npy':
return NumpyDirDataset(path, mode=mode, verbose=verbose)
elif fmt == 'mdtraj':
return MDTrajDataset(path, mode=mode, verbose=verbose, **kwargs)
elif fmt == 'hdf5':
return HDF5Dataset(path, mode=mode, verbose=verbose)
elif fmt.endswith("-union"):
raise ValueError("union datasets have been removed. "
"Please use msmbuilder.featurizer.FeatureUnion")
else:
raise NotImplementedError("Unknown format fmt='%s'" % fmt) | python | def dataset(path, mode='r', fmt=None, verbose=False, **kwargs):
"""Open a dataset object
MSMBuilder supports several dataset 'formats' for storing
lists of sequences on disk.
This function can also be used as a context manager.
Parameters
----------
path : str
The path to the dataset on the filesystem
mode : {'r', 'w', 'a'}
Open a dataset for reading, writing, or appending. Note that
some formats only support a subset of these modes.
fmt : {'dir-npy', 'hdf5', 'mdtraj'}
The format of the data on disk
``dir-npy``
A directory of binary numpy files, one file per sequence
``hdf5``
A single hdf5 file with each sequence as an array node
``mdtraj``
A read-only set of trajectory files that can be loaded
with mdtraj
verbose : bool
Whether to print information about the dataset
"""
if mode == 'r' and fmt is None:
fmt = _guess_format(path)
elif mode in 'wa' and fmt is None:
raise ValueError('mode="%s", but no fmt. fmt=%s' % (mode, fmt))
if fmt == 'dir-npy':
return NumpyDirDataset(path, mode=mode, verbose=verbose)
elif fmt == 'mdtraj':
return MDTrajDataset(path, mode=mode, verbose=verbose, **kwargs)
elif fmt == 'hdf5':
return HDF5Dataset(path, mode=mode, verbose=verbose)
elif fmt.endswith("-union"):
raise ValueError("union datasets have been removed. "
"Please use msmbuilder.featurizer.FeatureUnion")
else:
raise NotImplementedError("Unknown format fmt='%s'" % fmt) | [
"def",
"dataset",
"(",
"path",
",",
"mode",
"=",
"'r'",
",",
"fmt",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"==",
"'r'",
"and",
"fmt",
"is",
"None",
":",
"fmt",
"=",
"_guess_format",
"(",
"path"... | Open a dataset object
MSMBuilder supports several dataset 'formats' for storing
lists of sequences on disk.
This function can also be used as a context manager.
Parameters
----------
path : str
The path to the dataset on the filesystem
mode : {'r', 'w', 'a'}
Open a dataset for reading, writing, or appending. Note that
some formats only support a subset of these modes.
fmt : {'dir-npy', 'hdf5', 'mdtraj'}
The format of the data on disk
``dir-npy``
A directory of binary numpy files, one file per sequence
``hdf5``
A single hdf5 file with each sequence as an array node
``mdtraj``
A read-only set of trajectory files that can be loaded
with mdtraj
verbose : bool
Whether to print information about the dataset | [
"Open",
"a",
"dataset",
"object"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/dataset.py#L34-L82 | train | 212,751 |
msmbuilder/msmbuilder | msmbuilder/dataset.py | _BaseDataset.transform_with | def transform_with(self, estimator, out_ds, fmt=None):
"""Call the partial_transform method of the estimator on this dataset
Parameters
----------
estimator : object with ``partial_fit`` method
This object will be used to transform this dataset into a new
dataset. The estimator should be fitted prior to calling
this method.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The tranformed dataset.
"""
if isinstance(out_ds, str):
out_ds = self.create_derived(out_ds, fmt=fmt)
elif isinstance(out_ds, _BaseDataset):
err = "Dataset must be opened in write mode."
assert out_ds.mode in ('w', 'a'), err
else:
err = "Please specify a dataset path or an existing dataset."
raise ValueError(err)
for key in self.keys():
out_ds[key] = estimator.partial_transform(self[key])
return out_ds | python | def transform_with(self, estimator, out_ds, fmt=None):
"""Call the partial_transform method of the estimator on this dataset
Parameters
----------
estimator : object with ``partial_fit`` method
This object will be used to transform this dataset into a new
dataset. The estimator should be fitted prior to calling
this method.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The tranformed dataset.
"""
if isinstance(out_ds, str):
out_ds = self.create_derived(out_ds, fmt=fmt)
elif isinstance(out_ds, _BaseDataset):
err = "Dataset must be opened in write mode."
assert out_ds.mode in ('w', 'a'), err
else:
err = "Please specify a dataset path or an existing dataset."
raise ValueError(err)
for key in self.keys():
out_ds[key] = estimator.partial_transform(self[key])
return out_ds | [
"def",
"transform_with",
"(",
"self",
",",
"estimator",
",",
"out_ds",
",",
"fmt",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"out_ds",
",",
"str",
")",
":",
"out_ds",
"=",
"self",
".",
"create_derived",
"(",
"out_ds",
",",
"fmt",
"=",
"fmt",
")... | Call the partial_transform method of the estimator on this dataset
Parameters
----------
estimator : object with ``partial_fit`` method
This object will be used to transform this dataset into a new
dataset. The estimator should be fitted prior to calling
this method.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The tranformed dataset. | [
"Call",
"the",
"partial_transform",
"method",
"of",
"the",
"estimator",
"on",
"this",
"dataset"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/dataset.py#L174-L204 | train | 212,752 |
msmbuilder/msmbuilder | msmbuilder/dataset.py | _BaseDataset.fit_transform_with | def fit_transform_with(self, estimator, out_ds, fmt=None):
"""Create a new dataset with the given estimator.
The estimator will be fit by this dataset, and then each trajectory
will be transformed by the estimator.
Parameters
----------
estimator : BaseEstimator
This object will be fit and used to transform this dataset
into a new dataset.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The transformed dataset.
Examples
--------
diheds = dataset("diheds")
tica = diheds.fit_transform_with(tICA(), 'tica')
kmeans = tica.fit_transform_with(KMeans(), 'kmeans')
msm = kmeans.fit_with(MarkovStateModel())
"""
self.fit_with(estimator)
return self.transform_with(estimator, out_ds, fmt=fmt) | python | def fit_transform_with(self, estimator, out_ds, fmt=None):
"""Create a new dataset with the given estimator.
The estimator will be fit by this dataset, and then each trajectory
will be transformed by the estimator.
Parameters
----------
estimator : BaseEstimator
This object will be fit and used to transform this dataset
into a new dataset.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The transformed dataset.
Examples
--------
diheds = dataset("diheds")
tica = diheds.fit_transform_with(tICA(), 'tica')
kmeans = tica.fit_transform_with(KMeans(), 'kmeans')
msm = kmeans.fit_with(MarkovStateModel())
"""
self.fit_with(estimator)
return self.transform_with(estimator, out_ds, fmt=fmt) | [
"def",
"fit_transform_with",
"(",
"self",
",",
"estimator",
",",
"out_ds",
",",
"fmt",
"=",
"None",
")",
":",
"self",
".",
"fit_with",
"(",
"estimator",
")",
"return",
"self",
".",
"transform_with",
"(",
"estimator",
",",
"out_ds",
",",
"fmt",
"=",
"fmt"... | Create a new dataset with the given estimator.
The estimator will be fit by this dataset, and then each trajectory
will be transformed by the estimator.
Parameters
----------
estimator : BaseEstimator
This object will be fit and used to transform this dataset
into a new dataset.
out_ds : str or Dataset
This dataset will be transformed and saved into out_ds. If
out_ds is a path, a new dataset will be created at that path.
fmt : str
The type of dataset to create if out_ds is a string.
Returns
-------
out_ds : Dataset
The transformed dataset.
Examples
--------
diheds = dataset("diheds")
tica = diheds.fit_transform_with(tICA(), 'tica')
kmeans = tica.fit_transform_with(KMeans(), 'kmeans')
msm = kmeans.fit_with(MarkovStateModel()) | [
"Create",
"a",
"new",
"dataset",
"with",
"the",
"given",
"estimator",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/dataset.py#L206-L236 | train | 212,753 |
msmbuilder/msmbuilder | msmbuilder/msm/validation/bootstrapmsm.py | _mapped_populations | def _mapped_populations(mdl1, mdl2):
"""
Method to get the populations for states in mdl 1
from populations inferred in mdl 2. Resorts to 0
if population is not present.
"""
return_vect = np.zeros(mdl1.n_states_)
for i in range(mdl1.n_states_):
try:
#there has to be a better way to do this
mdl1_unmapped = mdl1.inverse_transform([i])[0][0]
mdl2_mapped = mdl2.mapping_[mdl1_unmapped]
return_vect[i] = mdl2.populations_[mdl2_mapped]
except:
pass
return return_vect | python | def _mapped_populations(mdl1, mdl2):
"""
Method to get the populations for states in mdl 1
from populations inferred in mdl 2. Resorts to 0
if population is not present.
"""
return_vect = np.zeros(mdl1.n_states_)
for i in range(mdl1.n_states_):
try:
#there has to be a better way to do this
mdl1_unmapped = mdl1.inverse_transform([i])[0][0]
mdl2_mapped = mdl2.mapping_[mdl1_unmapped]
return_vect[i] = mdl2.populations_[mdl2_mapped]
except:
pass
return return_vect | [
"def",
"_mapped_populations",
"(",
"mdl1",
",",
"mdl2",
")",
":",
"return_vect",
"=",
"np",
".",
"zeros",
"(",
"mdl1",
".",
"n_states_",
")",
"for",
"i",
"in",
"range",
"(",
"mdl1",
".",
"n_states_",
")",
":",
"try",
":",
"#there has to be a better way to ... | Method to get the populations for states in mdl 1
from populations inferred in mdl 2. Resorts to 0
if population is not present. | [
"Method",
"to",
"get",
"the",
"populations",
"for",
"states",
"in",
"mdl",
"1",
"from",
"populations",
"inferred",
"in",
"mdl",
"2",
".",
"Resorts",
"to",
"0",
"if",
"population",
"is",
"not",
"present",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/validation/bootstrapmsm.py#L199-L214 | train | 212,754 |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | top_path | def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray, shape = [n_states, n_states]
Net flux of the MSM
Returns
-------
top_path : np.ndarray
Array corresponding to the top path between sources and
sinks. It is an array of states visited along the path.
flux : float
Flux traveling through this path -- this is equal to the
minimum flux over edges in the path.
See Also
--------
msmbuilder.tpt.paths : function for calculating many high
flux paths through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
sources = np.array(sources, dtype=np.int).reshape((-1,))
sinks = np.array(sinks, dtype=np.int).reshape((-1,))
n_states = net_flux.shape[0]
queue = list(sources)
# nodes to check (the "queue")
# going to use list.pop method so I can't keep it as an array
visited = np.zeros(n_states).astype(np.bool)
# have we already checked this node?
previous_node = np.ones(n_states).astype(np.int) * -1
# what node was found before finding this one
min_fluxes = np.ones(n_states) * -1 * np.inf
# what is the flux of the highest flux path
# from this node to the source set.
min_fluxes[sources] = np.inf
# source states are connected to the source
# so this distance is zero which means the flux is infinite
while len(queue) > 0: # iterate until there's nothing to check anymore
test_node = queue.pop(min_fluxes[queue].argmax())
# find the node in the queue that has the
# highest flux path to it from the source set
visited[test_node] = True
if np.all(visited[sinks]):
# if we've visited all of the sink states, then we just have to choose
# the path that goes to the sink state that is closest to the source
break
# if test_node in sinks: # I *think* we want to break ... or are there paths we still
# need to check?
# continue
# I think if sinks is more than one state we have to check everything
# now update the distances for each neighbor of the test_node:
neighbors = np.where(net_flux[test_node, :] > 0)[0]
if len(neighbors) == 0:
continue
new_fluxes = net_flux[test_node, neighbors].flatten()
# flux from test_node to each neighbor
new_fluxes[np.where(new_fluxes > min_fluxes[test_node])] = min_fluxes[test_node]
# previous step to get to test_node was lower flux, so that is still the path flux
ind = np.where((1 - visited[neighbors]) & (new_fluxes > min_fluxes[neighbors]))
min_fluxes[neighbors[ind]] = new_fluxes[ind]
previous_node[neighbors[ind]] = test_node
# each of these neighbors came from this test_node
# we don't want to update the nodes that have already been visited
queue.extend(neighbors[ind])
top_path = []
# populate the path in reverse
top_path.append(int(sinks[min_fluxes[sinks].argmax()]))
# find the closest sink state
while previous_node[top_path[-1]] != -1:
top_path.append(previous_node[top_path[-1]])
return np.array(top_path[::-1]), min_fluxes[top_path[0]] | python | def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray, shape = [n_states, n_states]
Net flux of the MSM
Returns
-------
top_path : np.ndarray
Array corresponding to the top path between sources and
sinks. It is an array of states visited along the path.
flux : float
Flux traveling through this path -- this is equal to the
minimum flux over edges in the path.
See Also
--------
msmbuilder.tpt.paths : function for calculating many high
flux paths through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
sources = np.array(sources, dtype=np.int).reshape((-1,))
sinks = np.array(sinks, dtype=np.int).reshape((-1,))
n_states = net_flux.shape[0]
queue = list(sources)
# nodes to check (the "queue")
# going to use list.pop method so I can't keep it as an array
visited = np.zeros(n_states).astype(np.bool)
# have we already checked this node?
previous_node = np.ones(n_states).astype(np.int) * -1
# what node was found before finding this one
min_fluxes = np.ones(n_states) * -1 * np.inf
# what is the flux of the highest flux path
# from this node to the source set.
min_fluxes[sources] = np.inf
# source states are connected to the source
# so this distance is zero which means the flux is infinite
while len(queue) > 0: # iterate until there's nothing to check anymore
test_node = queue.pop(min_fluxes[queue].argmax())
# find the node in the queue that has the
# highest flux path to it from the source set
visited[test_node] = True
if np.all(visited[sinks]):
# if we've visited all of the sink states, then we just have to choose
# the path that goes to the sink state that is closest to the source
break
# if test_node in sinks: # I *think* we want to break ... or are there paths we still
# need to check?
# continue
# I think if sinks is more than one state we have to check everything
# now update the distances for each neighbor of the test_node:
neighbors = np.where(net_flux[test_node, :] > 0)[0]
if len(neighbors) == 0:
continue
new_fluxes = net_flux[test_node, neighbors].flatten()
# flux from test_node to each neighbor
new_fluxes[np.where(new_fluxes > min_fluxes[test_node])] = min_fluxes[test_node]
# previous step to get to test_node was lower flux, so that is still the path flux
ind = np.where((1 - visited[neighbors]) & (new_fluxes > min_fluxes[neighbors]))
min_fluxes[neighbors[ind]] = new_fluxes[ind]
previous_node[neighbors[ind]] = test_node
# each of these neighbors came from this test_node
# we don't want to update the nodes that have already been visited
queue.extend(neighbors[ind])
top_path = []
# populate the path in reverse
top_path.append(int(sinks[min_fluxes[sinks].argmax()]))
# find the closest sink state
while previous_node[top_path[-1]] != -1:
top_path.append(previous_node[top_path[-1]])
return np.array(top_path[::-1]), min_fluxes[top_path[0]] | [
"def",
"top_path",
"(",
"sources",
",",
"sinks",
",",
"net_flux",
")",
":",
"sources",
"=",
"np",
".",
"array",
"(",
"sources",
",",
"dtype",
"=",
"np",
".",
"int",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
")",
")",
"sinks",
"=",
"np",
"."... | Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray, shape = [n_states, n_states]
Net flux of the MSM
Returns
-------
top_path : np.ndarray
Array corresponding to the top path between sources and
sinks. It is an array of states visited along the path.
flux : float
Flux traveling through this path -- this is equal to the
minimum flux over edges in the path.
See Also
--------
msmbuilder.tpt.paths : function for calculating many high
flux paths through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. | [
"Use",
"the",
"Dijkstra",
"algorithm",
"for",
"finding",
"the",
"shortest",
"path",
"connecting",
"a",
"set",
"of",
"source",
"states",
"from",
"a",
"set",
"of",
"sink",
"states",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L44-L158 | train | 212,755 |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | _remove_bottleneck | def _remove_bottleneck(net_flux, path):
"""
Internal function for modifying the net flux matrix by removing
a particular edge, corresponding to the bottleneck of a particular
path.
"""
net_flux = copy.copy(net_flux)
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[bottleneck_ind], path[bottleneck_ind + 1]] = 0.0
return net_flux | python | def _remove_bottleneck(net_flux, path):
"""
Internal function for modifying the net flux matrix by removing
a particular edge, corresponding to the bottleneck of a particular
path.
"""
net_flux = copy.copy(net_flux)
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[bottleneck_ind], path[bottleneck_ind + 1]] = 0.0
return net_flux | [
"def",
"_remove_bottleneck",
"(",
"net_flux",
",",
"path",
")",
":",
"net_flux",
"=",
"copy",
".",
"copy",
"(",
"net_flux",
")",
"bottleneck_ind",
"=",
"net_flux",
"[",
"path",
"[",
":",
"-",
"1",
"]",
",",
"path",
"[",
"1",
":",
"]",
"]",
".",
"ar... | Internal function for modifying the net flux matrix by removing
a particular edge, corresponding to the bottleneck of a particular
path. | [
"Internal",
"function",
"for",
"modifying",
"the",
"net",
"flux",
"matrix",
"by",
"removing",
"a",
"particular",
"edge",
"corresponding",
"to",
"the",
"bottleneck",
"of",
"a",
"particular",
"path",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L161-L173 | train | 212,756 |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | _subtract_path_flux | def _subtract_path_flux(net_flux, path):
"""
Internal function for modifying the net flux matrix by subtracting
a path's flux from every edge in the path.
"""
net_flux = copy.copy(net_flux)
net_flux[path[:-1], path[1:]] -= net_flux[path[:-1], path[1:]].min()
# The above *should* make the bottleneck have zero flux, but
# numerically that may not be the case, so just set it to zero
# to be sure.
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[bottleneck_ind], path[bottleneck_ind + 1]] = 0.0
return net_flux | python | def _subtract_path_flux(net_flux, path):
"""
Internal function for modifying the net flux matrix by subtracting
a path's flux from every edge in the path.
"""
net_flux = copy.copy(net_flux)
net_flux[path[:-1], path[1:]] -= net_flux[path[:-1], path[1:]].min()
# The above *should* make the bottleneck have zero flux, but
# numerically that may not be the case, so just set it to zero
# to be sure.
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[bottleneck_ind], path[bottleneck_ind + 1]] = 0.0
return net_flux | [
"def",
"_subtract_path_flux",
"(",
"net_flux",
",",
"path",
")",
":",
"net_flux",
"=",
"copy",
".",
"copy",
"(",
"net_flux",
")",
"net_flux",
"[",
"path",
"[",
":",
"-",
"1",
"]",
",",
"path",
"[",
"1",
":",
"]",
"]",
"-=",
"net_flux",
"[",
"path",... | Internal function for modifying the net flux matrix by subtracting
a path's flux from every edge in the path. | [
"Internal",
"function",
"for",
"modifying",
"the",
"net",
"flux",
"matrix",
"by",
"subtracting",
"a",
"path",
"s",
"flux",
"from",
"every",
"edge",
"in",
"the",
"path",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L176-L192 | train | 212,757 |
msmbuilder/msmbuilder | msmbuilder/tpt/path.py | paths | def paths(sources, sinks, net_flux, remove_path='subtract',
num_paths=np.inf, flux_cutoff=(1-1E-10)):
"""
Get the top N paths by iteratively performing Dijkstra's
algorithm.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray
Net flux of the MSM
remove_path : str or callable, optional
Function for removing a path from the net flux matrix.
(if str, one of {'subtract', 'bottleneck'})
See note below for more details.
num_paths : int, optional
Number of paths to find
flux_cutoff : float, optional
Quit looking for paths once the explained flux is greater
than this cutoff (as a percentage of the total).
Returns
-------
paths : list
List of paths. Each item is an array of nodes visited
in the path.
fluxes : np.ndarray, shape = [n_paths,]
Flux of each path returned.
Notes
-----
The Dijkstra algorithm only allows for computing the
*single* top flux pathway through the net flux matrix. If
we want many paths, there are many ways of finding the
*second* highest flux pathway.
The algorithm proceeds as follows:
1. Using the Djikstra algorithm, find the highest flux
pathway from the sources to the sink states
2. Remove that pathway from the net flux matrix by
some criterion
3. Repeat (1) with the modified net flux matrix
Currently, there are two schemes for step (2):
- 'subtract' : Remove the path by subtracting the flux
of the path from every edge in the path. This was
suggested by Metzner, Schutte, and Vanden-Eijnden.
Transition Path Theory for Markov Jump Processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
- 'bottleneck' : Remove the path by only removing
the edge that corresponds to the bottleneck of the
path.
If a new scheme is desired, the user may pass a function
that takes the net_flux and the path to remove and returns
the new net flux matrix.
See Also
--------
msmbuilder.tpt.top_path : function for computing the single
highest flux pathway through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
if not callable(remove_path):
if remove_path == 'subtract':
remove_path = _subtract_path_flux
elif remove_path == 'bottleneck':
remove_path = _remove_bottleneck
else:
raise ValueError("remove_path_func (%s) must be a callable or one of ['subtract', 'bottleneck']" % str(remove_path))
net_flux = copy.copy(net_flux)
paths = []
fluxes = []
total_flux = net_flux[sources, :].sum()
# total flux is the total flux coming from the sources (or going into the sinks)
not_done = True
counter = 0
expl_flux = 0.0
while not_done:
path, flux = top_path(sources, sinks, net_flux)
if np.isinf(flux):
break
paths.append(path)
fluxes.append(flux)
expl_flux += flux / total_flux
counter += 1
if counter >= num_paths or expl_flux >= flux_cutoff:
break
# modify the net_flux matrix
net_flux = remove_path(net_flux, path)
fluxes = np.array(fluxes)
return paths, fluxes | python | def paths(sources, sinks, net_flux, remove_path='subtract',
num_paths=np.inf, flux_cutoff=(1-1E-10)):
"""
Get the top N paths by iteratively performing Dijkstra's
algorithm.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray
Net flux of the MSM
remove_path : str or callable, optional
Function for removing a path from the net flux matrix.
(if str, one of {'subtract', 'bottleneck'})
See note below for more details.
num_paths : int, optional
Number of paths to find
flux_cutoff : float, optional
Quit looking for paths once the explained flux is greater
than this cutoff (as a percentage of the total).
Returns
-------
paths : list
List of paths. Each item is an array of nodes visited
in the path.
fluxes : np.ndarray, shape = [n_paths,]
Flux of each path returned.
Notes
-----
The Dijkstra algorithm only allows for computing the
*single* top flux pathway through the net flux matrix. If
we want many paths, there are many ways of finding the
*second* highest flux pathway.
The algorithm proceeds as follows:
1. Using the Djikstra algorithm, find the highest flux
pathway from the sources to the sink states
2. Remove that pathway from the net flux matrix by
some criterion
3. Repeat (1) with the modified net flux matrix
Currently, there are two schemes for step (2):
- 'subtract' : Remove the path by subtracting the flux
of the path from every edge in the path. This was
suggested by Metzner, Schutte, and Vanden-Eijnden.
Transition Path Theory for Markov Jump Processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
- 'bottleneck' : Remove the path by only removing
the edge that corresponds to the bottleneck of the
path.
If a new scheme is desired, the user may pass a function
that takes the net_flux and the path to remove and returns
the new net flux matrix.
See Also
--------
msmbuilder.tpt.top_path : function for computing the single
highest flux pathway through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016.
"""
if not callable(remove_path):
if remove_path == 'subtract':
remove_path = _subtract_path_flux
elif remove_path == 'bottleneck':
remove_path = _remove_bottleneck
else:
raise ValueError("remove_path_func (%s) must be a callable or one of ['subtract', 'bottleneck']" % str(remove_path))
net_flux = copy.copy(net_flux)
paths = []
fluxes = []
total_flux = net_flux[sources, :].sum()
# total flux is the total flux coming from the sources (or going into the sinks)
not_done = True
counter = 0
expl_flux = 0.0
while not_done:
path, flux = top_path(sources, sinks, net_flux)
if np.isinf(flux):
break
paths.append(path)
fluxes.append(flux)
expl_flux += flux / total_flux
counter += 1
if counter >= num_paths or expl_flux >= flux_cutoff:
break
# modify the net_flux matrix
net_flux = remove_path(net_flux, path)
fluxes = np.array(fluxes)
return paths, fluxes | [
"def",
"paths",
"(",
"sources",
",",
"sinks",
",",
"net_flux",
",",
"remove_path",
"=",
"'subtract'",
",",
"num_paths",
"=",
"np",
".",
"inf",
",",
"flux_cutoff",
"=",
"(",
"1",
"-",
"1E-10",
")",
")",
":",
"if",
"not",
"callable",
"(",
"remove_path",
... | Get the top N paths by iteratively performing Dijkstra's
algorithm.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_like, int
One-dimensional list of nodes to define the sink states.
net_flux : np.ndarray
Net flux of the MSM
remove_path : str or callable, optional
Function for removing a path from the net flux matrix.
(if str, one of {'subtract', 'bottleneck'})
See note below for more details.
num_paths : int, optional
Number of paths to find
flux_cutoff : float, optional
Quit looking for paths once the explained flux is greater
than this cutoff (as a percentage of the total).
Returns
-------
paths : list
List of paths. Each item is an array of nodes visited
in the path.
fluxes : np.ndarray, shape = [n_paths,]
Flux of each path returned.
Notes
-----
The Dijkstra algorithm only allows for computing the
*single* top flux pathway through the net flux matrix. If
we want many paths, there are many ways of finding the
*second* highest flux pathway.
The algorithm proceeds as follows:
1. Using the Djikstra algorithm, find the highest flux
pathway from the sources to the sink states
2. Remove that pathway from the net flux matrix by
some criterion
3. Repeat (1) with the modified net flux matrix
Currently, there are two schemes for step (2):
- 'subtract' : Remove the path by subtracting the flux
of the path from every edge in the path. This was
suggested by Metzner, Schutte, and Vanden-Eijnden.
Transition Path Theory for Markov Jump Processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
- 'bottleneck' : Remove the path by only removing
the edge that corresponds to the bottleneck of the
path.
If a new scheme is desired, the user may pass a function
that takes the net_flux and the path to remove and returns
the new net flux matrix.
See Also
--------
msmbuilder.tpt.top_path : function for computing the single
highest flux pathway through a network.
References
----------
.. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of
transition paths. J. Stat. Phys. 123, 503-523 (2006).
.. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E.
Transition path theory for Markov jump processes.
Multiscale Model. Simul. 7, 1192-1219 (2009).
.. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive
flux and folding pathways in network models of
coarse-grained protein dynamics. J. Chem. Phys.
130, 205102 (2009).
.. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs.
Numeriche Mathematik 1, 269-271 (1959).
.. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding
pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. | [
"Get",
"the",
"top",
"N",
"paths",
"by",
"iteratively",
"performing",
"Dijkstra",
"s",
"algorithm",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/tpt/path.py#L195-L318 | train | 212,758 |
msmbuilder/msmbuilder | msmbuilder/decomposition/tica.py | rao_blackwell_ledoit_wolf | def rao_blackwell_ledoit_wolf(S, n):
"""Rao-Blackwellized Ledoit-Wolf shrinkaged estimator of the covariance
matrix.
Parameters
----------
S : array, shape=(n, n)
Sample covariance matrix (e.g. estimated with np.cov(X.T))
n : int
Number of data points.
Returns
-------
sigma : array, shape=(n, n)
shrinkage : float
References
----------
.. [1] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. "Shrinkage
estimation of high dimensional covariance matrices" ICASSP (2009)
"""
p = len(S)
assert S.shape == (p, p)
alpha = (n-2)/(n*(n+2))
beta = ((p+1)*n - 2) / (n*(n+2))
trace_S2 = np.sum(S*S) # np.trace(S.dot(S))
U = ((p * trace_S2 / np.trace(S)**2) - 1)
rho = min(alpha + beta/U, 1)
F = (np.trace(S) / p) * np.eye(p)
return (1-rho)*S + rho*F, rho | python | def rao_blackwell_ledoit_wolf(S, n):
"""Rao-Blackwellized Ledoit-Wolf shrinkaged estimator of the covariance
matrix.
Parameters
----------
S : array, shape=(n, n)
Sample covariance matrix (e.g. estimated with np.cov(X.T))
n : int
Number of data points.
Returns
-------
sigma : array, shape=(n, n)
shrinkage : float
References
----------
.. [1] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. "Shrinkage
estimation of high dimensional covariance matrices" ICASSP (2009)
"""
p = len(S)
assert S.shape == (p, p)
alpha = (n-2)/(n*(n+2))
beta = ((p+1)*n - 2) / (n*(n+2))
trace_S2 = np.sum(S*S) # np.trace(S.dot(S))
U = ((p * trace_S2 / np.trace(S)**2) - 1)
rho = min(alpha + beta/U, 1)
F = (np.trace(S) / p) * np.eye(p)
return (1-rho)*S + rho*F, rho | [
"def",
"rao_blackwell_ledoit_wolf",
"(",
"S",
",",
"n",
")",
":",
"p",
"=",
"len",
"(",
"S",
")",
"assert",
"S",
".",
"shape",
"==",
"(",
"p",
",",
"p",
")",
"alpha",
"=",
"(",
"n",
"-",
"2",
")",
"/",
"(",
"n",
"*",
"(",
"n",
"+",
"2",
"... | Rao-Blackwellized Ledoit-Wolf shrinkaged estimator of the covariance
matrix.
Parameters
----------
S : array, shape=(n, n)
Sample covariance matrix (e.g. estimated with np.cov(X.T))
n : int
Number of data points.
Returns
-------
sigma : array, shape=(n, n)
shrinkage : float
References
----------
.. [1] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. "Shrinkage
estimation of high dimensional covariance matrices" ICASSP (2009) | [
"Rao",
"-",
"Blackwellized",
"Ledoit",
"-",
"Wolf",
"shrinkaged",
"estimator",
"of",
"the",
"covariance",
"matrix",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/tica.py#L492-L524 | train | 212,759 |
msmbuilder/msmbuilder | msmbuilder/decomposition/tica.py | tICA.fit | def fit(self, sequences, y=None):
"""Fit the model with a collection of sequences.
This method is not online. Any state accumulated from previous calls to
fit() or partial_fit() will be cleared. For online learning, use
`partial_fit`.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
self : object
Returns the instance itself.
"""
self._initialized = False
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
for X in sequences:
self._fit(X)
if self.n_sequences_ == 0:
raise ValueError('All sequences were shorter than '
'the lag time, %d' % self.lag_time)
return self | python | def fit(self, sequences, y=None):
"""Fit the model with a collection of sequences.
This method is not online. Any state accumulated from previous calls to
fit() or partial_fit() will be cleared. For online learning, use
`partial_fit`.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
self : object
Returns the instance itself.
"""
self._initialized = False
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
for X in sequences:
self._fit(X)
if self.n_sequences_ == 0:
raise ValueError('All sequences were shorter than '
'the lag time, %d' % self.lag_time)
return self | [
"def",
"fit",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"_initialized",
"=",
"False",
"check_iter_of_sequences",
"(",
"sequences",
",",
"max_iter",
"=",
"3",
")",
"# we might be lazy-loading",
"for",
"X",
"in",
"sequences",... | Fit the model with a collection of sequences.
This method is not online. Any state accumulated from previous calls to
fit() or partial_fit() will be cleared. For online learning, use
`partial_fit`.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
y : None
Ignored
Returns
-------
self : object
Returns the instance itself. | [
"Fit",
"the",
"model",
"with",
"a",
"collection",
"of",
"sequences",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/tica.py#L261-L290 | train | 212,760 |
msmbuilder/msmbuilder | msmbuilder/decomposition/tica.py | tICA.transform | def transform(self, sequences):
"""Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
sequences_new = []
for X in sequences:
X = array2d(X)
if self.means_ is not None:
X = X - self.means_
X_transformed = np.dot(X, self.components_.T)
if self.kinetic_mapping:
X_transformed *= self.eigenvalues_
if self.commute_mapping:
# thanks to @maxentile and @jchodera for providing/directing to a
# reference implementation in pyemma
#(markovmodel/PyEMMA#963)
# dampening smaller timescales based recommendtion of [7]
#
# some timescales are NaNs and regularized timescales will
# be negative when they are less than the lag time; all these
# are set to zero using nan_to_num before returning
regularized_timescales = 0.5 * self.timescales_ *\
np.tanh( np.pi *((self.timescales_ - self.lag_time)
/self.lag_time) + 1)
X_transformed *= np.sqrt(regularized_timescales / 2)
X_transformed = np.nan_to_num(X_transformed)
sequences_new.append(X_transformed)
return sequences_new | python | def transform(self, sequences):
"""Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components)
"""
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
sequences_new = []
for X in sequences:
X = array2d(X)
if self.means_ is not None:
X = X - self.means_
X_transformed = np.dot(X, self.components_.T)
if self.kinetic_mapping:
X_transformed *= self.eigenvalues_
if self.commute_mapping:
# thanks to @maxentile and @jchodera for providing/directing to a
# reference implementation in pyemma
#(markovmodel/PyEMMA#963)
# dampening smaller timescales based recommendtion of [7]
#
# some timescales are NaNs and regularized timescales will
# be negative when they are less than the lag time; all these
# are set to zero using nan_to_num before returning
regularized_timescales = 0.5 * self.timescales_ *\
np.tanh( np.pi *((self.timescales_ - self.lag_time)
/self.lag_time) + 1)
X_transformed *= np.sqrt(regularized_timescales / 2)
X_transformed = np.nan_to_num(X_transformed)
sequences_new.append(X_transformed)
return sequences_new | [
"def",
"transform",
"(",
"self",
",",
"sequences",
")",
":",
"check_iter_of_sequences",
"(",
"sequences",
",",
"max_iter",
"=",
"3",
")",
"# we might be lazy-loading",
"sequences_new",
"=",
"[",
"]",
"for",
"X",
"in",
"sequences",
":",
"X",
"=",
"array2d",
"... | Apply the dimensionality reduction on X.
Parameters
----------
sequences: list of array-like, each of shape (n_samples_i, n_features)
Training data, where n_samples_i in the number of samples
in sequence i and n_features is the number of features.
Returns
-------
sequence_new : list of array-like, each of shape (n_samples_i, n_components) | [
"Apply",
"the",
"dimensionality",
"reduction",
"on",
"X",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/tica.py#L312-L354 | train | 212,761 |
msmbuilder/msmbuilder | msmbuilder/utils/subsampler.py | Subsampler.transform | def transform(self, X_all, y=None):
"""Subsample several time series.
Parameters
----------
X_all : list(np.ndarray)
List of feature time series
Returns
-------
features : list(np.ndarray), length = len(X_all)
The subsampled trajectories.
"""
if self._sliding_window:
return [X[k::self._lag_time] for k in range(self._lag_time) for X in X_all]
else:
return [X[::self._lag_time] for X in X_all] | python | def transform(self, X_all, y=None):
"""Subsample several time series.
Parameters
----------
X_all : list(np.ndarray)
List of feature time series
Returns
-------
features : list(np.ndarray), length = len(X_all)
The subsampled trajectories.
"""
if self._sliding_window:
return [X[k::self._lag_time] for k in range(self._lag_time) for X in X_all]
else:
return [X[::self._lag_time] for X in X_all] | [
"def",
"transform",
"(",
"self",
",",
"X_all",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"_sliding_window",
":",
"return",
"[",
"X",
"[",
"k",
":",
":",
"self",
".",
"_lag_time",
"]",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"_lag_t... | Subsample several time series.
Parameters
----------
X_all : list(np.ndarray)
List of feature time series
Returns
-------
features : list(np.ndarray), length = len(X_all)
The subsampled trajectories. | [
"Subsample",
"several",
"time",
"series",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/utils/subsampler.py#L29-L45 | train | 212,762 |
msmbuilder/msmbuilder | msmbuilder/decomposition/utils.py | iterate_tracker | def iterate_tracker(maxiter, max_nc, verbose=False):
"""Generator that breaks after maxiter, or after the same
array has been sent in more max_nc times in a row.
"""
last_hash = None
last_hash_count = 0
arr = yield
for i in xrange(maxiter):
arr = yield i
if arr is not None:
hsh = hashlib.sha1(arr.view(np.uint8)).hexdigest()
if last_hash == hsh:
last_hash_count += 1
else:
last_hash = hsh
last_hash_count = 1
if last_hash_count >= max_nc:
if verbose:
print('Termination. Over %d iterations without '
'change.' % max_nc)
break | python | def iterate_tracker(maxiter, max_nc, verbose=False):
"""Generator that breaks after maxiter, or after the same
array has been sent in more max_nc times in a row.
"""
last_hash = None
last_hash_count = 0
arr = yield
for i in xrange(maxiter):
arr = yield i
if arr is not None:
hsh = hashlib.sha1(arr.view(np.uint8)).hexdigest()
if last_hash == hsh:
last_hash_count += 1
else:
last_hash = hsh
last_hash_count = 1
if last_hash_count >= max_nc:
if verbose:
print('Termination. Over %d iterations without '
'change.' % max_nc)
break | [
"def",
"iterate_tracker",
"(",
"maxiter",
",",
"max_nc",
",",
"verbose",
"=",
"False",
")",
":",
"last_hash",
"=",
"None",
"last_hash_count",
"=",
"0",
"arr",
"=",
"yield",
"for",
"i",
"in",
"xrange",
"(",
"maxiter",
")",
":",
"arr",
"=",
"yield",
"i",... | Generator that breaks after maxiter, or after the same
array has been sent in more max_nc times in a row. | [
"Generator",
"that",
"breaks",
"after",
"maxiter",
"or",
"after",
"the",
"same",
"array",
"has",
"been",
"sent",
"in",
"more",
"max_nc",
"times",
"in",
"a",
"row",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/utils.py#L7-L29 | train | 212,763 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca.py | PCCA.fit | def fit(self, sequences, y=None):
"""Fit a PCCA lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self
"""
super(PCCA, self).fit(sequences, y=y)
self._do_lumping()
return self | python | def fit(self, sequences, y=None):
"""Fit a PCCA lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self
"""
super(PCCA, self).fit(sequences, y=y)
self._do_lumping()
return self | [
"def",
"fit",
"(",
"self",
",",
"sequences",
",",
"y",
"=",
"None",
")",
":",
"super",
"(",
"PCCA",
",",
"self",
")",
".",
"fit",
"(",
"sequences",
",",
"y",
"=",
"y",
")",
"self",
".",
"_do_lumping",
"(",
")",
"return",
"self"
] | Fit a PCCA lumping model using a sequence of cluster assignments.
Parameters
----------
sequences : list(np.ndarray(dtype='int'))
List of arrays of cluster assignments
y : None
Unused, present for sklearn compatibility only.
Returns
-------
self | [
"Fit",
"a",
"PCCA",
"lumping",
"model",
"using",
"a",
"sequence",
"of",
"cluster",
"assignments",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca.py#L38-L54 | train | 212,764 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca.py | PCCA._do_lumping | def _do_lumping(self):
"""Do the PCCA lumping.
Notes
-------
1. Iterate over the eigenvectors, starting with the slowest.
2. Calculate the spread of that eigenvector within each existing
macrostate.
3. Pick the macrostate with the largest eigenvector spread.
4. Split the macrostate based on the sign of the eigenvector.
"""
# Extract non-perron eigenvectors
right_eigenvectors = self.right_eigenvectors_[:, 1:]
assert self.n_states_ > 0
microstate_mapping = np.zeros(self.n_states_, dtype=int)
def spread(x):
return x.max() - x.min()
for i in range(self.n_macrostates - 1):
v = right_eigenvectors[:, i]
all_spreads = np.array([spread(v[microstate_mapping == k])
for k in range(i + 1)])
state_to_split = np.argmax(all_spreads)
inds = ((microstate_mapping == state_to_split) &
(v >= self.pcca_tolerance))
microstate_mapping[inds] = i + 1
self.microstate_mapping_ = microstate_mapping | python | def _do_lumping(self):
"""Do the PCCA lumping.
Notes
-------
1. Iterate over the eigenvectors, starting with the slowest.
2. Calculate the spread of that eigenvector within each existing
macrostate.
3. Pick the macrostate with the largest eigenvector spread.
4. Split the macrostate based on the sign of the eigenvector.
"""
# Extract non-perron eigenvectors
right_eigenvectors = self.right_eigenvectors_[:, 1:]
assert self.n_states_ > 0
microstate_mapping = np.zeros(self.n_states_, dtype=int)
def spread(x):
return x.max() - x.min()
for i in range(self.n_macrostates - 1):
v = right_eigenvectors[:, i]
all_spreads = np.array([spread(v[microstate_mapping == k])
for k in range(i + 1)])
state_to_split = np.argmax(all_spreads)
inds = ((microstate_mapping == state_to_split) &
(v >= self.pcca_tolerance))
microstate_mapping[inds] = i + 1
self.microstate_mapping_ = microstate_mapping | [
"def",
"_do_lumping",
"(",
"self",
")",
":",
"# Extract non-perron eigenvectors",
"right_eigenvectors",
"=",
"self",
".",
"right_eigenvectors_",
"[",
":",
",",
"1",
":",
"]",
"assert",
"self",
".",
"n_states_",
">",
"0",
"microstate_mapping",
"=",
"np",
".",
"... | Do the PCCA lumping.
Notes
-------
1. Iterate over the eigenvectors, starting with the slowest.
2. Calculate the spread of that eigenvector within each existing
macrostate.
3. Pick the macrostate with the largest eigenvector spread.
4. Split the macrostate based on the sign of the eigenvector. | [
"Do",
"the",
"PCCA",
"lumping",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca.py#L56-L86 | train | 212,765 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | metastability | def metastability(alpha, T, right_eigenvectors, square_map, pi):
"""Return the metastability PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
metastability: try to make metastable fuzzy state decomposition.
Defined in ref. [2].
"""
num_micro, num_eigen = right_eigenvectors.shape
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
has_constraint_violation(A, right_eigenvectors)):
return -1.0 * np.inf
obj = 0.0
# Calculate metastabilty of the lumped model. Eqn 4.20 in LAA.
for i in range(num_eigen):
obj += np.dot(T.dot(chi[:, i]), pi * chi[:, i]) / np.dot(chi[:, i], pi)
return obj | python | def metastability(alpha, T, right_eigenvectors, square_map, pi):
"""Return the metastability PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
metastability: try to make metastable fuzzy state decomposition.
Defined in ref. [2].
"""
num_micro, num_eigen = right_eigenvectors.shape
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
has_constraint_violation(A, right_eigenvectors)):
return -1.0 * np.inf
obj = 0.0
# Calculate metastabilty of the lumped model. Eqn 4.20 in LAA.
for i in range(num_eigen):
obj += np.dot(T.dot(chi[:, i]), pi * chi[:, i]) / np.dot(chi[:, i], pi)
return obj | [
"def",
"metastability",
"(",
"alpha",
",",
"T",
",",
"right_eigenvectors",
",",
"square_map",
",",
"pi",
")",
":",
"num_micro",
",",
"num_eigen",
"=",
"right_eigenvectors",
".",
"shape",
"A",
",",
"chi",
",",
"mapping",
"=",
"calculate_fuzzy_chi",
"(",
"alph... | Return the metastability PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
metastability: try to make metastable fuzzy state decomposition.
Defined in ref. [2]. | [
"Return",
"the",
"metastability",
"PCCA",
"+",
"objective",
"function",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L183-L225 | train | 212,766 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | crispness | def crispness(alpha, T, right_eigenvectors, square_map, pi):
"""Return the crispness PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
Tries to make crisp state decompostion. This function is
defined in [3].
"""
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
has_constraint_violation(A, right_eigenvectors)):
return -1.0 * np.inf
obj = tr(dot(diag(1. / A[0]), dot(A.transpose(), A)))
return obj | python | def crispness(alpha, T, right_eigenvectors, square_map, pi):
"""Return the crispness PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
Tries to make crisp state decompostion. This function is
defined in [3].
"""
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
has_constraint_violation(A, right_eigenvectors)):
return -1.0 * np.inf
obj = tr(dot(diag(1. / A[0]), dot(A.transpose(), A)))
return obj | [
"def",
"crispness",
"(",
"alpha",
",",
"T",
",",
"right_eigenvectors",
",",
"square_map",
",",
"pi",
")",
":",
"A",
",",
"chi",
",",
"mapping",
"=",
"calculate_fuzzy_chi",
"(",
"alpha",
",",
"square_map",
",",
"right_eigenvectors",
")",
"# If current point is ... | Return the crispness PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
The right eigenvectors.
square_map : ndarray
Mapping from square indices (i,j) to flat indices (k).
pi : ndarray
Equilibrium Populations of transition matrix.
Returns
-------
obj : float
The objective function
Notes
-------
Tries to make crisp state decompostion. This function is
defined in [3]. | [
"Return",
"the",
"crispness",
"PCCA",
"+",
"objective",
"function",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L278-L315 | train | 212,767 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | get_maps | def get_maps(A):
"""Get mappings from the square array A to the flat vector of parameters
alpha.
Helper function for PCCA+ optimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
flat_map : ndarray
Mapping from flat indices (k) to square (i,j) indices.
square map : ndarray
Mapping from square indices (i,j) to flat indices (k).
"""
N = A.shape[0]
flat_map = []
for i in range(1, N):
for j in range(1, N):
flat_map.append([i, j])
flat_map = np.array(flat_map)
square_map = np.zeros(A.shape, 'int')
for k in range((N - 1) ** 2):
i, j = flat_map[k]
square_map[i, j] = k
return flat_map, square_map | python | def get_maps(A):
"""Get mappings from the square array A to the flat vector of parameters
alpha.
Helper function for PCCA+ optimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
flat_map : ndarray
Mapping from flat indices (k) to square (i,j) indices.
square map : ndarray
Mapping from square indices (i,j) to flat indices (k).
"""
N = A.shape[0]
flat_map = []
for i in range(1, N):
for j in range(1, N):
flat_map.append([i, j])
flat_map = np.array(flat_map)
square_map = np.zeros(A.shape, 'int')
for k in range((N - 1) ** 2):
i, j = flat_map[k]
square_map[i, j] = k
return flat_map, square_map | [
"def",
"get_maps",
"(",
"A",
")",
":",
"N",
"=",
"A",
".",
"shape",
"[",
"0",
"]",
"flat_map",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"N",
")",
":",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"N",
")",
":",
"flat_map",
".... | Get mappings from the square array A to the flat vector of parameters
alpha.
Helper function for PCCA+ optimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
flat_map : ndarray
Mapping from flat indices (k) to square (i,j) indices.
square map : ndarray
Mapping from square indices (i,j) to flat indices (k). | [
"Get",
"mappings",
"from",
"the",
"square",
"array",
"A",
"to",
"the",
"flat",
"vector",
"of",
"parameters",
"alpha",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L318-L351 | train | 212,768 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | has_constraint_violation | def has_constraint_violation(A, right_eigenvectors, epsilon=1E-8):
"""Check for constraint violations in transformation matrix.
Parameters
----------
A : ndarray
The transformation matrix.
right_eigenvectors : ndarray
The right eigenvectors.
epsilon : float, optional
Tolerance of constraint violation.
Returns
-------
truth : bool
Whether or not the violation exists
Notes
-------
Checks constraints using Eqn 4.25 in [1].
References
----------
.. [1] Deuflhard P, Weber, M., "Robust perron cluster analysis in
conformation dynamics,"
Linear Algebra Appl., vol 398 pp 161-184 2005.
"""
lhs = 1 - A[0, 1:].sum()
rhs = dot(right_eigenvectors[:, 1:], A[1:, 0])
rhs = -1 * rhs.min()
if abs(lhs - rhs) > epsilon:
return True
else:
return False | python | def has_constraint_violation(A, right_eigenvectors, epsilon=1E-8):
"""Check for constraint violations in transformation matrix.
Parameters
----------
A : ndarray
The transformation matrix.
right_eigenvectors : ndarray
The right eigenvectors.
epsilon : float, optional
Tolerance of constraint violation.
Returns
-------
truth : bool
Whether or not the violation exists
Notes
-------
Checks constraints using Eqn 4.25 in [1].
References
----------
.. [1] Deuflhard P, Weber, M., "Robust perron cluster analysis in
conformation dynamics,"
Linear Algebra Appl., vol 398 pp 161-184 2005.
"""
lhs = 1 - A[0, 1:].sum()
rhs = dot(right_eigenvectors[:, 1:], A[1:, 0])
rhs = -1 * rhs.min()
if abs(lhs - rhs) > epsilon:
return True
else:
return False | [
"def",
"has_constraint_violation",
"(",
"A",
",",
"right_eigenvectors",
",",
"epsilon",
"=",
"1E-8",
")",
":",
"lhs",
"=",
"1",
"-",
"A",
"[",
"0",
",",
"1",
":",
"]",
".",
"sum",
"(",
")",
"rhs",
"=",
"dot",
"(",
"right_eigenvectors",
"[",
":",
",... | Check for constraint violations in transformation matrix.
Parameters
----------
A : ndarray
The transformation matrix.
right_eigenvectors : ndarray
The right eigenvectors.
epsilon : float, optional
Tolerance of constraint violation.
Returns
-------
truth : bool
Whether or not the violation exists
Notes
-------
Checks constraints using Eqn 4.25 in [1].
References
----------
.. [1] Deuflhard P, Weber, M., "Robust perron cluster analysis in
conformation dynamics,"
Linear Algebra Appl., vol 398 pp 161-184 2005. | [
"Check",
"for",
"constraint",
"violations",
"in",
"transformation",
"matrix",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L390-L427 | train | 212,769 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | index_search | def index_search(right_eigenvectors):
"""Find simplex structure in eigenvectors to begin PCCA+.
Parameters
----------
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
index : ndarray
Indices of simplex
"""
num_micro, num_eigen = right_eigenvectors.shape
index = np.zeros(num_eigen, 'int')
# first vertex: row with largest norm
index[0] = np.argmax(
[norm(right_eigenvectors[i]) for i in range(num_micro)])
ortho_sys = right_eigenvectors - np.outer(np.ones(num_micro),
right_eigenvectors[index[0]])
for j in range(1, num_eigen):
temp = ortho_sys[index[j - 1]].copy()
for l in range(num_micro):
ortho_sys[l] -= temp * dot(ortho_sys[l], temp)
dist_list = np.array([norm(ortho_sys[l]) for l in range(num_micro)])
index[j] = np.argmax(dist_list)
ortho_sys /= dist_list.max()
return index | python | def index_search(right_eigenvectors):
"""Find simplex structure in eigenvectors to begin PCCA+.
Parameters
----------
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
index : ndarray
Indices of simplex
"""
num_micro, num_eigen = right_eigenvectors.shape
index = np.zeros(num_eigen, 'int')
# first vertex: row with largest norm
index[0] = np.argmax(
[norm(right_eigenvectors[i]) for i in range(num_micro)])
ortho_sys = right_eigenvectors - np.outer(np.ones(num_micro),
right_eigenvectors[index[0]])
for j in range(1, num_eigen):
temp = ortho_sys[index[j - 1]].copy()
for l in range(num_micro):
ortho_sys[l] -= temp * dot(ortho_sys[l], temp)
dist_list = np.array([norm(ortho_sys[l]) for l in range(num_micro)])
index[j] = np.argmax(dist_list)
ortho_sys /= dist_list.max()
return index | [
"def",
"index_search",
"(",
"right_eigenvectors",
")",
":",
"num_micro",
",",
"num_eigen",
"=",
"right_eigenvectors",
".",
"shape",
"index",
"=",
"np",
".",
"zeros",
"(",
"num_eigen",
",",
"'int'",
")",
"# first vertex: row with largest norm",
"index",
"[",
"0",
... | Find simplex structure in eigenvectors to begin PCCA+.
Parameters
----------
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
index : ndarray
Indices of simplex | [
"Find",
"simplex",
"structure",
"in",
"eigenvectors",
"to",
"begin",
"PCCA",
"+",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L430-L467 | train | 212,770 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | fill_A | def fill_A(A, right_eigenvectors):
"""Construct feasible initial guess for transformation matrix A.
Parameters
----------
A : ndarray
Possibly non-feasible transformation matrix.
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
A : ndarray
Feasible transformation matrix.
"""
num_micro, num_eigen = right_eigenvectors.shape
A = A.copy()
# compute 1st column of A by row sum condition
A[1:, 0] = -1 * A[1:, 1:].sum(1)
# compute 1st row of A by maximum condition
A[0] = -1 * dot(right_eigenvectors[:, 1:].real, A[1:]).min(0)
# rescale A to be in the feasible set
A /= A[0].sum()
return A | python | def fill_A(A, right_eigenvectors):
"""Construct feasible initial guess for transformation matrix A.
Parameters
----------
A : ndarray
Possibly non-feasible transformation matrix.
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
A : ndarray
Feasible transformation matrix.
"""
num_micro, num_eigen = right_eigenvectors.shape
A = A.copy()
# compute 1st column of A by row sum condition
A[1:, 0] = -1 * A[1:, 1:].sum(1)
# compute 1st row of A by maximum condition
A[0] = -1 * dot(right_eigenvectors[:, 1:].real, A[1:]).min(0)
# rescale A to be in the feasible set
A /= A[0].sum()
return A | [
"def",
"fill_A",
"(",
"A",
",",
"right_eigenvectors",
")",
":",
"num_micro",
",",
"num_eigen",
"=",
"right_eigenvectors",
".",
"shape",
"A",
"=",
"A",
".",
"copy",
"(",
")",
"# compute 1st column of A by row sum condition",
"A",
"[",
"1",
":",
",",
"0",
"]",... | Construct feasible initial guess for transformation matrix A.
Parameters
----------
A : ndarray
Possibly non-feasible transformation matrix.
right_eigenvectors : ndarray
Right eigenvectors of transition matrix
Returns
-------
A : ndarray
Feasible transformation matrix. | [
"Construct",
"feasible",
"initial",
"guess",
"for",
"transformation",
"matrix",
"A",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L470-L499 | train | 212,771 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | PCCAPlus._do_lumping | def _do_lumping(self):
"""Perform PCCA+ algorithm by optimizing transformation matrix A.
Creates the following member variables:
-------
A : ndarray
The transformation matrix.
chi : ndarray
The membership matrix
microstate_mapping : ndarray
Mapping from microstates to macrostates.
"""
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
index = index_search(right_eigenvectors)
# compute transformation matrix A as initial guess for local
# optimization (maybe not feasible)
A = right_eigenvectors[index, :]
A = inv(A)
A = fill_A(A, right_eigenvectors)
if self.do_minimization:
A = self._optimize_A(A)
self.A_ = fill_A(A, right_eigenvectors)
self.chi_ = dot(right_eigenvectors, self.A_)
self.microstate_mapping_ = np.argmax(self.chi_, 1) | python | def _do_lumping(self):
"""Perform PCCA+ algorithm by optimizing transformation matrix A.
Creates the following member variables:
-------
A : ndarray
The transformation matrix.
chi : ndarray
The membership matrix
microstate_mapping : ndarray
Mapping from microstates to macrostates.
"""
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
index = index_search(right_eigenvectors)
# compute transformation matrix A as initial guess for local
# optimization (maybe not feasible)
A = right_eigenvectors[index, :]
A = inv(A)
A = fill_A(A, right_eigenvectors)
if self.do_minimization:
A = self._optimize_A(A)
self.A_ = fill_A(A, right_eigenvectors)
self.chi_ = dot(right_eigenvectors, self.A_)
self.microstate_mapping_ = np.argmax(self.chi_, 1) | [
"def",
"_do_lumping",
"(",
"self",
")",
":",
"right_eigenvectors",
"=",
"self",
".",
"right_eigenvectors_",
"[",
":",
",",
":",
"self",
".",
"n_macrostates",
"]",
"index",
"=",
"index_search",
"(",
"right_eigenvectors",
")",
"# compute transformation matrix A as ini... | Perform PCCA+ algorithm by optimizing transformation matrix A.
Creates the following member variables:
-------
A : ndarray
The transformation matrix.
chi : ndarray
The membership matrix
microstate_mapping : ndarray
Mapping from microstates to macrostates. | [
"Perform",
"PCCA",
"+",
"algorithm",
"by",
"optimizing",
"transformation",
"matrix",
"A",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L113-L141 | train | 212,772 |
msmbuilder/msmbuilder | msmbuilder/lumping/pcca_plus.py | PCCAPlus._optimize_A | def _optimize_A(self, A):
"""Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix.
"""
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
flat_map, square_map = get_maps(A)
alpha = to_flat(1.0 * A, flat_map)
def obj(x):
return -1 * self._objective_function(
x, self.transmat_, right_eigenvectors, square_map,
self.populations_
)
alpha = scipy.optimize.basinhopping(
obj, alpha, niter_success=1000,
)['x']
alpha = scipy.optimize.fmin(
obj, alpha, full_output=True, xtol=1E-4, ftol=1E-4,
maxfun=5000, maxiter=100000
)[0]
if np.isneginf(obj(alpha)):
raise ValueError(
"Error: minimization has not located a feasible point.")
A = to_square(alpha, square_map)
return A | python | def _optimize_A(self, A):
"""Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix.
"""
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
flat_map, square_map = get_maps(A)
alpha = to_flat(1.0 * A, flat_map)
def obj(x):
return -1 * self._objective_function(
x, self.transmat_, right_eigenvectors, square_map,
self.populations_
)
alpha = scipy.optimize.basinhopping(
obj, alpha, niter_success=1000,
)['x']
alpha = scipy.optimize.fmin(
obj, alpha, full_output=True, xtol=1E-4, ftol=1E-4,
maxfun=5000, maxiter=100000
)[0]
if np.isneginf(obj(alpha)):
raise ValueError(
"Error: minimization has not located a feasible point.")
A = to_square(alpha, square_map)
return A | [
"def",
"_optimize_A",
"(",
"self",
",",
"A",
")",
":",
"right_eigenvectors",
"=",
"self",
".",
"right_eigenvectors_",
"[",
":",
",",
":",
"self",
".",
"n_macrostates",
"]",
"flat_map",
",",
"square_map",
"=",
"get_maps",
"(",
"A",
")",
"alpha",
"=",
"to_... | Find optimal transformation matrix A by minimization.
Parameters
----------
A : ndarray
The transformation matrix A.
Returns
-------
A : ndarray
The transformation matrix. | [
"Find",
"optimal",
"transformation",
"matrix",
"A",
"by",
"minimization",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/pcca_plus.py#L143-L180 | train | 212,773 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _solve_msm_eigensystem | def _solve_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfunctions
according to the following criteria.
* The first left eigenvector, \phi_1, _is_ the stationary
distribution, and thus should be normalized to sum to 1.
* The left-right eigenpairs should be biorthonormal:
<\phi_i, \psi_j> = \delta_{ij}
* The left eigenvectors should satisfy
<\phi_i, \phi_i>_{\mu^{-1}} = 1
* The right eigenvectors should satisfy <\psi_i, \psi_i>_{\mu} = 1
Returns
-------
eigvals : np.ndarray, shape=(k,)
The largest `k` eigenvalues
lv : np.ndarray, shape=(n_states, k)
The normalized left eigenvectors (:math:`\phi`) of ``transmat``
rv : np.ndarray, shape=(n_states, k)
The normalized right eigenvectors (:math:`\psi`) of ``transmat``
"""
u, lv, rv = scipy.linalg.eig(transmat, left=True, right=True)
order = np.argsort(-np.real(u))
u = np.real_if_close(u[order[:k]])
lv = np.real_if_close(lv[:, order[:k]])
rv = np.real_if_close(rv[:, order[:k]])
return _normalize_eigensystem(u, lv, rv) | python | def _solve_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfunctions
according to the following criteria.
* The first left eigenvector, \phi_1, _is_ the stationary
distribution, and thus should be normalized to sum to 1.
* The left-right eigenpairs should be biorthonormal:
<\phi_i, \psi_j> = \delta_{ij}
* The left eigenvectors should satisfy
<\phi_i, \phi_i>_{\mu^{-1}} = 1
* The right eigenvectors should satisfy <\psi_i, \psi_i>_{\mu} = 1
Returns
-------
eigvals : np.ndarray, shape=(k,)
The largest `k` eigenvalues
lv : np.ndarray, shape=(n_states, k)
The normalized left eigenvectors (:math:`\phi`) of ``transmat``
rv : np.ndarray, shape=(n_states, k)
The normalized right eigenvectors (:math:`\psi`) of ``transmat``
"""
u, lv, rv = scipy.linalg.eig(transmat, left=True, right=True)
order = np.argsort(-np.real(u))
u = np.real_if_close(u[order[:k]])
lv = np.real_if_close(lv[:, order[:k]])
rv = np.real_if_close(rv[:, order[:k]])
return _normalize_eigensystem(u, lv, rv) | [
"def",
"_solve_msm_eigensystem",
"(",
"transmat",
",",
"k",
")",
":",
"u",
",",
"lv",
",",
"rv",
"=",
"scipy",
".",
"linalg",
".",
"eig",
"(",
"transmat",
",",
"left",
"=",
"True",
",",
"right",
"=",
"True",
")",
"order",
"=",
"np",
".",
"argsort",... | Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfunctions
according to the following criteria.
* The first left eigenvector, \phi_1, _is_ the stationary
distribution, and thus should be normalized to sum to 1.
* The left-right eigenpairs should be biorthonormal:
<\phi_i, \psi_j> = \delta_{ij}
* The left eigenvectors should satisfy
<\phi_i, \phi_i>_{\mu^{-1}} = 1
* The right eigenvectors should satisfy <\psi_i, \psi_i>_{\mu} = 1
Returns
-------
eigvals : np.ndarray, shape=(k,)
The largest `k` eigenvalues
lv : np.ndarray, shape=(n_states, k)
The normalized left eigenvectors (:math:`\phi`) of ``transmat``
rv : np.ndarray, shape=(n_states, k)
The normalized right eigenvectors (:math:`\psi`) of ``transmat`` | [
"Find",
"the",
"dominant",
"eigenpairs",
"of",
"an",
"MSM",
"transition",
"matrix"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L359-L395 | train | 212,774 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _normalize_eigensystem | def _normalize_eigensystem(u, lv, rv):
"""Normalize the eigenvectors of a reversible Markov state model according
to our preferred scheme.
"""
# first normalize the stationary distribution separately
lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0])
for i in range(1, lv.shape[1]):
# the remaining left eigenvectors to satisfy
# <\phi_i, \phi_i>_{\mu^{-1}} = 1
lv[:, i] = lv[:, i] / np.sqrt(np.dot(lv[:, i], lv[:, i] / lv[:, 0]))
for i in range(rv.shape[1]):
# the right eigenvectors to satisfy <\phi_i, \psi_j> = \delta_{ij}
rv[:, i] = rv[:, i] / np.dot(lv[:, i], rv[:, i])
return u, lv, rv | python | def _normalize_eigensystem(u, lv, rv):
"""Normalize the eigenvectors of a reversible Markov state model according
to our preferred scheme.
"""
# first normalize the stationary distribution separately
lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0])
for i in range(1, lv.shape[1]):
# the remaining left eigenvectors to satisfy
# <\phi_i, \phi_i>_{\mu^{-1}} = 1
lv[:, i] = lv[:, i] / np.sqrt(np.dot(lv[:, i], lv[:, i] / lv[:, 0]))
for i in range(rv.shape[1]):
# the right eigenvectors to satisfy <\phi_i, \psi_j> = \delta_{ij}
rv[:, i] = rv[:, i] / np.dot(lv[:, i], rv[:, i])
return u, lv, rv | [
"def",
"_normalize_eigensystem",
"(",
"u",
",",
"lv",
",",
"rv",
")",
":",
"# first normalize the stationary distribution separately",
"lv",
"[",
":",
",",
"0",
"]",
"=",
"lv",
"[",
":",
",",
"0",
"]",
"/",
"np",
".",
"sum",
"(",
"lv",
"[",
":",
",",
... | Normalize the eigenvectors of a reversible Markov state model according
to our preferred scheme. | [
"Normalize",
"the",
"eigenvectors",
"of",
"a",
"reversible",
"Markov",
"state",
"model",
"according",
"to",
"our",
"preferred",
"scheme",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L398-L414 | train | 212,775 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _strongly_connected_subgraph | def _strongly_connected_subgraph(counts, weight=1, verbose=True):
"""Trim a transition count matrix down to its maximal
strongly ergodic subgraph.
From the counts matrix, we define a graph where there exists
a directed edge between two nodes, `i` and `j` if
`counts[i][j] > weight`. We then find the nodes belonging to the largest
strongly connected subgraph of this graph, and return a new counts
matrix formed by these rows and columns of the input `counts` matrix.
Parameters
----------
counts : np.array, shape=(n_states_in, n_states_in)
Input set of directed counts.
weight : float
Threshold by which ergodicity is judged in the input data. Greater or
equal to this many transition counts in both directions are required
to include an edge in the ergodic subgraph.
verbose : bool
Print a short statement
Returns
-------
counts_component :
"Trimmed" version of ``counts``, including only states in the
maximal strongly ergodic subgraph.
mapping : dict
Mapping from "input" states indices to "output" state indices
The semantics of ``mapping[i] = j`` is that state ``i`` from the
"input space" for the counts matrix is represented by the index
``j`` in counts_component
"""
n_states_input = counts.shape[0]
n_components, component_assignments = csgraph.connected_components(
csr_matrix(counts >= weight), connection="strong")
populations = np.array(counts.sum(0)).flatten()
component_pops = np.array([populations[component_assignments == i].sum() for
i in range(n_components)])
which_component = component_pops.argmax()
def cpop(which):
csum = component_pops.sum()
return 100 * component_pops[which] / csum if csum != 0 else np.nan
percent_retained = cpop(which_component)
if verbose:
print("MSM contains %d strongly connected component%s "
"above weight=%.2f. Component %d selected, with "
"population %f%%" % (
n_components, 's' if (n_components != 1) else '',
weight, which_component, percent_retained))
# keys are all of the "input states" which have a valid mapping to the output.
keys = np.arange(n_states_input)[component_assignments == which_component]
if n_components == n_states_input and counts[np.ix_(keys, keys)] == 0:
# if we have a completely disconnected graph with no self-transitions
return np.zeros((0, 0)), {}, percent_retained
# values are the "output" state that these guys are mapped to
values = np.arange(len(keys))
mapping = dict(zip(keys, values))
n_states_output = len(mapping)
trimmed_counts = np.zeros((n_states_output, n_states_output),
dtype=counts.dtype)
trimmed_counts[np.ix_(values, values)] = counts[np.ix_(keys, keys)]
return trimmed_counts, mapping, percent_retained | python | def _strongly_connected_subgraph(counts, weight=1, verbose=True):
"""Trim a transition count matrix down to its maximal
strongly ergodic subgraph.
From the counts matrix, we define a graph where there exists
a directed edge between two nodes, `i` and `j` if
`counts[i][j] > weight`. We then find the nodes belonging to the largest
strongly connected subgraph of this graph, and return a new counts
matrix formed by these rows and columns of the input `counts` matrix.
Parameters
----------
counts : np.array, shape=(n_states_in, n_states_in)
Input set of directed counts.
weight : float
Threshold by which ergodicity is judged in the input data. Greater or
equal to this many transition counts in both directions are required
to include an edge in the ergodic subgraph.
verbose : bool
Print a short statement
Returns
-------
counts_component :
"Trimmed" version of ``counts``, including only states in the
maximal strongly ergodic subgraph.
mapping : dict
Mapping from "input" states indices to "output" state indices
The semantics of ``mapping[i] = j`` is that state ``i`` from the
"input space" for the counts matrix is represented by the index
``j`` in counts_component
"""
n_states_input = counts.shape[0]
n_components, component_assignments = csgraph.connected_components(
csr_matrix(counts >= weight), connection="strong")
populations = np.array(counts.sum(0)).flatten()
component_pops = np.array([populations[component_assignments == i].sum() for
i in range(n_components)])
which_component = component_pops.argmax()
def cpop(which):
csum = component_pops.sum()
return 100 * component_pops[which] / csum if csum != 0 else np.nan
percent_retained = cpop(which_component)
if verbose:
print("MSM contains %d strongly connected component%s "
"above weight=%.2f. Component %d selected, with "
"population %f%%" % (
n_components, 's' if (n_components != 1) else '',
weight, which_component, percent_retained))
# keys are all of the "input states" which have a valid mapping to the output.
keys = np.arange(n_states_input)[component_assignments == which_component]
if n_components == n_states_input and counts[np.ix_(keys, keys)] == 0:
# if we have a completely disconnected graph with no self-transitions
return np.zeros((0, 0)), {}, percent_retained
# values are the "output" state that these guys are mapped to
values = np.arange(len(keys))
mapping = dict(zip(keys, values))
n_states_output = len(mapping)
trimmed_counts = np.zeros((n_states_output, n_states_output),
dtype=counts.dtype)
trimmed_counts[np.ix_(values, values)] = counts[np.ix_(keys, keys)]
return trimmed_counts, mapping, percent_retained | [
"def",
"_strongly_connected_subgraph",
"(",
"counts",
",",
"weight",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"n_states_input",
"=",
"counts",
".",
"shape",
"[",
"0",
"]",
"n_components",
",",
"component_assignments",
"=",
"csgraph",
".",
"connected_co... | Trim a transition count matrix down to its maximal
strongly ergodic subgraph.
From the counts matrix, we define a graph where there exists
a directed edge between two nodes, `i` and `j` if
`counts[i][j] > weight`. We then find the nodes belonging to the largest
strongly connected subgraph of this graph, and return a new counts
matrix formed by these rows and columns of the input `counts` matrix.
Parameters
----------
counts : np.array, shape=(n_states_in, n_states_in)
Input set of directed counts.
weight : float
Threshold by which ergodicity is judged in the input data. Greater or
equal to this many transition counts in both directions are required
to include an edge in the ergodic subgraph.
verbose : bool
Print a short statement
Returns
-------
counts_component :
"Trimmed" version of ``counts``, including only states in the
maximal strongly ergodic subgraph.
mapping : dict
Mapping from "input" states indices to "output" state indices
The semantics of ``mapping[i] = j`` is that state ``i`` from the
"input space" for the counts matrix is represented by the index
``j`` in counts_component | [
"Trim",
"a",
"transition",
"count",
"matrix",
"down",
"to",
"its",
"maximal",
"strongly",
"ergodic",
"subgraph",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L417-L484 | train | 212,776 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _transition_counts | def _transition_counts(sequences, lag_time=1, sliding_window=True):
"""Count the number of directed transitions in a collection of sequences
in a discrete space.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
lag_time : int
The time (index) delay for the counts.
sliding_window : bool
When lag_time > 1, consider *all*
``N = lag_time`` strided sequences starting from index
0, 1, 2, ..., ``lag_time - 1``. The total, raw counts will
be divided by ``N``. When this is False, only start from index 0.
Returns
-------
counts : array, shape=(n_states, n_states)
``counts[i][j]`` counts the number of times a sequences was in state
`i` at time t, and state `j` at time `t+self.lag_time`, over the
full set of trajectories.
mapping : dict
Mapping from the items in the sequences to the indices in
``(0, n_states-1)`` used for the count matrix.
Examples
--------
>>> sequence = [0, 0, 0, 1, 1]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[2, 1],
[0, 1]]
>>> print mapping
{0: 0, 1: 1}
>>> sequence = [100, 200, 300]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
>>> print mapping
{100: 0, 200: 1, 300: 2}
Notes
-----
`None` and `NaN` are recognized immediately as invalid labels. Therefore,
transition counts from or to a sequence item which is NaN or None will not
be counted. The mapping return value will not include the NaN or None.
"""
if (not sliding_window) and lag_time > 1:
return _transition_counts([X[::lag_time] for X in sequences],
lag_time=1)
classes = np.unique(np.concatenate(sequences))
contains_nan = (classes.dtype.kind == 'f') and np.any(np.isnan(classes))
contains_none = any(c is None for c in classes)
if contains_nan:
classes = classes[~np.isnan(classes)]
if contains_none:
classes = [c for c in classes if c is not None]
n_states = len(classes)
mapping = dict(zip(classes, range(n_states)))
mapping_is_identity = (not contains_nan
and not contains_none
and classes.dtype.kind == 'i'
and np.all(classes == np.arange(n_states)))
mapping_fn = np.vectorize(mapping.get, otypes=[np.int])
none_to_nan = np.vectorize(lambda x: np.nan if x is None else x,
otypes=[np.float])
counts = np.zeros((n_states, n_states), dtype=float)
_transitions = []
for y in sequences:
y = np.asarray(y)
from_states = y[: -lag_time: 1]
to_states = y[lag_time::1]
if contains_none:
from_states = none_to_nan(from_states)
to_states = none_to_nan(to_states)
if contains_nan or contains_none:
# mask out nan in either from_states or to_states
mask = ~(np.isnan(from_states) + np.isnan(to_states))
from_states = from_states[mask]
to_states = to_states[mask]
if (not mapping_is_identity) and len(from_states) > 0 and len(
to_states) > 0:
from_states = mapping_fn(from_states)
to_states = mapping_fn(to_states)
_transitions.append(np.row_stack((from_states, to_states)))
transitions = np.hstack(_transitions)
C = coo_matrix((np.ones(transitions.shape[1], dtype=int), transitions),
shape=(n_states, n_states))
counts = counts + np.asarray(C.todense())
# If sliding window is False, this function will be called recursively
# with strided trajectories and lag_time = 1, which gives the desired
# number of counts. If sliding window is True, the counts are divided
# by the "number of windows" (i.e. the lag_time). Count magnitudes
# will be comparable between sliding-window and non-sliding-window cases.
# If lag_time = 1, sliding_window makes no difference.
counts /= float(lag_time)
return counts, mapping | python | def _transition_counts(sequences, lag_time=1, sliding_window=True):
"""Count the number of directed transitions in a collection of sequences
in a discrete space.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
lag_time : int
The time (index) delay for the counts.
sliding_window : bool
When lag_time > 1, consider *all*
``N = lag_time`` strided sequences starting from index
0, 1, 2, ..., ``lag_time - 1``. The total, raw counts will
be divided by ``N``. When this is False, only start from index 0.
Returns
-------
counts : array, shape=(n_states, n_states)
``counts[i][j]`` counts the number of times a sequences was in state
`i` at time t, and state `j` at time `t+self.lag_time`, over the
full set of trajectories.
mapping : dict
Mapping from the items in the sequences to the indices in
``(0, n_states-1)`` used for the count matrix.
Examples
--------
>>> sequence = [0, 0, 0, 1, 1]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[2, 1],
[0, 1]]
>>> print mapping
{0: 0, 1: 1}
>>> sequence = [100, 200, 300]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
>>> print mapping
{100: 0, 200: 1, 300: 2}
Notes
-----
`None` and `NaN` are recognized immediately as invalid labels. Therefore,
transition counts from or to a sequence item which is NaN or None will not
be counted. The mapping return value will not include the NaN or None.
"""
if (not sliding_window) and lag_time > 1:
return _transition_counts([X[::lag_time] for X in sequences],
lag_time=1)
classes = np.unique(np.concatenate(sequences))
contains_nan = (classes.dtype.kind == 'f') and np.any(np.isnan(classes))
contains_none = any(c is None for c in classes)
if contains_nan:
classes = classes[~np.isnan(classes)]
if contains_none:
classes = [c for c in classes if c is not None]
n_states = len(classes)
mapping = dict(zip(classes, range(n_states)))
mapping_is_identity = (not contains_nan
and not contains_none
and classes.dtype.kind == 'i'
and np.all(classes == np.arange(n_states)))
mapping_fn = np.vectorize(mapping.get, otypes=[np.int])
none_to_nan = np.vectorize(lambda x: np.nan if x is None else x,
otypes=[np.float])
counts = np.zeros((n_states, n_states), dtype=float)
_transitions = []
for y in sequences:
y = np.asarray(y)
from_states = y[: -lag_time: 1]
to_states = y[lag_time::1]
if contains_none:
from_states = none_to_nan(from_states)
to_states = none_to_nan(to_states)
if contains_nan or contains_none:
# mask out nan in either from_states or to_states
mask = ~(np.isnan(from_states) + np.isnan(to_states))
from_states = from_states[mask]
to_states = to_states[mask]
if (not mapping_is_identity) and len(from_states) > 0 and len(
to_states) > 0:
from_states = mapping_fn(from_states)
to_states = mapping_fn(to_states)
_transitions.append(np.row_stack((from_states, to_states)))
transitions = np.hstack(_transitions)
C = coo_matrix((np.ones(transitions.shape[1], dtype=int), transitions),
shape=(n_states, n_states))
counts = counts + np.asarray(C.todense())
# If sliding window is False, this function will be called recursively
# with strided trajectories and lag_time = 1, which gives the desired
# number of counts. If sliding window is True, the counts are divided
# by the "number of windows" (i.e. the lag_time). Count magnitudes
# will be comparable between sliding-window and non-sliding-window cases.
# If lag_time = 1, sliding_window makes no difference.
counts /= float(lag_time)
return counts, mapping | [
"def",
"_transition_counts",
"(",
"sequences",
",",
"lag_time",
"=",
"1",
",",
"sliding_window",
"=",
"True",
")",
":",
"if",
"(",
"not",
"sliding_window",
")",
"and",
"lag_time",
">",
"1",
":",
"return",
"_transition_counts",
"(",
"[",
"X",
"[",
":",
":... | Count the number of directed transitions in a collection of sequences
in a discrete space.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
lag_time : int
The time (index) delay for the counts.
sliding_window : bool
When lag_time > 1, consider *all*
``N = lag_time`` strided sequences starting from index
0, 1, 2, ..., ``lag_time - 1``. The total, raw counts will
be divided by ``N``. When this is False, only start from index 0.
Returns
-------
counts : array, shape=(n_states, n_states)
``counts[i][j]`` counts the number of times a sequences was in state
`i` at time t, and state `j` at time `t+self.lag_time`, over the
full set of trajectories.
mapping : dict
Mapping from the items in the sequences to the indices in
``(0, n_states-1)`` used for the count matrix.
Examples
--------
>>> sequence = [0, 0, 0, 1, 1]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[2, 1],
[0, 1]]
>>> print mapping
{0: 0, 1: 1}
>>> sequence = [100, 200, 300]
>>> counts, mapping = _transition_counts([sequence])
>>> print counts
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
>>> print mapping
{100: 0, 200: 1, 300: 2}
Notes
-----
`None` and `NaN` are recognized immediately as invalid labels. Therefore,
transition counts from or to a sequence item which is NaN or None will not
be counted. The mapping return value will not include the NaN or None. | [
"Count",
"the",
"number",
"of",
"directed",
"transitions",
"in",
"a",
"collection",
"of",
"sequences",
"in",
"a",
"discrete",
"space",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L487-L602 | train | 212,777 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _MappingTransformMixin.partial_transform | def partial_transform(self, sequence, mode='clip'):
"""Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequence : array-like
A 1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequence` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequence : list or ndarray
If mode is "fill", return an ndarray in internal indexing.
If mode is "clip", return a list of ndarrays each in internal
indexing.
"""
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequence = np.asarray(sequence)
if sequence.ndim != 1:
raise ValueError("Each sequence must be 1D")
f = np.vectorize(lambda k: self.mapping_.get(k, np.nan),
otypes=[np.float])
a = f(sequence)
if mode == 'fill':
if np.all(np.mod(a, 1) == 0):
result = a.astype(int)
else:
result = a
elif mode == 'clip':
result = [a[s].astype(int) for s in
np.ma.clump_unmasked(np.ma.masked_invalid(a))]
else:
raise RuntimeError()
return result | python | def partial_transform(self, sequence, mode='clip'):
"""Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequence : array-like
A 1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequence` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequence : list or ndarray
If mode is "fill", return an ndarray in internal indexing.
If mode is "clip", return a list of ndarrays each in internal
indexing.
"""
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequence = np.asarray(sequence)
if sequence.ndim != 1:
raise ValueError("Each sequence must be 1D")
f = np.vectorize(lambda k: self.mapping_.get(k, np.nan),
otypes=[np.float])
a = f(sequence)
if mode == 'fill':
if np.all(np.mod(a, 1) == 0):
result = a.astype(int)
else:
result = a
elif mode == 'clip':
result = [a[s].astype(int) for s in
np.ma.clump_unmasked(np.ma.masked_invalid(a))]
else:
raise RuntimeError()
return result | [
"def",
"partial_transform",
"(",
"self",
",",
"sequence",
",",
"mode",
"=",
"'clip'",
")",
":",
"if",
"mode",
"not",
"in",
"[",
"'clip'",
",",
"'fill'",
"]",
":",
"raise",
"ValueError",
"(",
"'mode must be one of [\"clip\", \"fill\"]: %s'",
"%",
"mode",
")",
... | Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequence : array-like
A 1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequence` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequence : list or ndarray
If mode is "fill", return an ndarray in internal indexing.
If mode is "clip", return a list of ndarrays each in internal
indexing. | [
"Transform",
"a",
"sequence",
"to",
"internal",
"indexing"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L29-L87 | train | 212,778 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _MappingTransformMixin.transform | def transform(self, sequences, mode='clip'):
"""Transform a list of sequences to internal indexing
Recall that `sequences` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequences : list
List of sequences in internal indexing
"""
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequences = list_of_1d(sequences)
result = []
for y in sequences:
if mode == 'fill':
result.append(self.partial_transform(y, mode))
elif mode == 'clip':
result.extend(self.partial_transform(y, mode))
else:
raise RuntimeError()
return result | python | def transform(self, sequences, mode='clip'):
"""Transform a list of sequences to internal indexing
Recall that `sequences` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequences : list
List of sequences in internal indexing
"""
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequences = list_of_1d(sequences)
result = []
for y in sequences:
if mode == 'fill':
result.append(self.partial_transform(y, mode))
elif mode == 'clip':
result.extend(self.partial_transform(y, mode))
else:
raise RuntimeError()
return result | [
"def",
"transform",
"(",
"self",
",",
"sequences",
",",
"mode",
"=",
"'clip'",
")",
":",
"if",
"mode",
"not",
"in",
"[",
"'clip'",
",",
"'fill'",
"]",
":",
"raise",
"ValueError",
"(",
"'mode must be one of [\"clip\", \"fill\"]: %s'",
"%",
"mode",
")",
"seque... | Transform a list of sequences to internal indexing
Recall that `sequences` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Parameters
----------
sequences : list of array-like
List of sequences, or a single sequence. Each sequence should be a
1D iterable of state labels. Labels can be integers, strings, or
other orderable objects.
mode : {'clip', 'fill'}
Method by which to treat labels in `sequences` which do not have
a corresponding index. This can be due, for example, to the ergodic
trimming step.
``clip``
Unmapped labels are removed during transform. If they occur
at the beginning or end of a sequence, the resulting transformed
sequence will be shorted. If they occur in the middle of a
sequence, that sequence will be broken into two (or more)
sequences. (Default)
``fill``
Unmapped labels will be replaced with NaN, to signal missing
data. [The use of NaN to signal missing data is not fantastic,
but it's consistent with current behavior of the ``pandas``
library.]
Returns
-------
mapped_sequences : list
List of sequences in internal indexing | [
"Transform",
"a",
"list",
"of",
"sequences",
"to",
"internal",
"indexing"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L89-L138 | train | 212,779 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _MappingTransformMixin._parse_ergodic_cutoff | def _parse_ergodic_cutoff(self):
"""Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'.
"""
ec_is_str = isinstance(self.ergodic_cutoff, str)
if ec_is_str and self.ergodic_cutoff.lower() == 'on':
if self.sliding_window:
return 1.0 / self.lag_time
else:
return 1.0
elif ec_is_str and self.ergodic_cutoff.lower() == 'off':
return 0.0
else:
return self.ergodic_cutoff | python | def _parse_ergodic_cutoff(self):
"""Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'.
"""
ec_is_str = isinstance(self.ergodic_cutoff, str)
if ec_is_str and self.ergodic_cutoff.lower() == 'on':
if self.sliding_window:
return 1.0 / self.lag_time
else:
return 1.0
elif ec_is_str and self.ergodic_cutoff.lower() == 'off':
return 0.0
else:
return self.ergodic_cutoff | [
"def",
"_parse_ergodic_cutoff",
"(",
"self",
")",
":",
"ec_is_str",
"=",
"isinstance",
"(",
"self",
".",
"ergodic_cutoff",
",",
"str",
")",
"if",
"ec_is_str",
"and",
"self",
".",
"ergodic_cutoff",
".",
"lower",
"(",
")",
"==",
"'on'",
":",
"if",
"self",
... | Get a numeric value from the ergodic_cutoff input,
which can be 'on' or 'off'. | [
"Get",
"a",
"numeric",
"value",
"from",
"the",
"ergodic_cutoff",
"input",
"which",
"can",
"be",
"on",
"or",
"off",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L140-L153 | train | 212,780 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _MappingTransformMixin.inverse_transform | def inverse_transform(self, sequences):
"""Transform a list of sequences from internal indexing into
labels
Parameters
----------
sequences : list
List of sequences, each of which is one-dimensional array of
integers in ``0, ..., n_states_ - 1``.
Returns
-------
sequences : list
List of sequences, each of which is one-dimensional array
of labels.
"""
sequences = list_of_1d(sequences)
inverse_mapping = {v: k for k, v in self.mapping_.items()}
f = np.vectorize(inverse_mapping.get)
result = []
for y in sequences:
uq = np.unique(y)
if not np.all(np.logical_and(0 <= uq, uq < self.n_states_)):
raise ValueError('sequence must be between 0 and n_states-1')
result.append(f(y))
return result | python | def inverse_transform(self, sequences):
"""Transform a list of sequences from internal indexing into
labels
Parameters
----------
sequences : list
List of sequences, each of which is one-dimensional array of
integers in ``0, ..., n_states_ - 1``.
Returns
-------
sequences : list
List of sequences, each of which is one-dimensional array
of labels.
"""
sequences = list_of_1d(sequences)
inverse_mapping = {v: k for k, v in self.mapping_.items()}
f = np.vectorize(inverse_mapping.get)
result = []
for y in sequences:
uq = np.unique(y)
if not np.all(np.logical_and(0 <= uq, uq < self.n_states_)):
raise ValueError('sequence must be between 0 and n_states-1')
result.append(f(y))
return result | [
"def",
"inverse_transform",
"(",
"self",
",",
"sequences",
")",
":",
"sequences",
"=",
"list_of_1d",
"(",
"sequences",
")",
"inverse_mapping",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"mapping_",
".",
"items",
"(",
")",
"}",
... | Transform a list of sequences from internal indexing into
labels
Parameters
----------
sequences : list
List of sequences, each of which is one-dimensional array of
integers in ``0, ..., n_states_ - 1``.
Returns
-------
sequences : list
List of sequences, each of which is one-dimensional array
of labels. | [
"Transform",
"a",
"list",
"of",
"sequences",
"from",
"internal",
"indexing",
"into",
"labels"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L155-L182 | train | 212,781 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _SampleMSMMixin.sample_discrete | def sample_discrete(self, state=None, n_steps=100, random_state=None):
r"""Generate a random sequence of states by propagating the model
using discrete time steps given by the model lagtime.
Parameters
----------
state : {None, ndarray, label}
Specify the starting state for the chain.
``None``
Choose the initial state by randomly drawing from the model's
stationary distribution.
``array-like``
If ``state`` is a 1D array with length equal to ``n_states_``,
then it is is interpreted as an initial multinomial
distribution from which to draw the chain's initial state.
Note that the indexing semantics of this array must match the
_internal_ indexing of this model.
otherwise
Otherwise, ``state`` is interpreted as a particular
deterministic state label from which to begin the trajectory.
n_steps : int
Lengths of the resulting trajectory
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Returns
-------
sequence : array of length n_steps
A randomly sampled label sequence
"""
random = check_random_state(random_state)
r = random.rand(1 + n_steps)
if state is None:
initial = np.sum(np.cumsum(self.populations_) < r[0])
elif hasattr(state, '__len__') and len(state) == self.n_states_:
initial = np.sum(np.cumsum(state) < r[0])
else:
initial = self.mapping_[state]
cstr = np.cumsum(self.transmat_, axis=1)
chain = [initial]
for i in range(1, n_steps):
chain.append(np.sum(cstr[chain[i - 1], :] < r[i]))
return self.inverse_transform([chain])[0] | python | def sample_discrete(self, state=None, n_steps=100, random_state=None):
r"""Generate a random sequence of states by propagating the model
using discrete time steps given by the model lagtime.
Parameters
----------
state : {None, ndarray, label}
Specify the starting state for the chain.
``None``
Choose the initial state by randomly drawing from the model's
stationary distribution.
``array-like``
If ``state`` is a 1D array with length equal to ``n_states_``,
then it is is interpreted as an initial multinomial
distribution from which to draw the chain's initial state.
Note that the indexing semantics of this array must match the
_internal_ indexing of this model.
otherwise
Otherwise, ``state`` is interpreted as a particular
deterministic state label from which to begin the trajectory.
n_steps : int
Lengths of the resulting trajectory
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Returns
-------
sequence : array of length n_steps
A randomly sampled label sequence
"""
random = check_random_state(random_state)
r = random.rand(1 + n_steps)
if state is None:
initial = np.sum(np.cumsum(self.populations_) < r[0])
elif hasattr(state, '__len__') and len(state) == self.n_states_:
initial = np.sum(np.cumsum(state) < r[0])
else:
initial = self.mapping_[state]
cstr = np.cumsum(self.transmat_, axis=1)
chain = [initial]
for i in range(1, n_steps):
chain.append(np.sum(cstr[chain[i - 1], :] < r[i]))
return self.inverse_transform([chain])[0] | [
"def",
"sample_discrete",
"(",
"self",
",",
"state",
"=",
"None",
",",
"n_steps",
"=",
"100",
",",
"random_state",
"=",
"None",
")",
":",
"random",
"=",
"check_random_state",
"(",
"random_state",
")",
"r",
"=",
"random",
".",
"rand",
"(",
"1",
"+",
"n_... | r"""Generate a random sequence of states by propagating the model
using discrete time steps given by the model lagtime.
Parameters
----------
state : {None, ndarray, label}
Specify the starting state for the chain.
``None``
Choose the initial state by randomly drawing from the model's
stationary distribution.
``array-like``
If ``state`` is a 1D array with length equal to ``n_states_``,
then it is is interpreted as an initial multinomial
distribution from which to draw the chain's initial state.
Note that the indexing semantics of this array must match the
_internal_ indexing of this model.
otherwise
Otherwise, ``state`` is interpreted as a particular
deterministic state label from which to begin the trajectory.
n_steps : int
Lengths of the resulting trajectory
random_state : int or RandomState instance or None (default)
Pseudo Random Number generator seed control. If None, use the
numpy.random singleton.
Returns
-------
sequence : array of length n_steps
A randomly sampled label sequence | [
"r",
"Generate",
"a",
"random",
"sequence",
"of",
"states",
"by",
"propagating",
"the",
"model",
"using",
"discrete",
"time",
"steps",
"given",
"by",
"the",
"model",
"lagtime",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L216-L264 | train | 212,782 |
msmbuilder/msmbuilder | msmbuilder/msm/core.py | _SampleMSMMixin.draw_samples | def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
n_samples : int
How many samples to return for any given state.
Returns
-------
selected_pairs_by_state : np.array, dtype=int,
shape=(n_states, n_samples, 2) selected_pairs_by_state[state] gives
an array of randomly selected (trj, frame) pairs from the specified
state.
See Also
--------
utils.map_drawn_samples : Extract conformations from MD trajectories by
index.
"""
if not any([isinstance(seq, collections.Iterable)
for seq in sequences]):
sequences = [sequences]
random = check_random_state(random_state)
selected_pairs_by_state = []
for state in range(self.n_states_):
all_frames = [np.where(a == state)[0] for a in sequences]
pairs = [(trj, frame) for (trj, frames) in enumerate(all_frames)
for frame in frames]
if pairs:
selected_pairs_by_state.append(
[pairs[random.choice(len(pairs))]
for i in range(n_samples)])
else:
selected_pairs_by_state.append([])
return np.array(selected_pairs_by_state) | python | def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
n_samples : int
How many samples to return for any given state.
Returns
-------
selected_pairs_by_state : np.array, dtype=int,
shape=(n_states, n_samples, 2) selected_pairs_by_state[state] gives
an array of randomly selected (trj, frame) pairs from the specified
state.
See Also
--------
utils.map_drawn_samples : Extract conformations from MD trajectories by
index.
"""
if not any([isinstance(seq, collections.Iterable)
for seq in sequences]):
sequences = [sequences]
random = check_random_state(random_state)
selected_pairs_by_state = []
for state in range(self.n_states_):
all_frames = [np.where(a == state)[0] for a in sequences]
pairs = [(trj, frame) for (trj, frames) in enumerate(all_frames)
for frame in frames]
if pairs:
selected_pairs_by_state.append(
[pairs[random.choice(len(pairs))]
for i in range(n_samples)])
else:
selected_pairs_by_state.append([])
return np.array(selected_pairs_by_state) | [
"def",
"draw_samples",
"(",
"self",
",",
"sequences",
",",
"n_samples",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"not",
"any",
"(",
"[",
"isinstance",
"(",
"seq",
",",
"collections",
".",
"Iterable",
")",
"for",
"seq",
"in",
"sequences",
"]",
... | Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
n_samples : int
How many samples to return for any given state.
Returns
-------
selected_pairs_by_state : np.array, dtype=int,
shape=(n_states, n_samples, 2) selected_pairs_by_state[state] gives
an array of randomly selected (trj, frame) pairs from the specified
state.
See Also
--------
utils.map_drawn_samples : Extract conformations from MD trajectories by
index. | [
"Sample",
"conformations",
"for",
"a",
"sequences",
"of",
"states",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/msm/core.py#L266-L308 | train | 212,783 |
msmbuilder/msmbuilder | msmbuilder/lumping/mvca.py | MVCA._do_lumping | def _do_lumping(self):
"""Do the MVCA lumping.
"""
model = LandmarkAgglomerative(linkage='ward',
n_clusters=self.n_macrostates,
metric=self.metric,
n_landmarks=self.n_landmarks,
landmark_strategy=self.landmark_strategy,
random_state=self.random_state)
model.fit([self.transmat_])
if self.fit_only:
microstate_mapping_ = model.landmark_labels_
else:
microstate_mapping_ = model.transform([self.transmat_])[0]
self.microstate_mapping_ = microstate_mapping_ | python | def _do_lumping(self):
"""Do the MVCA lumping.
"""
model = LandmarkAgglomerative(linkage='ward',
n_clusters=self.n_macrostates,
metric=self.metric,
n_landmarks=self.n_landmarks,
landmark_strategy=self.landmark_strategy,
random_state=self.random_state)
model.fit([self.transmat_])
if self.fit_only:
microstate_mapping_ = model.landmark_labels_
else:
microstate_mapping_ = model.transform([self.transmat_])[0]
self.microstate_mapping_ = microstate_mapping_ | [
"def",
"_do_lumping",
"(",
"self",
")",
":",
"model",
"=",
"LandmarkAgglomerative",
"(",
"linkage",
"=",
"'ward'",
",",
"n_clusters",
"=",
"self",
".",
"n_macrostates",
",",
"metric",
"=",
"self",
".",
"metric",
",",
"n_landmarks",
"=",
"self",
".",
"n_lan... | Do the MVCA lumping. | [
"Do",
"the",
"MVCA",
"lumping",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/lumping/mvca.py#L102-L119 | train | 212,784 |
msmbuilder/msmbuilder | msmbuilder/decomposition/ksparsetica.py | KSparseTICA._truncate | def _truncate(self, x, k):
''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 '''
not_F = np.argsort(np.abs(x))[:-k]
x[not_F] = 0
return x | python | def _truncate(self, x, k):
''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 '''
not_F = np.argsort(np.abs(x))[:-k]
x[not_F] = 0
return x | [
"def",
"_truncate",
"(",
"self",
",",
"x",
",",
"k",
")",
":",
"not_F",
"=",
"np",
".",
"argsort",
"(",
"np",
".",
"abs",
"(",
"x",
")",
")",
"[",
":",
"-",
"k",
"]",
"x",
"[",
"not_F",
"]",
"=",
"0",
"return",
"x"
] | given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 | [
"given",
"a",
"vector",
"x",
"leave",
"its",
"top",
"-",
"k",
"absolute",
"-",
"value",
"entries",
"alone",
"and",
"set",
"the",
"rest",
"to",
"0"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/ksparsetica.py#L129-L133 | train | 212,785 |
msmbuilder/msmbuilder | msmbuilder/decomposition/ksparsetica.py | KSparseTICA._truncated_power_method | def _truncated_power_method(self, A, x0, k, max_iter=10000, thresh=1e-8):
'''
given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncated Power Method for Sparse Eigenvalue Problems."
Journal of Machine Learning Research. Vol. 14. 2013.
http://www.jmlr.org/papers/volume14/yuan13a/yuan13a.pdf
'''
xts = [x0]
for t in range(max_iter):
xts.append(self._normalize(self._truncate(np.dot(A, xts[-1]), k)))
if np.linalg.norm(xts[-1] - xts[-2]) < thresh: break
return xts[-1] | python | def _truncated_power_method(self, A, x0, k, max_iter=10000, thresh=1e-8):
'''
given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncated Power Method for Sparse Eigenvalue Problems."
Journal of Machine Learning Research. Vol. 14. 2013.
http://www.jmlr.org/papers/volume14/yuan13a/yuan13a.pdf
'''
xts = [x0]
for t in range(max_iter):
xts.append(self._normalize(self._truncate(np.dot(A, xts[-1]), k)))
if np.linalg.norm(xts[-1] - xts[-2]) < thresh: break
return xts[-1] | [
"def",
"_truncated_power_method",
"(",
"self",
",",
"A",
",",
"x0",
",",
"k",
",",
"max_iter",
"=",
"10000",
",",
"thresh",
"=",
"1e-8",
")",
":",
"xts",
"=",
"[",
"x0",
"]",
"for",
"t",
"in",
"range",
"(",
"max_iter",
")",
":",
"xts",
".",
"appe... | given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncated Power Method for Sparse Eigenvalue Problems."
Journal of Machine Learning Research. Vol. 14. 2013.
http://www.jmlr.org/papers/volume14/yuan13a/yuan13a.pdf | [
"given",
"a",
"matrix",
"A",
"an",
"initial",
"guess",
"x0",
"and",
"a",
"maximum",
"cardinality",
"k",
"find",
"the",
"best",
"k",
"-",
"sparse",
"approximation",
"to",
"its",
"dominant",
"eigenvector"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/decomposition/ksparsetica.py#L139-L155 | train | 212,786 |
msmbuilder/msmbuilder | msmbuilder/cluster/apm.py | APM._run | def _run(self):
"""Do the APM lumping.
"""
# print("Doing APM Clustering...")
# Start looping for maxIter times
n_macrostates = 1 # initialized as 1 because no macrostate exist in loop 0
metaQ = -1.0
prevQ = -1.0
global_maxQ = -1.0
local_maxQ = -1.0
for iter in range(self.max_iter):
self.__max_state = -1
self.__micro_stack = []
for k in range(n_macrostates):
self._do_split(micro_state=k, sub_clus=self.sub_clus)
self._do_time_clustering(macro_state=k)
# do Lumping
n_micro_states = np.amax(self.__temp_labels_) + 1
if n_micro_states > self.n_macrostates:
# print("PCCA Lumping...", n_micro_states, "microstates")
self.__temp_MacroAssignments_ = self._do_lumping(
n_macrostates=n_macrostates)
#self.__temp_labels_ = [copy.copy(element) for element in self.__temp_MacroAssignments_]
#Calculate Metastabilty
prevQ = metaQ
metaQ = self.__temp_transmat_.diagonal().sum()
metaQ /= len(self.__temp_transmat_)
else:
self.__temp_MacroAssignments_ = [
copy.copy(element) for element in self.__temp_labels_
]
# Optimization / Monte-Carlo
acceptedMove = False
MCacc = np.exp(metaQ * metaQ - prevQ * prevQ)
if MCacc > 1.0:
MCacc = 1.0
optLim = 0.95
if MCacc > optLim:
acceptedMove = True
if acceptedMove:
local_maxQ = metaQ
if metaQ > global_maxQ:
global_maxQ = metaQ
self.MacroAssignments_ = [
copy.copy(element)
for element in self.__temp_MacroAssignments_
]
self.labels_ = [copy.copy(element)
for element in self.__temp_labels_]
self.transmat_ = self.__temp_transmat_
# print("Loop:", iter, "AcceptedMove?", acceptedMove, "metaQ:",
# metaQ, "prevQ:", prevQ, "global_maxQ:", global_maxQ,
# "local_maxQ:", local_maxQ, "macroCount:", n_macrostates)
#set n_macrostates
n_macrostates = self.n_macrostates
self.__temp_labels_ = [copy.copy(element)
for element in self.__temp_MacroAssignments_
] | python | def _run(self):
"""Do the APM lumping.
"""
# print("Doing APM Clustering...")
# Start looping for maxIter times
n_macrostates = 1 # initialized as 1 because no macrostate exist in loop 0
metaQ = -1.0
prevQ = -1.0
global_maxQ = -1.0
local_maxQ = -1.0
for iter in range(self.max_iter):
self.__max_state = -1
self.__micro_stack = []
for k in range(n_macrostates):
self._do_split(micro_state=k, sub_clus=self.sub_clus)
self._do_time_clustering(macro_state=k)
# do Lumping
n_micro_states = np.amax(self.__temp_labels_) + 1
if n_micro_states > self.n_macrostates:
# print("PCCA Lumping...", n_micro_states, "microstates")
self.__temp_MacroAssignments_ = self._do_lumping(
n_macrostates=n_macrostates)
#self.__temp_labels_ = [copy.copy(element) for element in self.__temp_MacroAssignments_]
#Calculate Metastabilty
prevQ = metaQ
metaQ = self.__temp_transmat_.diagonal().sum()
metaQ /= len(self.__temp_transmat_)
else:
self.__temp_MacroAssignments_ = [
copy.copy(element) for element in self.__temp_labels_
]
# Optimization / Monte-Carlo
acceptedMove = False
MCacc = np.exp(metaQ * metaQ - prevQ * prevQ)
if MCacc > 1.0:
MCacc = 1.0
optLim = 0.95
if MCacc > optLim:
acceptedMove = True
if acceptedMove:
local_maxQ = metaQ
if metaQ > global_maxQ:
global_maxQ = metaQ
self.MacroAssignments_ = [
copy.copy(element)
for element in self.__temp_MacroAssignments_
]
self.labels_ = [copy.copy(element)
for element in self.__temp_labels_]
self.transmat_ = self.__temp_transmat_
# print("Loop:", iter, "AcceptedMove?", acceptedMove, "metaQ:",
# metaQ, "prevQ:", prevQ, "global_maxQ:", global_maxQ,
# "local_maxQ:", local_maxQ, "macroCount:", n_macrostates)
#set n_macrostates
n_macrostates = self.n_macrostates
self.__temp_labels_ = [copy.copy(element)
for element in self.__temp_MacroAssignments_
] | [
"def",
"_run",
"(",
"self",
")",
":",
"# print(\"Doing APM Clustering...\")",
"# Start looping for maxIter times",
"n_macrostates",
"=",
"1",
"# initialized as 1 because no macrostate exist in loop 0",
"metaQ",
"=",
"-",
"1.0",
"prevQ",
"=",
"-",
"1.0",
"global_maxQ",
... | Do the APM lumping. | [
"Do",
"the",
"APM",
"lumping",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/apm.py#L102-L167 | train | 212,787 |
msmbuilder/msmbuilder | msmbuilder/featurizer/indices.py | get_atompair_indices | def get_atompair_indices(reference_traj, keep_atoms=None,
exclude_atoms=None, reject_bonded=True):
"""Get a list of acceptable atom pairs.
Parameters
----------
reference_traj : mdtraj.Trajectory
Trajectory to grab atom pairs from
keep_atoms : np.ndarray, dtype=string, optional
Select only these atom names. Defaults to N, CA, CB, C, O, H
exclude_atoms : np.ndarray, dtype=string, optional
Exclude these atom names
reject_bonded : bool, default=True
If True, exclude bonded atompairs.
Returns
-------
atom_indices : np.ndarray, dtype=int
The atom indices that pass your criteria
pair_indices : np.ndarray, dtype=int, shape=(N, 2)
Pairs of atom indices that pass your criteria.
Notes
-----
This function has been optimized for speed. A naive implementation
can be slow (~minutes) for large proteins.
"""
if keep_atoms is None:
keep_atoms = ATOM_NAMES
top, bonds = reference_traj.top.to_dataframe()
if keep_atoms is not None:
atom_indices = top[top.name.isin(keep_atoms) == True].index.values
if exclude_atoms is not None:
atom_indices = top[top.name.isin(exclude_atoms) == False].index.values
pair_indices = np.array(list(itertools.combinations(atom_indices, 2)))
if reject_bonded:
a_list = bonds.min(1)
b_list = bonds.max(1)
n = atom_indices.max() + 1
bond_hashes = a_list + b_list * n
pair_hashes = pair_indices[:, 0] + pair_indices[:, 1] * n
not_bonds = ~np.in1d(pair_hashes, bond_hashes)
pair_indices = np.array([(a, b) for k, (a, b)
in enumerate(pair_indices)
if not_bonds[k]])
return atom_indices, pair_indices | python | def get_atompair_indices(reference_traj, keep_atoms=None,
exclude_atoms=None, reject_bonded=True):
"""Get a list of acceptable atom pairs.
Parameters
----------
reference_traj : mdtraj.Trajectory
Trajectory to grab atom pairs from
keep_atoms : np.ndarray, dtype=string, optional
Select only these atom names. Defaults to N, CA, CB, C, O, H
exclude_atoms : np.ndarray, dtype=string, optional
Exclude these atom names
reject_bonded : bool, default=True
If True, exclude bonded atompairs.
Returns
-------
atom_indices : np.ndarray, dtype=int
The atom indices that pass your criteria
pair_indices : np.ndarray, dtype=int, shape=(N, 2)
Pairs of atom indices that pass your criteria.
Notes
-----
This function has been optimized for speed. A naive implementation
can be slow (~minutes) for large proteins.
"""
if keep_atoms is None:
keep_atoms = ATOM_NAMES
top, bonds = reference_traj.top.to_dataframe()
if keep_atoms is not None:
atom_indices = top[top.name.isin(keep_atoms) == True].index.values
if exclude_atoms is not None:
atom_indices = top[top.name.isin(exclude_atoms) == False].index.values
pair_indices = np.array(list(itertools.combinations(atom_indices, 2)))
if reject_bonded:
a_list = bonds.min(1)
b_list = bonds.max(1)
n = atom_indices.max() + 1
bond_hashes = a_list + b_list * n
pair_hashes = pair_indices[:, 0] + pair_indices[:, 1] * n
not_bonds = ~np.in1d(pair_hashes, bond_hashes)
pair_indices = np.array([(a, b) for k, (a, b)
in enumerate(pair_indices)
if not_bonds[k]])
return atom_indices, pair_indices | [
"def",
"get_atompair_indices",
"(",
"reference_traj",
",",
"keep_atoms",
"=",
"None",
",",
"exclude_atoms",
"=",
"None",
",",
"reject_bonded",
"=",
"True",
")",
":",
"if",
"keep_atoms",
"is",
"None",
":",
"keep_atoms",
"=",
"ATOM_NAMES",
"top",
",",
"bonds",
... | Get a list of acceptable atom pairs.
Parameters
----------
reference_traj : mdtraj.Trajectory
Trajectory to grab atom pairs from
keep_atoms : np.ndarray, dtype=string, optional
Select only these atom names. Defaults to N, CA, CB, C, O, H
exclude_atoms : np.ndarray, dtype=string, optional
Exclude these atom names
reject_bonded : bool, default=True
If True, exclude bonded atompairs.
Returns
-------
atom_indices : np.ndarray, dtype=int
The atom indices that pass your criteria
pair_indices : np.ndarray, dtype=int, shape=(N, 2)
Pairs of atom indices that pass your criteria.
Notes
-----
This function has been optimized for speed. A naive implementation
can be slow (~minutes) for large proteins. | [
"Get",
"a",
"list",
"of",
"acceptable",
"atom",
"pairs",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/indices.py#L8-L63 | train | 212,788 |
msmbuilder/msmbuilder | msmbuilder/io/sampling/sampling.py | sample_dimension | def sample_dimension(trajs, dimension, n_frames, scheme="linear"):
"""Sample a dimension of the data.
This method uses one of 3 schemes. All other dimensions are ignored, so
this might result in a really "jumpy" sampled trajectory.
Parameters
----------
trajs : dictionary of np.ndarray
Dictionary of tica-transformed trajectories, keyed by arbitrary keys.
The resulting trajectory indices will use these keys.
dimension : int
dimension to sample on
n_frames : int
Number of frames requested
scheme : {'linear', 'random', 'edges'}
'linear' samples the tic linearly, 'random' samples randomly
(thereby taking approximate free energies into account),
and 'edges' samples the edges of the tic only.
Returns
-------
inds : list of tuples
Tuples of (trajectory_index, frame_index), where trajectory_index is
in the domain of the keys of the input dictionary.
"""
fixed_indices = list(trajs.keys())
trajs = [trajs[k][:, [dimension]] for k in fixed_indices]
txx = np.concatenate([traj[:,0] for traj in trajs])
if scheme == "linear":
spaced_points = np.linspace(np.min(txx), np.max(txx), n_frames)
spaced_points = spaced_points[:, np.newaxis]
elif scheme == "random":
spaced_points = np.sort(np.random.choice(txx, n_frames))
spaced_points = spaced_points[:, np.newaxis]
elif scheme == "edge":
_cut_point = n_frames // 2
txx = np.sort(txx)
spaced_points = np.hstack((txx[:_cut_point],
txx[-_cut_point:]))
spaced_points = np.reshape(spaced_points, newshape=(len(spaced_points), 1))
else:
raise ValueError("Scheme has be to one of linear, random or edge")
tree = KDTree(trajs)
dists, inds = tree.query(spaced_points)
return [(fixed_indices[i], j) for i, j in inds] | python | def sample_dimension(trajs, dimension, n_frames, scheme="linear"):
"""Sample a dimension of the data.
This method uses one of 3 schemes. All other dimensions are ignored, so
this might result in a really "jumpy" sampled trajectory.
Parameters
----------
trajs : dictionary of np.ndarray
Dictionary of tica-transformed trajectories, keyed by arbitrary keys.
The resulting trajectory indices will use these keys.
dimension : int
dimension to sample on
n_frames : int
Number of frames requested
scheme : {'linear', 'random', 'edges'}
'linear' samples the tic linearly, 'random' samples randomly
(thereby taking approximate free energies into account),
and 'edges' samples the edges of the tic only.
Returns
-------
inds : list of tuples
Tuples of (trajectory_index, frame_index), where trajectory_index is
in the domain of the keys of the input dictionary.
"""
fixed_indices = list(trajs.keys())
trajs = [trajs[k][:, [dimension]] for k in fixed_indices]
txx = np.concatenate([traj[:,0] for traj in trajs])
if scheme == "linear":
spaced_points = np.linspace(np.min(txx), np.max(txx), n_frames)
spaced_points = spaced_points[:, np.newaxis]
elif scheme == "random":
spaced_points = np.sort(np.random.choice(txx, n_frames))
spaced_points = spaced_points[:, np.newaxis]
elif scheme == "edge":
_cut_point = n_frames // 2
txx = np.sort(txx)
spaced_points = np.hstack((txx[:_cut_point],
txx[-_cut_point:]))
spaced_points = np.reshape(spaced_points, newshape=(len(spaced_points), 1))
else:
raise ValueError("Scheme has be to one of linear, random or edge")
tree = KDTree(trajs)
dists, inds = tree.query(spaced_points)
return [(fixed_indices[i], j) for i, j in inds] | [
"def",
"sample_dimension",
"(",
"trajs",
",",
"dimension",
",",
"n_frames",
",",
"scheme",
"=",
"\"linear\"",
")",
":",
"fixed_indices",
"=",
"list",
"(",
"trajs",
".",
"keys",
"(",
")",
")",
"trajs",
"=",
"[",
"trajs",
"[",
"k",
"]",
"[",
":",
",",
... | Sample a dimension of the data.
This method uses one of 3 schemes. All other dimensions are ignored, so
this might result in a really "jumpy" sampled trajectory.
Parameters
----------
trajs : dictionary of np.ndarray
Dictionary of tica-transformed trajectories, keyed by arbitrary keys.
The resulting trajectory indices will use these keys.
dimension : int
dimension to sample on
n_frames : int
Number of frames requested
scheme : {'linear', 'random', 'edges'}
'linear' samples the tic linearly, 'random' samples randomly
(thereby taking approximate free energies into account),
and 'edges' samples the edges of the tic only.
Returns
-------
inds : list of tuples
Tuples of (trajectory_index, frame_index), where trajectory_index is
in the domain of the keys of the input dictionary. | [
"Sample",
"a",
"dimension",
"of",
"the",
"data",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/sampling/sampling.py#L11-L58 | train | 212,789 |
msmbuilder/msmbuilder | msmbuilder/cluster/ndgrid.py | _NDGrid.fit | def fit(self, X, y=None):
"""Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self
"""
X = array2d(X)
self.n_features = X.shape[1]
self.n_bins = self.n_bins_per_feature ** self.n_features
if self.min is None:
min = np.min(X, axis=0)
elif isinstance(self.min, numbers.Number):
min = self.min * np.ones(self.n_features)
else:
min = np.asarray(self.min)
if not min.shape == (self.n_features,):
raise ValueError('min shape error')
if self.max is None:
max = np.max(X, axis=0)
elif isinstance(self.max, numbers.Number):
max = self.max * np.ones(self.n_features)
else:
max = np.asarray(self.max)
if not max.shape == (self.n_features,):
raise ValueError('max shape error')
self.grid = np.array(
[np.linspace(min[i] - EPS, max[i] + EPS, self.n_bins_per_feature + 1)
for i in range(self.n_features)])
return self | python | def fit(self, X, y=None):
"""Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self
"""
X = array2d(X)
self.n_features = X.shape[1]
self.n_bins = self.n_bins_per_feature ** self.n_features
if self.min is None:
min = np.min(X, axis=0)
elif isinstance(self.min, numbers.Number):
min = self.min * np.ones(self.n_features)
else:
min = np.asarray(self.min)
if not min.shape == (self.n_features,):
raise ValueError('min shape error')
if self.max is None:
max = np.max(X, axis=0)
elif isinstance(self.max, numbers.Number):
max = self.max * np.ones(self.n_features)
else:
max = np.asarray(self.max)
if not max.shape == (self.n_features,):
raise ValueError('max shape error')
self.grid = np.array(
[np.linspace(min[i] - EPS, max[i] + EPS, self.n_bins_per_feature + 1)
for i in range(self.n_features)])
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
"=",
"array2d",
"(",
"X",
")",
"self",
".",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"n_bins",
"=",
"self",
".",
"n_bins_per_feature",
"**",
"se... | Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self | [
"Fit",
"the",
"grid"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/ndgrid.py#L66-L104 | train | 212,790 |
msmbuilder/msmbuilder | msmbuilder/cluster/ndgrid.py | _NDGrid.predict | def predict(self, X):
"""Get the index of the grid cell containing each sample in X
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data
Returns
-------
y : array, shape = [n_samples,]
Index of the grid cell containing each sample
"""
if np.any(X < self.grid[:, 0]) or np.any(X > self.grid[:, -1]):
raise ValueError('data out of min/max bounds')
binassign = np.zeros((self.n_features, len(X)), dtype=int)
for i in range(self.n_features):
binassign[i] = np.digitize(X[:, i], self.grid[i]) - 1
labels = np.dot(self.n_bins_per_feature ** np.arange(self.n_features), binassign)
assert np.max(labels) < self.n_bins
return labels | python | def predict(self, X):
"""Get the index of the grid cell containing each sample in X
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data
Returns
-------
y : array, shape = [n_samples,]
Index of the grid cell containing each sample
"""
if np.any(X < self.grid[:, 0]) or np.any(X > self.grid[:, -1]):
raise ValueError('data out of min/max bounds')
binassign = np.zeros((self.n_features, len(X)), dtype=int)
for i in range(self.n_features):
binassign[i] = np.digitize(X[:, i], self.grid[i]) - 1
labels = np.dot(self.n_bins_per_feature ** np.arange(self.n_features), binassign)
assert np.max(labels) < self.n_bins
return labels | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"if",
"np",
".",
"any",
"(",
"X",
"<",
"self",
".",
"grid",
"[",
":",
",",
"0",
"]",
")",
"or",
"np",
".",
"any",
"(",
"X",
">",
"self",
".",
"grid",
"[",
":",
",",
"-",
"1",
"]",
")",
... | Get the index of the grid cell containing each sample in X
Parameters
----------
X : array-like, shape = [n_samples, n_features]
New data
Returns
-------
y : array, shape = [n_samples,]
Index of the grid cell containing each sample | [
"Get",
"the",
"index",
"of",
"the",
"grid",
"cell",
"containing",
"each",
"sample",
"in",
"X"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/ndgrid.py#L106-L128 | train | 212,791 |
msmbuilder/msmbuilder | msmbuilder/featurizer/feature_union.py | FeatureUnion._check_same_length | def _check_same_length(self, trajs_tuple):
"""Check that the datasets are the same length"""
lens = [len(trajs) for trajs in trajs_tuple]
if len(set(lens)) > 1:
err = "Each dataset must be the same length. You gave: {}"
err = err.format(lens)
raise ValueError(err) | python | def _check_same_length(self, trajs_tuple):
"""Check that the datasets are the same length"""
lens = [len(trajs) for trajs in trajs_tuple]
if len(set(lens)) > 1:
err = "Each dataset must be the same length. You gave: {}"
err = err.format(lens)
raise ValueError(err) | [
"def",
"_check_same_length",
"(",
"self",
",",
"trajs_tuple",
")",
":",
"lens",
"=",
"[",
"len",
"(",
"trajs",
")",
"for",
"trajs",
"in",
"trajs_tuple",
"]",
"if",
"len",
"(",
"set",
"(",
"lens",
")",
")",
">",
"1",
":",
"err",
"=",
"\"Each dataset m... | Check that the datasets are the same length | [
"Check",
"that",
"the",
"datasets",
"are",
"the",
"same",
"length"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/feature_union.py#L45-L51 | train | 212,792 |
msmbuilder/msmbuilder | msmbuilder/featurizer/feature_union.py | FeatureUnion.transform | def transform(self, trajs_tuple, y=None):
"""Featurize a several trajectories.
Parameters
----------
traj_list : list(mdtraj.Trajectory)
Trajectories to be featurized.
Returns
-------
features : list(np.ndarray), length = len(traj_list)
The featurized trajectories. features[i] is the featurized
version of traj_list[i] and has shape
(n_samples_i, n_features)
"""
return [self.partial_transform(traj_zip)
for traj_zip in zip(*trajs_tuple)] | python | def transform(self, trajs_tuple, y=None):
"""Featurize a several trajectories.
Parameters
----------
traj_list : list(mdtraj.Trajectory)
Trajectories to be featurized.
Returns
-------
features : list(np.ndarray), length = len(traj_list)
The featurized trajectories. features[i] is the featurized
version of traj_list[i] and has shape
(n_samples_i, n_features)
"""
return [self.partial_transform(traj_zip)
for traj_zip in zip(*trajs_tuple)] | [
"def",
"transform",
"(",
"self",
",",
"trajs_tuple",
",",
"y",
"=",
"None",
")",
":",
"return",
"[",
"self",
".",
"partial_transform",
"(",
"traj_zip",
")",
"for",
"traj_zip",
"in",
"zip",
"(",
"*",
"trajs_tuple",
")",
"]"
] | Featurize a several trajectories.
Parameters
----------
traj_list : list(mdtraj.Trajectory)
Trajectories to be featurized.
Returns
-------
features : list(np.ndarray), length = len(traj_list)
The featurized trajectories. features[i] is the featurized
version of traj_list[i] and has shape
(n_samples_i, n_features) | [
"Featurize",
"a",
"several",
"trajectories",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/feature_union.py#L72-L88 | train | 212,793 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | backup | def backup(fn):
"""If ``fn`` exists, rename it and issue a warning
This function will rename an existing filename {fn}.bak.{i} where
i is the smallest integer that gives a filename that doesn't exist.
This naively uses a while loop to find such a filename, so there
shouldn't be too many existing backups or performance will degrade.
Parameters
----------
fn : str
The filename to check.
"""
if not os.path.exists(fn):
return
backnum = 1
backfmt = "{fn}.bak.{backnum}"
trial_fn = backfmt.format(fn=fn, backnum=backnum)
while os.path.exists(trial_fn):
backnum += 1
trial_fn = backfmt.format(fn=fn, backnum=backnum)
warnings.warn("{fn} exists. Moving it to {newfn}"
.format(fn=fn, newfn=trial_fn),
BackupWarning)
shutil.move(fn, trial_fn) | python | def backup(fn):
"""If ``fn`` exists, rename it and issue a warning
This function will rename an existing filename {fn}.bak.{i} where
i is the smallest integer that gives a filename that doesn't exist.
This naively uses a while loop to find such a filename, so there
shouldn't be too many existing backups or performance will degrade.
Parameters
----------
fn : str
The filename to check.
"""
if not os.path.exists(fn):
return
backnum = 1
backfmt = "{fn}.bak.{backnum}"
trial_fn = backfmt.format(fn=fn, backnum=backnum)
while os.path.exists(trial_fn):
backnum += 1
trial_fn = backfmt.format(fn=fn, backnum=backnum)
warnings.warn("{fn} exists. Moving it to {newfn}"
.format(fn=fn, newfn=trial_fn),
BackupWarning)
shutil.move(fn, trial_fn) | [
"def",
"backup",
"(",
"fn",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"return",
"backnum",
"=",
"1",
"backfmt",
"=",
"\"{fn}.bak.{backnum}\"",
"trial_fn",
"=",
"backfmt",
".",
"format",
"(",
"fn",
"=",
"fn",
",",
... | If ``fn`` exists, rename it and issue a warning
This function will rename an existing filename {fn}.bak.{i} where
i is the smallest integer that gives a filename that doesn't exist.
This naively uses a while loop to find such a filename, so there
shouldn't be too many existing backups or performance will degrade.
Parameters
----------
fn : str
The filename to check. | [
"If",
"fn",
"exists",
"rename",
"it",
"and",
"issue",
"a",
"warning"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L29-L55 | train | 212,794 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | default_key_to_path | def default_key_to_path(key, dfmt="{}", ffmt="{}.npy"):
"""Turn an arbitrary python object into a filename
This uses string formatting, so make sure your keys map
to unique strings. If the key is a tuple, it will join each
element of the tuple with '/', resulting in a filesystem
hierarchy of files.
"""
if isinstance(key, tuple):
paths = [dfmt.format(k) for k in key[:-1]]
paths += [ffmt.format(key[-1])]
return os.path.join(*paths)
else:
return ffmt.format(key) | python | def default_key_to_path(key, dfmt="{}", ffmt="{}.npy"):
"""Turn an arbitrary python object into a filename
This uses string formatting, so make sure your keys map
to unique strings. If the key is a tuple, it will join each
element of the tuple with '/', resulting in a filesystem
hierarchy of files.
"""
if isinstance(key, tuple):
paths = [dfmt.format(k) for k in key[:-1]]
paths += [ffmt.format(key[-1])]
return os.path.join(*paths)
else:
return ffmt.format(key) | [
"def",
"default_key_to_path",
"(",
"key",
",",
"dfmt",
"=",
"\"{}\"",
",",
"ffmt",
"=",
"\"{}.npy\"",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"tuple",
")",
":",
"paths",
"=",
"[",
"dfmt",
".",
"format",
"(",
"k",
")",
"for",
"k",
"in",
"key"... | Turn an arbitrary python object into a filename
This uses string formatting, so make sure your keys map
to unique strings. If the key is a tuple, it will join each
element of the tuple with '/', resulting in a filesystem
hierarchy of files. | [
"Turn",
"an",
"arbitrary",
"python",
"object",
"into",
"a",
"filename"
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L63-L76 | train | 212,795 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | preload_tops | def preload_tops(meta):
"""Load all topology files into memory.
This might save some performance compared to re-parsing the topology
file for each trajectory you try to load in. Typically, you have far
fewer (possibly 1) topologies than trajectories
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
tops : dict
Dictionary of ``md.Topology`` objects, keyed by "top_fn"
values.
"""
top_fns = set(meta['top_fn'])
tops = {}
for tfn in top_fns:
tops[tfn] = md.load_topology(tfn)
return tops | python | def preload_tops(meta):
"""Load all topology files into memory.
This might save some performance compared to re-parsing the topology
file for each trajectory you try to load in. Typically, you have far
fewer (possibly 1) topologies than trajectories
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
tops : dict
Dictionary of ``md.Topology`` objects, keyed by "top_fn"
values.
"""
top_fns = set(meta['top_fn'])
tops = {}
for tfn in top_fns:
tops[tfn] = md.load_topology(tfn)
return tops | [
"def",
"preload_tops",
"(",
"meta",
")",
":",
"top_fns",
"=",
"set",
"(",
"meta",
"[",
"'top_fn'",
"]",
")",
"tops",
"=",
"{",
"}",
"for",
"tfn",
"in",
"top_fns",
":",
"tops",
"[",
"tfn",
"]",
"=",
"md",
".",
"load_topology",
"(",
"tfn",
")",
"re... | Load all topology files into memory.
This might save some performance compared to re-parsing the topology
file for each trajectory you try to load in. Typically, you have far
fewer (possibly 1) topologies than trajectories
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
tops : dict
Dictionary of ``md.Topology`` objects, keyed by "top_fn"
values. | [
"Load",
"all",
"topology",
"files",
"into",
"memory",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L91-L113 | train | 212,796 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | preload_top | def preload_top(meta):
"""Load one topology file into memory.
This function checks to make sure there's only one topology file
in play. When sampling frames, you have to have all the same
topology to concatenate.
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
top : md.Topology
The one topology file that can be used for all trajectories.
"""
top_fns = set(meta['top_fn'])
if len(top_fns) != 1:
raise ValueError("More than one topology is used in this project!")
return md.load_topology(top_fns.pop()) | python | def preload_top(meta):
"""Load one topology file into memory.
This function checks to make sure there's only one topology file
in play. When sampling frames, you have to have all the same
topology to concatenate.
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
top : md.Topology
The one topology file that can be used for all trajectories.
"""
top_fns = set(meta['top_fn'])
if len(top_fns) != 1:
raise ValueError("More than one topology is used in this project!")
return md.load_topology(top_fns.pop()) | [
"def",
"preload_top",
"(",
"meta",
")",
":",
"top_fns",
"=",
"set",
"(",
"meta",
"[",
"'top_fn'",
"]",
")",
"if",
"len",
"(",
"top_fns",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"More than one topology is used in this project!\"",
")",
"return",
"m... | Load one topology file into memory.
This function checks to make sure there's only one topology file
in play. When sampling frames, you have to have all the same
topology to concatenate.
Parameters
----------
meta : pd.DataFrame
The DataFrame of metadata with a column named 'top_fn'
Returns
-------
top : md.Topology
The one topology file that can be used for all trajectories. | [
"Load",
"one",
"topology",
"file",
"into",
"memory",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L116-L136 | train | 212,797 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | itertrajs | def itertrajs(meta, stride=1):
"""Load one mdtraj trajectory at a time and yield it.
MDTraj does striding badly. It reads in the whole trajectory and
then performs a stride. We join(iterload) to conserve memory.
"""
tops = preload_tops(meta)
for i, row in meta.iterrows():
yield i, md.join(md.iterload(row['traj_fn'],
top=tops[row['top_fn']],
stride=stride),
discard_overlapping_frames=False,
check_topology=False) | python | def itertrajs(meta, stride=1):
"""Load one mdtraj trajectory at a time and yield it.
MDTraj does striding badly. It reads in the whole trajectory and
then performs a stride. We join(iterload) to conserve memory.
"""
tops = preload_tops(meta)
for i, row in meta.iterrows():
yield i, md.join(md.iterload(row['traj_fn'],
top=tops[row['top_fn']],
stride=stride),
discard_overlapping_frames=False,
check_topology=False) | [
"def",
"itertrajs",
"(",
"meta",
",",
"stride",
"=",
"1",
")",
":",
"tops",
"=",
"preload_tops",
"(",
"meta",
")",
"for",
"i",
",",
"row",
"in",
"meta",
".",
"iterrows",
"(",
")",
":",
"yield",
"i",
",",
"md",
".",
"join",
"(",
"md",
".",
"iter... | Load one mdtraj trajectory at a time and yield it.
MDTraj does striding badly. It reads in the whole trajectory and
then performs a stride. We join(iterload) to conserve memory. | [
"Load",
"one",
"mdtraj",
"trajectory",
"at",
"a",
"time",
"and",
"yield",
"it",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L139-L152 | train | 212,798 |
msmbuilder/msmbuilder | msmbuilder/io/io.py | render_meta | def render_meta(meta, fn="meta.pandas.html",
title="Project Metadata - MSMBuilder", pandas_kwargs=None):
"""Render a metadata dataframe as an html webpage for inspection.
Parameters
----------
meta : pd.Dataframe
The DataFrame of metadata
fn : str
Output filename (should end in html)
title : str
Page title
pandas_kwargs : dict
Arguments to be passed to pandas
"""
if pandas_kwargs is None:
pandas_kwargs = {}
kwargs_with_defaults = {
'classes': ('table', 'table-condensed', 'table-hover'),
}
kwargs_with_defaults.update(**pandas_kwargs)
env = Environment(loader=PackageLoader('msmbuilder', 'io_templates'))
templ = env.get_template("twitter-bootstrap.html")
rendered = templ.render(
title=title,
content=meta.to_html(**kwargs_with_defaults)
)
# Ugh, pandas hardcodes border="1"
rendered = re.sub(r' border="1"', '', rendered)
backup(fn)
with open(fn, 'w') as f:
f.write(rendered) | python | def render_meta(meta, fn="meta.pandas.html",
title="Project Metadata - MSMBuilder", pandas_kwargs=None):
"""Render a metadata dataframe as an html webpage for inspection.
Parameters
----------
meta : pd.Dataframe
The DataFrame of metadata
fn : str
Output filename (should end in html)
title : str
Page title
pandas_kwargs : dict
Arguments to be passed to pandas
"""
if pandas_kwargs is None:
pandas_kwargs = {}
kwargs_with_defaults = {
'classes': ('table', 'table-condensed', 'table-hover'),
}
kwargs_with_defaults.update(**pandas_kwargs)
env = Environment(loader=PackageLoader('msmbuilder', 'io_templates'))
templ = env.get_template("twitter-bootstrap.html")
rendered = templ.render(
title=title,
content=meta.to_html(**kwargs_with_defaults)
)
# Ugh, pandas hardcodes border="1"
rendered = re.sub(r' border="1"', '', rendered)
backup(fn)
with open(fn, 'w') as f:
f.write(rendered) | [
"def",
"render_meta",
"(",
"meta",
",",
"fn",
"=",
"\"meta.pandas.html\"",
",",
"title",
"=",
"\"Project Metadata - MSMBuilder\"",
",",
"pandas_kwargs",
"=",
"None",
")",
":",
"if",
"pandas_kwargs",
"is",
"None",
":",
"pandas_kwargs",
"=",
"{",
"}",
"kwargs_with... | Render a metadata dataframe as an html webpage for inspection.
Parameters
----------
meta : pd.Dataframe
The DataFrame of metadata
fn : str
Output filename (should end in html)
title : str
Page title
pandas_kwargs : dict
Arguments to be passed to pandas | [
"Render",
"a",
"metadata",
"dataframe",
"as",
"an",
"html",
"webpage",
"for",
"inspection",
"."
] | 556a93a170782f47be53f4a1e9d740fb1c8272b3 | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/io/io.py#L186-L222 | train | 212,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.