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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
requests/requests-kerberos | requests_kerberos/kerberos_.py | _negotiate_value | def _negotiate_value(response):
"""Extracts the gssapi authentication token from the appropriate header"""
if hasattr(_negotiate_value, 'regex'):
regex = _negotiate_value.regex
else:
# There's no need to re-compile this EVERY time it is called. Compile
# it once and you won't have the performance hit of the compilation.
regex = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)
_negotiate_value.regex = regex
authreq = response.headers.get('www-authenticate', None)
if authreq:
match_obj = regex.search(authreq)
if match_obj:
return match_obj.group(1)
return None | python | def _negotiate_value(response):
"""Extracts the gssapi authentication token from the appropriate header"""
if hasattr(_negotiate_value, 'regex'):
regex = _negotiate_value.regex
else:
# There's no need to re-compile this EVERY time it is called. Compile
# it once and you won't have the performance hit of the compilation.
regex = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)
_negotiate_value.regex = regex
authreq = response.headers.get('www-authenticate', None)
if authreq:
match_obj = regex.search(authreq)
if match_obj:
return match_obj.group(1)
return None | [
"def",
"_negotiate_value",
"(",
"response",
")",
":",
"if",
"hasattr",
"(",
"_negotiate_value",
",",
"'regex'",
")",
":",
"regex",
"=",
"_negotiate_value",
".",
"regex",
"else",
":",
"# There's no need to re-compile this EVERY time it is called. Compile",
"# it once and y... | Extracts the gssapi authentication token from the appropriate header | [
"Extracts",
"the",
"gssapi",
"authentication",
"token",
"from",
"the",
"appropriate",
"header"
] | d459afcd20d921f18bc435e8df0f120f3d2ea6a2 | https://github.com/requests/requests-kerberos/blob/d459afcd20d921f18bc435e8df0f120f3d2ea6a2/requests_kerberos/kerberos_.py#L78-L95 | train | 204,000 |
requests/requests-kerberos | requests_kerberos/kerberos_.py | HTTPKerberosAuth.generate_request_header | def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
# Flags used by kerberos module.
gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
if self.delegate:
gssflags |= kerberos.GSS_C_DELEG_FLAG
try:
kerb_stage = "authGSSClientInit()"
# contexts still need to be stored by host, but hostname_override
# allows use of an arbitrary hostname for the kerberos exchange
# (eg, in cases of aliased hosts, internal vs external, CNAMEs
# w/ name-based HTTP hosting)
kerb_host = self.hostname_override if self.hostname_override is not None else host
kerb_spn = "{0}@{1}".format(self.service, kerb_host)
result, self.context[host] = kerberos.authGSSClientInit(kerb_spn,
gssflags=gssflags, principal=self.principal)
if result < 1:
raise EnvironmentError(result, kerb_stage)
# if we have a previous response from the server, use it to continue
# the auth process, otherwise use an empty value
negotiate_resp_value = '' if is_preemptive else _negotiate_value(response)
kerb_stage = "authGSSClientStep()"
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host],
negotiate_resp_value,
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host],
negotiate_resp_value)
if result < 0:
raise EnvironmentError(result, kerb_stage)
kerb_stage = "authGSSClientResponse()"
gss_response = kerberos.authGSSClientResponse(self.context[host])
return "Negotiate {0}".format(gss_response)
except kerberos.GSSError as error:
log.exception(
"generate_request_header(): {0} failed:".format(kerb_stage))
log.exception(error)
raise KerberosExchangeError("%s failed: %s" % (kerb_stage, str(error.args)))
except EnvironmentError as error:
# ensure we raised this for translation to KerberosExchangeError
# by comparing errno to result, re-raise if not
if error.errno != result:
raise
message = "{0} failed, result: {1}".format(kerb_stage, result)
log.error("generate_request_header(): {0}".format(message))
raise KerberosExchangeError(message) | python | def generate_request_header(self, response, host, is_preemptive=False):
"""
Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail.
"""
# Flags used by kerberos module.
gssflags = kerberos.GSS_C_MUTUAL_FLAG | kerberos.GSS_C_SEQUENCE_FLAG
if self.delegate:
gssflags |= kerberos.GSS_C_DELEG_FLAG
try:
kerb_stage = "authGSSClientInit()"
# contexts still need to be stored by host, but hostname_override
# allows use of an arbitrary hostname for the kerberos exchange
# (eg, in cases of aliased hosts, internal vs external, CNAMEs
# w/ name-based HTTP hosting)
kerb_host = self.hostname_override if self.hostname_override is not None else host
kerb_spn = "{0}@{1}".format(self.service, kerb_host)
result, self.context[host] = kerberos.authGSSClientInit(kerb_spn,
gssflags=gssflags, principal=self.principal)
if result < 1:
raise EnvironmentError(result, kerb_stage)
# if we have a previous response from the server, use it to continue
# the auth process, otherwise use an empty value
negotiate_resp_value = '' if is_preemptive else _negotiate_value(response)
kerb_stage = "authGSSClientStep()"
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host],
negotiate_resp_value,
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host],
negotiate_resp_value)
if result < 0:
raise EnvironmentError(result, kerb_stage)
kerb_stage = "authGSSClientResponse()"
gss_response = kerberos.authGSSClientResponse(self.context[host])
return "Negotiate {0}".format(gss_response)
except kerberos.GSSError as error:
log.exception(
"generate_request_header(): {0} failed:".format(kerb_stage))
log.exception(error)
raise KerberosExchangeError("%s failed: %s" % (kerb_stage, str(error.args)))
except EnvironmentError as error:
# ensure we raised this for translation to KerberosExchangeError
# by comparing errno to result, re-raise if not
if error.errno != result:
raise
message = "{0} failed, result: {1}".format(kerb_stage, result)
log.error("generate_request_header(): {0}".format(message))
raise KerberosExchangeError(message) | [
"def",
"generate_request_header",
"(",
"self",
",",
"response",
",",
"host",
",",
"is_preemptive",
"=",
"False",
")",
":",
"# Flags used by kerberos module.",
"gssflags",
"=",
"kerberos",
".",
"GSS_C_MUTUAL_FLAG",
"|",
"kerberos",
".",
"GSS_C_SEQUENCE_FLAG",
"if",
"... | Generates the GSSAPI authentication token with kerberos.
If any GSSAPI step fails, raise KerberosExchangeError
with failure detail. | [
"Generates",
"the",
"GSSAPI",
"authentication",
"token",
"with",
"kerberos",
"."
] | d459afcd20d921f18bc435e8df0f120f3d2ea6a2 | https://github.com/requests/requests-kerberos/blob/d459afcd20d921f18bc435e8df0f120f3d2ea6a2/requests_kerberos/kerberos_.py#L189-L253 | train | 204,001 |
requests/requests-kerberos | requests_kerberos/kerberos_.py | HTTPKerberosAuth.handle_other | def handle_other(self, response):
"""Handles all responses with the exception of 401s.
This is necessary so that we can authenticate responses if requested"""
log.debug("handle_other(): Handling: %d" % response.status_code)
if self.mutual_authentication in (REQUIRED, OPTIONAL) and not self.auth_done:
is_http_error = response.status_code >= 400
if _negotiate_value(response) is not None:
log.debug("handle_other(): Authenticating the server")
if not self.authenticate_server(response):
# Mutual authentication failure when mutual auth is wanted,
# raise an exception so the user doesn't use an untrusted
# response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
# Authentication successful
log.debug("handle_other(): returning {0}".format(response))
self.auth_done = True
return response
elif is_http_error or self.mutual_authentication == OPTIONAL:
if not response.ok:
log.error("handle_other(): Mutual authentication unavailable "
"on {0} response".format(response.status_code))
if(self.mutual_authentication == REQUIRED and
self.sanitize_mutual_error_response):
return SanitizedResponse(response)
else:
return response
else:
# Unable to attempt mutual authentication when mutual auth is
# required, raise an exception so the user doesn't use an
# untrusted response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
else:
log.debug("handle_other(): returning {0}".format(response))
return response | python | def handle_other(self, response):
"""Handles all responses with the exception of 401s.
This is necessary so that we can authenticate responses if requested"""
log.debug("handle_other(): Handling: %d" % response.status_code)
if self.mutual_authentication in (REQUIRED, OPTIONAL) and not self.auth_done:
is_http_error = response.status_code >= 400
if _negotiate_value(response) is not None:
log.debug("handle_other(): Authenticating the server")
if not self.authenticate_server(response):
# Mutual authentication failure when mutual auth is wanted,
# raise an exception so the user doesn't use an untrusted
# response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
# Authentication successful
log.debug("handle_other(): returning {0}".format(response))
self.auth_done = True
return response
elif is_http_error or self.mutual_authentication == OPTIONAL:
if not response.ok:
log.error("handle_other(): Mutual authentication unavailable "
"on {0} response".format(response.status_code))
if(self.mutual_authentication == REQUIRED and
self.sanitize_mutual_error_response):
return SanitizedResponse(response)
else:
return response
else:
# Unable to attempt mutual authentication when mutual auth is
# required, raise an exception so the user doesn't use an
# untrusted response.
log.error("handle_other(): Mutual authentication failed")
raise MutualAuthenticationError("Unable to authenticate "
"{0}".format(response))
else:
log.debug("handle_other(): returning {0}".format(response))
return response | [
"def",
"handle_other",
"(",
"self",
",",
"response",
")",
":",
"log",
".",
"debug",
"(",
"\"handle_other(): Handling: %d\"",
"%",
"response",
".",
"status_code",
")",
"if",
"self",
".",
"mutual_authentication",
"in",
"(",
"REQUIRED",
",",
"OPTIONAL",
")",
"and... | Handles all responses with the exception of 401s.
This is necessary so that we can authenticate responses if requested | [
"Handles",
"all",
"responses",
"with",
"the",
"exception",
"of",
"401s",
"."
] | d459afcd20d921f18bc435e8df0f120f3d2ea6a2 | https://github.com/requests/requests-kerberos/blob/d459afcd20d921f18bc435e8df0f120f3d2ea6a2/requests_kerberos/kerberos_.py#L294-L339 | train | 204,002 |
requests/requests-kerberos | requests_kerberos/kerberos_.py | HTTPKerberosAuth.authenticate_server | def authenticate_server(self, response):
"""
Uses GSSAPI to authenticate the server.
Returns True on success, False on failure.
"""
log.debug("authenticate_server(): Authenticate header: {0}".format(
_negotiate_value(response)))
host = urlparse(response.url).hostname
try:
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host],
_negotiate_value(response),
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host],
_negotiate_value(response))
except kerberos.GSSError:
log.exception("authenticate_server(): authGSSClientStep() failed:")
return False
if result < 1:
log.error("authenticate_server(): authGSSClientStep() failed: "
"{0}".format(result))
return False
log.debug("authenticate_server(): returning {0}".format(response))
return True | python | def authenticate_server(self, response):
"""
Uses GSSAPI to authenticate the server.
Returns True on success, False on failure.
"""
log.debug("authenticate_server(): Authenticate header: {0}".format(
_negotiate_value(response)))
host = urlparse(response.url).hostname
try:
# If this is set pass along the struct to Kerberos
if self.cbt_struct:
result = kerberos.authGSSClientStep(self.context[host],
_negotiate_value(response),
channel_bindings=self.cbt_struct)
else:
result = kerberos.authGSSClientStep(self.context[host],
_negotiate_value(response))
except kerberos.GSSError:
log.exception("authenticate_server(): authGSSClientStep() failed:")
return False
if result < 1:
log.error("authenticate_server(): authGSSClientStep() failed: "
"{0}".format(result))
return False
log.debug("authenticate_server(): returning {0}".format(response))
return True | [
"def",
"authenticate_server",
"(",
"self",
",",
"response",
")",
":",
"log",
".",
"debug",
"(",
"\"authenticate_server(): Authenticate header: {0}\"",
".",
"format",
"(",
"_negotiate_value",
"(",
"response",
")",
")",
")",
"host",
"=",
"urlparse",
"(",
"response",... | Uses GSSAPI to authenticate the server.
Returns True on success, False on failure. | [
"Uses",
"GSSAPI",
"to",
"authenticate",
"the",
"server",
"."
] | d459afcd20d921f18bc435e8df0f120f3d2ea6a2 | https://github.com/requests/requests-kerberos/blob/d459afcd20d921f18bc435e8df0f120f3d2ea6a2/requests_kerberos/kerberos_.py#L341-L372 | train | 204,003 |
requests/requests-kerberos | requests_kerberos/kerberos_.py | HTTPKerberosAuth.handle_response | def handle_response(self, response, **kwargs):
"""Takes the given response and tries kerberos-auth, as needed."""
num_401s = kwargs.pop('num_401s', 0)
# Check if we have already tried to get the CBT data value
if not self.cbt_binding_tried and self.send_cbt:
# If we haven't tried, try getting it now
cbt_application_data = _get_channel_bindings_application_data(response)
if cbt_application_data:
# Only the latest version of pykerberos has this method available
try:
self.cbt_struct = kerberos.channelBindings(application_data=cbt_application_data)
except AttributeError:
# Using older version set to None
self.cbt_struct = None
# Regardless of the result, set tried to True so we don't waste time next time
self.cbt_binding_tried = True
if self.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
response.request.body.seek(self.pos)
if response.status_code == 401 and num_401s < 2:
# 401 Unauthorized. Handle it, and if it still comes back as 401,
# that means authentication failed.
_r = self.handle_401(response, **kwargs)
log.debug("handle_response(): returning %s", _r)
log.debug("handle_response() has seen %d 401 responses", num_401s)
num_401s += 1
return self.handle_response(_r, num_401s=num_401s, **kwargs)
elif response.status_code == 401 and num_401s >= 2:
# Still receiving 401 responses after attempting to handle them.
# Authentication has failed. Return the 401 response.
log.debug("handle_response(): returning 401 %s", response)
return response
else:
_r = self.handle_other(response)
log.debug("handle_response(): returning %s", _r)
return _r | python | def handle_response(self, response, **kwargs):
"""Takes the given response and tries kerberos-auth, as needed."""
num_401s = kwargs.pop('num_401s', 0)
# Check if we have already tried to get the CBT data value
if not self.cbt_binding_tried and self.send_cbt:
# If we haven't tried, try getting it now
cbt_application_data = _get_channel_bindings_application_data(response)
if cbt_application_data:
# Only the latest version of pykerberos has this method available
try:
self.cbt_struct = kerberos.channelBindings(application_data=cbt_application_data)
except AttributeError:
# Using older version set to None
self.cbt_struct = None
# Regardless of the result, set tried to True so we don't waste time next time
self.cbt_binding_tried = True
if self.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
response.request.body.seek(self.pos)
if response.status_code == 401 and num_401s < 2:
# 401 Unauthorized. Handle it, and if it still comes back as 401,
# that means authentication failed.
_r = self.handle_401(response, **kwargs)
log.debug("handle_response(): returning %s", _r)
log.debug("handle_response() has seen %d 401 responses", num_401s)
num_401s += 1
return self.handle_response(_r, num_401s=num_401s, **kwargs)
elif response.status_code == 401 and num_401s >= 2:
# Still receiving 401 responses after attempting to handle them.
# Authentication has failed. Return the 401 response.
log.debug("handle_response(): returning 401 %s", response)
return response
else:
_r = self.handle_other(response)
log.debug("handle_response(): returning %s", _r)
return _r | [
"def",
"handle_response",
"(",
"self",
",",
"response",
",",
"*",
"*",
"kwargs",
")",
":",
"num_401s",
"=",
"kwargs",
".",
"pop",
"(",
"'num_401s'",
",",
"0",
")",
"# Check if we have already tried to get the CBT data value",
"if",
"not",
"self",
".",
"cbt_bindi... | Takes the given response and tries kerberos-auth, as needed. | [
"Takes",
"the",
"given",
"response",
"and",
"tries",
"kerberos",
"-",
"auth",
"as",
"needed",
"."
] | d459afcd20d921f18bc435e8df0f120f3d2ea6a2 | https://github.com/requests/requests-kerberos/blob/d459afcd20d921f18bc435e8df0f120f3d2ea6a2/requests_kerberos/kerberos_.py#L374-L413 | train | 204,004 |
lionheart/bottlenose | bottlenose/api.py | _quote_query | def _quote_query(query):
"""Turn a dictionary into a query string in a URL, with keys
in alphabetical order."""
return "&".join("%s=%s" % (
k, urllib_quote(
unicode(query[k]).encode('utf-8'), safe='~'))
for k in sorted(query)) | python | def _quote_query(query):
"""Turn a dictionary into a query string in a URL, with keys
in alphabetical order."""
return "&".join("%s=%s" % (
k, urllib_quote(
unicode(query[k]).encode('utf-8'), safe='~'))
for k in sorted(query)) | [
"def",
"_quote_query",
"(",
"query",
")",
":",
"return",
"\"&\"",
".",
"join",
"(",
"\"%s=%s\"",
"%",
"(",
"k",
",",
"urllib_quote",
"(",
"unicode",
"(",
"query",
"[",
"k",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"'~'",
")",... | Turn a dictionary into a query string in a URL, with keys
in alphabetical order. | [
"Turn",
"a",
"dictionary",
"into",
"a",
"query",
"string",
"in",
"a",
"URL",
"with",
"keys",
"in",
"alphabetical",
"order",
"."
] | 14811c4fd87b8715039ad83b7b42560fd2fe1eee | https://github.com/lionheart/bottlenose/blob/14811c4fd87b8715039ad83b7b42560fd2fe1eee/bottlenose/api.py#L86-L92 | train | 204,005 |
lionheart/bottlenose | bottlenose/api.py | AmazonCall.api_url | def api_url(self, **kwargs):
"""The URL for making the given query against the API."""
query = {
'Operation': self.Operation,
'Service': "AWSECommerceService",
'Timestamp': time.strftime(
"%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
'Version': self.Version,
}
query.update(kwargs)
query['AWSAccessKeyId'] = self.AWSAccessKeyId
query['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ",
time.gmtime())
if self.AssociateTag:
query['AssociateTag'] = self.AssociateTag
service_domain = SERVICE_DOMAINS[self.Region][0]
quoted_strings = _quote_query(query)
data = "GET\n" + service_domain + "\n/onca/xml\n" + quoted_strings
# convert unicode to UTF8 bytes for hmac library
if type(self.AWSSecretAccessKey) is unicode:
self.AWSSecretAccessKey = self.AWSSecretAccessKey.encode('utf-8')
if type(data) is unicode:
data = data.encode('utf-8')
# calculate sha256 signature
digest = hmac.new(self.AWSSecretAccessKey, data, sha256).digest()
# base64 encode and urlencode
if sys.version_info[0] == 3:
signature = urllib.parse.quote(b64encode(digest))
else:
signature = urllib.quote(b64encode(digest))
return ("https://" + service_domain + "/onca/xml?" +
quoted_strings + "&Signature=%s" % signature) | python | def api_url(self, **kwargs):
"""The URL for making the given query against the API."""
query = {
'Operation': self.Operation,
'Service': "AWSECommerceService",
'Timestamp': time.strftime(
"%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
'Version': self.Version,
}
query.update(kwargs)
query['AWSAccessKeyId'] = self.AWSAccessKeyId
query['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ",
time.gmtime())
if self.AssociateTag:
query['AssociateTag'] = self.AssociateTag
service_domain = SERVICE_DOMAINS[self.Region][0]
quoted_strings = _quote_query(query)
data = "GET\n" + service_domain + "\n/onca/xml\n" + quoted_strings
# convert unicode to UTF8 bytes for hmac library
if type(self.AWSSecretAccessKey) is unicode:
self.AWSSecretAccessKey = self.AWSSecretAccessKey.encode('utf-8')
if type(data) is unicode:
data = data.encode('utf-8')
# calculate sha256 signature
digest = hmac.new(self.AWSSecretAccessKey, data, sha256).digest()
# base64 encode and urlencode
if sys.version_info[0] == 3:
signature = urllib.parse.quote(b64encode(digest))
else:
signature = urllib.quote(b64encode(digest))
return ("https://" + service_domain + "/onca/xml?" +
quoted_strings + "&Signature=%s" % signature) | [
"def",
"api_url",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"{",
"'Operation'",
":",
"self",
".",
"Operation",
",",
"'Service'",
":",
"\"AWSECommerceService\"",
",",
"'Timestamp'",
":",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%SZ\... | The URL for making the given query against the API. | [
"The",
"URL",
"for",
"making",
"the",
"given",
"query",
"against",
"the",
"API",
"."
] | 14811c4fd87b8715039ad83b7b42560fd2fe1eee | https://github.com/lionheart/bottlenose/blob/14811c4fd87b8715039ad83b7b42560fd2fe1eee/bottlenose/api.py#L159-L199 | train | 204,006 |
etingof/pyasn1 | pyasn1/type/base.py | Asn1ItemBase.isSameTypeWith | def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
"""Examine |ASN.1| type for equality with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is |ASN.1| type,
:class:`False` otherwise.
"""
return (self is other or
(not matchTags or self.tagSet == other.tagSet) and
(not matchConstraints or self.subtypeSpec == other.subtypeSpec)) | python | def isSameTypeWith(self, other, matchTags=True, matchConstraints=True):
"""Examine |ASN.1| type for equality with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is |ASN.1| type,
:class:`False` otherwise.
"""
return (self is other or
(not matchTags or self.tagSet == other.tagSet) and
(not matchConstraints or self.subtypeSpec == other.subtypeSpec)) | [
"def",
"isSameTypeWith",
"(",
"self",
",",
"other",
",",
"matchTags",
"=",
"True",
",",
"matchConstraints",
"=",
"True",
")",
":",
"return",
"(",
"self",
"is",
"other",
"or",
"(",
"not",
"matchTags",
"or",
"self",
".",
"tagSet",
"==",
"other",
".",
"ta... | Examine |ASN.1| type for equality with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is |ASN.1| type,
:class:`False` otherwise. | [
"Examine",
"|ASN",
".",
"1|",
"type",
"for",
"equality",
"with",
"other",
"ASN",
".",
"1",
"type",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L77-L99 | train | 204,007 |
etingof/pyasn1 | pyasn1/type/base.py | Asn1ItemBase.isSuperTypeOf | def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):
"""Examine |ASN.1| type for subtype relationship with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is a subtype of |ASN.1| type,
:class:`False` otherwise.
"""
return (not matchTags or
(self.tagSet.isSuperTagSetOf(other.tagSet)) and
(not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec))) | python | def isSuperTypeOf(self, other, matchTags=True, matchConstraints=True):
"""Examine |ASN.1| type for subtype relationship with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is a subtype of |ASN.1| type,
:class:`False` otherwise.
"""
return (not matchTags or
(self.tagSet.isSuperTagSetOf(other.tagSet)) and
(not matchConstraints or self.subtypeSpec.isSuperTypeOf(other.subtypeSpec))) | [
"def",
"isSuperTypeOf",
"(",
"self",
",",
"other",
",",
"matchTags",
"=",
"True",
",",
"matchConstraints",
"=",
"True",
")",
":",
"return",
"(",
"not",
"matchTags",
"or",
"(",
"self",
".",
"tagSet",
".",
"isSuperTagSetOf",
"(",
"other",
".",
"tagSet",
")... | Examine |ASN.1| type for subtype relationship with other ASN.1 type.
ASN.1 tags (:py:mod:`~pyasn1.type.tag`) and constraints
(:py:mod:`~pyasn1.type.constraint`) are examined when carrying
out ASN.1 types comparison.
Python class inheritance relationship is NOT considered.
Parameters
----------
other: a pyasn1 type object
Class instance representing ASN.1 type.
Returns
-------
: :class:`bool`
:class:`True` if *other* is a subtype of |ASN.1| type,
:class:`False` otherwise. | [
"Examine",
"|ASN",
".",
"1|",
"type",
"for",
"subtype",
"relationship",
"with",
"other",
"ASN",
".",
"1",
"type",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L101-L123 | train | 204,008 |
etingof/pyasn1 | pyasn1/type/base.py | AbstractSimpleAsn1Item.clone | def clone(self, value=noValue, **kwargs):
"""Create a modified version of |ASN.1| schema or value object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
if value is noValue:
if not kwargs:
return self
value = self._value
initializers = self.readOnly.copy()
initializers.update(kwargs)
return self.__class__(value, **initializers) | python | def clone(self, value=noValue, **kwargs):
"""Create a modified version of |ASN.1| schema or value object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
if value is noValue:
if not kwargs:
return self
value = self._value
initializers = self.readOnly.copy()
initializers.update(kwargs)
return self.__class__(value, **initializers) | [
"def",
"clone",
"(",
"self",
",",
"value",
"=",
"noValue",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"noValue",
":",
"if",
"not",
"kwargs",
":",
"return",
"self",
"value",
"=",
"self",
".",
"_value",
"initializers",
"=",
"self",
".",
... | Create a modified version of |ASN.1| schema or value object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead. | [
"Create",
"a",
"modified",
"version",
"of",
"|ASN",
".",
"1|",
"schema",
"or",
"value",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L324-L349 | train | 204,009 |
etingof/pyasn1 | pyasn1/type/base.py | AbstractSimpleAsn1Item.subtype | def subtype(self, value=noValue, **kwargs):
"""Create a specialization of |ASN.1| schema or value object.
The subtype relationship between ASN.1 types has no correlation with
subtype relationship between Python types. ASN.1 type is mainly identified
by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range
constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`).
These ASN.1 type properties are implemented as |ASN.1| attributes.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type:
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| schema or value object
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
if value is noValue:
if not kwargs:
return self
value = self._value
initializers = self.readOnly.copy()
implicitTag = kwargs.pop('implicitTag', None)
if implicitTag is not None:
initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
explicitTag = kwargs.pop('explicitTag', None)
if explicitTag is not None:
initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
for arg, option in kwargs.items():
initializers[arg] += option
return self.__class__(value, **initializers) | python | def subtype(self, value=noValue, **kwargs):
"""Create a specialization of |ASN.1| schema or value object.
The subtype relationship between ASN.1 types has no correlation with
subtype relationship between Python types. ASN.1 type is mainly identified
by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range
constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`).
These ASN.1 type properties are implemented as |ASN.1| attributes.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type:
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| schema or value object
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
if value is noValue:
if not kwargs:
return self
value = self._value
initializers = self.readOnly.copy()
implicitTag = kwargs.pop('implicitTag', None)
if implicitTag is not None:
initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
explicitTag = kwargs.pop('explicitTag', None)
if explicitTag is not None:
initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
for arg, option in kwargs.items():
initializers[arg] += option
return self.__class__(value, **initializers) | [
"def",
"subtype",
"(",
"self",
",",
"value",
"=",
"noValue",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"noValue",
":",
"if",
"not",
"kwargs",
":",
"return",
"self",
"value",
"=",
"self",
".",
"_value",
"initializers",
"=",
"self",
".",
... | Create a specialization of |ASN.1| schema or value object.
The subtype relationship between ASN.1 types has no correlation with
subtype relationship between Python types. ASN.1 type is mainly identified
by its tag(s) (:py:class:`~pyasn1.type.tag.TagSet`) and value range
constraints (:py:class:`~pyasn1.type.constraint.ConstraintsIntersection`).
These ASN.1 type properties are implemented as |ASN.1| attributes.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type:
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| schema or value object
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead. | [
"Create",
"a",
"specialization",
"of",
"|ASN",
".",
"1|",
"schema",
"or",
"value",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L351-L417 | train | 204,010 |
etingof/pyasn1 | pyasn1/type/base.py | AbstractConstructedAsn1Item.clone | def clone(self, **kwargs):
"""Create a modified version of |ASN.1| schema object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Possible values of `self` are never copied over thus `clone()` can
only create a new schema object.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the mutable nature of the |ASN.1| object, even if no arguments
are supplied, new |ASN.1| object will always be created as a shallow
copy of `self`.
"""
cloneValueFlag = kwargs.pop('cloneValueFlag', False)
initializers = self.readOnly.copy()
initializers.update(kwargs)
clone = self.__class__(**initializers)
if cloneValueFlag:
self._cloneComponentValues(clone, cloneValueFlag)
return clone | python | def clone(self, **kwargs):
"""Create a modified version of |ASN.1| schema object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Possible values of `self` are never copied over thus `clone()` can
only create a new schema object.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the mutable nature of the |ASN.1| object, even if no arguments
are supplied, new |ASN.1| object will always be created as a shallow
copy of `self`.
"""
cloneValueFlag = kwargs.pop('cloneValueFlag', False)
initializers = self.readOnly.copy()
initializers.update(kwargs)
clone = self.__class__(**initializers)
if cloneValueFlag:
self._cloneComponentValues(clone, cloneValueFlag)
return clone | [
"def",
"clone",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"cloneValueFlag",
"=",
"kwargs",
".",
"pop",
"(",
"'cloneValueFlag'",
",",
"False",
")",
"initializers",
"=",
"self",
".",
"readOnly",
".",
"copy",
"(",
")",
"initializers",
".",
"update",
... | Create a modified version of |ASN.1| schema object.
The `clone()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all arguments
of the `clone()` method are optional.
Whatever arguments are supplied, they are used to create a copy
of `self` taking precedence over the ones used to instantiate `self`.
Possible values of `self` are never copied over thus `clone()` can
only create a new schema object.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the mutable nature of the |ASN.1| object, even if no arguments
are supplied, new |ASN.1| object will always be created as a shallow
copy of `self`. | [
"Create",
"a",
"modified",
"version",
"of",
"|ASN",
".",
"1|",
"schema",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L517-L551 | train | 204,011 |
etingof/pyasn1 | pyasn1/type/base.py | AbstractConstructedAsn1Item.subtype | def subtype(self, **kwargs):
"""Create a specialization of |ASN.1| schema object.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type.
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
initializers = self.readOnly.copy()
cloneValueFlag = kwargs.pop('cloneValueFlag', False)
implicitTag = kwargs.pop('implicitTag', None)
if implicitTag is not None:
initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
explicitTag = kwargs.pop('explicitTag', None)
if explicitTag is not None:
initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
for arg, option in kwargs.items():
initializers[arg] += option
clone = self.__class__(**initializers)
if cloneValueFlag:
self._cloneComponentValues(clone, cloneValueFlag)
return clone | python | def subtype(self, **kwargs):
"""Create a specialization of |ASN.1| schema object.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type.
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead.
"""
initializers = self.readOnly.copy()
cloneValueFlag = kwargs.pop('cloneValueFlag', False)
implicitTag = kwargs.pop('implicitTag', None)
if implicitTag is not None:
initializers['tagSet'] = self.tagSet.tagImplicitly(implicitTag)
explicitTag = kwargs.pop('explicitTag', None)
if explicitTag is not None:
initializers['tagSet'] = self.tagSet.tagExplicitly(explicitTag)
for arg, option in kwargs.items():
initializers[arg] += option
clone = self.__class__(**initializers)
if cloneValueFlag:
self._cloneComponentValues(clone, cloneValueFlag)
return clone | [
"def",
"subtype",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"initializers",
"=",
"self",
".",
"readOnly",
".",
"copy",
"(",
")",
"cloneValueFlag",
"=",
"kwargs",
".",
"pop",
"(",
"'cloneValueFlag'",
",",
"False",
")",
"implicitTag",
"=",
"kwargs",
... | Create a specialization of |ASN.1| schema object.
The `subtype()` method accepts the same set arguments as |ASN.1|
class takes on instantiation except that all parameters
of the `subtype()` method are optional.
With the exception of the arguments described below, the rest of
supplied arguments they are used to create a copy of `self` taking
precedence over the ones used to instantiate `self`.
The following arguments to `subtype()` create a ASN.1 subtype out of
|ASN.1| type.
Other Parameters
----------------
implicitTag: :py:class:`~pyasn1.type.tag.Tag`
Implicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
explicitTag: :py:class:`~pyasn1.type.tag.Tag`
Explicitly apply given ASN.1 tag object to `self`'s
:py:class:`~pyasn1.type.tag.TagSet`, then use the result as
new object's ASN.1 tag(s).
subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection`
Add ASN.1 constraints object to one of the `self`'s, then
use the result as new object's ASN.1 constraints.
Returns
-------
:
new instance of |ASN.1| type/value
Note
----
Due to the immutable nature of the |ASN.1| object, if no arguments
are supplied, no new |ASN.1| object will be created and `self` will
be returned instead. | [
"Create",
"a",
"specialization",
"of",
"|ASN",
".",
"1|",
"schema",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/base.py#L553-L616 | train | 204,012 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getTypeByPosition | def getTypeByPosition(self, idx):
"""Return ASN.1 type object by its position in fields set.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
:
ASN.1 type
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range
"""
try:
return self.__namedTypes[idx].asn1Object
except IndexError:
raise error.PyAsn1Error('Type position out of range') | python | def getTypeByPosition(self, idx):
"""Return ASN.1 type object by its position in fields set.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
:
ASN.1 type
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range
"""
try:
return self.__namedTypes[idx].asn1Object
except IndexError:
raise error.PyAsn1Error('Type position out of range') | [
"def",
"getTypeByPosition",
"(",
"self",
",",
"idx",
")",
":",
"try",
":",
"return",
"self",
".",
"__namedTypes",
"[",
"idx",
"]",
".",
"asn1Object",
"except",
"IndexError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Type position out of range'",
")"
] | Return ASN.1 type object by its position in fields set.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
:
ASN.1 type
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range | [
"Return",
"ASN",
".",
"1",
"type",
"object",
"by",
"its",
"position",
"in",
"fields",
"set",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L281-L303 | train | 204,013 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getPositionByType | def getPositionByType(self, tagSet):
"""Return field position by its ASN.1 type.
Parameters
----------
tagSet: :class:`~pysnmp.type.tag.TagSet`
ASN.1 tag set distinguishing one ASN.1 type from others.
Returns
-------
: :py:class:`int`
ASN.1 type position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes*
"""
try:
return self.__tagToPosMap[tagSet]
except KeyError:
raise error.PyAsn1Error('Type %s not found' % (tagSet,)) | python | def getPositionByType(self, tagSet):
"""Return field position by its ASN.1 type.
Parameters
----------
tagSet: :class:`~pysnmp.type.tag.TagSet`
ASN.1 tag set distinguishing one ASN.1 type from others.
Returns
-------
: :py:class:`int`
ASN.1 type position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes*
"""
try:
return self.__tagToPosMap[tagSet]
except KeyError:
raise error.PyAsn1Error('Type %s not found' % (tagSet,)) | [
"def",
"getPositionByType",
"(",
"self",
",",
"tagSet",
")",
":",
"try",
":",
"return",
"self",
".",
"__tagToPosMap",
"[",
"tagSet",
"]",
"except",
"KeyError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Type %s not found'",
"%",
"(",
"tagSet",
",",
... | Return field position by its ASN.1 type.
Parameters
----------
tagSet: :class:`~pysnmp.type.tag.TagSet`
ASN.1 tag set distinguishing one ASN.1 type from others.
Returns
-------
: :py:class:`int`
ASN.1 type position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes* | [
"Return",
"field",
"position",
"by",
"its",
"ASN",
".",
"1",
"type",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L305-L327 | train | 204,014 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getNameByPosition | def getNameByPosition(self, idx):
"""Return field name by its position in fields set.
Parameters
----------
idx: :py:class:`idx`
Field index
Returns
-------
: :py:class:`str`
Field name
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given field name is not present in callee *NamedTypes*
"""
try:
return self.__namedTypes[idx].name
except IndexError:
raise error.PyAsn1Error('Type position out of range') | python | def getNameByPosition(self, idx):
"""Return field name by its position in fields set.
Parameters
----------
idx: :py:class:`idx`
Field index
Returns
-------
: :py:class:`str`
Field name
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given field name is not present in callee *NamedTypes*
"""
try:
return self.__namedTypes[idx].name
except IndexError:
raise error.PyAsn1Error('Type position out of range') | [
"def",
"getNameByPosition",
"(",
"self",
",",
"idx",
")",
":",
"try",
":",
"return",
"self",
".",
"__namedTypes",
"[",
"idx",
"]",
".",
"name",
"except",
"IndexError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Type position out of range'",
")"
] | Return field name by its position in fields set.
Parameters
----------
idx: :py:class:`idx`
Field index
Returns
-------
: :py:class:`str`
Field name
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given field name is not present in callee *NamedTypes* | [
"Return",
"field",
"name",
"by",
"its",
"position",
"in",
"fields",
"set",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L329-L351 | train | 204,015 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getPositionByName | def getPositionByName(self, name):
"""Return field position by filed name.
Parameters
----------
name: :py:class:`str`
Field name
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *name* is not present or not unique within callee *NamedTypes*
"""
try:
return self.__nameToPosMap[name]
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,)) | python | def getPositionByName(self, name):
"""Return field position by filed name.
Parameters
----------
name: :py:class:`str`
Field name
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *name* is not present or not unique within callee *NamedTypes*
"""
try:
return self.__nameToPosMap[name]
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,)) | [
"def",
"getPositionByName",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"self",
".",
"__nameToPosMap",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Name %s not found'",
"%",
"(",
"name",
",",
")",
... | Return field position by filed name.
Parameters
----------
name: :py:class:`str`
Field name
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *name* is not present or not unique within callee *NamedTypes* | [
"Return",
"field",
"position",
"by",
"filed",
"name",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L353-L375 | train | 204,016 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getTagMapNearPosition | def getTagMapNearPosition(self, idx):
"""Return ASN.1 types that are allowed at or past given field position.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know which types can possibly be
present at any given position in the field sets.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
: :class:`~pyasn1.type.tagmap.TagMap`
Map if ASN.1 types allowed at given field position
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range
"""
try:
return self.__ambiguousTypes[idx].tagMap
except KeyError:
raise error.PyAsn1Error('Type position out of range') | python | def getTagMapNearPosition(self, idx):
"""Return ASN.1 types that are allowed at or past given field position.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know which types can possibly be
present at any given position in the field sets.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
: :class:`~pyasn1.type.tagmap.TagMap`
Map if ASN.1 types allowed at given field position
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range
"""
try:
return self.__ambiguousTypes[idx].tagMap
except KeyError:
raise error.PyAsn1Error('Type position out of range') | [
"def",
"getTagMapNearPosition",
"(",
"self",
",",
"idx",
")",
":",
"try",
":",
"return",
"self",
".",
"__ambiguousTypes",
"[",
"idx",
"]",
".",
"tagMap",
"except",
"KeyError",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Type position out of range'",
")"
... | Return ASN.1 types that are allowed at or past given field position.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know which types can possibly be
present at any given position in the field sets.
Parameters
----------
idx: :py:class:`int`
Field index
Returns
-------
: :class:`~pyasn1.type.tagmap.TagMap`
Map if ASN.1 types allowed at given field position
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If given position is out of fields range | [
"Return",
"ASN",
".",
"1",
"types",
"that",
"are",
"allowed",
"at",
"or",
"past",
"given",
"field",
"position",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L377-L404 | train | 204,017 |
etingof/pyasn1 | pyasn1/type/namedtype.py | NamedTypes.getPositionNearType | def getPositionNearType(self, tagSet, idx):
"""Return the closest field position where given ASN.1 type is allowed.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know at which field position, in field set,
given *tagSet* is allowed at or past *idx* position.
Parameters
----------
tagSet: :class:`~pyasn1.type.tag.TagSet`
ASN.1 type which field position to look up
idx: :py:class:`int`
Field position at or past which to perform ASN.1 type look up
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or not unique within callee *NamedTypes*
or *idx* is out of fields range
"""
try:
return idx + self.__ambiguousTypes[idx].getPositionByType(tagSet)
except KeyError:
raise error.PyAsn1Error('Type position out of range') | python | def getPositionNearType(self, tagSet, idx):
"""Return the closest field position where given ASN.1 type is allowed.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know at which field position, in field set,
given *tagSet* is allowed at or past *idx* position.
Parameters
----------
tagSet: :class:`~pyasn1.type.tag.TagSet`
ASN.1 type which field position to look up
idx: :py:class:`int`
Field position at or past which to perform ASN.1 type look up
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or not unique within callee *NamedTypes*
or *idx* is out of fields range
"""
try:
return idx + self.__ambiguousTypes[idx].getPositionByType(tagSet)
except KeyError:
raise error.PyAsn1Error('Type position out of range') | [
"def",
"getPositionNearType",
"(",
"self",
",",
"tagSet",
",",
"idx",
")",
":",
"try",
":",
"return",
"idx",
"+",
"self",
".",
"__ambiguousTypes",
"[",
"idx",
"]",
".",
"getPositionByType",
"(",
"tagSet",
")",
"except",
"KeyError",
":",
"raise",
"error",
... | Return the closest field position where given ASN.1 type is allowed.
Some ASN.1 serialisation allow for skipping optional and defaulted fields.
Some constructed ASN.1 types allow reordering of the fields. When recovering
such objects it may be important to know at which field position, in field set,
given *tagSet* is allowed at or past *idx* position.
Parameters
----------
tagSet: :class:`~pyasn1.type.tag.TagSet`
ASN.1 type which field position to look up
idx: :py:class:`int`
Field position at or past which to perform ASN.1 type look up
Returns
-------
: :py:class:`int`
Field position in fields set
Raises
------
: :class:`~pyasn1.error.PyAsn1Error`
If *tagSet* is not present or not unique within callee *NamedTypes*
or *idx* is out of fields range | [
"Return",
"the",
"closest",
"field",
"position",
"where",
"given",
"ASN",
".",
"1",
"type",
"is",
"allowed",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/namedtype.py#L406-L437 | train | 204,018 |
etingof/pyasn1 | pyasn1/type/univ.py | BitString.asBinary | def asBinary(self):
"""Get |ASN.1| value as a text string of bits.
"""
binString = binary.bin(self._value)[2:]
return '0' * (len(self._value) - len(binString)) + binString | python | def asBinary(self):
"""Get |ASN.1| value as a text string of bits.
"""
binString = binary.bin(self._value)[2:]
return '0' * (len(self._value) - len(binString)) + binString | [
"def",
"asBinary",
"(",
"self",
")",
":",
"binString",
"=",
"binary",
".",
"bin",
"(",
"self",
".",
"_value",
")",
"[",
"2",
":",
"]",
"return",
"'0'",
"*",
"(",
"len",
"(",
"self",
".",
"_value",
")",
"-",
"len",
"(",
"binString",
")",
")",
"+... | Get |ASN.1| value as a text string of bits. | [
"Get",
"|ASN",
".",
"1|",
"value",
"as",
"a",
"text",
"string",
"of",
"bits",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L574-L578 | train | 204,019 |
etingof/pyasn1 | pyasn1/type/univ.py | BitString.fromOctetString | def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0):
"""Create a |ASN.1| object initialized from a string.
Parameters
----------
value: :class:`str` (Py2) or :class:`bytes` (Py3)
Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
"""
value = SizedInteger(integer.from_bytes(value) >> padding).setBitLength(len(value) * 8 - padding)
if prepend is not None:
value = SizedInteger(
(SizedInteger(prepend) << len(value)) | value
).setBitLength(len(prepend) + len(value))
if not internalFormat:
value = cls(value)
return value | python | def fromOctetString(cls, value, internalFormat=False, prepend=None, padding=0):
"""Create a |ASN.1| object initialized from a string.
Parameters
----------
value: :class:`str` (Py2) or :class:`bytes` (Py3)
Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3)
"""
value = SizedInteger(integer.from_bytes(value) >> padding).setBitLength(len(value) * 8 - padding)
if prepend is not None:
value = SizedInteger(
(SizedInteger(prepend) << len(value)) | value
).setBitLength(len(prepend) + len(value))
if not internalFormat:
value = cls(value)
return value | [
"def",
"fromOctetString",
"(",
"cls",
",",
"value",
",",
"internalFormat",
"=",
"False",
",",
"prepend",
"=",
"None",
",",
"padding",
"=",
"0",
")",
":",
"value",
"=",
"SizedInteger",
"(",
"integer",
".",
"from_bytes",
"(",
"value",
")",
">>",
"padding",... | Create a |ASN.1| object initialized from a string.
Parameters
----------
value: :class:`str` (Py2) or :class:`bytes` (Py3)
Text string like '\\\\x01\\\\xff' (Py2) or b'\\\\x01\\\\xff' (Py3) | [
"Create",
"a",
"|ASN",
".",
"1|",
"object",
"initialized",
"from",
"a",
"string",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L631-L649 | train | 204,020 |
etingof/pyasn1 | pyasn1/type/univ.py | OctetString.fromBinaryString | def fromBinaryString(value):
"""Create a |ASN.1| object initialized from a string of '0' and '1'.
Parameters
----------
value: :class:`str`
Text string like '1010111'
"""
bitNo = 8
byte = 0
r = []
for v in value:
if bitNo:
bitNo -= 1
else:
bitNo = 7
r.append(byte)
byte = 0
if v in ('0', '1'):
v = int(v)
else:
raise error.PyAsn1Error(
'Non-binary OCTET STRING initializer %s' % (v,)
)
byte |= v << bitNo
r.append(byte)
return octets.ints2octs(r) | python | def fromBinaryString(value):
"""Create a |ASN.1| object initialized from a string of '0' and '1'.
Parameters
----------
value: :class:`str`
Text string like '1010111'
"""
bitNo = 8
byte = 0
r = []
for v in value:
if bitNo:
bitNo -= 1
else:
bitNo = 7
r.append(byte)
byte = 0
if v in ('0', '1'):
v = int(v)
else:
raise error.PyAsn1Error(
'Non-binary OCTET STRING initializer %s' % (v,)
)
byte |= v << bitNo
r.append(byte)
return octets.ints2octs(r) | [
"def",
"fromBinaryString",
"(",
"value",
")",
":",
"bitNo",
"=",
"8",
"byte",
"=",
"0",
"r",
"=",
"[",
"]",
"for",
"v",
"in",
"value",
":",
"if",
"bitNo",
":",
"bitNo",
"-=",
"1",
"else",
":",
"bitNo",
"=",
"7",
"r",
".",
"append",
"(",
"byte",... | Create a |ASN.1| object initialized from a string of '0' and '1'.
Parameters
----------
value: :class:`str`
Text string like '1010111' | [
"Create",
"a",
"|ASN",
".",
"1|",
"object",
"initialized",
"from",
"a",
"string",
"of",
"0",
"and",
"1",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L937-L965 | train | 204,021 |
etingof/pyasn1 | pyasn1/type/univ.py | ObjectIdentifier.isPrefixOf | def isPrefixOf(self, other):
"""Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
Parameters
----------
other: |ASN.1| object
|ASN.1| object
Returns
-------
: :class:`bool`
:class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object
or :class:`False` otherwise.
"""
l = len(self)
if l <= len(other):
if self._value[:l] == other[:l]:
return True
return False | python | def isPrefixOf(self, other):
"""Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
Parameters
----------
other: |ASN.1| object
|ASN.1| object
Returns
-------
: :class:`bool`
:class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object
or :class:`False` otherwise.
"""
l = len(self)
if l <= len(other):
if self._value[:l] == other[:l]:
return True
return False | [
"def",
"isPrefixOf",
"(",
"self",
",",
"other",
")",
":",
"l",
"=",
"len",
"(",
"self",
")",
"if",
"l",
"<=",
"len",
"(",
"other",
")",
":",
"if",
"self",
".",
"_value",
"[",
":",
"l",
"]",
"==",
"other",
"[",
":",
"l",
"]",
":",
"return",
... | Indicate if this |ASN.1| object is a prefix of other |ASN.1| object.
Parameters
----------
other: |ASN.1| object
|ASN.1| object
Returns
-------
: :class:`bool`
:class:`True` if this |ASN.1| object is a parent (e.g. prefix) of the other |ASN.1| object
or :class:`False` otherwise. | [
"Indicate",
"if",
"this",
"|ASN",
".",
"1|",
"object",
"is",
"a",
"prefix",
"of",
"other",
"|ASN",
".",
"1|",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L1165-L1183 | train | 204,022 |
etingof/pyasn1 | pyasn1/type/univ.py | SequenceOfAndSetOfBase.getComponentByPosition | def getComponentByPosition(self, idx, default=noValue, instantiate=True):
"""Return |ASN.1| type component value by position.
Equivalent to Python sequence subscription operation (e.g. `[]`).
Parameters
----------
idx : :class:`int`
Component index (zero-based). Must either refer to an existing
component or to N+1 component (if *componentType* is set). In the latter
case a new component type gets instantiated and appended to the |ASN.1|
sequence.
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value
Examples
--------
.. code-block:: python
# can also be SetOf
class MySequenceOf(SequenceOf):
componentType = OctetString()
s = MySequenceOf()
# returns component #0 with `.isValue` property False
s.getComponentByPosition(0)
# returns None
s.getComponentByPosition(0, default=None)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False)
# sets component #0 to OctetString() ASN.1 schema
# object and returns it
s.getComponentByPosition(0, instantiate=True)
# sets component #0 to ASN.1 value object
s.setComponentByPosition(0, 'ABCD')
# returns OctetString('ABCD') value object
s.getComponentByPosition(0, instantiate=False)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False)
"""
try:
componentValue = self._componentValues[idx]
except IndexError:
if not instantiate:
return default
self.setComponentByPosition(idx)
componentValue = self._componentValues[idx]
if default is noValue or componentValue.isValue:
return componentValue
else:
return default | python | def getComponentByPosition(self, idx, default=noValue, instantiate=True):
"""Return |ASN.1| type component value by position.
Equivalent to Python sequence subscription operation (e.g. `[]`).
Parameters
----------
idx : :class:`int`
Component index (zero-based). Must either refer to an existing
component or to N+1 component (if *componentType* is set). In the latter
case a new component type gets instantiated and appended to the |ASN.1|
sequence.
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value
Examples
--------
.. code-block:: python
# can also be SetOf
class MySequenceOf(SequenceOf):
componentType = OctetString()
s = MySequenceOf()
# returns component #0 with `.isValue` property False
s.getComponentByPosition(0)
# returns None
s.getComponentByPosition(0, default=None)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False)
# sets component #0 to OctetString() ASN.1 schema
# object and returns it
s.getComponentByPosition(0, instantiate=True)
# sets component #0 to ASN.1 value object
s.setComponentByPosition(0, 'ABCD')
# returns OctetString('ABCD') value object
s.getComponentByPosition(0, instantiate=False)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False)
"""
try:
componentValue = self._componentValues[idx]
except IndexError:
if not instantiate:
return default
self.setComponentByPosition(idx)
componentValue = self._componentValues[idx]
if default is noValue or componentValue.isValue:
return componentValue
else:
return default | [
"def",
"getComponentByPosition",
"(",
"self",
",",
"idx",
",",
"default",
"=",
"noValue",
",",
"instantiate",
"=",
"True",
")",
":",
"try",
":",
"componentValue",
"=",
"self",
".",
"_componentValues",
"[",
"idx",
"]",
"except",
"IndexError",
":",
"if",
"no... | Return |ASN.1| type component value by position.
Equivalent to Python sequence subscription operation (e.g. `[]`).
Parameters
----------
idx : :class:`int`
Component index (zero-based). Must either refer to an existing
component or to N+1 component (if *componentType* is set). In the latter
case a new component type gets instantiated and appended to the |ASN.1|
sequence.
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value
Examples
--------
.. code-block:: python
# can also be SetOf
class MySequenceOf(SequenceOf):
componentType = OctetString()
s = MySequenceOf()
# returns component #0 with `.isValue` property False
s.getComponentByPosition(0)
# returns None
s.getComponentByPosition(0, default=None)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False)
# sets component #0 to OctetString() ASN.1 schema
# object and returns it
s.getComponentByPosition(0, instantiate=True)
# sets component #0 to ASN.1 value object
s.setComponentByPosition(0, 'ABCD')
# returns OctetString('ABCD') value object
s.getComponentByPosition(0, instantiate=False)
s.clear()
# returns noValue
s.getComponentByPosition(0, instantiate=False) | [
"Return",
"|ASN",
".",
"1|",
"type",
"component",
"value",
"by",
"position",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L1672-L1752 | train | 204,023 |
etingof/pyasn1 | pyasn1/type/univ.py | SequenceAndSetBase.getComponentByName | def getComponentByName(self, name, default=noValue, instantiate=True):
"""Returns |ASN.1| type component by name.
Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value
"""
if self._componentTypeLen:
idx = self.componentType.getPositionByName(name)
else:
try:
idx = self._dynamicNames.getPositionByName(name)
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,))
return self.getComponentByPosition(idx, default=default, instantiate=instantiate) | python | def getComponentByName(self, name, default=noValue, instantiate=True):
"""Returns |ASN.1| type component by name.
Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value
"""
if self._componentTypeLen:
idx = self.componentType.getPositionByName(name)
else:
try:
idx = self._dynamicNames.getPositionByName(name)
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,))
return self.getComponentByPosition(idx, default=default, instantiate=instantiate) | [
"def",
"getComponentByName",
"(",
"self",
",",
"name",
",",
"default",
"=",
"noValue",
",",
"instantiate",
"=",
"True",
")",
":",
"if",
"self",
".",
"_componentTypeLen",
":",
"idx",
"=",
"self",
".",
"componentType",
".",
"getPositionByName",
"(",
"name",
... | Returns |ASN.1| type component by name.
Equivalent to Python :class:`dict` subscription operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
Instantiate |ASN.1| component type or return existing component value | [
"Returns",
"|ASN",
".",
"1|",
"type",
"component",
"by",
"name",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2128-L2163 | train | 204,024 |
etingof/pyasn1 | pyasn1/type/univ.py | SequenceAndSetBase.setComponentByName | def setComponentByName(self, name, value=noValue,
verifyConstraints=True,
matchTags=True,
matchConstraints=True):
"""Assign |ASN.1| type component by name.
Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints: :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
Returns
-------
self
"""
if self._componentTypeLen:
idx = self.componentType.getPositionByName(name)
else:
try:
idx = self._dynamicNames.getPositionByName(name)
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,))
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
) | python | def setComponentByName(self, name, value=noValue,
verifyConstraints=True,
matchTags=True,
matchConstraints=True):
"""Assign |ASN.1| type component by name.
Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints: :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
Returns
-------
self
"""
if self._componentTypeLen:
idx = self.componentType.getPositionByName(name)
else:
try:
idx = self._dynamicNames.getPositionByName(name)
except KeyError:
raise error.PyAsn1Error('Name %s not found' % (name,))
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
) | [
"def",
"setComponentByName",
"(",
"self",
",",
"name",
",",
"value",
"=",
"noValue",
",",
"verifyConstraints",
"=",
"True",
",",
"matchTags",
"=",
"True",
",",
"matchConstraints",
"=",
"True",
")",
":",
"if",
"self",
".",
"_componentTypeLen",
":",
"idx",
"... | Assign |ASN.1| type component by name.
Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`).
Parameters
----------
name: :class:`str`
|ASN.1| type component name
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints: :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
Returns
-------
self | [
"Assign",
"|ASN",
".",
"1|",
"type",
"component",
"by",
"name",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2165-L2208 | train | 204,025 |
etingof/pyasn1 | pyasn1/type/univ.py | SequenceAndSetBase.prettyPrint | def prettyPrint(self, scope=0):
"""Return an object representation string.
Returns
-------
: :class:`str`
Human-friendly object representation.
"""
scope += 1
representation = self.__class__.__name__ + ':\n'
for idx, componentValue in enumerate(self._componentValues):
if componentValue is not noValue and componentValue.isValue:
representation += ' ' * scope
if self.componentType:
representation += self.componentType.getNameByPosition(idx)
else:
representation += self._dynamicNames.getNameByPosition(idx)
representation = '%s=%s\n' % (
representation, componentValue.prettyPrint(scope)
)
return representation | python | def prettyPrint(self, scope=0):
"""Return an object representation string.
Returns
-------
: :class:`str`
Human-friendly object representation.
"""
scope += 1
representation = self.__class__.__name__ + ':\n'
for idx, componentValue in enumerate(self._componentValues):
if componentValue is not noValue and componentValue.isValue:
representation += ' ' * scope
if self.componentType:
representation += self.componentType.getNameByPosition(idx)
else:
representation += self._dynamicNames.getNameByPosition(idx)
representation = '%s=%s\n' % (
representation, componentValue.prettyPrint(scope)
)
return representation | [
"def",
"prettyPrint",
"(",
"self",
",",
"scope",
"=",
"0",
")",
":",
"scope",
"+=",
"1",
"representation",
"=",
"self",
".",
"__class__",
".",
"__name__",
"+",
"':\\n'",
"for",
"idx",
",",
"componentValue",
"in",
"enumerate",
"(",
"self",
".",
"_componen... | Return an object representation string.
Returns
-------
: :class:`str`
Human-friendly object representation. | [
"Return",
"an",
"object",
"representation",
"string",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2451-L2471 | train | 204,026 |
etingof/pyasn1 | pyasn1/type/univ.py | Set.getComponentByType | def getComponentByType(self, tagSet, default=noValue,
instantiate=True, innerFlag=False):
"""Returns |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a pyasn1 object
"""
componentValue = self.getComponentByPosition(
self.componentType.getPositionByType(tagSet),
default=default, instantiate=instantiate
)
if innerFlag and isinstance(componentValue, Set):
# get inner component by inner tagSet
return componentValue.getComponent(innerFlag=True)
else:
# get outer component by inner tagSet
return componentValue | python | def getComponentByType(self, tagSet, default=noValue,
instantiate=True, innerFlag=False):
"""Returns |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a pyasn1 object
"""
componentValue = self.getComponentByPosition(
self.componentType.getPositionByType(tagSet),
default=default, instantiate=instantiate
)
if innerFlag and isinstance(componentValue, Set):
# get inner component by inner tagSet
return componentValue.getComponent(innerFlag=True)
else:
# get outer component by inner tagSet
return componentValue | [
"def",
"getComponentByType",
"(",
"self",
",",
"tagSet",
",",
"default",
"=",
"noValue",
",",
"instantiate",
"=",
"True",
",",
"innerFlag",
"=",
"False",
")",
":",
"componentValue",
"=",
"self",
".",
"getComponentByPosition",
"(",
"self",
".",
"componentType",... | Returns |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
default: :class:`object`
If set and requested component is a schema object, return the `default`
object instead of the requested component.
instantiate: :class:`bool`
If `True` (default), inner component will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a pyasn1 object | [
"Returns",
"|ASN",
".",
"1|",
"type",
"component",
"by",
"ASN",
".",
"1",
"tag",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2569-L2604 | train | 204,027 |
etingof/pyasn1 | pyasn1/type/univ.py | Set.setComponentByType | def setComponentByType(self, tagSet, value=noValue,
verifyConstraints=True,
matchTags=True,
matchConstraints=True,
innerFlag=False):
"""Assign |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints : :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
innerFlag: :class:`bool`
If `True`, search for matching *tagSet* recursively.
Returns
-------
self
"""
idx = self.componentType.getPositionByType(tagSet)
if innerFlag: # set inner component by inner tagSet
componentType = self.componentType.getTypeByPosition(idx)
if componentType.tagSet:
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
)
else:
componentType = self.getComponentByPosition(idx)
return componentType.setComponentByType(
tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag
)
else: # set outer component by inner tagSet
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
) | python | def setComponentByType(self, tagSet, value=noValue,
verifyConstraints=True,
matchTags=True,
matchConstraints=True,
innerFlag=False):
"""Assign |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints : :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
innerFlag: :class:`bool`
If `True`, search for matching *tagSet* recursively.
Returns
-------
self
"""
idx = self.componentType.getPositionByType(tagSet)
if innerFlag: # set inner component by inner tagSet
componentType = self.componentType.getTypeByPosition(idx)
if componentType.tagSet:
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
)
else:
componentType = self.getComponentByPosition(idx)
return componentType.setComponentByType(
tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag
)
else: # set outer component by inner tagSet
return self.setComponentByPosition(
idx, value, verifyConstraints, matchTags, matchConstraints
) | [
"def",
"setComponentByType",
"(",
"self",
",",
"tagSet",
",",
"value",
"=",
"noValue",
",",
"verifyConstraints",
"=",
"True",
",",
"matchTags",
"=",
"True",
",",
"matchConstraints",
"=",
"True",
",",
"innerFlag",
"=",
"False",
")",
":",
"idx",
"=",
"self",... | Assign |ASN.1| type component by ASN.1 tag.
Parameters
----------
tagSet : :py:class:`~pyasn1.type.tag.TagSet`
Object representing ASN.1 tags to identify one of
|ASN.1| object component
Keyword Args
------------
value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative
A Python value to initialize |ASN.1| component with (if *componentType* is set)
or ASN.1 value object to assign to |ASN.1| component.
verifyConstraints : :class:`bool`
If `False`, skip constraints validation
matchTags: :class:`bool`
If `False`, skip component tags matching
matchConstraints: :class:`bool`
If `False`, skip component constraints matching
innerFlag: :class:`bool`
If `True`, search for matching *tagSet* recursively.
Returns
-------
self | [
"Assign",
"|ASN",
".",
"1|",
"type",
"component",
"by",
"ASN",
".",
"1",
"tag",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2606-L2658 | train | 204,028 |
etingof/pyasn1 | pyasn1/type/univ.py | Choice.getComponent | def getComponent(self, innerFlag=False):
"""Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component not chosen')
else:
c = self._componentValues[self._currentIdx]
if innerFlag and isinstance(c, Choice):
return c.getComponent(innerFlag)
else:
return c | python | def getComponent(self, innerFlag=False):
"""Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component not chosen')
else:
c = self._componentValues[self._currentIdx]
if innerFlag and isinstance(c, Choice):
return c.getComponent(innerFlag)
else:
return c | [
"def",
"getComponent",
"(",
"self",
",",
"innerFlag",
"=",
"False",
")",
":",
"if",
"self",
".",
"_currentIdx",
"is",
"None",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Component not chosen'",
")",
"else",
":",
"c",
"=",
"self",
".",
"_componentValu... | Return currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object | [
"Return",
"currently",
"assigned",
"component",
"of",
"the",
"|ASN",
".",
"1|",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2892-L2907 | train | 204,029 |
etingof/pyasn1 | pyasn1/type/univ.py | Choice.getName | def getName(self, innerFlag=False):
"""Return the name of currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`str`
|ASN.1| component name
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component not chosen')
else:
if innerFlag:
c = self._componentValues[self._currentIdx]
if isinstance(c, Choice):
return c.getName(innerFlag)
return self.componentType.getNameByPosition(self._currentIdx) | python | def getName(self, innerFlag=False):
"""Return the name of currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`str`
|ASN.1| component name
"""
if self._currentIdx is None:
raise error.PyAsn1Error('Component not chosen')
else:
if innerFlag:
c = self._componentValues[self._currentIdx]
if isinstance(c, Choice):
return c.getName(innerFlag)
return self.componentType.getNameByPosition(self._currentIdx) | [
"def",
"getName",
"(",
"self",
",",
"innerFlag",
"=",
"False",
")",
":",
"if",
"self",
".",
"_currentIdx",
"is",
"None",
":",
"raise",
"error",
".",
"PyAsn1Error",
"(",
"'Component not chosen'",
")",
"else",
":",
"if",
"innerFlag",
":",
"c",
"=",
"self",... | Return the name of currently assigned component of the |ASN.1| object.
Returns
-------
: :py:class:`str`
|ASN.1| component name | [
"Return",
"the",
"name",
"of",
"currently",
"assigned",
"component",
"of",
"the",
"|ASN",
".",
"1|",
"object",
"."
] | 25cf116ef8d11bb0e08454c0f3635c9f4002c2d6 | https://github.com/etingof/pyasn1/blob/25cf116ef8d11bb0e08454c0f3635c9f4002c2d6/pyasn1/type/univ.py#L2909-L2924 | train | 204,030 |
brean/python-pathfinding | pathfinding/core/util.py | expand_path | def expand_path(path):
'''
Given a compressed path, return a new path that has all the segments
in it interpolated.
'''
expanded = []
if len(path) < 2:
return expanded
for i in range(len(path)-1):
expanded += bresenham(path[i], path[i + 1])
expanded += [path[:-1]]
return expanded | python | def expand_path(path):
'''
Given a compressed path, return a new path that has all the segments
in it interpolated.
'''
expanded = []
if len(path) < 2:
return expanded
for i in range(len(path)-1):
expanded += bresenham(path[i], path[i + 1])
expanded += [path[:-1]]
return expanded | [
"def",
"expand_path",
"(",
"path",
")",
":",
"expanded",
"=",
"[",
"]",
"if",
"len",
"(",
"path",
")",
"<",
"2",
":",
"return",
"expanded",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"path",
")",
"-",
"1",
")",
":",
"expanded",
"+=",
"bresenham"... | Given a compressed path, return a new path that has all the segments
in it interpolated. | [
"Given",
"a",
"compressed",
"path",
"return",
"a",
"new",
"path",
"that",
"has",
"all",
"the",
"segments",
"in",
"it",
"interpolated",
"."
] | b857bf85e514a1712b40e29ccb5a473cd7fd5c80 | https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/util.py#L97-L108 | train | 204,031 |
brean/python-pathfinding | pathfinding/finder/finder.py | Finder.apply_heuristic | def apply_heuristic(self, node_a, node_b, heuristic=None):
"""
helper function to apply heuristic
"""
if not heuristic:
heuristic = self.heuristic
return heuristic(
abs(node_a.x - node_b.x),
abs(node_a.y - node_b.y)) | python | def apply_heuristic(self, node_a, node_b, heuristic=None):
"""
helper function to apply heuristic
"""
if not heuristic:
heuristic = self.heuristic
return heuristic(
abs(node_a.x - node_b.x),
abs(node_a.y - node_b.y)) | [
"def",
"apply_heuristic",
"(",
"self",
",",
"node_a",
",",
"node_b",
",",
"heuristic",
"=",
"None",
")",
":",
"if",
"not",
"heuristic",
":",
"heuristic",
"=",
"self",
".",
"heuristic",
"return",
"heuristic",
"(",
"abs",
"(",
"node_a",
".",
"x",
"-",
"n... | helper function to apply heuristic | [
"helper",
"function",
"to",
"apply",
"heuristic"
] | b857bf85e514a1712b40e29ccb5a473cd7fd5c80 | https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/finder/finder.py#L74-L82 | train | 204,032 |
brean/python-pathfinding | pathfinding/core/node.py | Node.cleanup | def cleanup(self):
"""
reset all calculated values, fresh start for pathfinding
"""
# cost from this node to the goal
self.h = 0.0
# cost from the start node to this node
self.g = 0.0
# distance from start to this point (f = g + h )
self.f = 0.0
self.opened = 0
self.closed = False
# used for backtracking to the start point
self.parent = None
# used for recurion tracking of IDA*
self.retain_count = 0
# used for IDA* and Jump-Point-Search
self.tested = False | python | def cleanup(self):
"""
reset all calculated values, fresh start for pathfinding
"""
# cost from this node to the goal
self.h = 0.0
# cost from the start node to this node
self.g = 0.0
# distance from start to this point (f = g + h )
self.f = 0.0
self.opened = 0
self.closed = False
# used for backtracking to the start point
self.parent = None
# used for recurion tracking of IDA*
self.retain_count = 0
# used for IDA* and Jump-Point-Search
self.tested = False | [
"def",
"cleanup",
"(",
"self",
")",
":",
"# cost from this node to the goal",
"self",
".",
"h",
"=",
"0.0",
"# cost from the start node to this node",
"self",
".",
"g",
"=",
"0.0",
"# distance from start to this point (f = g + h )",
"self",
".",
"f",
"=",
"0.0",
"self... | reset all calculated values, fresh start for pathfinding | [
"reset",
"all",
"calculated",
"values",
"fresh",
"start",
"for",
"pathfinding"
] | b857bf85e514a1712b40e29ccb5a473cd7fd5c80 | https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/node.py#L30-L52 | train | 204,033 |
brean/python-pathfinding | pathfinding/core/grid.py | Grid.walkable | def walkable(self, x, y):
"""
check, if the tile is inside grid and if it is set as walkable
"""
return self.inside(x, y) and self.nodes[y][x].walkable | python | def walkable(self, x, y):
"""
check, if the tile is inside grid and if it is set as walkable
"""
return self.inside(x, y) and self.nodes[y][x].walkable | [
"def",
"walkable",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"self",
".",
"inside",
"(",
"x",
",",
"y",
")",
"and",
"self",
".",
"nodes",
"[",
"y",
"]",
"[",
"x",
"]",
".",
"walkable"
] | check, if the tile is inside grid and if it is set as walkable | [
"check",
"if",
"the",
"tile",
"is",
"inside",
"grid",
"and",
"if",
"it",
"is",
"set",
"as",
"walkable"
] | b857bf85e514a1712b40e29ccb5a473cd7fd5c80 | https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L70-L74 | train | 204,034 |
brean/python-pathfinding | pathfinding/core/grid.py | Grid.grid_str | def grid_str(self, path=None, start=None, end=None,
border=True, start_chr='s', end_chr='e',
path_chr='x', empty_chr=' ', block_chr='#',
show_weight=False):
"""
create a printable string from the grid using ASCII characters
:param path: list of nodes that show the path
:param start: start node
:param end: end node
:param border: create a border around the grid
:param start_chr: character for the start (default "s")
:param end_chr: character for the destination (default "e")
:param path_chr: character to show the path (default "x")
:param empty_chr: character for empty fields (default " ")
:param block_chr: character for blocking elements (default "#")
:param show_weight: instead of empty_chr show the cost of each empty
field (shows a + if the value of weight is > 10)
:return:
"""
data = ''
if border:
data = '+{}+'.format('-'*len(self.nodes[0]))
for y in range(len(self.nodes)):
line = ''
for x in range(len(self.nodes[y])):
node = self.nodes[y][x]
if node == start:
line += start_chr
elif node == end:
line += end_chr
elif path and ((node.x, node.y) in path or node in path):
line += path_chr
elif node.walkable:
# empty field
weight = str(node.weight) if node.weight < 10 else '+'
line += weight if show_weight else empty_chr
else:
line += block_chr # blocked field
if border:
line = '|'+line+'|'
if data:
data += '\n'
data += line
if border:
data += '\n+{}+'.format('-'*len(self.nodes[0]))
return data | python | def grid_str(self, path=None, start=None, end=None,
border=True, start_chr='s', end_chr='e',
path_chr='x', empty_chr=' ', block_chr='#',
show_weight=False):
"""
create a printable string from the grid using ASCII characters
:param path: list of nodes that show the path
:param start: start node
:param end: end node
:param border: create a border around the grid
:param start_chr: character for the start (default "s")
:param end_chr: character for the destination (default "e")
:param path_chr: character to show the path (default "x")
:param empty_chr: character for empty fields (default " ")
:param block_chr: character for blocking elements (default "#")
:param show_weight: instead of empty_chr show the cost of each empty
field (shows a + if the value of weight is > 10)
:return:
"""
data = ''
if border:
data = '+{}+'.format('-'*len(self.nodes[0]))
for y in range(len(self.nodes)):
line = ''
for x in range(len(self.nodes[y])):
node = self.nodes[y][x]
if node == start:
line += start_chr
elif node == end:
line += end_chr
elif path and ((node.x, node.y) in path or node in path):
line += path_chr
elif node.walkable:
# empty field
weight = str(node.weight) if node.weight < 10 else '+'
line += weight if show_weight else empty_chr
else:
line += block_chr # blocked field
if border:
line = '|'+line+'|'
if data:
data += '\n'
data += line
if border:
data += '\n+{}+'.format('-'*len(self.nodes[0]))
return data | [
"def",
"grid_str",
"(",
"self",
",",
"path",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"border",
"=",
"True",
",",
"start_chr",
"=",
"'s'",
",",
"end_chr",
"=",
"'e'",
",",
"path_chr",
"=",
"'x'",
",",
"empty_chr",
"=",
... | create a printable string from the grid using ASCII characters
:param path: list of nodes that show the path
:param start: start node
:param end: end node
:param border: create a border around the grid
:param start_chr: character for the start (default "s")
:param end_chr: character for the destination (default "e")
:param path_chr: character to show the path (default "x")
:param empty_chr: character for empty fields (default " ")
:param block_chr: character for blocking elements (default "#")
:param show_weight: instead of empty_chr show the cost of each empty
field (shows a + if the value of weight is > 10)
:return: | [
"create",
"a",
"printable",
"string",
"from",
"the",
"grid",
"using",
"ASCII",
"characters"
] | b857bf85e514a1712b40e29ccb5a473cd7fd5c80 | https://github.com/brean/python-pathfinding/blob/b857bf85e514a1712b40e29ccb5a473cd7fd5c80/pathfinding/core/grid.py#L142-L188 | train | 204,035 |
NaturalHistoryMuseum/pyzbar | pyzbar/zbar_library.py | load | def load():
"""Loads the libzar shared library and its dependencies.
"""
if 'Windows' == platform.system():
# Possible scenarios here
# 1. Run from source, DLLs are in pyzbar directory
# cdll.LoadLibrary() imports DLLs in repo root directory
# 2. Wheel install into CPython installation
# cdll.LoadLibrary() imports DLLs in package directory
# 3. Wheel install into virtualenv
# cdll.LoadLibrary() imports DLLs in package directory
# 4. Frozen
# cdll.LoadLibrary() imports DLLs alongside executable
fname, dependencies = _windows_fnames()
def load_objects(directory):
# Load dependencies before loading libzbar dll
deps = [
cdll.LoadLibrary(str(directory.joinpath(dep)))
for dep in dependencies
]
libzbar = cdll.LoadLibrary(str(directory.joinpath(fname)))
return deps, libzbar
try:
dependencies, libzbar = load_objects(Path(''))
except OSError:
dependencies, libzbar = load_objects(Path(__file__).parent)
else:
# Assume a shared library on the path
path = find_library('zbar')
if not path:
raise ImportError('Unable to find zbar shared library')
libzbar = cdll.LoadLibrary(path)
dependencies = []
return libzbar, dependencies | python | def load():
"""Loads the libzar shared library and its dependencies.
"""
if 'Windows' == platform.system():
# Possible scenarios here
# 1. Run from source, DLLs are in pyzbar directory
# cdll.LoadLibrary() imports DLLs in repo root directory
# 2. Wheel install into CPython installation
# cdll.LoadLibrary() imports DLLs in package directory
# 3. Wheel install into virtualenv
# cdll.LoadLibrary() imports DLLs in package directory
# 4. Frozen
# cdll.LoadLibrary() imports DLLs alongside executable
fname, dependencies = _windows_fnames()
def load_objects(directory):
# Load dependencies before loading libzbar dll
deps = [
cdll.LoadLibrary(str(directory.joinpath(dep)))
for dep in dependencies
]
libzbar = cdll.LoadLibrary(str(directory.joinpath(fname)))
return deps, libzbar
try:
dependencies, libzbar = load_objects(Path(''))
except OSError:
dependencies, libzbar = load_objects(Path(__file__).parent)
else:
# Assume a shared library on the path
path = find_library('zbar')
if not path:
raise ImportError('Unable to find zbar shared library')
libzbar = cdll.LoadLibrary(path)
dependencies = []
return libzbar, dependencies | [
"def",
"load",
"(",
")",
":",
"if",
"'Windows'",
"==",
"platform",
".",
"system",
"(",
")",
":",
"# Possible scenarios here",
"# 1. Run from source, DLLs are in pyzbar directory",
"# cdll.LoadLibrary() imports DLLs in repo root directory",
"# 2. Wheel install into CPython... | Loads the libzar shared library and its dependencies. | [
"Loads",
"the",
"libzar",
"shared",
"library",
"and",
"its",
"dependencies",
"."
] | 833b375c0e84077943b7100cc9dc22a7bd48754b | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/zbar_library.py#L33-L69 | train | 204,036 |
NaturalHistoryMuseum/pyzbar | pyzbar/wrapper.py | load_libzbar | def load_libzbar():
"""Loads the zbar shared library and its dependencies.
Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES.
"""
global LIBZBAR
global EXTERNAL_DEPENDENCIES
if not LIBZBAR:
libzbar, dependencies = zbar_library.load()
LIBZBAR = libzbar
EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies
return LIBZBAR | python | def load_libzbar():
"""Loads the zbar shared library and its dependencies.
Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES.
"""
global LIBZBAR
global EXTERNAL_DEPENDENCIES
if not LIBZBAR:
libzbar, dependencies = zbar_library.load()
LIBZBAR = libzbar
EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies
return LIBZBAR | [
"def",
"load_libzbar",
"(",
")",
":",
"global",
"LIBZBAR",
"global",
"EXTERNAL_DEPENDENCIES",
"if",
"not",
"LIBZBAR",
":",
"libzbar",
",",
"dependencies",
"=",
"zbar_library",
".",
"load",
"(",
")",
"LIBZBAR",
"=",
"libzbar",
"EXTERNAL_DEPENDENCIES",
"=",
"[",
... | Loads the zbar shared library and its dependencies.
Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES. | [
"Loads",
"the",
"zbar",
"shared",
"library",
"and",
"its",
"dependencies",
"."
] | 833b375c0e84077943b7100cc9dc22a7bd48754b | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/wrapper.py#L107-L119 | train | 204,037 |
NaturalHistoryMuseum/pyzbar | pyzbar/wrapper.py | zbar_function | def zbar_function(fname, restype, *args):
"""Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.CFunctionType: A wrapper around the function.
"""
prototype = CFUNCTYPE(restype, *args)
return prototype((fname, load_libzbar())) | python | def zbar_function(fname, restype, *args):
"""Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.CFunctionType: A wrapper around the function.
"""
prototype = CFUNCTYPE(restype, *args)
return prototype((fname, load_libzbar())) | [
"def",
"zbar_function",
"(",
"fname",
",",
"restype",
",",
"*",
"args",
")",
":",
"prototype",
"=",
"CFUNCTYPE",
"(",
"restype",
",",
"*",
"args",
")",
"return",
"prototype",
"(",
"(",
"fname",
",",
"load_libzbar",
"(",
")",
")",
")"
] | Returns a foreign function exported by `zbar`.
Args:
fname (:obj:`str`): Name of the exported function as string.
restype (:obj:): Return type - one of the `ctypes` primitive C data
types.
*args: Arguments - a sequence of `ctypes` primitive C data types.
Returns:
cddl.CFunctionType: A wrapper around the function. | [
"Returns",
"a",
"foreign",
"function",
"exported",
"by",
"zbar",
"."
] | 833b375c0e84077943b7100cc9dc22a7bd48754b | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/wrapper.py#L123-L136 | train | 204,038 |
NaturalHistoryMuseum/pyzbar | pyzbar/pyzbar.py | _symbols_for_image | def _symbols_for_image(image):
"""Generator of symbols.
Args:
image: `zbar_image`
Yields:
POINTER(zbar_symbol): Symbol
"""
symbol = zbar_image_first_symbol(image)
while symbol:
yield symbol
symbol = zbar_symbol_next(symbol) | python | def _symbols_for_image(image):
"""Generator of symbols.
Args:
image: `zbar_image`
Yields:
POINTER(zbar_symbol): Symbol
"""
symbol = zbar_image_first_symbol(image)
while symbol:
yield symbol
symbol = zbar_symbol_next(symbol) | [
"def",
"_symbols_for_image",
"(",
"image",
")",
":",
"symbol",
"=",
"zbar_image_first_symbol",
"(",
"image",
")",
"while",
"symbol",
":",
"yield",
"symbol",
"symbol",
"=",
"zbar_symbol_next",
"(",
"symbol",
")"
] | Generator of symbols.
Args:
image: `zbar_image`
Yields:
POINTER(zbar_symbol): Symbol | [
"Generator",
"of",
"symbols",
"."
] | 833b375c0e84077943b7100cc9dc22a7bd48754b | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/pyzbar.py#L75-L87 | train | 204,039 |
NaturalHistoryMuseum/pyzbar | pyzbar/pyzbar.py | _decode_symbols | def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a value in the ZBarSymbol enumeration
symbol_type = ZBarSymbol(symbol.contents.type).name
polygon = convex_hull(
(
zbar_symbol_get_loc_x(symbol, index),
zbar_symbol_get_loc_y(symbol, index)
)
for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))
)
yield Decoded(
data=data,
type=symbol_type,
rect=bounding_box(polygon),
polygon=polygon
) | python | def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a value in the ZBarSymbol enumeration
symbol_type = ZBarSymbol(symbol.contents.type).name
polygon = convex_hull(
(
zbar_symbol_get_loc_x(symbol, index),
zbar_symbol_get_loc_y(symbol, index)
)
for index in _RANGEFN(zbar_symbol_get_loc_size(symbol))
)
yield Decoded(
data=data,
type=symbol_type,
rect=bounding_box(polygon),
polygon=polygon
) | [
"def",
"_decode_symbols",
"(",
"symbols",
")",
":",
"for",
"symbol",
"in",
"symbols",
":",
"data",
"=",
"string_at",
"(",
"zbar_symbol_get_data",
"(",
"symbol",
")",
")",
"# The 'type' int in a value in the ZBarSymbol enumeration",
"symbol_type",
"=",
"ZBarSymbol",
"(... | Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol | [
"Generator",
"of",
"decoded",
"symbol",
"information",
"."
] | 833b375c0e84077943b7100cc9dc22a7bd48754b | https://github.com/NaturalHistoryMuseum/pyzbar/blob/833b375c0e84077943b7100cc9dc22a7bd48754b/pyzbar/pyzbar.py#L90-L116 | train | 204,040 |
django-admin-bootstrapped/django-admin-bootstrapped | django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py | render_app_name | def render_app_name(context, app, template="/admin_app_name.html"):
""" Render the application name using the default template name. If it cannot find a
template matching the given path, fallback to the application name.
"""
try:
template = app['app_label'] + template
text = render_to_string(template, context)
except:
text = app['name']
return text | python | def render_app_name(context, app, template="/admin_app_name.html"):
""" Render the application name using the default template name. If it cannot find a
template matching the given path, fallback to the application name.
"""
try:
template = app['app_label'] + template
text = render_to_string(template, context)
except:
text = app['name']
return text | [
"def",
"render_app_name",
"(",
"context",
",",
"app",
",",
"template",
"=",
"\"/admin_app_name.html\"",
")",
":",
"try",
":",
"template",
"=",
"app",
"[",
"'app_label'",
"]",
"+",
"template",
"text",
"=",
"render_to_string",
"(",
"template",
",",
"context",
... | Render the application name using the default template name. If it cannot find a
template matching the given path, fallback to the application name. | [
"Render",
"the",
"application",
"name",
"using",
"the",
"default",
"template",
"name",
".",
"If",
"it",
"cannot",
"find",
"a",
"template",
"matching",
"the",
"given",
"path",
"fallback",
"to",
"the",
"application",
"name",
"."
] | 30380f20cc82e898754e94b5d12cacafabca01bd | https://github.com/django-admin-bootstrapped/django-admin-bootstrapped/blob/30380f20cc82e898754e94b5d12cacafabca01bd/django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py#L77-L86 | train | 204,041 |
django-admin-bootstrapped/django-admin-bootstrapped | django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py | render_app_label | def render_app_label(context, app, fallback=""):
""" Render the application label.
"""
try:
text = app['app_label']
except KeyError:
text = fallback
except TypeError:
text = app
return text | python | def render_app_label(context, app, fallback=""):
""" Render the application label.
"""
try:
text = app['app_label']
except KeyError:
text = fallback
except TypeError:
text = app
return text | [
"def",
"render_app_label",
"(",
"context",
",",
"app",
",",
"fallback",
"=",
"\"\"",
")",
":",
"try",
":",
"text",
"=",
"app",
"[",
"'app_label'",
"]",
"except",
"KeyError",
":",
"text",
"=",
"fallback",
"except",
"TypeError",
":",
"text",
"=",
"app",
... | Render the application label. | [
"Render",
"the",
"application",
"label",
"."
] | 30380f20cc82e898754e94b5d12cacafabca01bd | https://github.com/django-admin-bootstrapped/django-admin-bootstrapped/blob/30380f20cc82e898754e94b5d12cacafabca01bd/django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py#L90-L99 | train | 204,042 |
django-admin-bootstrapped/django-admin-bootstrapped | django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py | render_app_description | def render_app_description(context, app, fallback="", template="/admin_app_description.html"):
""" Render the application description using the default template name. If it cannot find a
template matching the given path, fallback to the fallback argument.
"""
try:
template = app['app_label'] + template
text = render_to_string(template, context)
except:
text = fallback
return text | python | def render_app_description(context, app, fallback="", template="/admin_app_description.html"):
""" Render the application description using the default template name. If it cannot find a
template matching the given path, fallback to the fallback argument.
"""
try:
template = app['app_label'] + template
text = render_to_string(template, context)
except:
text = fallback
return text | [
"def",
"render_app_description",
"(",
"context",
",",
"app",
",",
"fallback",
"=",
"\"\"",
",",
"template",
"=",
"\"/admin_app_description.html\"",
")",
":",
"try",
":",
"template",
"=",
"app",
"[",
"'app_label'",
"]",
"+",
"template",
"text",
"=",
"render_to_... | Render the application description using the default template name. If it cannot find a
template matching the given path, fallback to the fallback argument. | [
"Render",
"the",
"application",
"description",
"using",
"the",
"default",
"template",
"name",
".",
"If",
"it",
"cannot",
"find",
"a",
"template",
"matching",
"the",
"given",
"path",
"fallback",
"to",
"the",
"fallback",
"argument",
"."
] | 30380f20cc82e898754e94b5d12cacafabca01bd | https://github.com/django-admin-bootstrapped/django-admin-bootstrapped/blob/30380f20cc82e898754e94b5d12cacafabca01bd/django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py#L103-L112 | train | 204,043 |
django-admin-bootstrapped/django-admin-bootstrapped | django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py | custom_field_rendering | def custom_field_rendering(context, field, *args, **kwargs):
""" Wrapper for rendering the field via an external renderer """
if CUSTOM_FIELD_RENDERER:
mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1)
field_renderer = getattr(import_module(mod), cls)
if field_renderer:
return field_renderer(field, **kwargs).render()
return field | python | def custom_field_rendering(context, field, *args, **kwargs):
""" Wrapper for rendering the field via an external renderer """
if CUSTOM_FIELD_RENDERER:
mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1)
field_renderer = getattr(import_module(mod), cls)
if field_renderer:
return field_renderer(field, **kwargs).render()
return field | [
"def",
"custom_field_rendering",
"(",
"context",
",",
"field",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"CUSTOM_FIELD_RENDERER",
":",
"mod",
",",
"cls",
"=",
"CUSTOM_FIELD_RENDERER",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"field_rend... | Wrapper for rendering the field via an external renderer | [
"Wrapper",
"for",
"rendering",
"the",
"field",
"via",
"an",
"external",
"renderer"
] | 30380f20cc82e898754e94b5d12cacafabca01bd | https://github.com/django-admin-bootstrapped/django-admin-bootstrapped/blob/30380f20cc82e898754e94b5d12cacafabca01bd/django_admin_bootstrapped/templatetags/bootstrapped_goodies_tags.py#L116-L123 | train | 204,044 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.filenames | def filenames(self):
""" list of file names the data is originally being read from.
Returns
-------
names : list of str
list of file names at the beginning of the input chain.
"""
if self._is_reader:
assert self._filenames is not None
return self._filenames
else:
return self.data_producer.filenames | python | def filenames(self):
""" list of file names the data is originally being read from.
Returns
-------
names : list of str
list of file names at the beginning of the input chain.
"""
if self._is_reader:
assert self._filenames is not None
return self._filenames
else:
return self.data_producer.filenames | [
"def",
"filenames",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_reader",
":",
"assert",
"self",
".",
"_filenames",
"is",
"not",
"None",
"return",
"self",
".",
"_filenames",
"else",
":",
"return",
"self",
".",
"data_producer",
".",
"filenames"
] | list of file names the data is originally being read from.
Returns
-------
names : list of str
list of file names at the beginning of the input chain. | [
"list",
"of",
"file",
"names",
"the",
"data",
"is",
"originally",
"being",
"read",
"from",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L57-L69 | train | 204,045 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource._data_flow_chain | def _data_flow_chain(self):
"""
Get a list of all elements in the data flow graph.
The first element is the original source, the next one reads from the prior and so on and so forth.
Returns
-------
list: list of data sources
"""
if self.data_producer is None:
return []
res = []
ds = self.data_producer
while not ds.is_reader:
res.append(ds)
ds = ds.data_producer
res.append(ds)
res = res[::-1]
return res | python | def _data_flow_chain(self):
"""
Get a list of all elements in the data flow graph.
The first element is the original source, the next one reads from the prior and so on and so forth.
Returns
-------
list: list of data sources
"""
if self.data_producer is None:
return []
res = []
ds = self.data_producer
while not ds.is_reader:
res.append(ds)
ds = ds.data_producer
res.append(ds)
res = res[::-1]
return res | [
"def",
"_data_flow_chain",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_producer",
"is",
"None",
":",
"return",
"[",
"]",
"res",
"=",
"[",
"]",
"ds",
"=",
"self",
".",
"data_producer",
"while",
"not",
"ds",
".",
"is_reader",
":",
"res",
".",
"appe... | Get a list of all elements in the data flow graph.
The first element is the original source, the next one reads from the prior and so on and so forth.
Returns
-------
list: list of data sources | [
"Get",
"a",
"list",
"of",
"all",
"elements",
"in",
"the",
"data",
"flow",
"graph",
".",
"The",
"first",
"element",
"is",
"the",
"original",
"source",
"the",
"next",
"one",
"reads",
"from",
"the",
"prior",
"and",
"so",
"on",
"and",
"so",
"forth",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L188-L208 | train | 204,046 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.number_of_trajectories | def number_of_trajectories(self, stride=None):
r""" Returns the number of trajectories.
Parameters
----------
stride: None (default) or np.ndarray
Returns
-------
int : number of trajectories
"""
if not IteratorState.is_uniform_stride(stride):
n = len(np.unique(stride[:, 0]))
else:
n = self.ntraj
return n | python | def number_of_trajectories(self, stride=None):
r""" Returns the number of trajectories.
Parameters
----------
stride: None (default) or np.ndarray
Returns
-------
int : number of trajectories
"""
if not IteratorState.is_uniform_stride(stride):
n = len(np.unique(stride[:, 0]))
else:
n = self.ntraj
return n | [
"def",
"number_of_trajectories",
"(",
"self",
",",
"stride",
"=",
"None",
")",
":",
"if",
"not",
"IteratorState",
".",
"is_uniform_stride",
"(",
"stride",
")",
":",
"n",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"stride",
"[",
":",
",",
"0",
"]",
")... | r""" Returns the number of trajectories.
Parameters
----------
stride: None (default) or np.ndarray
Returns
-------
int : number of trajectories | [
"r",
"Returns",
"the",
"number",
"of",
"trajectories",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L227-L242 | train | 204,047 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.trajectory_length | def trajectory_length(self, itraj, stride=1, skip=0):
r"""Returns the length of trajectory of the requested index.
Parameters
----------
itraj : int
trajectory index
stride : int
return value is the number of frames in the trajectory when
running through it with a step size of `stride`.
skip: int or None
skip n frames.
Returns
-------
int : length of trajectory
"""
if itraj >= self.ntraj:
raise IndexError("given index (%s) exceeds number of data sets (%s)."
" Zero based indexing!" % (itraj, self.ntraj))
if not IteratorState.is_uniform_stride(stride):
selection = stride[stride[:, 0] == itraj][:, 0]
return 0 if itraj not in selection else len(selection)
else:
res = max((self._lengths[itraj] - skip - 1) // int(stride) + 1, 0)
return res | python | def trajectory_length(self, itraj, stride=1, skip=0):
r"""Returns the length of trajectory of the requested index.
Parameters
----------
itraj : int
trajectory index
stride : int
return value is the number of frames in the trajectory when
running through it with a step size of `stride`.
skip: int or None
skip n frames.
Returns
-------
int : length of trajectory
"""
if itraj >= self.ntraj:
raise IndexError("given index (%s) exceeds number of data sets (%s)."
" Zero based indexing!" % (itraj, self.ntraj))
if not IteratorState.is_uniform_stride(stride):
selection = stride[stride[:, 0] == itraj][:, 0]
return 0 if itraj not in selection else len(selection)
else:
res = max((self._lengths[itraj] - skip - 1) // int(stride) + 1, 0)
return res | [
"def",
"trajectory_length",
"(",
"self",
",",
"itraj",
",",
"stride",
"=",
"1",
",",
"skip",
"=",
"0",
")",
":",
"if",
"itraj",
">=",
"self",
".",
"ntraj",
":",
"raise",
"IndexError",
"(",
"\"given index (%s) exceeds number of data sets (%s).\"",
"\" Zero based ... | r"""Returns the length of trajectory of the requested index.
Parameters
----------
itraj : int
trajectory index
stride : int
return value is the number of frames in the trajectory when
running through it with a step size of `stride`.
skip: int or None
skip n frames.
Returns
-------
int : length of trajectory | [
"r",
"Returns",
"the",
"length",
"of",
"trajectory",
"of",
"the",
"requested",
"index",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L244-L269 | train | 204,048 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.trajectory_lengths | def trajectory_lengths(self, stride=1, skip=0):
r""" Returns the length of each trajectory.
Parameters
----------
stride : int
return value is the number of frames of the trajectories when
running through them with a step size of `stride`.
skip : int
skip parameter
Returns
-------
array(dtype=int) : containing length of each trajectory
"""
n = self.ntraj
if not IteratorState.is_uniform_stride(stride):
return np.fromiter((self.trajectory_length(itraj, stride)
for itraj in range(n)),
dtype=int, count=n)
else:
return np.fromiter((self.trajectory_length(itraj, stride, skip)
for itraj in range(n)),
dtype=int, count=n) | python | def trajectory_lengths(self, stride=1, skip=0):
r""" Returns the length of each trajectory.
Parameters
----------
stride : int
return value is the number of frames of the trajectories when
running through them with a step size of `stride`.
skip : int
skip parameter
Returns
-------
array(dtype=int) : containing length of each trajectory
"""
n = self.ntraj
if not IteratorState.is_uniform_stride(stride):
return np.fromiter((self.trajectory_length(itraj, stride)
for itraj in range(n)),
dtype=int, count=n)
else:
return np.fromiter((self.trajectory_length(itraj, stride, skip)
for itraj in range(n)),
dtype=int, count=n) | [
"def",
"trajectory_lengths",
"(",
"self",
",",
"stride",
"=",
"1",
",",
"skip",
"=",
"0",
")",
":",
"n",
"=",
"self",
".",
"ntraj",
"if",
"not",
"IteratorState",
".",
"is_uniform_stride",
"(",
"stride",
")",
":",
"return",
"np",
".",
"fromiter",
"(",
... | r""" Returns the length of each trajectory.
Parameters
----------
stride : int
return value is the number of frames of the trajectories when
running through them with a step size of `stride`.
skip : int
skip parameter
Returns
-------
array(dtype=int) : containing length of each trajectory | [
"r",
"Returns",
"the",
"length",
"of",
"each",
"trajectory",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L287-L311 | train | 204,049 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.n_frames_total | def n_frames_total(self, stride=1, skip=0):
r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
n_frames_total : int
total number of frames.
"""
if not IteratorState.is_uniform_stride(stride):
return len(stride)
return sum(self.trajectory_lengths(stride=stride, skip=skip)) | python | def n_frames_total(self, stride=1, skip=0):
r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
n_frames_total : int
total number of frames.
"""
if not IteratorState.is_uniform_stride(stride):
return len(stride)
return sum(self.trajectory_lengths(stride=stride, skip=skip)) | [
"def",
"n_frames_total",
"(",
"self",
",",
"stride",
"=",
"1",
",",
"skip",
"=",
"0",
")",
":",
"if",
"not",
"IteratorState",
".",
"is_uniform_stride",
"(",
"stride",
")",
":",
"return",
"len",
"(",
"stride",
")",
"return",
"sum",
"(",
"self",
".",
"... | r"""Returns total number of frames.
Parameters
----------
stride : int
return value is the number of frames in trajectories when
running through them with a step size of `stride`.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
n_frames_total : int
total number of frames. | [
"r",
"Returns",
"total",
"number",
"of",
"frames",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L313-L331 | train | 204,050 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSource.write_to_csv | def write_to_csv(self, filename=None, extension='.dat', overwrite=False,
stride=1, chunksize=None, **kw):
""" write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
If filename is not given, it is being tried to obtain the filenames
from the data source of this iterator.
extension : str, optional, default='.dat'
filename extension of created files
overwrite : bool, optional, default=False
shall existing files be overwritten? If a file exists, this method will raise.
stride : int
omit every n'th frame
chunksize: int, default=None
how many frames to process at once
kw : dict, optional
named arguments passed into numpy.savetxt (header, seperator etc.)
Example
-------
Assume you want to save features calculated by some FeatureReader to ASCII:
>>> import numpy as np, pyemma
>>> import os
>>> from pyemma.util.files import TemporaryDirectory
>>> from pyemma.util.contexts import settings
>>> data = [np.random.random((10,3))] * 3
>>> reader = pyemma.coordinates.source(data)
>>> filename = "distances_{itraj}.dat"
>>> with TemporaryDirectory() as td, settings(show_progress_bars=False):
... out = os.path.join(td, filename)
... reader.write_to_csv(out, header='', delimiter=';')
... print(sorted(os.listdir(td)))
['distances_0.dat', 'distances_1.dat', 'distances_2.dat']
"""
import os
if not filename:
assert hasattr(self, 'filenames')
# raise RuntimeError("could not determine filenames")
filenames = []
for f in self.filenames:
base, _ = os.path.splitext(f)
filenames.append(base + extension)
elif isinstance(filename, str):
filename = filename.replace('{stride}', str(stride))
filenames = [filename.replace('{itraj}', str(itraj)) for itraj
in range(self.number_of_trajectories())]
else:
raise TypeError("filename should be str or None")
self.logger.debug("write_to_csv, filenames=%s" % filenames)
# check files before starting to write
import errno
for f in filenames:
try:
st = os.stat(f)
raise OSError(errno.EEXIST)
except OSError as e:
if e.errno == errno.EEXIST:
if overwrite:
continue
elif e.errno == errno.ENOENT:
continue
raise
f = None
from pyemma._base.progress import ProgressReporter
pg = ProgressReporter()
it = self.iterator(stride, chunk=chunksize, return_trajindex=False)
pg.register(it.n_chunks, "saving to csv")
with it, pg.context():
oldtraj = -1
for X in it:
if oldtraj != it.current_trajindex:
if f is not None:
f.close()
fn = filenames[it.current_trajindex]
self.logger.debug("opening file %s for writing csv." % fn)
f = open(fn, 'wb')
oldtraj = it.current_trajindex
np.savetxt(f, X, **kw)
f.flush()
pg.update(1, 0)
if f is not None:
f.close() | python | def write_to_csv(self, filename=None, extension='.dat', overwrite=False,
stride=1, chunksize=None, **kw):
""" write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
If filename is not given, it is being tried to obtain the filenames
from the data source of this iterator.
extension : str, optional, default='.dat'
filename extension of created files
overwrite : bool, optional, default=False
shall existing files be overwritten? If a file exists, this method will raise.
stride : int
omit every n'th frame
chunksize: int, default=None
how many frames to process at once
kw : dict, optional
named arguments passed into numpy.savetxt (header, seperator etc.)
Example
-------
Assume you want to save features calculated by some FeatureReader to ASCII:
>>> import numpy as np, pyemma
>>> import os
>>> from pyemma.util.files import TemporaryDirectory
>>> from pyemma.util.contexts import settings
>>> data = [np.random.random((10,3))] * 3
>>> reader = pyemma.coordinates.source(data)
>>> filename = "distances_{itraj}.dat"
>>> with TemporaryDirectory() as td, settings(show_progress_bars=False):
... out = os.path.join(td, filename)
... reader.write_to_csv(out, header='', delimiter=';')
... print(sorted(os.listdir(td)))
['distances_0.dat', 'distances_1.dat', 'distances_2.dat']
"""
import os
if not filename:
assert hasattr(self, 'filenames')
# raise RuntimeError("could not determine filenames")
filenames = []
for f in self.filenames:
base, _ = os.path.splitext(f)
filenames.append(base + extension)
elif isinstance(filename, str):
filename = filename.replace('{stride}', str(stride))
filenames = [filename.replace('{itraj}', str(itraj)) for itraj
in range(self.number_of_trajectories())]
else:
raise TypeError("filename should be str or None")
self.logger.debug("write_to_csv, filenames=%s" % filenames)
# check files before starting to write
import errno
for f in filenames:
try:
st = os.stat(f)
raise OSError(errno.EEXIST)
except OSError as e:
if e.errno == errno.EEXIST:
if overwrite:
continue
elif e.errno == errno.ENOENT:
continue
raise
f = None
from pyemma._base.progress import ProgressReporter
pg = ProgressReporter()
it = self.iterator(stride, chunk=chunksize, return_trajindex=False)
pg.register(it.n_chunks, "saving to csv")
with it, pg.context():
oldtraj = -1
for X in it:
if oldtraj != it.current_trajindex:
if f is not None:
f.close()
fn = filenames[it.current_trajindex]
self.logger.debug("opening file %s for writing csv." % fn)
f = open(fn, 'wb')
oldtraj = it.current_trajindex
np.savetxt(f, X, **kw)
f.flush()
pg.update(1, 0)
if f is not None:
f.close() | [
"def",
"write_to_csv",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"extension",
"=",
"'.dat'",
",",
"overwrite",
"=",
"False",
",",
"stride",
"=",
"1",
",",
"chunksize",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"import",
"os",
"if",
"not",
"... | write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
If filename is not given, it is being tried to obtain the filenames
from the data source of this iterator.
extension : str, optional, default='.dat'
filename extension of created files
overwrite : bool, optional, default=False
shall existing files be overwritten? If a file exists, this method will raise.
stride : int
omit every n'th frame
chunksize: int, default=None
how many frames to process at once
kw : dict, optional
named arguments passed into numpy.savetxt (header, seperator etc.)
Example
-------
Assume you want to save features calculated by some FeatureReader to ASCII:
>>> import numpy as np, pyemma
>>> import os
>>> from pyemma.util.files import TemporaryDirectory
>>> from pyemma.util.contexts import settings
>>> data = [np.random.random((10,3))] * 3
>>> reader = pyemma.coordinates.source(data)
>>> filename = "distances_{itraj}.dat"
>>> with TemporaryDirectory() as td, settings(show_progress_bars=False):
... out = os.path.join(td, filename)
... reader.write_to_csv(out, header='', delimiter=';')
... print(sorted(os.listdir(td)))
['distances_0.dat', 'distances_1.dat', 'distances_2.dat'] | [
"write",
"all",
"data",
"to",
"csv",
"with",
"numpy",
".",
"savetxt"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L519-L608 | train | 204,051 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSourceIterator.n_chunks | def n_chunks(self):
""" rough estimate of how many chunks will be processed """
return self._data_source.n_chunks(self.chunksize, stride=self.stride, skip=self.skip) | python | def n_chunks(self):
""" rough estimate of how many chunks will be processed """
return self._data_source.n_chunks(self.chunksize, stride=self.stride, skip=self.skip) | [
"def",
"n_chunks",
"(",
"self",
")",
":",
"return",
"self",
".",
"_data_source",
".",
"n_chunks",
"(",
"self",
".",
"chunksize",
",",
"stride",
"=",
"self",
".",
"stride",
",",
"skip",
"=",
"self",
".",
"skip",
")"
] | rough estimate of how many chunks will be processed | [
"rough",
"estimate",
"of",
"how",
"many",
"chunks",
"will",
"be",
"processed"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L729-L731 | train | 204,052 |
markovmodel/PyEMMA | pyemma/coordinates/data/_base/datasource.py | DataSourceIterator._select_file_guard | def _select_file_guard(datasource_method):
""" in case we call _select_file multiple times with the same value, we do not want to reopen file handles."""
from functools import wraps
@wraps(datasource_method)
def wrapper(self, itraj):
# itraj already selected, we're done.
if itraj == self._selected_itraj:
return
datasource_method(self, itraj)
self._itraj = self._selected_itraj = itraj
return wrapper | python | def _select_file_guard(datasource_method):
""" in case we call _select_file multiple times with the same value, we do not want to reopen file handles."""
from functools import wraps
@wraps(datasource_method)
def wrapper(self, itraj):
# itraj already selected, we're done.
if itraj == self._selected_itraj:
return
datasource_method(self, itraj)
self._itraj = self._selected_itraj = itraj
return wrapper | [
"def",
"_select_file_guard",
"(",
"datasource_method",
")",
":",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"datasource_method",
")",
"def",
"wrapper",
"(",
"self",
",",
"itraj",
")",
":",
"# itraj already selected, we're done.",
"if",
"itraj",
"==... | in case we call _select_file multiple times with the same value, we do not want to reopen file handles. | [
"in",
"case",
"we",
"call",
"_select_file",
"multiple",
"times",
"with",
"the",
"same",
"value",
"we",
"do",
"not",
"want",
"to",
"reopen",
"file",
"handles",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/datasource.py#L753-L763 | train | 204,053 |
markovmodel/PyEMMA | pyemma/_base/loggable.py | Loggable.name | def name(self):
"""The name of this instance"""
try:
return self._name
except AttributeError:
self._name = "%s.%s[%i]" % (self.__module__,
self.__class__.__name__,
next(Loggable.__ids))
return self._name | python | def name(self):
"""The name of this instance"""
try:
return self._name
except AttributeError:
self._name = "%s.%s[%i]" % (self.__module__,
self.__class__.__name__,
next(Loggable.__ids))
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_name",
"except",
"AttributeError",
":",
"self",
".",
"_name",
"=",
"\"%s.%s[%i]\"",
"%",
"(",
"self",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"ne... | The name of this instance | [
"The",
"name",
"of",
"this",
"instance"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/loggable.py#L44-L52 | train | 204,054 |
markovmodel/PyEMMA | pyemma/_base/model.py | Model._get_model_param_names | def _get_model_param_names(cls):
r"""Get parameter names for the model"""
# fetch model parameters
if hasattr(cls, 'set_model_params'):
# introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = getargspec_no_self(cls.set_model_params)
if varargs is not None:
raise RuntimeError("PyEMMA models should always specify their parameters in the signature"
" of their set_model_params (no varargs). %s doesn't follow this convention."
% (cls,))
return args
else:
# No parameters known
return [] | python | def _get_model_param_names(cls):
r"""Get parameter names for the model"""
# fetch model parameters
if hasattr(cls, 'set_model_params'):
# introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = getargspec_no_self(cls.set_model_params)
if varargs is not None:
raise RuntimeError("PyEMMA models should always specify their parameters in the signature"
" of their set_model_params (no varargs). %s doesn't follow this convention."
% (cls,))
return args
else:
# No parameters known
return [] | [
"def",
"_get_model_param_names",
"(",
"cls",
")",
":",
"# fetch model parameters",
"if",
"hasattr",
"(",
"cls",
",",
"'set_model_params'",
")",
":",
"# introspect the constructor arguments to find the model parameters",
"# to represent",
"args",
",",
"varargs",
",",
"kw",
... | r"""Get parameter names for the model | [
"r",
"Get",
"parameter",
"names",
"for",
"the",
"model"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L55-L69 | train | 204,055 |
markovmodel/PyEMMA | pyemma/_base/model.py | Model.update_model_params | def update_model_params(self, **params):
r"""Update given model parameter if they are set to specific values"""
for key, value in params.items():
if not hasattr(self, key):
setattr(self, key, value) # set parameter for the first time.
elif getattr(self, key) is None:
setattr(self, key, value) # update because this parameter is still None.
elif value is not None:
setattr(self, key, value) | python | def update_model_params(self, **params):
r"""Update given model parameter if they are set to specific values"""
for key, value in params.items():
if not hasattr(self, key):
setattr(self, key, value) # set parameter for the first time.
elif getattr(self, key) is None:
setattr(self, key, value) # update because this parameter is still None.
elif value is not None:
setattr(self, key, value) | [
"def",
"update_model_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"key",
")",
":",
"setattr",
"(",
"self",
",",
"key",
... | r"""Update given model parameter if they are set to specific values | [
"r",
"Update",
"given",
"model",
"parameter",
"if",
"they",
"are",
"set",
"to",
"specific",
"values"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L75-L83 | train | 204,056 |
markovmodel/PyEMMA | pyemma/_base/model.py | Model.get_model_params | def get_model_params(self, deep=True):
r"""Get parameters for this model.
Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
for key in self._get_model_param_names():
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
from pyemma.util.exceptions import PyEMMA_DeprecationWarning
warnings.simplefilter("always", DeprecationWarning)
warnings.simplefilter("always", PyEMMA_DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category in(DeprecationWarning, PyEMMA_DeprecationWarning):
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0)
warnings.filters.pop(0)
# XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = list(value.get_params().items())
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out | python | def get_model_params(self, deep=True):
r"""Get parameters for this model.
Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Parameter names mapped to their values.
"""
out = dict()
for key in self._get_model_param_names():
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
from pyemma.util.exceptions import PyEMMA_DeprecationWarning
warnings.simplefilter("always", DeprecationWarning)
warnings.simplefilter("always", PyEMMA_DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category in(DeprecationWarning, PyEMMA_DeprecationWarning):
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0)
warnings.filters.pop(0)
# XXX: should we rather test if instance of estimator?
if deep and hasattr(value, 'get_params'):
deep_items = list(value.get_params().items())
out.update((key + '__' + k, val) for k, val in deep_items)
out[key] = value
return out | [
"def",
"get_model_params",
"(",
"self",
",",
"deep",
"=",
"True",
")",
":",
"out",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"self",
".",
"_get_model_param_names",
"(",
")",
":",
"# We need deprecation warnings to always be on in order to",
"# catch deprecated para... | r"""Get parameters for this model.
Parameters
----------
deep: boolean, optional
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : mapping of string to any
Parameter names mapped to their values. | [
"r",
"Get",
"parameters",
"for",
"this",
"model",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L85-L123 | train | 204,057 |
markovmodel/PyEMMA | pyemma/_base/model.py | SampledModel.sample_f | def sample_f(self, f, *args, **kwargs):
r"""Evaluated method f for all samples
Calls f(\*args, \*\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
vals : list
list of results of the method calls
"""
self._check_samples_available()
# TODO: can we use np.fromiter here? We would ne the same shape of every member for this!
return [call_member(M, f, *args, **kwargs) for M in self.samples] | python | def sample_f(self, f, *args, **kwargs):
r"""Evaluated method f for all samples
Calls f(\*args, \*\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
vals : list
list of results of the method calls
"""
self._check_samples_available()
# TODO: can we use np.fromiter here? We would ne the same shape of every member for this!
return [call_member(M, f, *args, **kwargs) for M in self.samples] | [
"def",
"sample_f",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_samples_available",
"(",
")",
"# TODO: can we use np.fromiter here? We would ne the same shape of every member for this!",
"return",
"[",
"call_member",
... | r"""Evaluated method f for all samples
Calls f(\*args, \*\*kwargs) on all samples.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
vals : list
list of results of the method calls | [
"r",
"Evaluated",
"method",
"f",
"for",
"all",
"samples"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L154-L178 | train | 204,058 |
markovmodel/PyEMMA | pyemma/_base/model.py | SampledModel.sample_mean | def sample_mean(self, f, *args, **kwargs):
r"""Sample mean of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the mean.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
mean : float or ndarray
mean value or mean array
"""
vals = self.sample_f(f, *args, **kwargs)
return _np.mean(vals, axis=0) | python | def sample_mean(self, f, *args, **kwargs):
r"""Sample mean of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the mean.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
mean : float or ndarray
mean value or mean array
"""
vals = self.sample_f(f, *args, **kwargs)
return _np.mean(vals, axis=0) | [
"def",
"sample_mean",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vals",
"=",
"self",
".",
"sample_f",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_np",
".",
"mean",
"(",
"vals",
",",
... | r"""Sample mean of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the mean.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
mean : float or ndarray
mean value or mean array | [
"r",
"Sample",
"mean",
"of",
"numerical",
"method",
"f",
"over",
"all",
"samples"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L180-L202 | train | 204,059 |
markovmodel/PyEMMA | pyemma/_base/model.py | SampledModel.sample_std | def sample_std(self, f, *args, **kwargs):
r"""Sample standard deviation of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the standard deviation.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
std : float or ndarray
standard deviation or array of standard deviations
"""
vals = self.sample_f(f, *args, **kwargs)
return _np.std(vals, axis=0) | python | def sample_std(self, f, *args, **kwargs):
r"""Sample standard deviation of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the standard deviation.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
std : float or ndarray
standard deviation or array of standard deviations
"""
vals = self.sample_f(f, *args, **kwargs)
return _np.std(vals, axis=0) | [
"def",
"sample_std",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vals",
"=",
"self",
".",
"sample_f",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_np",
".",
"std",
"(",
"vals",
",",
"a... | r"""Sample standard deviation of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the standard deviation.
f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
std : float or ndarray
standard deviation or array of standard deviations | [
"r",
"Sample",
"standard",
"deviation",
"of",
"numerical",
"method",
"f",
"over",
"all",
"samples"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L204-L226 | train | 204,060 |
markovmodel/PyEMMA | pyemma/_base/model.py | SampledModel.sample_conf | def sample_conf(self, f, *args, **kwargs):
r"""Sample confidence interval of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the confidence interval.
Size of confidence interval is given in the construction of the
SampledModel. f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
L : float or ndarray
lower value or array of confidence interval
R : float or ndarray
upper value or array of confidence interval
"""
vals = self.sample_f(f, *args, **kwargs)
return confidence_interval(vals, conf=self.conf) | python | def sample_conf(self, f, *args, **kwargs):
r"""Sample confidence interval of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the confidence interval.
Size of confidence interval is given in the construction of the
SampledModel. f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
L : float or ndarray
lower value or array of confidence interval
R : float or ndarray
upper value or array of confidence interval
"""
vals = self.sample_f(f, *args, **kwargs)
return confidence_interval(vals, conf=self.conf) | [
"def",
"sample_conf",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vals",
"=",
"self",
".",
"sample_f",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"confidence_interval",
"(",
"vals",
",",
"... | r"""Sample confidence interval of numerical method f over all samples
Calls f(\*args, \*\*kwargs) on all samples and computes the confidence interval.
Size of confidence interval is given in the construction of the
SampledModel. f must return a numerical value or an ndarray.
Parameters
----------
f : method reference or name (str)
Model method to be evaluated for each model sample
args : arguments
Non-keyword arguments to be passed to the method in each call
kwargs : keyword-argments
Keyword arguments to be passed to the method in each call
Returns
-------
L : float or ndarray
lower value or array of confidence interval
R : float or ndarray
upper value or array of confidence interval | [
"r",
"Sample",
"confidence",
"interval",
"of",
"numerical",
"method",
"f",
"over",
"all",
"samples"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/model.py#L228-L253 | train | 204,061 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.describe | def describe(self):
"""
Returns a list of strings, one for each feature selected,
with human-readable descriptions of the features.
Returns
-------
labels : list of str
An ordered list of strings, one for each feature selected,
with human-readable descriptions of the features.
"""
all_labels = []
for f in self.active_features:
all_labels += f.describe()
return all_labels | python | def describe(self):
"""
Returns a list of strings, one for each feature selected,
with human-readable descriptions of the features.
Returns
-------
labels : list of str
An ordered list of strings, one for each feature selected,
with human-readable descriptions of the features.
"""
all_labels = []
for f in self.active_features:
all_labels += f.describe()
return all_labels | [
"def",
"describe",
"(",
"self",
")",
":",
"all_labels",
"=",
"[",
"]",
"for",
"f",
"in",
"self",
".",
"active_features",
":",
"all_labels",
"+=",
"f",
".",
"describe",
"(",
")",
"return",
"all_labels"
] | Returns a list of strings, one for each feature selected,
with human-readable descriptions of the features.
Returns
-------
labels : list of str
An ordered list of strings, one for each feature selected,
with human-readable descriptions of the features. | [
"Returns",
"a",
"list",
"of",
"strings",
"one",
"for",
"each",
"feature",
"selected",
"with",
"human",
"-",
"readable",
"descriptions",
"of",
"the",
"features",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L96-L111 | train | 204,062 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_distances | def add_distances(self, indices, periodic=True, indices2=None):
r"""
Adds the distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import DistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = DistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) | python | def add_distances(self, indices, periodic=True, indices2=None):
r"""
Adds the distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import DistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = DistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) | [
"def",
"add_distances",
"(",
"self",
",",
"indices",
",",
"periodic",
"=",
"True",
",",
"indices2",
"=",
"None",
")",
":",
"from",
".",
"distances",
"import",
"DistanceFeature",
"atom_pairs",
"=",
"_parse_pairwise_input",
"(",
"indices",
",",
"indices2",
",",
... | r"""
Adds the distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the iterable of integers input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added. | [
"r",
"Adds",
"the",
"distances",
"between",
"atoms",
"to",
"the",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L304-L339 | train | 204,063 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_distances_ca | def add_distances_ca(self, periodic=True, excluded_neighbors=2):
"""
Adds the distances between all Ca's to the feature list.
Parameters
----------
periodic : boolean, default is True
Use the minimum image convetion when computing distances
excluded_neighbors : int, default is 2
Number of exclusions when compiling the list of pairs. Two CA-atoms are considered
neighbors if they belong to adjacent residues.
"""
# Atom indices for CAs
at_idxs_ca = self.select_Ca()
# Residue indices for residues contatinig CAs
res_idxs_ca = [self.topology.atom(ca).residue.index for ca in at_idxs_ca]
# Pairs of those residues, with possibility to exclude neighbors
res_idxs_ca_pairs = self.pairs(res_idxs_ca, excluded_neighbors=excluded_neighbors)
# Mapping back pairs of residue indices to pairs of CA indices
distance_indexes = []
for ri, rj in res_idxs_ca_pairs:
distance_indexes.append([self.topology.residue(ri).atom('CA').index,
self.topology.residue(rj).atom('CA').index
])
distance_indexes = np.array(distance_indexes)
self.add_distances(distance_indexes, periodic=periodic) | python | def add_distances_ca(self, periodic=True, excluded_neighbors=2):
"""
Adds the distances between all Ca's to the feature list.
Parameters
----------
periodic : boolean, default is True
Use the minimum image convetion when computing distances
excluded_neighbors : int, default is 2
Number of exclusions when compiling the list of pairs. Two CA-atoms are considered
neighbors if they belong to adjacent residues.
"""
# Atom indices for CAs
at_idxs_ca = self.select_Ca()
# Residue indices for residues contatinig CAs
res_idxs_ca = [self.topology.atom(ca).residue.index for ca in at_idxs_ca]
# Pairs of those residues, with possibility to exclude neighbors
res_idxs_ca_pairs = self.pairs(res_idxs_ca, excluded_neighbors=excluded_neighbors)
# Mapping back pairs of residue indices to pairs of CA indices
distance_indexes = []
for ri, rj in res_idxs_ca_pairs:
distance_indexes.append([self.topology.residue(ri).atom('CA').index,
self.topology.residue(rj).atom('CA').index
])
distance_indexes = np.array(distance_indexes)
self.add_distances(distance_indexes, periodic=periodic) | [
"def",
"add_distances_ca",
"(",
"self",
",",
"periodic",
"=",
"True",
",",
"excluded_neighbors",
"=",
"2",
")",
":",
"# Atom indices for CAs",
"at_idxs_ca",
"=",
"self",
".",
"select_Ca",
"(",
")",
"# Residue indices for residues contatinig CAs",
"res_idxs_ca",
"=",
... | Adds the distances between all Ca's to the feature list.
Parameters
----------
periodic : boolean, default is True
Use the minimum image convetion when computing distances
excluded_neighbors : int, default is 2
Number of exclusions when compiling the list of pairs. Two CA-atoms are considered
neighbors if they belong to adjacent residues. | [
"Adds",
"the",
"distances",
"between",
"all",
"Ca",
"s",
"to",
"the",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L341-L370 | train | 204,064 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_inverse_distances | def add_inverse_distances(self, indices, periodic=True, indices2=None):
"""
Adds the inverse distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the inverse distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import InverseDistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_inverse_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = InverseDistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) | python | def add_inverse_distances(self, indices, periodic=True, indices2=None):
"""
Adds the inverse distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the inverse distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import InverseDistanceFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_inverse_distances()')
atom_pairs = self._check_indices(atom_pairs)
f = InverseDistanceFeature(self.topology, atom_pairs, periodic=periodic)
self.__add_feature(f) | [
"def",
"add_inverse_distances",
"(",
"self",
",",
"indices",
",",
"periodic",
"=",
"True",
",",
"indices2",
"=",
"None",
")",
":",
"from",
".",
"distances",
"import",
"InverseDistanceFeature",
"atom_pairs",
"=",
"_parse_pairwise_input",
"(",
"indices",
",",
"ind... | Adds the inverse distances between atoms to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the inverse distances shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the inverse distances shall be computed.
periodic : optional, boolean, default is True
If periodic is True and the trajectory contains unitcell information,
distances will be computed under the minimum image convention.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the inverse distances between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added. | [
"Adds",
"the",
"inverse",
"distances",
"between",
"atoms",
"to",
"the",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L372-L407 | train | 204,065 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_contacts | def add_contacts(self, indices, indices2=None, threshold=0.3, periodic=True, count_contacts=False):
r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the contacts shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the contacts shall be computed.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the contacts between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
threshold : float, optional, default = .3
distances below this threshold (in nm) will result in a feature 1.0, distances above will result in 0.0.
The default is set to .3 nm (3 Angstrom)
periodic : boolean, default True
use the minimum image convention if unitcell information is available
count_contacts : boolean, default False
If set to true, this feature will return the number of formed contacts (and not feature values with either 1.0 or 0)
The ouput of this feature will be of shape (Nt,1), and not (Nt, nr_of_contacts)
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import ContactFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_contacts()')
atom_pairs = self._check_indices(atom_pairs)
f = ContactFeature(self.topology, atom_pairs, threshold, periodic, count_contacts)
self.__add_feature(f) | python | def add_contacts(self, indices, indices2=None, threshold=0.3, periodic=True, count_contacts=False):
r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the contacts shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the contacts shall be computed.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the contacts between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
threshold : float, optional, default = .3
distances below this threshold (in nm) will result in a feature 1.0, distances above will result in 0.0.
The default is set to .3 nm (3 Angstrom)
periodic : boolean, default True
use the minimum image convention if unitcell information is available
count_contacts : boolean, default False
If set to true, this feature will return the number of formed contacts (and not feature values with either 1.0 or 0)
The ouput of this feature will be of shape (Nt,1), and not (Nt, nr_of_contacts)
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added.
"""
from .distances import ContactFeature
atom_pairs = _parse_pairwise_input(
indices, indices2, self.logger, fname='add_contacts()')
atom_pairs = self._check_indices(atom_pairs)
f = ContactFeature(self.topology, atom_pairs, threshold, periodic, count_contacts)
self.__add_feature(f) | [
"def",
"add_contacts",
"(",
"self",
",",
"indices",
",",
"indices2",
"=",
"None",
",",
"threshold",
"=",
"0.3",
",",
"periodic",
"=",
"True",
",",
"count_contacts",
"=",
"False",
")",
":",
"from",
".",
"distances",
"import",
"ContactFeature",
"atom_pairs",
... | r"""
Adds the contacts to the feature list.
Parameters
----------
indices : can be of two types:
ndarray((n, 2), dtype=int):
n x 2 array with the pairs of atoms between which the contacts shall be computed
iterable of integers (either list or ndarray(n, dtype=int)):
indices (not pairs of indices) of the atoms between which the contacts shall be computed.
indices2: iterable of integers (either list or ndarray(n, dtype=int)), optional:
Only has effect if :py:obj:`indices` is an iterable of integers. Instead of the above behaviour,
only the contacts between the atoms in :py:obj:`indices` and :py:obj:`indices2` will be computed.
threshold : float, optional, default = .3
distances below this threshold (in nm) will result in a feature 1.0, distances above will result in 0.0.
The default is set to .3 nm (3 Angstrom)
periodic : boolean, default True
use the minimum image convention if unitcell information is available
count_contacts : boolean, default False
If set to true, this feature will return the number of formed contacts (and not feature values with either 1.0 or 0)
The ouput of this feature will be of shape (Nt,1), and not (Nt, nr_of_contacts)
.. note::
When using the *iterable of integers* input, :py:obj:`indices` and :py:obj:`indices2`
will be sorted numerically and made unique before converting them to a pairlist.
Please look carefully at the output of :py:func:`describe()` to see what features exactly have been added. | [
"r",
"Adds",
"the",
"contacts",
"to",
"the",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L409-L450 | train | 204,066 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_angles | def add_angles(self, indexes, deg=False, cossin=False, periodic=True):
"""
Adds the list of angles to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 3), dtype=int
an array with triplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention.
"""
from .angles import AngleFeature
indexes = self._check_indices(indexes, pair_n=3)
f = AngleFeature(self.topology, indexes, deg=deg, cossin=cossin,
periodic=periodic)
self.__add_feature(f) | python | def add_angles(self, indexes, deg=False, cossin=False, periodic=True):
"""
Adds the list of angles to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 3), dtype=int
an array with triplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention.
"""
from .angles import AngleFeature
indexes = self._check_indices(indexes, pair_n=3)
f = AngleFeature(self.topology, indexes, deg=deg, cossin=cossin,
periodic=periodic)
self.__add_feature(f) | [
"def",
"add_angles",
"(",
"self",
",",
"indexes",
",",
"deg",
"=",
"False",
",",
"cossin",
"=",
"False",
",",
"periodic",
"=",
"True",
")",
":",
"from",
".",
"angles",
"import",
"AngleFeature",
"indexes",
"=",
"self",
".",
"_check_indices",
"(",
"indexes... | Adds the list of angles to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 3), dtype=int
an array with triplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention. | [
"Adds",
"the",
"list",
"of",
"angles",
"to",
"the",
"feature",
"list"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L624-L649 | train | 204,067 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_dihedrals | def add_dihedrals(self, indexes, deg=False, cossin=False, periodic=True):
"""
Adds the list of dihedrals to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 4), dtype=int
an array with quadruplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention.
"""
from .angles import DihedralFeature
indexes = self._check_indices(indexes, pair_n=4)
f = DihedralFeature(self.topology, indexes, deg=deg, cossin=cossin,
periodic=periodic)
self.__add_feature(f) | python | def add_dihedrals(self, indexes, deg=False, cossin=False, periodic=True):
"""
Adds the list of dihedrals to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 4), dtype=int
an array with quadruplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention.
"""
from .angles import DihedralFeature
indexes = self._check_indices(indexes, pair_n=4)
f = DihedralFeature(self.topology, indexes, deg=deg, cossin=cossin,
periodic=periodic)
self.__add_feature(f) | [
"def",
"add_dihedrals",
"(",
"self",
",",
"indexes",
",",
"deg",
"=",
"False",
",",
"cossin",
"=",
"False",
",",
"periodic",
"=",
"True",
")",
":",
"from",
".",
"angles",
"import",
"DihedralFeature",
"indexes",
"=",
"self",
".",
"_check_indices",
"(",
"i... | Adds the list of dihedrals to the feature list
Parameters
----------
indexes : np.ndarray, shape=(num_pairs, 4), dtype=int
an array with quadruplets of atom indices
deg : bool, optional, default = False
If False (default), angles will be computed in radians.
If True, angles will be computed in degrees.
cossin : bool, optional, default = False
If True, each angle will be returned as a pair of (sin(x), cos(x)).
This is useful, if you calculate the mean (e.g TICA/PCA, clustering)
in that space.
periodic : bool, optional, default = True
If `periodic` is True and the trajectory contains unitcell
information, we will treat dihedrals that cross periodic images
using the minimum image convention. | [
"Adds",
"the",
"list",
"of",
"dihedrals",
"to",
"the",
"feature",
"list"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L651-L676 | train | 204,068 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_custom_feature | def add_custom_feature(self, feature):
"""
Adds a custom feature to the feature list.
Parameters
----------
feature : object
an object with interface like CustomFeature (map, describe methods)
"""
if feature.dimension <= 0:
raise ValueError("Dimension has to be positive. "
"Please override dimension attribute in feature!")
if not hasattr(feature, 'transform'):
raise ValueError("no 'transform' method in given feature")
elif not callable(getattr(feature, 'transform')):
raise ValueError("'transform' attribute exists but is not a method")
self.__add_feature(feature) | python | def add_custom_feature(self, feature):
"""
Adds a custom feature to the feature list.
Parameters
----------
feature : object
an object with interface like CustomFeature (map, describe methods)
"""
if feature.dimension <= 0:
raise ValueError("Dimension has to be positive. "
"Please override dimension attribute in feature!")
if not hasattr(feature, 'transform'):
raise ValueError("no 'transform' method in given feature")
elif not callable(getattr(feature, 'transform')):
raise ValueError("'transform' attribute exists but is not a method")
self.__add_feature(feature) | [
"def",
"add_custom_feature",
"(",
"self",
",",
"feature",
")",
":",
"if",
"feature",
".",
"dimension",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Dimension has to be positive. \"",
"\"Please override dimension attribute in feature!\"",
")",
"if",
"not",
"hasattr",
... | Adds a custom feature to the feature list.
Parameters
----------
feature : object
an object with interface like CustomFeature (map, describe methods) | [
"Adds",
"a",
"custom",
"feature",
"to",
"the",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L760-L779 | train | 204,069 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.add_custom_func | def add_custom_func(self, func, dim, *args, **kwargs):
""" adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arguments as desired.
Has to return a numpy.ndarray ndim=2.
dim : int
output dimension of :py:obj:`function`
description: str or None
a message for the describe feature list.
args : any number of positional arguments
these have to be in the same order as :py:obj:`func` is expecting them
kwargs : dictionary
named arguments passed to func
Notes
-----
You can pass a description list to describe the output of your function by element,
by passing a list of strings with the same lengths as dimensions.
Alternatively a single element list or str will be expanded to match the output dimension.
"""
description = kwargs.pop('description', None)
f = CustomFeature(func, dim=dim, description=description, fun_args=args, fun_kwargs=kwargs)
self.add_custom_feature(f) | python | def add_custom_func(self, func, dim, *args, **kwargs):
""" adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arguments as desired.
Has to return a numpy.ndarray ndim=2.
dim : int
output dimension of :py:obj:`function`
description: str or None
a message for the describe feature list.
args : any number of positional arguments
these have to be in the same order as :py:obj:`func` is expecting them
kwargs : dictionary
named arguments passed to func
Notes
-----
You can pass a description list to describe the output of your function by element,
by passing a list of strings with the same lengths as dimensions.
Alternatively a single element list or str will be expanded to match the output dimension.
"""
description = kwargs.pop('description', None)
f = CustomFeature(func, dim=dim, description=description, fun_args=args, fun_kwargs=kwargs)
self.add_custom_feature(f) | [
"def",
"add_custom_func",
"(",
"self",
",",
"func",
",",
"dim",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"description",
"=",
"kwargs",
".",
"pop",
"(",
"'description'",
",",
"None",
")",
"f",
"=",
"CustomFeature",
"(",
"func",
",",
"dim",... | adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arguments as desired.
Has to return a numpy.ndarray ndim=2.
dim : int
output dimension of :py:obj:`function`
description: str or None
a message for the describe feature list.
args : any number of positional arguments
these have to be in the same order as :py:obj:`func` is expecting them
kwargs : dictionary
named arguments passed to func
Notes
-----
You can pass a description list to describe the output of your function by element,
by passing a list of strings with the same lengths as dimensions.
Alternatively a single element list or str will be expanded to match the output dimension. | [
"adds",
"a",
"user",
"defined",
"function",
"to",
"extract",
"features"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L814-L841 | train | 204,070 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.remove_all_custom_funcs | def remove_all_custom_funcs(self):
""" Remove all instances of CustomFeature from the active feature list.
"""
custom_feats = [f for f in self.active_features if isinstance(f, CustomFeature)]
for f in custom_feats:
self.active_features.remove(f) | python | def remove_all_custom_funcs(self):
""" Remove all instances of CustomFeature from the active feature list.
"""
custom_feats = [f for f in self.active_features if isinstance(f, CustomFeature)]
for f in custom_feats:
self.active_features.remove(f) | [
"def",
"remove_all_custom_funcs",
"(",
"self",
")",
":",
"custom_feats",
"=",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"active_features",
"if",
"isinstance",
"(",
"f",
",",
"CustomFeature",
")",
"]",
"for",
"f",
"in",
"custom_feats",
":",
"self",
".",
"a... | Remove all instances of CustomFeature from the active feature list. | [
"Remove",
"all",
"instances",
"of",
"CustomFeature",
"from",
"the",
"active",
"feature",
"list",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L843-L848 | train | 204,071 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.dimension | def dimension(self):
""" current dimension due to selected features
Returns
-------
dim : int
total dimension due to all selection features
"""
dim = sum(f.dimension for f in self.active_features)
return dim | python | def dimension(self):
""" current dimension due to selected features
Returns
-------
dim : int
total dimension due to all selection features
"""
dim = sum(f.dimension for f in self.active_features)
return dim | [
"def",
"dimension",
"(",
"self",
")",
":",
"dim",
"=",
"sum",
"(",
"f",
".",
"dimension",
"for",
"f",
"in",
"self",
".",
"active_features",
")",
"return",
"dim"
] | current dimension due to selected features
Returns
-------
dim : int
total dimension due to all selection features | [
"current",
"dimension",
"due",
"to",
"selected",
"features"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L850-L860 | train | 204,072 |
markovmodel/PyEMMA | pyemma/coordinates/data/featurization/featurizer.py | MDFeaturizer.transform | def transform(self, traj):
"""
Maps an mdtraj Trajectory object to the selected output features
Parameters
----------
traj : mdtraj Trajectory
Trajectory object used as an input
Returns
-------
out : ndarray((T, n), dtype=float32)
Output features: For each of T time steps in the given trajectory,
a vector with all n output features selected.
"""
# if there are no features selected, return given trajectory
if not self.active_features:
self.add_selection(np.arange(self.topology.n_atoms))
warnings.warn("You have not selected any features. Returning plain coordinates.")
# otherwise build feature vector.
feature_vec = []
# TODO: consider parallel evaluation computation here, this effort is
# only worth it, if computation time dominates memory transfers
for f in self.active_features:
# perform sanity checks for custom feature input
if isinstance(f, CustomFeature):
# NOTE: casting=safe raises in numpy>=1.9
vec = f.transform(traj).astype(np.float32, casting='safe')
if vec.shape[0] == 0:
vec = np.empty((0, f.dimension))
if not isinstance(vec, np.ndarray):
raise ValueError('Your custom feature %s did not return'
' a numpy.ndarray!' % str(f.describe()))
if not vec.ndim == 2:
raise ValueError('Your custom feature %s did not return'
' a 2d array. Shape was %s'
% (str(f.describe()),
str(vec.shape)))
if not vec.shape[0] == traj.xyz.shape[0]:
raise ValueError('Your custom feature %s did not return'
' as many frames as it received!'
'Input was %i, output was %i'
% (str(f.describe()),
traj.xyz.shape[0],
vec.shape[0]))
else:
vec = f.transform(traj).astype(np.float32)
feature_vec.append(vec)
if len(feature_vec) > 1:
res = np.hstack(feature_vec)
else:
res = feature_vec[0]
return res | python | def transform(self, traj):
"""
Maps an mdtraj Trajectory object to the selected output features
Parameters
----------
traj : mdtraj Trajectory
Trajectory object used as an input
Returns
-------
out : ndarray((T, n), dtype=float32)
Output features: For each of T time steps in the given trajectory,
a vector with all n output features selected.
"""
# if there are no features selected, return given trajectory
if not self.active_features:
self.add_selection(np.arange(self.topology.n_atoms))
warnings.warn("You have not selected any features. Returning plain coordinates.")
# otherwise build feature vector.
feature_vec = []
# TODO: consider parallel evaluation computation here, this effort is
# only worth it, if computation time dominates memory transfers
for f in self.active_features:
# perform sanity checks for custom feature input
if isinstance(f, CustomFeature):
# NOTE: casting=safe raises in numpy>=1.9
vec = f.transform(traj).astype(np.float32, casting='safe')
if vec.shape[0] == 0:
vec = np.empty((0, f.dimension))
if not isinstance(vec, np.ndarray):
raise ValueError('Your custom feature %s did not return'
' a numpy.ndarray!' % str(f.describe()))
if not vec.ndim == 2:
raise ValueError('Your custom feature %s did not return'
' a 2d array. Shape was %s'
% (str(f.describe()),
str(vec.shape)))
if not vec.shape[0] == traj.xyz.shape[0]:
raise ValueError('Your custom feature %s did not return'
' as many frames as it received!'
'Input was %i, output was %i'
% (str(f.describe()),
traj.xyz.shape[0],
vec.shape[0]))
else:
vec = f.transform(traj).astype(np.float32)
feature_vec.append(vec)
if len(feature_vec) > 1:
res = np.hstack(feature_vec)
else:
res = feature_vec[0]
return res | [
"def",
"transform",
"(",
"self",
",",
"traj",
")",
":",
"# if there are no features selected, return given trajectory",
"if",
"not",
"self",
".",
"active_features",
":",
"self",
".",
"add_selection",
"(",
"np",
".",
"arange",
"(",
"self",
".",
"topology",
".",
"... | Maps an mdtraj Trajectory object to the selected output features
Parameters
----------
traj : mdtraj Trajectory
Trajectory object used as an input
Returns
-------
out : ndarray((T, n), dtype=float32)
Output features: For each of T time steps in the given trajectory,
a vector with all n output features selected. | [
"Maps",
"an",
"mdtraj",
"Trajectory",
"object",
"to",
"the",
"selected",
"output",
"features"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/featurizer.py#L862-L920 | train | 204,073 |
markovmodel/PyEMMA | pyemma/msm/estimators/_OOM_MSM.py | bootstrapping_dtrajs | def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
"""
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of active set, all count matrices will be restricted
to active set.
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values
"""
# Get the number of simulations:
Q = len(dtrajs)
# Get the number of states in the active set:
if active_set is not None:
N = active_set.size
else:
N = N_full
# Build up a matrix of count matrices for each simulation. Size is Q*N^2:
traj_ind = []
state1 = []
state2 = []
q = 0
for traj in dtrajs:
traj_ind.append(q*np.ones(traj[:-lag].size))
state1.append(traj[:-lag])
state2.append(traj[lag:])
q += 1
traj_inds = np.concatenate(traj_ind)
pairs = N_full * np.concatenate(state1) + np.concatenate(state2)
data = np.ones(pairs.size)
Ct_traj = scipy.sparse.coo_matrix((data, (traj_inds, pairs)), shape=(Q, N_full*N_full))
Ct_traj = Ct_traj.tocsr()
# Perform re-sampling:
svals = np.zeros((nbs, N))
for s in range(nbs):
# Choose selection:
sel = np.random.choice(Q, Q, replace=True)
# Compute count matrix for selection:
Ct_sel = Ct_traj[sel, :].sum(axis=0)
Ct_sel = np.asarray(Ct_sel).reshape((N_full, N_full))
if active_set is not None:
from pyemma.util.linalg import submatrix
Ct_sel = submatrix(Ct_sel, active_set)
svals[s, :] = scl.svdvals(Ct_sel)
# Compute mean and uncertainties:
smean = np.mean(svals, axis=0)
sdev = np.std(svals, axis=0)
return smean, sdev | python | def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
"""
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of active set, all count matrices will be restricted
to active set.
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values
"""
# Get the number of simulations:
Q = len(dtrajs)
# Get the number of states in the active set:
if active_set is not None:
N = active_set.size
else:
N = N_full
# Build up a matrix of count matrices for each simulation. Size is Q*N^2:
traj_ind = []
state1 = []
state2 = []
q = 0
for traj in dtrajs:
traj_ind.append(q*np.ones(traj[:-lag].size))
state1.append(traj[:-lag])
state2.append(traj[lag:])
q += 1
traj_inds = np.concatenate(traj_ind)
pairs = N_full * np.concatenate(state1) + np.concatenate(state2)
data = np.ones(pairs.size)
Ct_traj = scipy.sparse.coo_matrix((data, (traj_inds, pairs)), shape=(Q, N_full*N_full))
Ct_traj = Ct_traj.tocsr()
# Perform re-sampling:
svals = np.zeros((nbs, N))
for s in range(nbs):
# Choose selection:
sel = np.random.choice(Q, Q, replace=True)
# Compute count matrix for selection:
Ct_sel = Ct_traj[sel, :].sum(axis=0)
Ct_sel = np.asarray(Ct_sel).reshape((N_full, N_full))
if active_set is not None:
from pyemma.util.linalg import submatrix
Ct_sel = submatrix(Ct_sel, active_set)
svals[s, :] = scl.svdvals(Ct_sel)
# Compute mean and uncertainties:
smean = np.mean(svals, axis=0)
sdev = np.std(svals, axis=0)
return smean, sdev | [
"def",
"bootstrapping_dtrajs",
"(",
"dtrajs",
",",
"lag",
",",
"N_full",
",",
"nbs",
"=",
"10000",
",",
"active_set",
"=",
"None",
")",
":",
"# Get the number of simulations:",
"Q",
"=",
"len",
"(",
"dtrajs",
")",
"# Get the number of states in the active set:",
"... | Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of active set, all count matrices will be restricted
to active set.
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values | [
"Perform",
"trajectory",
"based",
"re",
"-",
"sampling",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/estimators/_OOM_MSM.py#L28-L94 | train | 204,074 |
markovmodel/PyEMMA | pyemma/msm/estimators/_OOM_MSM.py | bootstrapping_count_matrix | def bootstrapping_count_matrix(Ct, nbs=10000):
"""
Perform bootstrapping on trajectories to estimate uncertainties for singular values of count matrices.
Parameters
----------
Ct : csr-matrix
count matrix of the data.
nbs : int, optional
the number of re-samplings to be drawn from dtrajs
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values
"""
# Get the number of states:
N = Ct.shape[0]
# Get the number of transition pairs:
T = Ct.sum()
# Reshape and normalize the count matrix:
p = Ct.toarray()
p = np.reshape(p, (N*N,)).astype(np.float)
p = p / T
# Perform the bootstrapping:
svals = np.zeros((nbs, N))
for s in range(nbs):
# Draw sample:
sel = np.random.multinomial(T, p)
# Compute the count-matrix:
sC = np.reshape(sel, (N, N))
# Compute singular values:
svals[s, :] = scl.svdvals(sC)
# Compute mean and uncertainties:
smean = np.mean(svals, axis=0)
sdev = np.std(svals, axis=0)
return smean, sdev | python | def bootstrapping_count_matrix(Ct, nbs=10000):
"""
Perform bootstrapping on trajectories to estimate uncertainties for singular values of count matrices.
Parameters
----------
Ct : csr-matrix
count matrix of the data.
nbs : int, optional
the number of re-samplings to be drawn from dtrajs
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values
"""
# Get the number of states:
N = Ct.shape[0]
# Get the number of transition pairs:
T = Ct.sum()
# Reshape and normalize the count matrix:
p = Ct.toarray()
p = np.reshape(p, (N*N,)).astype(np.float)
p = p / T
# Perform the bootstrapping:
svals = np.zeros((nbs, N))
for s in range(nbs):
# Draw sample:
sel = np.random.multinomial(T, p)
# Compute the count-matrix:
sC = np.reshape(sel, (N, N))
# Compute singular values:
svals[s, :] = scl.svdvals(sC)
# Compute mean and uncertainties:
smean = np.mean(svals, axis=0)
sdev = np.std(svals, axis=0)
return smean, sdev | [
"def",
"bootstrapping_count_matrix",
"(",
"Ct",
",",
"nbs",
"=",
"10000",
")",
":",
"# Get the number of states:",
"N",
"=",
"Ct",
".",
"shape",
"[",
"0",
"]",
"# Get the number of transition pairs:",
"T",
"=",
"Ct",
".",
"sum",
"(",
")",
"# Reshape and normaliz... | Perform bootstrapping on trajectories to estimate uncertainties for singular values of count matrices.
Parameters
----------
Ct : csr-matrix
count matrix of the data.
nbs : int, optional
the number of re-samplings to be drawn from dtrajs
Returns
-------
smean : ndarray(N,)
mean values of singular values
sdev : ndarray(N,)
standard deviations of singular values | [
"Perform",
"bootstrapping",
"on",
"trajectories",
"to",
"estimate",
"uncertainties",
"for",
"singular",
"values",
"of",
"count",
"matrices",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/estimators/_OOM_MSM.py#L96-L136 | train | 204,075 |
markovmodel/PyEMMA | pyemma/msm/estimators/_OOM_MSM.py | twostep_count_matrix | def twostep_count_matrix(dtrajs, lag, N):
"""
Compute all two-step count matrices from discrete trajectories.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
the lag time for count matrix estimation
N : int
the number of states in the discrete trajectories.
Returns
-------
C2t : sparse csc-matrix (N, N, N)
two-step count matrices for all states. C2t[:, n, :] is a count matrix for each n
"""
# List all transition triples:
rows = []
cols = []
states = []
for dtraj in dtrajs:
if dtraj.size > 2*lag:
rows.append(dtraj[0:-2*lag])
states.append(dtraj[lag:-lag])
cols.append(dtraj[2*lag:])
row = np.concatenate(rows)
col = np.concatenate(cols)
state = np.concatenate(states)
data = np.ones(row.size)
# Transform the rows and cols into a single list with N*+2 possible values:
pair = N * row + col
# Estimate sparse matrix:
C2t = scipy.sparse.coo_matrix((data, (pair, state)), shape=(N*N, N))
return C2t.tocsc() | python | def twostep_count_matrix(dtrajs, lag, N):
"""
Compute all two-step count matrices from discrete trajectories.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
the lag time for count matrix estimation
N : int
the number of states in the discrete trajectories.
Returns
-------
C2t : sparse csc-matrix (N, N, N)
two-step count matrices for all states. C2t[:, n, :] is a count matrix for each n
"""
# List all transition triples:
rows = []
cols = []
states = []
for dtraj in dtrajs:
if dtraj.size > 2*lag:
rows.append(dtraj[0:-2*lag])
states.append(dtraj[lag:-lag])
cols.append(dtraj[2*lag:])
row = np.concatenate(rows)
col = np.concatenate(cols)
state = np.concatenate(states)
data = np.ones(row.size)
# Transform the rows and cols into a single list with N*+2 possible values:
pair = N * row + col
# Estimate sparse matrix:
C2t = scipy.sparse.coo_matrix((data, (pair, state)), shape=(N*N, N))
return C2t.tocsc() | [
"def",
"twostep_count_matrix",
"(",
"dtrajs",
",",
"lag",
",",
"N",
")",
":",
"# List all transition triples:",
"rows",
"=",
"[",
"]",
"cols",
"=",
"[",
"]",
"states",
"=",
"[",
"]",
"for",
"dtraj",
"in",
"dtrajs",
":",
"if",
"dtraj",
".",
"size",
">",... | Compute all two-step count matrices from discrete trajectories.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
the lag time for count matrix estimation
N : int
the number of states in the discrete trajectories.
Returns
-------
C2t : sparse csc-matrix (N, N, N)
two-step count matrices for all states. C2t[:, n, :] is a count matrix for each n | [
"Compute",
"all",
"two",
"-",
"step",
"count",
"matrices",
"from",
"discrete",
"trajectories",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/estimators/_OOM_MSM.py#L138-L175 | train | 204,076 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | featurizer | def featurizer(topfile):
r""" Featurizer to select features from MD data.
Parameters
----------
topfile : str or mdtraj.Topology instance
path to topology file (e.g pdb file) or a mdtraj.Topology object
Returns
-------
feat : :class:`Featurizer <pyemma.coordinates.data.featurization.featurizer.MDFeaturizer>`
Examples
--------
Create a featurizer and add backbone torsion angles to active features.
Then use it in :func:`source`
>>> import pyemma.coordinates # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer('my_protein.pdb') # doctest: +SKIP
>>> feat.add_backbone_torsions() # doctest: +SKIP
>>> reader = pyemma.coordinates.source(["my_traj01.xtc", "my_traj02.xtc"], features=feat) # doctest: +SKIP
or
>>> traj = mdtraj.load('my_protein.pdb') # # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer(traj.topology) # doctest: +SKIP
.. autoclass:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:attributes:
"""
from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer
return MDFeaturizer(topfile) | python | def featurizer(topfile):
r""" Featurizer to select features from MD data.
Parameters
----------
topfile : str or mdtraj.Topology instance
path to topology file (e.g pdb file) or a mdtraj.Topology object
Returns
-------
feat : :class:`Featurizer <pyemma.coordinates.data.featurization.featurizer.MDFeaturizer>`
Examples
--------
Create a featurizer and add backbone torsion angles to active features.
Then use it in :func:`source`
>>> import pyemma.coordinates # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer('my_protein.pdb') # doctest: +SKIP
>>> feat.add_backbone_torsions() # doctest: +SKIP
>>> reader = pyemma.coordinates.source(["my_traj01.xtc", "my_traj02.xtc"], features=feat) # doctest: +SKIP
or
>>> traj = mdtraj.load('my_protein.pdb') # # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer(traj.topology) # doctest: +SKIP
.. autoclass:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:attributes:
"""
from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer
return MDFeaturizer(topfile) | [
"def",
"featurizer",
"(",
"topfile",
")",
":",
"from",
"pyemma",
".",
"coordinates",
".",
"data",
".",
"featurization",
".",
"featurizer",
"import",
"MDFeaturizer",
"return",
"MDFeaturizer",
"(",
"topfile",
")"
] | r""" Featurizer to select features from MD data.
Parameters
----------
topfile : str or mdtraj.Topology instance
path to topology file (e.g pdb file) or a mdtraj.Topology object
Returns
-------
feat : :class:`Featurizer <pyemma.coordinates.data.featurization.featurizer.MDFeaturizer>`
Examples
--------
Create a featurizer and add backbone torsion angles to active features.
Then use it in :func:`source`
>>> import pyemma.coordinates # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer('my_protein.pdb') # doctest: +SKIP
>>> feat.add_backbone_torsions() # doctest: +SKIP
>>> reader = pyemma.coordinates.source(["my_traj01.xtc", "my_traj02.xtc"], features=feat) # doctest: +SKIP
or
>>> traj = mdtraj.load('my_protein.pdb') # # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer(traj.topology) # doctest: +SKIP
.. autoclass:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:attributes: | [
"r",
"Featurizer",
"to",
"select",
"features",
"from",
"MD",
"data",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L99-L142 | train | 204,077 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | load | def load(trajfiles, features=None, top=None, stride=1, chunksize=None, **kw):
r""" Loads coordinate features into memory.
If your memory is not big enough consider the use of **pipeline**, or use
the stride option to subsample the data.
Parameters
----------
trajfiles : str, list of str or nested list (one level) of str
A filename or a list of filenames to trajectory files that can be
processed by pyemma. Both molecular dynamics trajectory files and raw
data files (tabulated ASCII or binary) can be loaded.
If a nested list of filenames is given, eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
When molecular dynamics trajectory files are loaded either a featurizer
must be specified (for reading specific quantities such as distances or
dihedrals), or a topology file (in that case only Cartesian coordinates
will be read). In the latter case, the resulting feature vectors will
have length 3N for each trajectory frame, with N being the number of
atoms and (x1, y1, z1, x2, y2, z2, ...) being the sequence of
coordinates in the vector.
Molecular dynamics trajectory files are loaded through mdtraj (http://mdtraj.org/latest/),
and can possess any of the mdtraj-compatible trajectory formats
including:
* CHARMM/NAMD (.dcd)
* Gromacs (.xtc)
* Gromacs (.trr)
* AMBER (.binpos)
* AMBER (.netcdf)
* PDB trajectory format (.pdb)
* TINKER (.arc),
* MDTRAJ (.hdf5)
* LAMMPS trajectory format (.lammpstrj)
Raw data can be in the following format:
* tabulated ASCII (.dat, .txt)
* binary python (.npy, .npz)
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should
be read (e.g. intramolecular distances, angles, dihedrals, etc).
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A molecular topology file, e.g. in PDB (.pdb) format or an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
stride : int, optional, default = 1
Load only every stride'th frame. By default, every frame is loaded
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
data : ndarray or list of ndarray
If a single filename was given as an input (and unless the format is
.npz), the return will be a single ndarray of size (T, d), where T is
the number of time steps in the trajectory and d is the number of features
(coordinates, observables). When reading from molecular dynamics data
without a specific featurizer, each feature vector will have size d=3N
and will hold the Cartesian coordinates in the sequence
(x1, y1, z1, x2, y2, z2, ...).
If multiple filenames were given, or if the file is a .npz holding
multiple arrays, the result is a list of appropriately shaped arrays
See also
--------
:func:`pyemma.coordinates.source`
if your memory is not big enough, specify data source and put it into your
transformation or clustering algorithms instead of the loaded data. This
will stream the data and save memory on the cost of longer processing
times.
Examples
--------
>>> from pyemma.coordinates import load
>>> files = ['traj01.xtc', 'traj02.xtc'] # doctest: +SKIP
>>> output = load(files, top='my_structure.pdb') # doctest: +SKIP
"""
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(load)['chunksize'], **kw)
if isinstance(trajfiles, _string_types) or (
isinstance(trajfiles, (list, tuple))
and (any(isinstance(item, (list, tuple, str)) for item in trajfiles)
or len(trajfiles) is 0)):
reader = create_file_reader(trajfiles, top, features, chunksize=cs, **kw)
trajs = reader.get_output(stride=stride)
if len(trajs) == 1:
return trajs[0]
else:
return trajs
else:
raise ValueError('unsupported type (%s) of input' % type(trajfiles)) | python | def load(trajfiles, features=None, top=None, stride=1, chunksize=None, **kw):
r""" Loads coordinate features into memory.
If your memory is not big enough consider the use of **pipeline**, or use
the stride option to subsample the data.
Parameters
----------
trajfiles : str, list of str or nested list (one level) of str
A filename or a list of filenames to trajectory files that can be
processed by pyemma. Both molecular dynamics trajectory files and raw
data files (tabulated ASCII or binary) can be loaded.
If a nested list of filenames is given, eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
When molecular dynamics trajectory files are loaded either a featurizer
must be specified (for reading specific quantities such as distances or
dihedrals), or a topology file (in that case only Cartesian coordinates
will be read). In the latter case, the resulting feature vectors will
have length 3N for each trajectory frame, with N being the number of
atoms and (x1, y1, z1, x2, y2, z2, ...) being the sequence of
coordinates in the vector.
Molecular dynamics trajectory files are loaded through mdtraj (http://mdtraj.org/latest/),
and can possess any of the mdtraj-compatible trajectory formats
including:
* CHARMM/NAMD (.dcd)
* Gromacs (.xtc)
* Gromacs (.trr)
* AMBER (.binpos)
* AMBER (.netcdf)
* PDB trajectory format (.pdb)
* TINKER (.arc),
* MDTRAJ (.hdf5)
* LAMMPS trajectory format (.lammpstrj)
Raw data can be in the following format:
* tabulated ASCII (.dat, .txt)
* binary python (.npy, .npz)
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should
be read (e.g. intramolecular distances, angles, dihedrals, etc).
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A molecular topology file, e.g. in PDB (.pdb) format or an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
stride : int, optional, default = 1
Load only every stride'th frame. By default, every frame is loaded
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
data : ndarray or list of ndarray
If a single filename was given as an input (and unless the format is
.npz), the return will be a single ndarray of size (T, d), where T is
the number of time steps in the trajectory and d is the number of features
(coordinates, observables). When reading from molecular dynamics data
without a specific featurizer, each feature vector will have size d=3N
and will hold the Cartesian coordinates in the sequence
(x1, y1, z1, x2, y2, z2, ...).
If multiple filenames were given, or if the file is a .npz holding
multiple arrays, the result is a list of appropriately shaped arrays
See also
--------
:func:`pyemma.coordinates.source`
if your memory is not big enough, specify data source and put it into your
transformation or clustering algorithms instead of the loaded data. This
will stream the data and save memory on the cost of longer processing
times.
Examples
--------
>>> from pyemma.coordinates import load
>>> files = ['traj01.xtc', 'traj02.xtc'] # doctest: +SKIP
>>> output = load(files, top='my_structure.pdb') # doctest: +SKIP
"""
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(load)['chunksize'], **kw)
if isinstance(trajfiles, _string_types) or (
isinstance(trajfiles, (list, tuple))
and (any(isinstance(item, (list, tuple, str)) for item in trajfiles)
or len(trajfiles) is 0)):
reader = create_file_reader(trajfiles, top, features, chunksize=cs, **kw)
trajs = reader.get_output(stride=stride)
if len(trajs) == 1:
return trajs[0]
else:
return trajs
else:
raise ValueError('unsupported type (%s) of input' % type(trajfiles)) | [
"def",
"load",
"(",
"trajfiles",
",",
"features",
"=",
"None",
",",
"top",
"=",
"None",
",",
"stride",
"=",
"1",
",",
"chunksize",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"from",
"pyemma",
".",
"coordinates",
".",
"data",
".",
"util",
".",
"r... | r""" Loads coordinate features into memory.
If your memory is not big enough consider the use of **pipeline**, or use
the stride option to subsample the data.
Parameters
----------
trajfiles : str, list of str or nested list (one level) of str
A filename or a list of filenames to trajectory files that can be
processed by pyemma. Both molecular dynamics trajectory files and raw
data files (tabulated ASCII or binary) can be loaded.
If a nested list of filenames is given, eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
When molecular dynamics trajectory files are loaded either a featurizer
must be specified (for reading specific quantities such as distances or
dihedrals), or a topology file (in that case only Cartesian coordinates
will be read). In the latter case, the resulting feature vectors will
have length 3N for each trajectory frame, with N being the number of
atoms and (x1, y1, z1, x2, y2, z2, ...) being the sequence of
coordinates in the vector.
Molecular dynamics trajectory files are loaded through mdtraj (http://mdtraj.org/latest/),
and can possess any of the mdtraj-compatible trajectory formats
including:
* CHARMM/NAMD (.dcd)
* Gromacs (.xtc)
* Gromacs (.trr)
* AMBER (.binpos)
* AMBER (.netcdf)
* PDB trajectory format (.pdb)
* TINKER (.arc),
* MDTRAJ (.hdf5)
* LAMMPS trajectory format (.lammpstrj)
Raw data can be in the following format:
* tabulated ASCII (.dat, .txt)
* binary python (.npy, .npz)
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should
be read (e.g. intramolecular distances, angles, dihedrals, etc).
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A molecular topology file, e.g. in PDB (.pdb) format or an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
stride : int, optional, default = 1
Load only every stride'th frame. By default, every frame is loaded
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
data : ndarray or list of ndarray
If a single filename was given as an input (and unless the format is
.npz), the return will be a single ndarray of size (T, d), where T is
the number of time steps in the trajectory and d is the number of features
(coordinates, observables). When reading from molecular dynamics data
without a specific featurizer, each feature vector will have size d=3N
and will hold the Cartesian coordinates in the sequence
(x1, y1, z1, x2, y2, z2, ...).
If multiple filenames were given, or if the file is a .npz holding
multiple arrays, the result is a list of appropriately shaped arrays
See also
--------
:func:`pyemma.coordinates.source`
if your memory is not big enough, specify data source and put it into your
transformation or clustering algorithms instead of the loaded data. This
will stream the data and save memory on the cost of longer processing
times.
Examples
--------
>>> from pyemma.coordinates import load
>>> files = ['traj01.xtc', 'traj02.xtc'] # doctest: +SKIP
>>> output = load(files, top='my_structure.pdb') # doctest: +SKIP | [
"r",
"Loads",
"coordinate",
"features",
"into",
"memory",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L146-L251 | train | 204,078 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | source | def source(inp, features=None, top=None, chunksize=None, **kw):
r""" Defines trajectory data source
This function defines input trajectories without loading them. You can pass
the resulting object into transformers such as :func:`pyemma.coordinates.tica`
or clustering algorithms such as :func:`pyemma.coordinates.cluster_kmeans`.
Then, the data will be streamed instead of being loaded, thus saving memory.
You can also use this function to construct the first stage of a data
processing :func:`pipeline`.
Parameters
----------
inp : str (file name) or ndarray or list of strings (file names) or list of ndarrays or nested list of str|ndarray (1 level)
The inp file names or input data. Can be given in any of
these ways:
1. File name of a single trajectory. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
2. List of trajectory file names. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
3. Molecular dynamics trajectory in memory as a numpy array of shape
(T, N, 3) with T time steps, N atoms each having three (x,y,z)
spatial coordinates.
4. List of molecular dynamics trajectories in memory, each given as a
numpy array of shape (T_i, N, 3), where trajectory i has T_i time
steps and all trajectories have shape (N, 3).
5. Trajectory of some features or order parameters in memory
as a numpy array of shape (T, N) with T time steps and N dimensions.
6. List of trajectories of some features or order parameters in memory,
each given as a numpy array of shape (T_i, N), where trajectory i
has T_i time steps and all trajectories have N dimensions.
7. List of NumPy array files (.npy) of shape (T, N). Note these
arrays are not being loaded completely, but mapped into memory
(read-only).
8. List of tabulated ASCII files of shape (T, N).
9. Nested lists (1 level) like), eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should be
read (e.g. intramolecular distances, angles, dihedrals, etc). This
parameter only makes sense if the input comes in the form of molecular
dynamics trajectories or data, and will otherwise create a warning and
have no effect.
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A topology file name. This is needed when molecular dynamics
trajectories are given and no featurizer is given.
In this case, only the Cartesian coordinates will be read. You can also pass an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
reader : :class:`DataSource <pyemma.coordinates.data._base.datasource.DataSource>` object
See also
--------
:func:`pyemma.coordinates.load`
If your memory is big enough to load all features into memory, don't
bother using source - working in memory is faster!
:func:`pyemma.coordinates.pipeline`
The data input is the first stage for your pipeline. Add other stages
to it and build a pipeline to analyze big data in streaming mode.
Examples
--------
Create a reader for NumPy files:
>>> import numpy as np
>>> from pyemma.coordinates import source
>>> reader = source(['001.npy', '002.npy'] # doctest: +SKIP
Create a reader for trajectory files and select some distance as feature:
>>> reader = source(['traj01.xtc', 'traj02.xtc'], top='my_structure.pdb') # doctest: +SKIP
>>> reader.featurizer.add_distances([[0, 1], [5, 6]]) # doctest: +SKIP
>>> calculated_features = reader.get_output() # doctest: +SKIP
create a reader for a csv file:
>>> reader = source('data.csv') # doctest: +SKIP
Create a reader for huge NumPy in-memory arrays to process them in
huge chunks to avoid memory issues:
>>> data = np.random.random(int(1e6))
>>> reader = source(data, chunksize=1000)
>>> from pyemma.coordinates import cluster_regspace
>>> regspace = cluster_regspace(reader, dmin=0.1)
Returns
-------
reader : a reader instance
.. autoclass:: pyemma.coordinates.data.interface.ReaderInterface
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:attributes:
"""
from pyemma.coordinates.data._base.iterable import Iterable
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(source)['chunksize'], **kw)
# CASE 1: input is a string or list of strings
# check: if single string create a one-element list
if isinstance(inp, _string_types) or (
isinstance(inp, (list, tuple))
and (any(isinstance(item, (list, tuple, _string_types)) for item in inp) or len(inp) is 0)):
reader = create_file_reader(inp, top, features, chunksize=cs, **kw)
elif isinstance(inp, _np.ndarray) or (isinstance(inp, (list, tuple))
and (any(isinstance(item, _np.ndarray) for item in inp) or len(inp) is 0)):
# CASE 2: input is a (T, N, 3) array or list of (T_i, N, 3) arrays
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N, 3)? If not: raise ValueError.
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N)? If not: raise ValueError.
# create MemoryReader
from pyemma.coordinates.data.data_in_memory import DataInMemory as _DataInMemory
reader = _DataInMemory(inp, chunksize=cs, **kw)
elif isinstance(inp, Iterable):
inp.chunksize = cs
return inp
else:
raise ValueError('unsupported type (%s) of input' % type(inp))
return reader | python | def source(inp, features=None, top=None, chunksize=None, **kw):
r""" Defines trajectory data source
This function defines input trajectories without loading them. You can pass
the resulting object into transformers such as :func:`pyemma.coordinates.tica`
or clustering algorithms such as :func:`pyemma.coordinates.cluster_kmeans`.
Then, the data will be streamed instead of being loaded, thus saving memory.
You can also use this function to construct the first stage of a data
processing :func:`pipeline`.
Parameters
----------
inp : str (file name) or ndarray or list of strings (file names) or list of ndarrays or nested list of str|ndarray (1 level)
The inp file names or input data. Can be given in any of
these ways:
1. File name of a single trajectory. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
2. List of trajectory file names. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
3. Molecular dynamics trajectory in memory as a numpy array of shape
(T, N, 3) with T time steps, N atoms each having three (x,y,z)
spatial coordinates.
4. List of molecular dynamics trajectories in memory, each given as a
numpy array of shape (T_i, N, 3), where trajectory i has T_i time
steps and all trajectories have shape (N, 3).
5. Trajectory of some features or order parameters in memory
as a numpy array of shape (T, N) with T time steps and N dimensions.
6. List of trajectories of some features or order parameters in memory,
each given as a numpy array of shape (T_i, N), where trajectory i
has T_i time steps and all trajectories have N dimensions.
7. List of NumPy array files (.npy) of shape (T, N). Note these
arrays are not being loaded completely, but mapped into memory
(read-only).
8. List of tabulated ASCII files of shape (T, N).
9. Nested lists (1 level) like), eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should be
read (e.g. intramolecular distances, angles, dihedrals, etc). This
parameter only makes sense if the input comes in the form of molecular
dynamics trajectories or data, and will otherwise create a warning and
have no effect.
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A topology file name. This is needed when molecular dynamics
trajectories are given and no featurizer is given.
In this case, only the Cartesian coordinates will be read. You can also pass an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
reader : :class:`DataSource <pyemma.coordinates.data._base.datasource.DataSource>` object
See also
--------
:func:`pyemma.coordinates.load`
If your memory is big enough to load all features into memory, don't
bother using source - working in memory is faster!
:func:`pyemma.coordinates.pipeline`
The data input is the first stage for your pipeline. Add other stages
to it and build a pipeline to analyze big data in streaming mode.
Examples
--------
Create a reader for NumPy files:
>>> import numpy as np
>>> from pyemma.coordinates import source
>>> reader = source(['001.npy', '002.npy'] # doctest: +SKIP
Create a reader for trajectory files and select some distance as feature:
>>> reader = source(['traj01.xtc', 'traj02.xtc'], top='my_structure.pdb') # doctest: +SKIP
>>> reader.featurizer.add_distances([[0, 1], [5, 6]]) # doctest: +SKIP
>>> calculated_features = reader.get_output() # doctest: +SKIP
create a reader for a csv file:
>>> reader = source('data.csv') # doctest: +SKIP
Create a reader for huge NumPy in-memory arrays to process them in
huge chunks to avoid memory issues:
>>> data = np.random.random(int(1e6))
>>> reader = source(data, chunksize=1000)
>>> from pyemma.coordinates import cluster_regspace
>>> regspace = cluster_regspace(reader, dmin=0.1)
Returns
-------
reader : a reader instance
.. autoclass:: pyemma.coordinates.data.interface.ReaderInterface
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:attributes:
"""
from pyemma.coordinates.data._base.iterable import Iterable
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(source)['chunksize'], **kw)
# CASE 1: input is a string or list of strings
# check: if single string create a one-element list
if isinstance(inp, _string_types) or (
isinstance(inp, (list, tuple))
and (any(isinstance(item, (list, tuple, _string_types)) for item in inp) or len(inp) is 0)):
reader = create_file_reader(inp, top, features, chunksize=cs, **kw)
elif isinstance(inp, _np.ndarray) or (isinstance(inp, (list, tuple))
and (any(isinstance(item, _np.ndarray) for item in inp) or len(inp) is 0)):
# CASE 2: input is a (T, N, 3) array or list of (T_i, N, 3) arrays
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N, 3)? If not: raise ValueError.
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N)? If not: raise ValueError.
# create MemoryReader
from pyemma.coordinates.data.data_in_memory import DataInMemory as _DataInMemory
reader = _DataInMemory(inp, chunksize=cs, **kw)
elif isinstance(inp, Iterable):
inp.chunksize = cs
return inp
else:
raise ValueError('unsupported type (%s) of input' % type(inp))
return reader | [
"def",
"source",
"(",
"inp",
",",
"features",
"=",
"None",
",",
"top",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"from",
"pyemma",
".",
"coordinates",
".",
"data",
".",
"_base",
".",
"iterable",
"import",
"Iterable",
... | r""" Defines trajectory data source
This function defines input trajectories without loading them. You can pass
the resulting object into transformers such as :func:`pyemma.coordinates.tica`
or clustering algorithms such as :func:`pyemma.coordinates.cluster_kmeans`.
Then, the data will be streamed instead of being loaded, thus saving memory.
You can also use this function to construct the first stage of a data
processing :func:`pipeline`.
Parameters
----------
inp : str (file name) or ndarray or list of strings (file names) or list of ndarrays or nested list of str|ndarray (1 level)
The inp file names or input data. Can be given in any of
these ways:
1. File name of a single trajectory. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
2. List of trajectory file names. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
3. Molecular dynamics trajectory in memory as a numpy array of shape
(T, N, 3) with T time steps, N atoms each having three (x,y,z)
spatial coordinates.
4. List of molecular dynamics trajectories in memory, each given as a
numpy array of shape (T_i, N, 3), where trajectory i has T_i time
steps and all trajectories have shape (N, 3).
5. Trajectory of some features or order parameters in memory
as a numpy array of shape (T, N) with T time steps and N dimensions.
6. List of trajectories of some features or order parameters in memory,
each given as a numpy array of shape (T_i, N), where trajectory i
has T_i time steps and all trajectories have N dimensions.
7. List of NumPy array files (.npy) of shape (T, N). Note these
arrays are not being loaded completely, but mapped into memory
(read-only).
8. List of tabulated ASCII files of shape (T, N).
9. Nested lists (1 level) like), eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should be
read (e.g. intramolecular distances, angles, dihedrals, etc). This
parameter only makes sense if the input comes in the form of molecular
dynamics trajectories or data, and will otherwise create a warning and
have no effect.
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A topology file name. This is needed when molecular dynamics
trajectories are given and no featurizer is given.
In this case, only the Cartesian coordinates will be read. You can also pass an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
reader : :class:`DataSource <pyemma.coordinates.data._base.datasource.DataSource>` object
See also
--------
:func:`pyemma.coordinates.load`
If your memory is big enough to load all features into memory, don't
bother using source - working in memory is faster!
:func:`pyemma.coordinates.pipeline`
The data input is the first stage for your pipeline. Add other stages
to it and build a pipeline to analyze big data in streaming mode.
Examples
--------
Create a reader for NumPy files:
>>> import numpy as np
>>> from pyemma.coordinates import source
>>> reader = source(['001.npy', '002.npy'] # doctest: +SKIP
Create a reader for trajectory files and select some distance as feature:
>>> reader = source(['traj01.xtc', 'traj02.xtc'], top='my_structure.pdb') # doctest: +SKIP
>>> reader.featurizer.add_distances([[0, 1], [5, 6]]) # doctest: +SKIP
>>> calculated_features = reader.get_output() # doctest: +SKIP
create a reader for a csv file:
>>> reader = source('data.csv') # doctest: +SKIP
Create a reader for huge NumPy in-memory arrays to process them in
huge chunks to avoid memory issues:
>>> data = np.random.random(int(1e6))
>>> reader = source(data, chunksize=1000)
>>> from pyemma.coordinates import cluster_regspace
>>> regspace = cluster_regspace(reader, dmin=0.1)
Returns
-------
reader : a reader instance
.. autoclass:: pyemma.coordinates.data.interface.ReaderInterface
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:attributes: | [
"r",
"Defines",
"trajectory",
"data",
"source"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L254-L404 | train | 204,079 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | combine_sources | def combine_sources(sources, chunksize=None):
r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting only one source,
which is usually the case. All the parameters for iterator creation are passed to the actual sources, to ensure
consistent behaviour.
Parameters
----------
sources : list, tuple
list of DataSources (Readers, StreamingTransformers etc.) to combine for streaming access.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Notes
-----
This is currently only implemented for matching lengths trajectories.
Returns
-------
merger : :class:`SourcesMerger <pyemma.coordinates.data.sources_merger.SourcesMerger>`
"""
from pyemma.coordinates.data.sources_merger import SourcesMerger
return SourcesMerger(sources, chunk=chunksize) | python | def combine_sources(sources, chunksize=None):
r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting only one source,
which is usually the case. All the parameters for iterator creation are passed to the actual sources, to ensure
consistent behaviour.
Parameters
----------
sources : list, tuple
list of DataSources (Readers, StreamingTransformers etc.) to combine for streaming access.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Notes
-----
This is currently only implemented for matching lengths trajectories.
Returns
-------
merger : :class:`SourcesMerger <pyemma.coordinates.data.sources_merger.SourcesMerger>`
"""
from pyemma.coordinates.data.sources_merger import SourcesMerger
return SourcesMerger(sources, chunk=chunksize) | [
"def",
"combine_sources",
"(",
"sources",
",",
"chunksize",
"=",
"None",
")",
":",
"from",
"pyemma",
".",
"coordinates",
".",
"data",
".",
"sources_merger",
"import",
"SourcesMerger",
"return",
"SourcesMerger",
"(",
"sources",
",",
"chunk",
"=",
"chunksize",
"... | r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting only one source,
which is usually the case. All the parameters for iterator creation are passed to the actual sources, to ensure
consistent behaviour.
Parameters
----------
sources : list, tuple
list of DataSources (Readers, StreamingTransformers etc.) to combine for streaming access.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Notes
-----
This is currently only implemented for matching lengths trajectories.
Returns
-------
merger : :class:`SourcesMerger <pyemma.coordinates.data.sources_merger.SourcesMerger>` | [
"r",
"Combines",
"multiple",
"data",
"sources",
"to",
"stream",
"from",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L407-L436 | train | 204,080 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | pipeline | def pipeline(stages, run=True, stride=1, chunksize=None):
r""" Data analysis pipeline.
Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it
(unless prevented).
If this function takes too long, consider loading data in memory.
Alternatively if the data is to large to be loaded into memory make use
of the stride parameter.
Parameters
----------
stages : data input or list of pipeline stages
If given a single pipeline stage this must be a data input constructed
by :py:func:`source`. If a list of pipelining stages are given, the
first stage must be a data input constructed by :py:func:`source`.
run : bool, optional, default = True
If True, the pipeline will be parametrized immediately with the given
stages. If only an input stage is given, the run flag has no effect at
this time. True also means that the pipeline will be immediately
re-parametrized when further stages are added to it.
*Attention* True means this function may take a long time to compute.
If False, the pipeline will be passive, i.e. it will not do any
computations before you call parametrize()
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline to
parametrize its stages. Note that this could cause the parametrization
step to be very slow for large data sets. Since molecular dynamics data
is usually correlated at short timescales, it is often sufficient to
parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>`
A pipeline object that is able to conduct big data analysis with
limited memory in streaming mode.
Examples
--------
>>> import numpy as np
>>> from pyemma.coordinates import source, tica, assign_to_centers, pipeline
Create some random data and cluster centers:
>>> data = np.random.random((1000, 3))
>>> centers = data[np.random.choice(1000, 10)]
>>> reader = source(data)
Define a TICA transformation with lag time 10:
>>> tica_obj = tica(lag=10)
Assign any input to given centers:
>>> assign = assign_to_centers(centers=centers)
>>> pipe = pipeline([reader, tica_obj, assign])
>>> pipe.parametrize()
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.pipelines import Pipeline
if not isinstance(stages, list):
stages = [stages]
p = Pipeline(stages, param_stride=stride, chunksize=chunksize)
if run:
p.parametrize()
return p | python | def pipeline(stages, run=True, stride=1, chunksize=None):
r""" Data analysis pipeline.
Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it
(unless prevented).
If this function takes too long, consider loading data in memory.
Alternatively if the data is to large to be loaded into memory make use
of the stride parameter.
Parameters
----------
stages : data input or list of pipeline stages
If given a single pipeline stage this must be a data input constructed
by :py:func:`source`. If a list of pipelining stages are given, the
first stage must be a data input constructed by :py:func:`source`.
run : bool, optional, default = True
If True, the pipeline will be parametrized immediately with the given
stages. If only an input stage is given, the run flag has no effect at
this time. True also means that the pipeline will be immediately
re-parametrized when further stages are added to it.
*Attention* True means this function may take a long time to compute.
If False, the pipeline will be passive, i.e. it will not do any
computations before you call parametrize()
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline to
parametrize its stages. Note that this could cause the parametrization
step to be very slow for large data sets. Since molecular dynamics data
is usually correlated at short timescales, it is often sufficient to
parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>`
A pipeline object that is able to conduct big data analysis with
limited memory in streaming mode.
Examples
--------
>>> import numpy as np
>>> from pyemma.coordinates import source, tica, assign_to_centers, pipeline
Create some random data and cluster centers:
>>> data = np.random.random((1000, 3))
>>> centers = data[np.random.choice(1000, 10)]
>>> reader = source(data)
Define a TICA transformation with lag time 10:
>>> tica_obj = tica(lag=10)
Assign any input to given centers:
>>> assign = assign_to_centers(centers=centers)
>>> pipe = pipeline([reader, tica_obj, assign])
>>> pipe.parametrize()
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.pipelines import Pipeline
if not isinstance(stages, list):
stages = [stages]
p = Pipeline(stages, param_stride=stride, chunksize=chunksize)
if run:
p.parametrize()
return p | [
"def",
"pipeline",
"(",
"stages",
",",
"run",
"=",
"True",
",",
"stride",
"=",
"1",
",",
"chunksize",
"=",
"None",
")",
":",
"from",
"pyemma",
".",
"coordinates",
".",
"pipelines",
"import",
"Pipeline",
"if",
"not",
"isinstance",
"(",
"stages",
",",
"l... | r""" Data analysis pipeline.
Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it
(unless prevented).
If this function takes too long, consider loading data in memory.
Alternatively if the data is to large to be loaded into memory make use
of the stride parameter.
Parameters
----------
stages : data input or list of pipeline stages
If given a single pipeline stage this must be a data input constructed
by :py:func:`source`. If a list of pipelining stages are given, the
first stage must be a data input constructed by :py:func:`source`.
run : bool, optional, default = True
If True, the pipeline will be parametrized immediately with the given
stages. If only an input stage is given, the run flag has no effect at
this time. True also means that the pipeline will be immediately
re-parametrized when further stages are added to it.
*Attention* True means this function may take a long time to compute.
If False, the pipeline will be passive, i.e. it will not do any
computations before you call parametrize()
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline to
parametrize its stages. Note that this could cause the parametrization
step to be very slow for large data sets. Since molecular dynamics data
is usually correlated at short timescales, it is often sufficient to
parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>`
A pipeline object that is able to conduct big data analysis with
limited memory in streaming mode.
Examples
--------
>>> import numpy as np
>>> from pyemma.coordinates import source, tica, assign_to_centers, pipeline
Create some random data and cluster centers:
>>> data = np.random.random((1000, 3))
>>> centers = data[np.random.choice(1000, 10)]
>>> reader = source(data)
Define a TICA transformation with lag time 10:
>>> tica_obj = tica(lag=10)
Assign any input to given centers:
>>> assign = assign_to_centers(centers=centers)
>>> pipe = pipeline([reader, tica_obj, assign])
>>> pipe.parametrize()
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes: | [
"r",
"Data",
"analysis",
"pipeline",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L439-L524 | train | 204,081 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | save_traj | def save_traj(traj_inp, indexes, outfile, top=None, stride = 1, chunksize=None, image_molecules=False, verbose=True):
r""" Saves a sequence of frames as a single trajectory.
Extracts the specified sequence of time/trajectory indexes from traj_inp
and saves it to one single molecular dynamics trajectory file. The output
format will be determined by the outfile name.
Parameters
----------
traj_inp :
traj_inp can be of two types.
1. a python list of strings containing the filenames associated with
the indices in :py:obj:`indexes`. With this type of input, a :py:obj:`topfile` is mandatory.
2. a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader`
object containing the filename list in :py:obj:`traj_inp.trajfiles`.
Please use :py:func:`pyemma.coordinates.source` to construct it.
With this type of input, the input :py:obj:`topfile` will be ignored.
and :py:obj:`traj_inp.topfile` will be used instead
indexes : ndarray(T, 2) or list of ndarray(T_i, 2)
A (T x 2) array for writing a trajectory of T time steps. Each row
contains two indexes (i, t), where i is the index of the trajectory
from the input and t is the index of the time step within the trajectory.
If a list of index arrays is given, these will be simply concatenated,
i.e. they will be written subsequently in the same trajectory file.
outfile : str.
The name of the output file. Its extension will determine the file type
written. Example: "out.dcd" If set to None, the trajectory object is
returned to memory
top : str, mdtraj.Trajectory, or mdtraj.Topology
The topology needed to read the files in the list :py:obj:`traj_inp`.
If :py:obj:`traj_inp` is not a list, this parameter is ignored.
stride : integer, default is 1
This parameter informs :py:func:`save_traj` about the stride used in
:py:obj:`indexes`. Typically, :py:obj:`indexes` contains frame-indexes
that match exactly the frames of the files contained in :py:obj:`traj_inp.trajfiles`.
However, in certain situations, that might not be the case. Examples
are cases in which a stride value != 1 was used when
reading/featurizing/transforming/discretizing the files contained
in :py:obj:`traj_inp.trajfiles`.
chunksize : int. Default=None.
The chunksize for reading input trajectory files. If :py:obj:`traj_inp`
is a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader` object,
this input variable will be ignored and :py:obj:`traj_inp.chunksize` will be used instead.
image_molecules: boolean, default is False
If set to true, :py:obj:`save_traj` will call the method traj.image_molecules and try to correct for broken
molecules accross periodic boundary conditions.
(http://mdtraj.org/1.7.2/api/generated/mdtraj.Trajectory.html#mdtraj.Trajectory.image_molecules)
verbose : boolean, default is True
Inform about created filenames
Returns
-------
traj : :py:obj:`mdtraj.Trajectory` object
Will only return this object if :py:obj:`outfile` is None
"""
from mdtraj import Topology, Trajectory
from pyemma.coordinates.data.feature_reader import FeatureReader
from pyemma.coordinates.data.fragmented_trajectory_reader import FragmentedTrajectoryReader
from pyemma.coordinates.data.util.frames_from_file import frames_from_files
from pyemma.coordinates.data.util.reader_utils import enforce_top
import itertools
# Determine the type of input and extract necessary parameters
if isinstance(traj_inp, (FeatureReader, FragmentedTrajectoryReader)):
if isinstance(traj_inp, FragmentedTrajectoryReader):
# lengths array per reader
if not all(isinstance(reader, FeatureReader)
for reader in itertools.chain.from_iterable(traj_inp._readers)):
raise ValueError("Only FeatureReaders (MD-data) are supported for fragmented trajectories.")
trajfiles = traj_inp.filenames_flat
top = traj_inp._readers[0][0].featurizer.topology
else:
top = traj_inp.featurizer.topology
trajfiles = traj_inp.filenames
chunksize = traj_inp.chunksize
reader = traj_inp
else:
# Do we have what we need?
if not isinstance(traj_inp, (list, tuple)):
raise TypeError("traj_inp has to be of type list, not %s" % type(traj_inp))
if not isinstance(top, (_string_types, Topology, Trajectory)):
raise TypeError("traj_inp cannot be a list of files without an input "
"top of type str (eg filename.pdb), mdtraj.Trajectory or mdtraj.Topology. "
"Got type %s instead" % type(top))
trajfiles = traj_inp
reader = None
# Enforce the input topology to actually be an md.Topology object
top = enforce_top(top)
# Convert to index (T,2) array if parsed a list or a list of arrays
indexes = _np.vstack(indexes)
# Check that we've been given enough filenames
if len(trajfiles) < indexes[:, 0].max():
raise ValueError("traj_inp contains %u trajfiles, "
"but indexes will ask for file nr. %u"
% (len(trajfiles), indexes[:,0].max()))
traj = frames_from_files(trajfiles, top, indexes, chunksize, stride, reader=reader)
# Avoid broken molecules
if image_molecules:
traj.image_molecules(inplace=True)
# Return to memory as an mdtraj trajectory object
if outfile is None:
return traj
# or to disk as a molecular trajectory file
else:
traj.save(outfile)
if verbose:
_logger.info("Created file %s" % outfile) | python | def save_traj(traj_inp, indexes, outfile, top=None, stride = 1, chunksize=None, image_molecules=False, verbose=True):
r""" Saves a sequence of frames as a single trajectory.
Extracts the specified sequence of time/trajectory indexes from traj_inp
and saves it to one single molecular dynamics trajectory file. The output
format will be determined by the outfile name.
Parameters
----------
traj_inp :
traj_inp can be of two types.
1. a python list of strings containing the filenames associated with
the indices in :py:obj:`indexes`. With this type of input, a :py:obj:`topfile` is mandatory.
2. a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader`
object containing the filename list in :py:obj:`traj_inp.trajfiles`.
Please use :py:func:`pyemma.coordinates.source` to construct it.
With this type of input, the input :py:obj:`topfile` will be ignored.
and :py:obj:`traj_inp.topfile` will be used instead
indexes : ndarray(T, 2) or list of ndarray(T_i, 2)
A (T x 2) array for writing a trajectory of T time steps. Each row
contains two indexes (i, t), where i is the index of the trajectory
from the input and t is the index of the time step within the trajectory.
If a list of index arrays is given, these will be simply concatenated,
i.e. they will be written subsequently in the same trajectory file.
outfile : str.
The name of the output file. Its extension will determine the file type
written. Example: "out.dcd" If set to None, the trajectory object is
returned to memory
top : str, mdtraj.Trajectory, or mdtraj.Topology
The topology needed to read the files in the list :py:obj:`traj_inp`.
If :py:obj:`traj_inp` is not a list, this parameter is ignored.
stride : integer, default is 1
This parameter informs :py:func:`save_traj` about the stride used in
:py:obj:`indexes`. Typically, :py:obj:`indexes` contains frame-indexes
that match exactly the frames of the files contained in :py:obj:`traj_inp.trajfiles`.
However, in certain situations, that might not be the case. Examples
are cases in which a stride value != 1 was used when
reading/featurizing/transforming/discretizing the files contained
in :py:obj:`traj_inp.trajfiles`.
chunksize : int. Default=None.
The chunksize for reading input trajectory files. If :py:obj:`traj_inp`
is a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader` object,
this input variable will be ignored and :py:obj:`traj_inp.chunksize` will be used instead.
image_molecules: boolean, default is False
If set to true, :py:obj:`save_traj` will call the method traj.image_molecules and try to correct for broken
molecules accross periodic boundary conditions.
(http://mdtraj.org/1.7.2/api/generated/mdtraj.Trajectory.html#mdtraj.Trajectory.image_molecules)
verbose : boolean, default is True
Inform about created filenames
Returns
-------
traj : :py:obj:`mdtraj.Trajectory` object
Will only return this object if :py:obj:`outfile` is None
"""
from mdtraj import Topology, Trajectory
from pyemma.coordinates.data.feature_reader import FeatureReader
from pyemma.coordinates.data.fragmented_trajectory_reader import FragmentedTrajectoryReader
from pyemma.coordinates.data.util.frames_from_file import frames_from_files
from pyemma.coordinates.data.util.reader_utils import enforce_top
import itertools
# Determine the type of input and extract necessary parameters
if isinstance(traj_inp, (FeatureReader, FragmentedTrajectoryReader)):
if isinstance(traj_inp, FragmentedTrajectoryReader):
# lengths array per reader
if not all(isinstance(reader, FeatureReader)
for reader in itertools.chain.from_iterable(traj_inp._readers)):
raise ValueError("Only FeatureReaders (MD-data) are supported for fragmented trajectories.")
trajfiles = traj_inp.filenames_flat
top = traj_inp._readers[0][0].featurizer.topology
else:
top = traj_inp.featurizer.topology
trajfiles = traj_inp.filenames
chunksize = traj_inp.chunksize
reader = traj_inp
else:
# Do we have what we need?
if not isinstance(traj_inp, (list, tuple)):
raise TypeError("traj_inp has to be of type list, not %s" % type(traj_inp))
if not isinstance(top, (_string_types, Topology, Trajectory)):
raise TypeError("traj_inp cannot be a list of files without an input "
"top of type str (eg filename.pdb), mdtraj.Trajectory or mdtraj.Topology. "
"Got type %s instead" % type(top))
trajfiles = traj_inp
reader = None
# Enforce the input topology to actually be an md.Topology object
top = enforce_top(top)
# Convert to index (T,2) array if parsed a list or a list of arrays
indexes = _np.vstack(indexes)
# Check that we've been given enough filenames
if len(trajfiles) < indexes[:, 0].max():
raise ValueError("traj_inp contains %u trajfiles, "
"but indexes will ask for file nr. %u"
% (len(trajfiles), indexes[:,0].max()))
traj = frames_from_files(trajfiles, top, indexes, chunksize, stride, reader=reader)
# Avoid broken molecules
if image_molecules:
traj.image_molecules(inplace=True)
# Return to memory as an mdtraj trajectory object
if outfile is None:
return traj
# or to disk as a molecular trajectory file
else:
traj.save(outfile)
if verbose:
_logger.info("Created file %s" % outfile) | [
"def",
"save_traj",
"(",
"traj_inp",
",",
"indexes",
",",
"outfile",
",",
"top",
"=",
"None",
",",
"stride",
"=",
"1",
",",
"chunksize",
"=",
"None",
",",
"image_molecules",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"mdtraj",
"import... | r""" Saves a sequence of frames as a single trajectory.
Extracts the specified sequence of time/trajectory indexes from traj_inp
and saves it to one single molecular dynamics trajectory file. The output
format will be determined by the outfile name.
Parameters
----------
traj_inp :
traj_inp can be of two types.
1. a python list of strings containing the filenames associated with
the indices in :py:obj:`indexes`. With this type of input, a :py:obj:`topfile` is mandatory.
2. a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader`
object containing the filename list in :py:obj:`traj_inp.trajfiles`.
Please use :py:func:`pyemma.coordinates.source` to construct it.
With this type of input, the input :py:obj:`topfile` will be ignored.
and :py:obj:`traj_inp.topfile` will be used instead
indexes : ndarray(T, 2) or list of ndarray(T_i, 2)
A (T x 2) array for writing a trajectory of T time steps. Each row
contains two indexes (i, t), where i is the index of the trajectory
from the input and t is the index of the time step within the trajectory.
If a list of index arrays is given, these will be simply concatenated,
i.e. they will be written subsequently in the same trajectory file.
outfile : str.
The name of the output file. Its extension will determine the file type
written. Example: "out.dcd" If set to None, the trajectory object is
returned to memory
top : str, mdtraj.Trajectory, or mdtraj.Topology
The topology needed to read the files in the list :py:obj:`traj_inp`.
If :py:obj:`traj_inp` is not a list, this parameter is ignored.
stride : integer, default is 1
This parameter informs :py:func:`save_traj` about the stride used in
:py:obj:`indexes`. Typically, :py:obj:`indexes` contains frame-indexes
that match exactly the frames of the files contained in :py:obj:`traj_inp.trajfiles`.
However, in certain situations, that might not be the case. Examples
are cases in which a stride value != 1 was used when
reading/featurizing/transforming/discretizing the files contained
in :py:obj:`traj_inp.trajfiles`.
chunksize : int. Default=None.
The chunksize for reading input trajectory files. If :py:obj:`traj_inp`
is a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader` object,
this input variable will be ignored and :py:obj:`traj_inp.chunksize` will be used instead.
image_molecules: boolean, default is False
If set to true, :py:obj:`save_traj` will call the method traj.image_molecules and try to correct for broken
molecules accross periodic boundary conditions.
(http://mdtraj.org/1.7.2/api/generated/mdtraj.Trajectory.html#mdtraj.Trajectory.image_molecules)
verbose : boolean, default is True
Inform about created filenames
Returns
-------
traj : :py:obj:`mdtraj.Trajectory` object
Will only return this object if :py:obj:`outfile` is None | [
"r",
"Saves",
"a",
"sequence",
"of",
"frames",
"as",
"a",
"single",
"trajectory",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L636-L759 | train | 204,082 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | save_trajs | def save_trajs(traj_inp, indexes, prefix='set_', fmt=None, outfiles=None,
inmemory=False, stride=1, verbose=False):
r""" Saves sequences of frames as multiple trajectories.
Extracts a number of specified sequences of time/trajectory indexes from the
input loader and saves them in a set of molecular dynamics trajectories.
The output filenames are obtained by prefix + str(n) + .fmt, where n counts
the output trajectory and extension is either set by the user, or else
determined from the input. Example: When the input is in dcd format, and
indexes is a list of length 3, the output will by default go to files
"set_1.dcd", "set_2.dcd", "set_3.dcd". If you want files to be stored
in a specific subfolder, simply specify the relative path in the prefix,
e.g. prefix='~/macrostates/\pcca_'
Parameters
----------
traj_inp : :py:class:`pyemma.coordinates.data.feature_reader.FeatureReader`
A data source as provided by Please use :py:func:`pyemma.coordinates.source` to construct it.
indexes : list of ndarray(T_i, 2)
A list of N arrays, each of size (T_n x 2) for writing N trajectories
of T_i time steps. Each row contains two indexes (i, t), where i is the
index of the trajectory from the input and t is the index of the time
step within the trajectory.
prefix : str, optional, default = `set_`
output filename prefix. Can include an absolute or relative path name.
fmt : str, optional, default = None
Outpuf file format. By default, the file extension and format. It will
be determined from the input. If a different format is desired, specify
the corresponding file extension here without a dot, e.g. "dcd" or "xtc".
outfiles : list of str, optional, default = None
A list of output filenames. When given, this will override the settings
of prefix and fmt, and output will be written to these files.
inmemory : Boolean, default = False (untested for large files)
Instead of internally calling traj_save for every (T_i,2) array in
"indexes", only one call is made. Internally, this generates a
potentially large molecular trajectory object in memory that is
subsequently sliced into the files of "outfiles". Should be faster for
large "indexes" arrays and large files, though it is quite memory
intensive. The optimal situation is to avoid streaming two times
through a huge file for "indexes" of type: indexes = [[1 4000000],[1 4000001]]
stride : integer, default is 1
This parameter informs :py:func:`save_trajs` about the stride used in
the indexes variable. Typically, the variable indexes contains frame
indexes that match exactly the frames of the files contained in
traj_inp.trajfiles. However, in certain situations, that might not be
the case. Examples of these situations are cases in which stride
value != 1 was used when reading/featurizing/transforming/discretizing
the files contained in traj_inp.trajfiles.
verbose : boolean, default is False
Verbose output while looking for "indexes" in the "traj_inp.trajfiles"
Returns
-------
outfiles : list of str
The list of absolute paths that the output files have been written to.
"""
# Make sure indexes is iterable
assert _types.is_iterable(indexes), "Indexes must be an iterable of matrices."
# only if 2d-array, convert into a list
if isinstance(indexes, _np.ndarray):
if indexes.ndim == 2:
indexes = [indexes]
# Make sure the elements of that lists are arrays, and that they are shaped properly
for i_indexes in indexes:
assert isinstance(i_indexes, _np.ndarray), "The elements in the 'indexes' variable must be numpy.ndarrays"
assert i_indexes.ndim == 2, \
"The elements in the 'indexes' variable must have ndim = 2, and not %u" % i_indexes.ndim
assert i_indexes.shape[1] == 2, \
"The elements in the 'indexes' variable must be of shape (T_i,2), and not (%u,%u)" % i_indexes.shape
# Determine output format of the molecular trajectory file
if fmt is None:
import os
_, fmt = os.path.splitext(traj_inp.filenames[0])
else:
fmt = '.' + fmt
# Prepare the list of outfiles before the loop
if outfiles is None:
outfiles = []
for ii in range(len(indexes)):
outfiles.append(prefix + '%06u' % ii + fmt)
# Check that we have the same name of outfiles as (T, 2)-indexes arrays
if len(indexes) != len(outfiles):
raise Exception('len(indexes) (%s) does not match len(outfiles) (%s)' % (len(indexes), len(outfiles)))
# This implementation looks for "i_indexes" separately, and thus one traj_inp.trajfile
# might be accessed more than once (less memory intensive)
if not inmemory:
for i_indexes, outfile in zip(indexes, outfiles):
# TODO: use **kwargs to parse to save_traj
save_traj(traj_inp, i_indexes, outfile, stride=stride, verbose=verbose)
# This implementation is "one file - one pass" but might temporally create huge memory objects
else:
traj = save_traj(traj_inp, indexes, outfile=None, stride=stride, verbose=verbose)
i_idx = 0
for i_indexes, outfile in zip(indexes, outfiles):
# Create indices for slicing the mdtraj trajectory object
f_idx = i_idx + len(i_indexes)
# print i_idx, f_idx
traj[i_idx:f_idx].save(outfile)
_logger.info("Created file %s" % outfile)
# update the initial frame index
i_idx = f_idx
return outfiles | python | def save_trajs(traj_inp, indexes, prefix='set_', fmt=None, outfiles=None,
inmemory=False, stride=1, verbose=False):
r""" Saves sequences of frames as multiple trajectories.
Extracts a number of specified sequences of time/trajectory indexes from the
input loader and saves them in a set of molecular dynamics trajectories.
The output filenames are obtained by prefix + str(n) + .fmt, where n counts
the output trajectory and extension is either set by the user, or else
determined from the input. Example: When the input is in dcd format, and
indexes is a list of length 3, the output will by default go to files
"set_1.dcd", "set_2.dcd", "set_3.dcd". If you want files to be stored
in a specific subfolder, simply specify the relative path in the prefix,
e.g. prefix='~/macrostates/\pcca_'
Parameters
----------
traj_inp : :py:class:`pyemma.coordinates.data.feature_reader.FeatureReader`
A data source as provided by Please use :py:func:`pyemma.coordinates.source` to construct it.
indexes : list of ndarray(T_i, 2)
A list of N arrays, each of size (T_n x 2) for writing N trajectories
of T_i time steps. Each row contains two indexes (i, t), where i is the
index of the trajectory from the input and t is the index of the time
step within the trajectory.
prefix : str, optional, default = `set_`
output filename prefix. Can include an absolute or relative path name.
fmt : str, optional, default = None
Outpuf file format. By default, the file extension and format. It will
be determined from the input. If a different format is desired, specify
the corresponding file extension here without a dot, e.g. "dcd" or "xtc".
outfiles : list of str, optional, default = None
A list of output filenames. When given, this will override the settings
of prefix and fmt, and output will be written to these files.
inmemory : Boolean, default = False (untested for large files)
Instead of internally calling traj_save for every (T_i,2) array in
"indexes", only one call is made. Internally, this generates a
potentially large molecular trajectory object in memory that is
subsequently sliced into the files of "outfiles". Should be faster for
large "indexes" arrays and large files, though it is quite memory
intensive. The optimal situation is to avoid streaming two times
through a huge file for "indexes" of type: indexes = [[1 4000000],[1 4000001]]
stride : integer, default is 1
This parameter informs :py:func:`save_trajs` about the stride used in
the indexes variable. Typically, the variable indexes contains frame
indexes that match exactly the frames of the files contained in
traj_inp.trajfiles. However, in certain situations, that might not be
the case. Examples of these situations are cases in which stride
value != 1 was used when reading/featurizing/transforming/discretizing
the files contained in traj_inp.trajfiles.
verbose : boolean, default is False
Verbose output while looking for "indexes" in the "traj_inp.trajfiles"
Returns
-------
outfiles : list of str
The list of absolute paths that the output files have been written to.
"""
# Make sure indexes is iterable
assert _types.is_iterable(indexes), "Indexes must be an iterable of matrices."
# only if 2d-array, convert into a list
if isinstance(indexes, _np.ndarray):
if indexes.ndim == 2:
indexes = [indexes]
# Make sure the elements of that lists are arrays, and that they are shaped properly
for i_indexes in indexes:
assert isinstance(i_indexes, _np.ndarray), "The elements in the 'indexes' variable must be numpy.ndarrays"
assert i_indexes.ndim == 2, \
"The elements in the 'indexes' variable must have ndim = 2, and not %u" % i_indexes.ndim
assert i_indexes.shape[1] == 2, \
"The elements in the 'indexes' variable must be of shape (T_i,2), and not (%u,%u)" % i_indexes.shape
# Determine output format of the molecular trajectory file
if fmt is None:
import os
_, fmt = os.path.splitext(traj_inp.filenames[0])
else:
fmt = '.' + fmt
# Prepare the list of outfiles before the loop
if outfiles is None:
outfiles = []
for ii in range(len(indexes)):
outfiles.append(prefix + '%06u' % ii + fmt)
# Check that we have the same name of outfiles as (T, 2)-indexes arrays
if len(indexes) != len(outfiles):
raise Exception('len(indexes) (%s) does not match len(outfiles) (%s)' % (len(indexes), len(outfiles)))
# This implementation looks for "i_indexes" separately, and thus one traj_inp.trajfile
# might be accessed more than once (less memory intensive)
if not inmemory:
for i_indexes, outfile in zip(indexes, outfiles):
# TODO: use **kwargs to parse to save_traj
save_traj(traj_inp, i_indexes, outfile, stride=stride, verbose=verbose)
# This implementation is "one file - one pass" but might temporally create huge memory objects
else:
traj = save_traj(traj_inp, indexes, outfile=None, stride=stride, verbose=verbose)
i_idx = 0
for i_indexes, outfile in zip(indexes, outfiles):
# Create indices for slicing the mdtraj trajectory object
f_idx = i_idx + len(i_indexes)
# print i_idx, f_idx
traj[i_idx:f_idx].save(outfile)
_logger.info("Created file %s" % outfile)
# update the initial frame index
i_idx = f_idx
return outfiles | [
"def",
"save_trajs",
"(",
"traj_inp",
",",
"indexes",
",",
"prefix",
"=",
"'set_'",
",",
"fmt",
"=",
"None",
",",
"outfiles",
"=",
"None",
",",
"inmemory",
"=",
"False",
",",
"stride",
"=",
"1",
",",
"verbose",
"=",
"False",
")",
":",
"# Make sure inde... | r""" Saves sequences of frames as multiple trajectories.
Extracts a number of specified sequences of time/trajectory indexes from the
input loader and saves them in a set of molecular dynamics trajectories.
The output filenames are obtained by prefix + str(n) + .fmt, where n counts
the output trajectory and extension is either set by the user, or else
determined from the input. Example: When the input is in dcd format, and
indexes is a list of length 3, the output will by default go to files
"set_1.dcd", "set_2.dcd", "set_3.dcd". If you want files to be stored
in a specific subfolder, simply specify the relative path in the prefix,
e.g. prefix='~/macrostates/\pcca_'
Parameters
----------
traj_inp : :py:class:`pyemma.coordinates.data.feature_reader.FeatureReader`
A data source as provided by Please use :py:func:`pyemma.coordinates.source` to construct it.
indexes : list of ndarray(T_i, 2)
A list of N arrays, each of size (T_n x 2) for writing N trajectories
of T_i time steps. Each row contains two indexes (i, t), where i is the
index of the trajectory from the input and t is the index of the time
step within the trajectory.
prefix : str, optional, default = `set_`
output filename prefix. Can include an absolute or relative path name.
fmt : str, optional, default = None
Outpuf file format. By default, the file extension and format. It will
be determined from the input. If a different format is desired, specify
the corresponding file extension here without a dot, e.g. "dcd" or "xtc".
outfiles : list of str, optional, default = None
A list of output filenames. When given, this will override the settings
of prefix and fmt, and output will be written to these files.
inmemory : Boolean, default = False (untested for large files)
Instead of internally calling traj_save for every (T_i,2) array in
"indexes", only one call is made. Internally, this generates a
potentially large molecular trajectory object in memory that is
subsequently sliced into the files of "outfiles". Should be faster for
large "indexes" arrays and large files, though it is quite memory
intensive. The optimal situation is to avoid streaming two times
through a huge file for "indexes" of type: indexes = [[1 4000000],[1 4000001]]
stride : integer, default is 1
This parameter informs :py:func:`save_trajs` about the stride used in
the indexes variable. Typically, the variable indexes contains frame
indexes that match exactly the frames of the files contained in
traj_inp.trajfiles. However, in certain situations, that might not be
the case. Examples of these situations are cases in which stride
value != 1 was used when reading/featurizing/transforming/discretizing
the files contained in traj_inp.trajfiles.
verbose : boolean, default is False
Verbose output while looking for "indexes" in the "traj_inp.trajfiles"
Returns
-------
outfiles : list of str
The list of absolute paths that the output files have been written to. | [
"r",
"Saves",
"sequences",
"of",
"frames",
"as",
"multiple",
"trajectories",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L762-L879 | train | 204,083 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | cluster_mini_batch_kmeans | def cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean',
init_strategy='kmeans++', n_jobs=None, chunksize=None, skip=0, clustercenters=None, **kwargs):
r"""k-means clustering with mini-batch strategy
Mini-batch k-means is an approximation to k-means which picks a randomly
selected subset of data points to be updated in each iteration. Usually
much faster than k-means but will likely deliver a less optimal result.
Returns
-------
kmeans_mini : a :class:`MiniBatchKmeansClustering <pyemma.coordinates.clustering.MiniBatchKmeansClustering>` clustering object
Object for mini-batch kmeans clustering.
It holds discrete trajectories and cluster center information.
See also
--------
:func:`kmeans <pyemma.coordinates.kmeans>` : for full k-means clustering
.. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:attributes:
References
----------
.. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf
"""
from pyemma.coordinates.clustering.kmeans import MiniBatchKmeansClustering
res = MiniBatchKmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, init_strategy=init_strategy,
batch_size=batch_size, n_jobs=n_jobs, skip=skip, clustercenters=clustercenters)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_mini_batch_kmeans)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = chunksize
return res | python | def cluster_mini_batch_kmeans(data=None, k=100, max_iter=10, batch_size=0.2, metric='euclidean',
init_strategy='kmeans++', n_jobs=None, chunksize=None, skip=0, clustercenters=None, **kwargs):
r"""k-means clustering with mini-batch strategy
Mini-batch k-means is an approximation to k-means which picks a randomly
selected subset of data points to be updated in each iteration. Usually
much faster than k-means but will likely deliver a less optimal result.
Returns
-------
kmeans_mini : a :class:`MiniBatchKmeansClustering <pyemma.coordinates.clustering.MiniBatchKmeansClustering>` clustering object
Object for mini-batch kmeans clustering.
It holds discrete trajectories and cluster center information.
See also
--------
:func:`kmeans <pyemma.coordinates.kmeans>` : for full k-means clustering
.. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:attributes:
References
----------
.. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf
"""
from pyemma.coordinates.clustering.kmeans import MiniBatchKmeansClustering
res = MiniBatchKmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, init_strategy=init_strategy,
batch_size=batch_size, n_jobs=n_jobs, skip=skip, clustercenters=clustercenters)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_mini_batch_kmeans)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = chunksize
return res | [
"def",
"cluster_mini_batch_kmeans",
"(",
"data",
"=",
"None",
",",
"k",
"=",
"100",
",",
"max_iter",
"=",
"10",
",",
"batch_size",
"=",
"0.2",
",",
"metric",
"=",
"'euclidean'",
",",
"init_strategy",
"=",
"'kmeans++'",
",",
"n_jobs",
"=",
"None",
",",
"c... | r"""k-means clustering with mini-batch strategy
Mini-batch k-means is an approximation to k-means which picks a randomly
selected subset of data points to be updated in each iteration. Usually
much faster than k-means but will likely deliver a less optimal result.
Returns
-------
kmeans_mini : a :class:`MiniBatchKmeansClustering <pyemma.coordinates.clustering.MiniBatchKmeansClustering>` clustering object
Object for mini-batch kmeans clustering.
It holds discrete trajectories and cluster center information.
See also
--------
:func:`kmeans <pyemma.coordinates.kmeans>` : for full k-means clustering
.. autoclass:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.MiniBatchKmeansClustering
:attributes:
References
----------
.. [1] http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf | [
"r",
"k",
"-",
"means",
"clustering",
"with",
"mini",
"-",
"batch",
"strategy"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L1645-L1692 | train | 204,084 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | cluster_kmeans | def cluster_kmeans(data=None, k=None, max_iter=10, tolerance=1e-5, stride=1,
metric='euclidean', init_strategy='kmeans++', fixed_seed=False,
n_jobs=None, chunksize=None, skip=0, keep_data=False, clustercenters=None, **kwargs):
r"""k-means clustering
If data is given, it performs a k-means clustering and then assigns the
data using a Voronoi discretization. It returns a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
object that can be used to extract the discretized data sequences, or to
assign other data points to the same partition. If data is not given, an
empty :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
will be created that still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data: ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source`
input data, if available in memory
k: int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
max_iter : int
maximum number of iterations before stopping. When not specified (None), min(sqrt(N),5000) is chosen
as default value, where N denotes the number of data points
tolerance : float
stop iteration when the relative change in the cost function
:math:`C(S) = \sum_{i=1}^{k} \sum_{\mathbf x \in S_i} \left\| \mathbf x - \boldsymbol\mu_i \right\|^2`
is smaller than tolerance.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it
is often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
init_strategy : str
determines if the initial cluster centers are chosen according to the kmeans++-algorithm
or drawn uniformly distributed from the provided data set
fixed_seed : bool or (positive) integer
if set to true, the random seed gets fixed resulting in deterministic behavior; default is false.
If an integer >= 0 is given, use this to initialize the random generator.
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
keep_data: boolean, default=False
if you intend to quickly resume a non-converged kmeans iteration, set this to True.
Otherwise the linear memory array will have to be re-created. Note that the data will also be deleted,
if and only if the estimation converged within the given tolerance parameter.
clustercenters: ndarray (k, dim), default=None
if passed, the init_strategy is ignored and these centers will be iterated.
Returns
-------
kmeans : a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>` clustering object
Object for kmeans clustering.
It holds discrete trajectories and cluster center information.
Examples
--------
>>> import numpy as np
>>> from pyemma.util.contexts import settings
>>> import pyemma.coordinates as coor
>>> traj_data = [np.random.random((100, 3)), np.random.random((100,3))]
>>> with settings(show_progress_bars=False):
... cluster_obj = coor.cluster_kmeans(traj_data, k=20, stride=1)
... cluster_obj.get_output() # doctest: +ELLIPSIS
[array([...
.. seealso:: **Theoretical background**: `Wiki page <http://en.wikipedia.org/wiki/K-means_clustering>`_
.. autoclass:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:attributes:
References
----------
The k-means algorithms was invented in [1]_. The term k-means was
first used in [2]_.
.. [1] Steinhaus, H. (1957).
Sur la division des corps materiels en parties.
Bull. Acad. Polon. Sci. (in French) 4, 801-804.
.. [2] MacQueen, J. B. (1967).
Some Methods for classification and Analysis of Multivariate Observations.
Proceedings of 5th Berkeley Symposium on Mathematical Statistics and
Probability 1. University of California Press. pp. 281-297
"""
from pyemma.coordinates.clustering.kmeans import KmeansClustering
res = KmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, tolerance=tolerance,
init_strategy=init_strategy, fixed_seed=fixed_seed, n_jobs=n_jobs, skip=skip,
keep_data=keep_data, clustercenters=clustercenters, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_kmeans)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | python | def cluster_kmeans(data=None, k=None, max_iter=10, tolerance=1e-5, stride=1,
metric='euclidean', init_strategy='kmeans++', fixed_seed=False,
n_jobs=None, chunksize=None, skip=0, keep_data=False, clustercenters=None, **kwargs):
r"""k-means clustering
If data is given, it performs a k-means clustering and then assigns the
data using a Voronoi discretization. It returns a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
object that can be used to extract the discretized data sequences, or to
assign other data points to the same partition. If data is not given, an
empty :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
will be created that still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data: ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source`
input data, if available in memory
k: int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
max_iter : int
maximum number of iterations before stopping. When not specified (None), min(sqrt(N),5000) is chosen
as default value, where N denotes the number of data points
tolerance : float
stop iteration when the relative change in the cost function
:math:`C(S) = \sum_{i=1}^{k} \sum_{\mathbf x \in S_i} \left\| \mathbf x - \boldsymbol\mu_i \right\|^2`
is smaller than tolerance.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it
is often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
init_strategy : str
determines if the initial cluster centers are chosen according to the kmeans++-algorithm
or drawn uniformly distributed from the provided data set
fixed_seed : bool or (positive) integer
if set to true, the random seed gets fixed resulting in deterministic behavior; default is false.
If an integer >= 0 is given, use this to initialize the random generator.
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
keep_data: boolean, default=False
if you intend to quickly resume a non-converged kmeans iteration, set this to True.
Otherwise the linear memory array will have to be re-created. Note that the data will also be deleted,
if and only if the estimation converged within the given tolerance parameter.
clustercenters: ndarray (k, dim), default=None
if passed, the init_strategy is ignored and these centers will be iterated.
Returns
-------
kmeans : a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>` clustering object
Object for kmeans clustering.
It holds discrete trajectories and cluster center information.
Examples
--------
>>> import numpy as np
>>> from pyemma.util.contexts import settings
>>> import pyemma.coordinates as coor
>>> traj_data = [np.random.random((100, 3)), np.random.random((100,3))]
>>> with settings(show_progress_bars=False):
... cluster_obj = coor.cluster_kmeans(traj_data, k=20, stride=1)
... cluster_obj.get_output() # doctest: +ELLIPSIS
[array([...
.. seealso:: **Theoretical background**: `Wiki page <http://en.wikipedia.org/wiki/K-means_clustering>`_
.. autoclass:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:attributes:
References
----------
The k-means algorithms was invented in [1]_. The term k-means was
first used in [2]_.
.. [1] Steinhaus, H. (1957).
Sur la division des corps materiels en parties.
Bull. Acad. Polon. Sci. (in French) 4, 801-804.
.. [2] MacQueen, J. B. (1967).
Some Methods for classification and Analysis of Multivariate Observations.
Proceedings of 5th Berkeley Symposium on Mathematical Statistics and
Probability 1. University of California Press. pp. 281-297
"""
from pyemma.coordinates.clustering.kmeans import KmeansClustering
res = KmeansClustering(n_clusters=k, max_iter=max_iter, metric=metric, tolerance=tolerance,
init_strategy=init_strategy, fixed_seed=fixed_seed, n_jobs=n_jobs, skip=skip,
keep_data=keep_data, clustercenters=clustercenters, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_kmeans)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | [
"def",
"cluster_kmeans",
"(",
"data",
"=",
"None",
",",
"k",
"=",
"None",
",",
"max_iter",
"=",
"10",
",",
"tolerance",
"=",
"1e-5",
",",
"stride",
"=",
"1",
",",
"metric",
"=",
"'euclidean'",
",",
"init_strategy",
"=",
"'kmeans++'",
",",
"fixed_seed",
... | r"""k-means clustering
If data is given, it performs a k-means clustering and then assigns the
data using a Voronoi discretization. It returns a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
object that can be used to extract the discretized data sequences, or to
assign other data points to the same partition. If data is not given, an
empty :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>`
will be created that still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data: ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source`
input data, if available in memory
k: int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
max_iter : int
maximum number of iterations before stopping. When not specified (None), min(sqrt(N),5000) is chosen
as default value, where N denotes the number of data points
tolerance : float
stop iteration when the relative change in the cost function
:math:`C(S) = \sum_{i=1}^{k} \sum_{\mathbf x \in S_i} \left\| \mathbf x - \boldsymbol\mu_i \right\|^2`
is smaller than tolerance.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it
is often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
init_strategy : str
determines if the initial cluster centers are chosen according to the kmeans++-algorithm
or drawn uniformly distributed from the provided data set
fixed_seed : bool or (positive) integer
if set to true, the random seed gets fixed resulting in deterministic behavior; default is false.
If an integer >= 0 is given, use this to initialize the random generator.
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
keep_data: boolean, default=False
if you intend to quickly resume a non-converged kmeans iteration, set this to True.
Otherwise the linear memory array will have to be re-created. Note that the data will also be deleted,
if and only if the estimation converged within the given tolerance parameter.
clustercenters: ndarray (k, dim), default=None
if passed, the init_strategy is ignored and these centers will be iterated.
Returns
-------
kmeans : a :class:`KmeansClustering <pyemma.coordinates.clustering.KmeansClustering>` clustering object
Object for kmeans clustering.
It holds discrete trajectories and cluster center information.
Examples
--------
>>> import numpy as np
>>> from pyemma.util.contexts import settings
>>> import pyemma.coordinates as coor
>>> traj_data = [np.random.random((100, 3)), np.random.random((100,3))]
>>> with settings(show_progress_bars=False):
... cluster_obj = coor.cluster_kmeans(traj_data, k=20, stride=1)
... cluster_obj.get_output() # doctest: +ELLIPSIS
[array([...
.. seealso:: **Theoretical background**: `Wiki page <http://en.wikipedia.org/wiki/K-means_clustering>`_
.. autoclass:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.kmeans.KmeansClustering
:attributes:
References
----------
The k-means algorithms was invented in [1]_. The term k-means was
first used in [2]_.
.. [1] Steinhaus, H. (1957).
Sur la division des corps materiels en parties.
Bull. Acad. Polon. Sci. (in French) 4, 801-804.
.. [2] MacQueen, J. B. (1967).
Some Methods for classification and Analysis of Multivariate Observations.
Proceedings of 5th Berkeley Symposium on Mathematical Statistics and
Probability 1. University of California Press. pp. 281-297 | [
"r",
"k",
"-",
"means",
"clustering"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L1695-L1829 | train | 204,085 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | cluster_uniform_time | def cluster_uniform_time(data=None, k=None, stride=1, metric='euclidean',
n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Uniform time clustering
If given data, performs a clustering that selects data points uniformly in
time and then assigns the data using a Voronoi discretization. Returns a
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` object
that can be used to extract the discretized data sequences, or to assign
other data points to the same partition. If data is not given, an empty
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` will be created that
still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created
by source function input data, if available in memory
k : int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
uniformTime : a :class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` clustering object
Object for uniform time clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:attributes:
"""
from pyemma.coordinates.clustering.uniform_time import UniformTimeClustering
res = UniformTimeClustering(k, metric=metric, n_jobs=n_jobs, skip=skip, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_uniform_time)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | python | def cluster_uniform_time(data=None, k=None, stride=1, metric='euclidean',
n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Uniform time clustering
If given data, performs a clustering that selects data points uniformly in
time and then assigns the data using a Voronoi discretization. Returns a
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` object
that can be used to extract the discretized data sequences, or to assign
other data points to the same partition. If data is not given, an empty
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` will be created that
still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created
by source function input data, if available in memory
k : int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
uniformTime : a :class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` clustering object
Object for uniform time clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:attributes:
"""
from pyemma.coordinates.clustering.uniform_time import UniformTimeClustering
res = UniformTimeClustering(k, metric=metric, n_jobs=n_jobs, skip=skip, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_uniform_time)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | [
"def",
"cluster_uniform_time",
"(",
"data",
"=",
"None",
",",
"k",
"=",
"None",
",",
"stride",
"=",
"1",
",",
"metric",
"=",
"'euclidean'",
",",
"n_jobs",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"*",
"*",
"kwargs",
"... | r"""Uniform time clustering
If given data, performs a clustering that selects data points uniformly in
time and then assigns the data using a Voronoi discretization. Returns a
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` object
that can be used to extract the discretized data sequences, or to assign
other data points to the same partition. If data is not given, an empty
:class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` will be created that
still needs to be parametrized, e.g. in a :func:`pipeline`.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created
by source function input data, if available in memory
k : int
the number of cluster centers. When not specified (None), min(sqrt(N), 5000) is chosen as default value,
where N denotes the number of data points
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride.
Note that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
skip : int, default=0
skip the first initial n frames per trajectory.
Returns
-------
uniformTime : a :class:`UniformTimeClustering <pyemma.coordinates.clustering.UniformTimeClustering>` clustering object
Object for uniform time clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.uniform_time.UniformTimeClustering
:attributes: | [
"r",
"Uniform",
"time",
"clustering"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L1832-L1908 | train | 204,086 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | cluster_regspace | def cluster_regspace(data=None, dmin=-1, max_centers=1000, stride=1, metric='euclidean',
n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Regular space clustering
If given data, it performs a regular space clustering [1]_ and returns a
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` object that
can be used to extract the discretized data sequences, or to assign other
data points to the same partition. If data is not given, an empty
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` will be created
that still needs to be parametrized, e.g. in a :func:`pipeline`.
Regular space clustering is very similar to Hartigan's leader algorithm [2]_.
It consists of two passes through the data. Initially, the first data point
is added to the list of centers. For every subsequent data point, if it has
a greater distance than dmin from every center, it also becomes a center.
In the second pass, a Voronoi discretization with the computed centers is
used to partition the data.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source
input data, if available in memory
dmin : float
the minimal distance between cluster centers
max_centers : int (optional), default=1000
If max_centers is reached, the algorithm will stop to find more centers,
but it is possible that parts of the state space are not properly `
discretized. This will generate a warning. If that happens, it is
suggested to increase dmin such that the number of centers stays below
max_centers.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride. Note
that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
regSpace : a :class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` clustering object
Object for regular space clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:attributes:
References
----------
.. [1] Prinz J-H, Wu H, Sarich M, Keller B, Senne M, Held M, Chodera JD, Schuette Ch and Noe F. 2011.
Markov models of molecular kinetics: Generation and Validation.
J. Chem. Phys. 134, 174105.
.. [2] Hartigan J. Clustering algorithms.
New York: Wiley; 1975.
"""
if dmin == -1:
raise ValueError("provide a minimum distance for clustering, e.g. 2.0")
from pyemma.coordinates.clustering.regspace import RegularSpaceClustering as _RegularSpaceClustering
res = _RegularSpaceClustering(dmin, max_centers=max_centers, metric=metric,
n_jobs=n_jobs, stride=stride, skip=skip)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_regspace)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | python | def cluster_regspace(data=None, dmin=-1, max_centers=1000, stride=1, metric='euclidean',
n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Regular space clustering
If given data, it performs a regular space clustering [1]_ and returns a
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` object that
can be used to extract the discretized data sequences, or to assign other
data points to the same partition. If data is not given, an empty
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` will be created
that still needs to be parametrized, e.g. in a :func:`pipeline`.
Regular space clustering is very similar to Hartigan's leader algorithm [2]_.
It consists of two passes through the data. Initially, the first data point
is added to the list of centers. For every subsequent data point, if it has
a greater distance than dmin from every center, it also becomes a center.
In the second pass, a Voronoi discretization with the computed centers is
used to partition the data.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source
input data, if available in memory
dmin : float
the minimal distance between cluster centers
max_centers : int (optional), default=1000
If max_centers is reached, the algorithm will stop to find more centers,
but it is possible that parts of the state space are not properly `
discretized. This will generate a warning. If that happens, it is
suggested to increase dmin such that the number of centers stays below
max_centers.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride. Note
that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
regSpace : a :class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` clustering object
Object for regular space clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:attributes:
References
----------
.. [1] Prinz J-H, Wu H, Sarich M, Keller B, Senne M, Held M, Chodera JD, Schuette Ch and Noe F. 2011.
Markov models of molecular kinetics: Generation and Validation.
J. Chem. Phys. 134, 174105.
.. [2] Hartigan J. Clustering algorithms.
New York: Wiley; 1975.
"""
if dmin == -1:
raise ValueError("provide a minimum distance for clustering, e.g. 2.0")
from pyemma.coordinates.clustering.regspace import RegularSpaceClustering as _RegularSpaceClustering
res = _RegularSpaceClustering(dmin, max_centers=max_centers, metric=metric,
n_jobs=n_jobs, stride=stride, skip=skip)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(cluster_regspace)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
else:
res.chunksize = cs
return res | [
"def",
"cluster_regspace",
"(",
"data",
"=",
"None",
",",
"dmin",
"=",
"-",
"1",
",",
"max_centers",
"=",
"1000",
",",
"stride",
"=",
"1",
",",
"metric",
"=",
"'euclidean'",
",",
"n_jobs",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"skip",
"=",... | r"""Regular space clustering
If given data, it performs a regular space clustering [1]_ and returns a
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` object that
can be used to extract the discretized data sequences, or to assign other
data points to the same partition. If data is not given, an empty
:class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` will be created
that still needs to be parametrized, e.g. in a :func:`pipeline`.
Regular space clustering is very similar to Hartigan's leader algorithm [2]_.
It consists of two passes through the data. Initially, the first data point
is added to the list of centers. For every subsequent data point, if it has
a greater distance than dmin from every center, it also becomes a center.
In the second pass, a Voronoi discretization with the computed centers is
used to partition the data.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by :func:`source
input data, if available in memory
dmin : float
the minimal distance between cluster centers
max_centers : int (optional), default=1000
If max_centers is reached, the algorithm will stop to find more centers,
but it is possible that parts of the state space are not properly `
discretized. This will generate a warning. If that happens, it is
suggested to increase dmin such that the number of centers stays below
max_centers.
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that this
could cause this calculation to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales, it is
often sufficient to estimate transformations at a longer stride. Note
that the stride option in the get_output() function of the returned
object is independent, so you can parametrize at a long stride, and
still map all frames through the transformer.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
regSpace : a :class:`RegularSpaceClustering <pyemma.coordinates.clustering.RegularSpaceClustering>` clustering object
Object for regular space clustering.
It holds discrete trajectories and cluster center information.
.. autoclass:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.regspace.RegularSpaceClustering
:attributes:
References
----------
.. [1] Prinz J-H, Wu H, Sarich M, Keller B, Senne M, Held M, Chodera JD, Schuette Ch and Noe F. 2011.
Markov models of molecular kinetics: Generation and Validation.
J. Chem. Phys. 134, 174105.
.. [2] Hartigan J. Clustering algorithms.
New York: Wiley; 1975. | [
"r",
"Regular",
"space",
"clustering"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L1911-L2009 | train | 204,087 |
markovmodel/PyEMMA | pyemma/coordinates/api.py | assign_to_centers | def assign_to_centers(data=None, centers=None, stride=1, return_dtrajs=True,
metric='euclidean', n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Assigns data to the nearest cluster centers
Creates a Voronoi partition with the given cluster centers. If given
trajectories as data, this function will by default discretize the
trajectories and return discrete trajectories of corresponding lengths.
Otherwise, an assignment object will be returned that can be used to
assign data later or can serve as a pipeline stage.
Parameters
----------
data : ndarray or list of arrays or reader created by source function
data to be assigned
centers : path to file or ndarray or a reader created by source function
cluster centers to use in assignment of data
stride : int, optional, default = 1
assign only every n'th frame to the centers. Usually you want to assign
all the data and only use a stride during calculation the centers.
return_dtrajs : bool, optional, default = True
If True, it will return the discretized trajectories obtained from
assigning the coordinates in the data input. This will only have effect
if data is given. When data is not given or return_dtrajs is False,
the :class:'AssignCenters <_AssignCenters>' object will be returned.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
assignment : list of integer arrays or an :class:`AssignCenters <pyemma.coordinates.clustering.AssignCenters>` object
assigned data
Examples
--------
Load data to assign to clusters from 'my_data.csv' by using the cluster
centers from file 'my_centers.csv'
>>> import numpy as np
Generate some random data and choose 10 random centers:
>>> data = np.random.random((100, 3))
>>> cluster_centers = data[np.random.randint(0, 99, size=10)]
>>> dtrajs = assign_to_centers(data, cluster_centers)
>>> print(dtrajs) # doctest: +ELLIPSIS
[array([...
.. autoclass:: pyemma.coordinates.clustering.assign.AssignCenters
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:attributes:
"""
if centers is None:
raise ValueError('You have to provide centers in form of a filename'
' or NumPy array or a reader created by source function')
from pyemma.coordinates.clustering.assign import AssignCenters
res = AssignCenters(centers, metric=metric, n_jobs=n_jobs, skip=skip, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(assign_to_centers)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
if return_dtrajs:
return res.dtrajs
else:
res.chunksize = cs
return res | python | def assign_to_centers(data=None, centers=None, stride=1, return_dtrajs=True,
metric='euclidean', n_jobs=None, chunksize=None, skip=0, **kwargs):
r"""Assigns data to the nearest cluster centers
Creates a Voronoi partition with the given cluster centers. If given
trajectories as data, this function will by default discretize the
trajectories and return discrete trajectories of corresponding lengths.
Otherwise, an assignment object will be returned that can be used to
assign data later or can serve as a pipeline stage.
Parameters
----------
data : ndarray or list of arrays or reader created by source function
data to be assigned
centers : path to file or ndarray or a reader created by source function
cluster centers to use in assignment of data
stride : int, optional, default = 1
assign only every n'th frame to the centers. Usually you want to assign
all the data and only use a stride during calculation the centers.
return_dtrajs : bool, optional, default = True
If True, it will return the discretized trajectories obtained from
assigning the coordinates in the data input. This will only have effect
if data is given. When data is not given or return_dtrajs is False,
the :class:'AssignCenters <_AssignCenters>' object will be returned.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
assignment : list of integer arrays or an :class:`AssignCenters <pyemma.coordinates.clustering.AssignCenters>` object
assigned data
Examples
--------
Load data to assign to clusters from 'my_data.csv' by using the cluster
centers from file 'my_centers.csv'
>>> import numpy as np
Generate some random data and choose 10 random centers:
>>> data = np.random.random((100, 3))
>>> cluster_centers = data[np.random.randint(0, 99, size=10)]
>>> dtrajs = assign_to_centers(data, cluster_centers)
>>> print(dtrajs) # doctest: +ELLIPSIS
[array([...
.. autoclass:: pyemma.coordinates.clustering.assign.AssignCenters
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:attributes:
"""
if centers is None:
raise ValueError('You have to provide centers in form of a filename'
' or NumPy array or a reader created by source function')
from pyemma.coordinates.clustering.assign import AssignCenters
res = AssignCenters(centers, metric=metric, n_jobs=n_jobs, skip=skip, stride=stride)
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(assign_to_centers)['chunksize'], **kwargs)
if data is not None:
res.estimate(data, chunksize=cs)
if return_dtrajs:
return res.dtrajs
else:
res.chunksize = cs
return res | [
"def",
"assign_to_centers",
"(",
"data",
"=",
"None",
",",
"centers",
"=",
"None",
",",
"stride",
"=",
"1",
",",
"return_dtrajs",
"=",
"True",
",",
"metric",
"=",
"'euclidean'",
",",
"n_jobs",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"skip",
"=... | r"""Assigns data to the nearest cluster centers
Creates a Voronoi partition with the given cluster centers. If given
trajectories as data, this function will by default discretize the
trajectories and return discrete trajectories of corresponding lengths.
Otherwise, an assignment object will be returned that can be used to
assign data later or can serve as a pipeline stage.
Parameters
----------
data : ndarray or list of arrays or reader created by source function
data to be assigned
centers : path to file or ndarray or a reader created by source function
cluster centers to use in assignment of data
stride : int, optional, default = 1
assign only every n'th frame to the centers. Usually you want to assign
all the data and only use a stride during calculation the centers.
return_dtrajs : bool, optional, default = True
If True, it will return the discretized trajectories obtained from
assigning the coordinates in the data input. This will only have effect
if data is given. When data is not given or return_dtrajs is False,
the :class:'AssignCenters <_AssignCenters>' object will be returned.
metric : str
metric to use during clustering ('euclidean', 'minRMSD')
n_jobs : int or None, default None
Number of threads to use during assignment of the data.
If None, all available CPUs will be used.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
assignment : list of integer arrays or an :class:`AssignCenters <pyemma.coordinates.clustering.AssignCenters>` object
assigned data
Examples
--------
Load data to assign to clusters from 'my_data.csv' by using the cluster
centers from file 'my_centers.csv'
>>> import numpy as np
Generate some random data and choose 10 random centers:
>>> data = np.random.random((100, 3))
>>> cluster_centers = data[np.random.randint(0, 99, size=10)]
>>> dtrajs = assign_to_centers(data, cluster_centers)
>>> print(dtrajs) # doctest: +ELLIPSIS
[array([...
.. autoclass:: pyemma.coordinates.clustering.assign.AssignCenters
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.clustering.assign.AssignCenters
:attributes: | [
"r",
"Assigns",
"data",
"to",
"the",
"nearest",
"cluster",
"centers"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/api.py#L2012-L2103 | train | 204,088 |
markovmodel/PyEMMA | pyemma/datasets/double_well_discrete.py | DoubleWell_Discrete_Data.dtraj_T100K_dt10_n | def dtraj_T100K_dt10_n(self, divides):
""" 100K frames trajectory at timestep 10, arbitrary n-state discretization. """
disc = np.zeros(100, dtype=int)
divides = np.concatenate([divides, [100]])
for i in range(len(divides)-1):
disc[divides[i]:divides[i+1]] = i+1
return disc[self.dtraj_T100K_dt10] | python | def dtraj_T100K_dt10_n(self, divides):
""" 100K frames trajectory at timestep 10, arbitrary n-state discretization. """
disc = np.zeros(100, dtype=int)
divides = np.concatenate([divides, [100]])
for i in range(len(divides)-1):
disc[divides[i]:divides[i+1]] = i+1
return disc[self.dtraj_T100K_dt10] | [
"def",
"dtraj_T100K_dt10_n",
"(",
"self",
",",
"divides",
")",
":",
"disc",
"=",
"np",
".",
"zeros",
"(",
"100",
",",
"dtype",
"=",
"int",
")",
"divides",
"=",
"np",
".",
"concatenate",
"(",
"[",
"divides",
",",
"[",
"100",
"]",
"]",
")",
"for",
... | 100K frames trajectory at timestep 10, arbitrary n-state discretization. | [
"100K",
"frames",
"trajectory",
"at",
"timestep",
"10",
"arbitrary",
"n",
"-",
"state",
"discretization",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/double_well_discrete.py#L62-L68 | train | 204,089 |
markovmodel/PyEMMA | pyemma/datasets/double_well_discrete.py | DoubleWell_Discrete_Data.generate_traj | def generate_traj(self, N, start=None, stop=None, dt=1):
""" Generates a random trajectory of length N with time step dt """
from msmtools.generation import generate_traj
return generate_traj(self._P, N, start=start, stop=stop, dt=dt) | python | def generate_traj(self, N, start=None, stop=None, dt=1):
""" Generates a random trajectory of length N with time step dt """
from msmtools.generation import generate_traj
return generate_traj(self._P, N, start=start, stop=stop, dt=dt) | [
"def",
"generate_traj",
"(",
"self",
",",
"N",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"dt",
"=",
"1",
")",
":",
"from",
"msmtools",
".",
"generation",
"import",
"generate_traj",
"return",
"generate_traj",
"(",
"self",
".",
"_P",
",",... | Generates a random trajectory of length N with time step dt | [
"Generates",
"a",
"random",
"trajectory",
"of",
"length",
"N",
"with",
"time",
"step",
"dt"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/double_well_discrete.py#L80-L83 | train | 204,090 |
markovmodel/PyEMMA | pyemma/datasets/double_well_discrete.py | DoubleWell_Discrete_Data.generate_trajs | def generate_trajs(self, M, N, start=None, stop=None, dt=1):
""" Generates M random trajectories of length N each with time step dt """
from msmtools.generation import generate_trajs
return generate_trajs(self._P, M, N, start=start, stop=stop, dt=dt) | python | def generate_trajs(self, M, N, start=None, stop=None, dt=1):
""" Generates M random trajectories of length N each with time step dt """
from msmtools.generation import generate_trajs
return generate_trajs(self._P, M, N, start=start, stop=stop, dt=dt) | [
"def",
"generate_trajs",
"(",
"self",
",",
"M",
",",
"N",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"dt",
"=",
"1",
")",
":",
"from",
"msmtools",
".",
"generation",
"import",
"generate_trajs",
"return",
"generate_trajs",
"(",
"self",
".... | Generates M random trajectories of length N each with time step dt | [
"Generates",
"M",
"random",
"trajectories",
"of",
"length",
"N",
"each",
"with",
"time",
"step",
"dt"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/double_well_discrete.py#L85-L88 | train | 204,091 |
markovmodel/PyEMMA | pyemma/_ext/variational/solvers/direct.py | spd_eig | def spd_eig(W, epsilon=1e-10, method='QR', canonical_signs=False):
""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
canonical_signs : boolean, default = False
Fix signs in V, s. t. the largest element of in every row of V is positive.
Returns
-------
s : ndarray(k)
k non-negligible eigenvalues, sorted by descending norms
V : ndarray(n, k)
k leading eigenvectors
"""
# check input
assert _np.allclose(W.T, W), 'W is not a symmetric matrix'
if method.lower() == 'qr':
from .eig_qr.eig_qr import eig_qr
s, V = eig_qr(W)
# compute the Eigenvalues of C0 using Schur factorization
elif method.lower() == 'schur':
from scipy.linalg import schur
S, V = schur(W)
s = _np.diag(S)
else:
raise ValueError('method not implemented: ' + method)
s, V = sort_by_norm(s, V) # sort them
# determine the cutoff. We know that C0 is an spd matrix,
# so we select the truncation threshold such that everything that is negative vanishes
evmin = _np.min(s)
if evmin < 0:
epsilon = max(epsilon, -evmin + 1e-16)
# determine effective rank m and perform low-rank approximations.
evnorms = _np.abs(s)
n = _np.shape(evnorms)[0]
m = n - _np.searchsorted(evnorms[::-1], epsilon)
if m == 0:
raise _ZeroRankError('All eigenvalues are smaller than %g, rank reduction would discard all dimensions.'%epsilon)
Vm = V[:, 0:m]
sm = s[0:m]
if canonical_signs:
# enforce canonical eigenvector signs
for j in range(m):
jj = _np.argmax(_np.abs(Vm[:, j]))
Vm[:, j] *= _np.sign(Vm[jj, j])
return sm, Vm | python | def spd_eig(W, epsilon=1e-10, method='QR', canonical_signs=False):
""" Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
canonical_signs : boolean, default = False
Fix signs in V, s. t. the largest element of in every row of V is positive.
Returns
-------
s : ndarray(k)
k non-negligible eigenvalues, sorted by descending norms
V : ndarray(n, k)
k leading eigenvectors
"""
# check input
assert _np.allclose(W.T, W), 'W is not a symmetric matrix'
if method.lower() == 'qr':
from .eig_qr.eig_qr import eig_qr
s, V = eig_qr(W)
# compute the Eigenvalues of C0 using Schur factorization
elif method.lower() == 'schur':
from scipy.linalg import schur
S, V = schur(W)
s = _np.diag(S)
else:
raise ValueError('method not implemented: ' + method)
s, V = sort_by_norm(s, V) # sort them
# determine the cutoff. We know that C0 is an spd matrix,
# so we select the truncation threshold such that everything that is negative vanishes
evmin = _np.min(s)
if evmin < 0:
epsilon = max(epsilon, -evmin + 1e-16)
# determine effective rank m and perform low-rank approximations.
evnorms = _np.abs(s)
n = _np.shape(evnorms)[0]
m = n - _np.searchsorted(evnorms[::-1], epsilon)
if m == 0:
raise _ZeroRankError('All eigenvalues are smaller than %g, rank reduction would discard all dimensions.'%epsilon)
Vm = V[:, 0:m]
sm = s[0:m]
if canonical_signs:
# enforce canonical eigenvector signs
for j in range(m):
jj = _np.argmax(_np.abs(Vm[:, j]))
Vm[:, j] *= _np.sign(Vm[jj, j])
return sm, Vm | [
"def",
"spd_eig",
"(",
"W",
",",
"epsilon",
"=",
"1e-10",
",",
"method",
"=",
"'QR'",
",",
"canonical_signs",
"=",
"False",
")",
":",
"# check input",
"assert",
"_np",
".",
"allclose",
"(",
"W",
".",
"T",
",",
"W",
")",
",",
"'W is not a symmetric matrix... | Rank-reduced eigenvalue decomposition of symmetric positive definite matrix.
Removes all negligible eigenvalues
Parameters
----------
W : ndarray((n, n), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Truncation parameter. Eigenvalues with norms smaller than this cutoff will
be removed.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
canonical_signs : boolean, default = False
Fix signs in V, s. t. the largest element of in every row of V is positive.
Returns
-------
s : ndarray(k)
k non-negligible eigenvalues, sorted by descending norms
V : ndarray(n, k)
k leading eigenvectors | [
"Rank",
"-",
"reduced",
"eigenvalue",
"decomposition",
"of",
"symmetric",
"positive",
"definite",
"matrix",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/solvers/direct.py#L35-L100 | train | 204,092 |
markovmodel/PyEMMA | pyemma/_ext/variational/solvers/direct.py | eig_corr | def eig_corr(C0, Ct, epsilon=1e-10, method='QR', sign_maxelement=False):
r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct
Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue
problem of the form
.. math::
\mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i
Computes :math:`m` dominant eigenvalues :math:`l_i` and eigenvectors
:math:`\mathbf{r}_i`, where :math:`m` is the numerical rank of the problem.
This is done by first conducting a Schur decomposition of the symmetric
positive matrix :math:`\mathbf{C}_0`, then truncating its spectrum to
retain only eigenvalues that are numerically greater than zero, then using
this decomposition to define an ordinary eigenvalue Problem for
:math:`\mathbf{C}_t` of size :math:`m`, and then solving this eigenvalue
problem.
Parameters
----------
C0 : ndarray (n,n)
time-instantaneous correlation matrix. Must be symmetric positive definite
Ct : ndarray (n,n)
time-lagged correlation matrix. Must be symmetric
epsilon : float
eigenvalue norm cutoff. Eigenvalues of C0 with norms <= epsilon will be
cut off. The remaining number of Eigenvalues define the size of
the output.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
sign_maxelement : bool
If True, re-scale each eigenvector such that its entry with maximal absolute value
is positive.
Returns
-------
l : ndarray (m)
The first m generalized eigenvalues, sorted by descending norm
R : ndarray (n,m)
The first m generalized eigenvectors, as a column matrix.
"""
L = spd_inv_split(C0, epsilon=epsilon, method=method, canonical_signs=True)
Ct_trans = _np.dot(_np.dot(L.T, Ct), L)
# solve the symmetric eigenvalue problem in the new basis
if _np.allclose(Ct.T, Ct):
from scipy.linalg import eigh
l, R_trans = eigh(Ct_trans)
else:
from scipy.linalg import eig
l, R_trans = eig(Ct_trans)
# sort eigenpairs
l, R_trans = sort_by_norm(l, R_trans)
# transform the eigenvectors back to the old basis
R = _np.dot(L, R_trans)
# Change signs of eigenvectors:
if sign_maxelement:
for j in range(R.shape[1]):
imax = _np.argmax(_np.abs(R[:, j]))
R[:, j] *= _np.sign(R[imax, j])
# return result
return l, R | python | def eig_corr(C0, Ct, epsilon=1e-10, method='QR', sign_maxelement=False):
r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct
Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue
problem of the form
.. math::
\mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i
Computes :math:`m` dominant eigenvalues :math:`l_i` and eigenvectors
:math:`\mathbf{r}_i`, where :math:`m` is the numerical rank of the problem.
This is done by first conducting a Schur decomposition of the symmetric
positive matrix :math:`\mathbf{C}_0`, then truncating its spectrum to
retain only eigenvalues that are numerically greater than zero, then using
this decomposition to define an ordinary eigenvalue Problem for
:math:`\mathbf{C}_t` of size :math:`m`, and then solving this eigenvalue
problem.
Parameters
----------
C0 : ndarray (n,n)
time-instantaneous correlation matrix. Must be symmetric positive definite
Ct : ndarray (n,n)
time-lagged correlation matrix. Must be symmetric
epsilon : float
eigenvalue norm cutoff. Eigenvalues of C0 with norms <= epsilon will be
cut off. The remaining number of Eigenvalues define the size of
the output.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
sign_maxelement : bool
If True, re-scale each eigenvector such that its entry with maximal absolute value
is positive.
Returns
-------
l : ndarray (m)
The first m generalized eigenvalues, sorted by descending norm
R : ndarray (n,m)
The first m generalized eigenvectors, as a column matrix.
"""
L = spd_inv_split(C0, epsilon=epsilon, method=method, canonical_signs=True)
Ct_trans = _np.dot(_np.dot(L.T, Ct), L)
# solve the symmetric eigenvalue problem in the new basis
if _np.allclose(Ct.T, Ct):
from scipy.linalg import eigh
l, R_trans = eigh(Ct_trans)
else:
from scipy.linalg import eig
l, R_trans = eig(Ct_trans)
# sort eigenpairs
l, R_trans = sort_by_norm(l, R_trans)
# transform the eigenvectors back to the old basis
R = _np.dot(L, R_trans)
# Change signs of eigenvectors:
if sign_maxelement:
for j in range(R.shape[1]):
imax = _np.argmax(_np.abs(R[:, j]))
R[:, j] *= _np.sign(R[imax, j])
# return result
return l, R | [
"def",
"eig_corr",
"(",
"C0",
",",
"Ct",
",",
"epsilon",
"=",
"1e-10",
",",
"method",
"=",
"'QR'",
",",
"sign_maxelement",
"=",
"False",
")",
":",
"L",
"=",
"spd_inv_split",
"(",
"C0",
",",
"epsilon",
"=",
"epsilon",
",",
"method",
"=",
"method",
","... | r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct
Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue
problem of the form
.. math::
\mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i
Computes :math:`m` dominant eigenvalues :math:`l_i` and eigenvectors
:math:`\mathbf{r}_i`, where :math:`m` is the numerical rank of the problem.
This is done by first conducting a Schur decomposition of the symmetric
positive matrix :math:`\mathbf{C}_0`, then truncating its spectrum to
retain only eigenvalues that are numerically greater than zero, then using
this decomposition to define an ordinary eigenvalue Problem for
:math:`\mathbf{C}_t` of size :math:`m`, and then solving this eigenvalue
problem.
Parameters
----------
C0 : ndarray (n,n)
time-instantaneous correlation matrix. Must be symmetric positive definite
Ct : ndarray (n,n)
time-lagged correlation matrix. Must be symmetric
epsilon : float
eigenvalue norm cutoff. Eigenvalues of C0 with norms <= epsilon will be
cut off. The remaining number of Eigenvalues define the size of
the output.
method : str
Method to perform the decomposition of :math:`W` before inverting. Options are:
* 'QR': QR-based robust eigenvalue decomposition of W
* 'schur': Schur decomposition of W
sign_maxelement : bool
If True, re-scale each eigenvector such that its entry with maximal absolute value
is positive.
Returns
-------
l : ndarray (m)
The first m generalized eigenvalues, sorted by descending norm
R : ndarray (n,m)
The first m generalized eigenvectors, as a column matrix. | [
"r",
"Solve",
"generalized",
"eigenvalue",
"problem",
"with",
"correlation",
"matrices",
"C0",
"and",
"Ct"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/solvers/direct.py#L225-L295 | train | 204,093 |
markovmodel/PyEMMA | pyemma/util/linalg.py | mdot | def mdot(*args):
"""Computes a matrix product of multiple ndarrays
This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead
use mdot(A, B, C, D).
Parameters
----------
*args : an arbitrarily long list of ndarrays that must be compatible for multiplication,
i.e. args[i].shape[1] = args[i+1].shape[0].
"""
if len(args) < 1:
raise ValueError('need at least one argument')
elif len(args) == 1:
return args[0]
elif len(args) == 2:
return np.dot(args[0], args[1])
else:
return np.dot(args[0], mdot(*args[1:])) | python | def mdot(*args):
"""Computes a matrix product of multiple ndarrays
This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead
use mdot(A, B, C, D).
Parameters
----------
*args : an arbitrarily long list of ndarrays that must be compatible for multiplication,
i.e. args[i].shape[1] = args[i+1].shape[0].
"""
if len(args) < 1:
raise ValueError('need at least one argument')
elif len(args) == 1:
return args[0]
elif len(args) == 2:
return np.dot(args[0], args[1])
else:
return np.dot(args[0], mdot(*args[1:])) | [
"def",
"mdot",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"'need at least one argument'",
")",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"args",
"[",
"0",
"]",
"elif",
"len... | Computes a matrix product of multiple ndarrays
This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead
use mdot(A, B, C, D).
Parameters
----------
*args : an arbitrarily long list of ndarrays that must be compatible for multiplication,
i.e. args[i].shape[1] = args[i+1].shape[0]. | [
"Computes",
"a",
"matrix",
"product",
"of",
"multiple",
"ndarrays"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/linalg.py#L30-L48 | train | 204,094 |
markovmodel/PyEMMA | pyemma/util/linalg.py | submatrix | def submatrix(M, sel):
"""Returns a submatrix of the quadratic matrix M, given by the selected columns and row
Parameters
----------
M : ndarray(n,n)
symmetric matrix
sel : int-array
selection of rows and columns. Element i,j will be selected if both are in sel.
Returns
-------
S : ndarray(m,m)
submatrix with m=len(sel)
"""
assert len(M.shape) == 2, 'M is not a matrix'
assert M.shape[0] == M.shape[1], 'M is not quadratic'
"""Row slicing"""
if scipy.sparse.issparse(M):
C_cc = M.tocsr()
else:
C_cc = M
C_cc = C_cc[sel, :]
"""Column slicing"""
if scipy.sparse.issparse(M):
C_cc = C_cc.tocsc()
C_cc = C_cc[:, sel]
if scipy.sparse.issparse(M):
return C_cc.tocoo()
else:
return C_cc | python | def submatrix(M, sel):
"""Returns a submatrix of the quadratic matrix M, given by the selected columns and row
Parameters
----------
M : ndarray(n,n)
symmetric matrix
sel : int-array
selection of rows and columns. Element i,j will be selected if both are in sel.
Returns
-------
S : ndarray(m,m)
submatrix with m=len(sel)
"""
assert len(M.shape) == 2, 'M is not a matrix'
assert M.shape[0] == M.shape[1], 'M is not quadratic'
"""Row slicing"""
if scipy.sparse.issparse(M):
C_cc = M.tocsr()
else:
C_cc = M
C_cc = C_cc[sel, :]
"""Column slicing"""
if scipy.sparse.issparse(M):
C_cc = C_cc.tocsc()
C_cc = C_cc[:, sel]
if scipy.sparse.issparse(M):
return C_cc.tocoo()
else:
return C_cc | [
"def",
"submatrix",
"(",
"M",
",",
"sel",
")",
":",
"assert",
"len",
"(",
"M",
".",
"shape",
")",
"==",
"2",
",",
"'M is not a matrix'",
"assert",
"M",
".",
"shape",
"[",
"0",
"]",
"==",
"M",
".",
"shape",
"[",
"1",
"]",
",",
"'M is not quadratic'"... | Returns a submatrix of the quadratic matrix M, given by the selected columns and row
Parameters
----------
M : ndarray(n,n)
symmetric matrix
sel : int-array
selection of rows and columns. Element i,j will be selected if both are in sel.
Returns
-------
S : ndarray(m,m)
submatrix with m=len(sel) | [
"Returns",
"a",
"submatrix",
"of",
"the",
"quadratic",
"matrix",
"M",
"given",
"by",
"the",
"selected",
"columns",
"and",
"row"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/linalg.py#L51-L85 | train | 204,095 |
markovmodel/PyEMMA | pyemma/thermo/models/multi_therm.py | MultiThermModel.meval | def meval(self, f, *args, **kw):
"""Evaluates the given function call for all models
Returns the results of the calls in a list
"""
# !! PART OF ORIGINAL DOCSTRING INCOMPATIBLE WITH CLASS INTERFACE !!
# Example
# -------
# We set up multiple stationary models, one for a reference (ground)
# state, and two for biased states, and group them in a
# MultiStationaryModel.
# >>> from pyemma.thermo import StationaryModel, MEMM
# >>> m_1 = StationaryModel(f=[1.0, 0], label='biased 1')
# >>> m_2 = StationaryModel(f=[2.0, 0], label='biased 2')
# >>> m_mult = MEMM([m_1, m_2], [0, 0], label='unbiased')
# Compute the stationary distribution for the two biased models
# >>> m_mult.meval('stationary_distribution')
# [array([ 0.73105858, 0.26894142]), array([ 0.88079708, 0.11920292])]
# We set up multiple Markov state models for different temperatures
# and group them in a MultiStationaryModel.
# >>> import numpy as np
# >>> from pyemma.msm import MSM
# >>> from pyemma.thermo import MEMM
# >>> b = 20 # transition barrier in kJ / mol
# >>> temps = np.arange(300, 500, 25) # temperatures 300 to 500 K
# >>> p_trans = [np.exp(- b / kT) for kT in 0.00831*temps ]
# >>> # build MSMs for different temperatures
# >>> msms = [MSM(P=np.array([[1.0-p, p], [p, 1.0-p]])) for p in p_trans]
# >>> # build Multi-MSM
# >>> msm_mult = MEMM(pi=msms[0].stationary_distribution, label='300 K', models=msms)
# Compute the timescales and see how they decay with temperature
# Greetings to Arrhenius.
# >>> np.hstack(msm_mult.meval('timescales'))
# array([ 1523.83827932, 821.88040004, 484.06386176, 305.87880068,
# 204.64109413, 143.49286817, 104.62539128, 78.83331598])
# !! END OF INCOMPATIBLE PART !!
return [_call_member(M, f, *args, **kw) for M in self.models] | python | def meval(self, f, *args, **kw):
"""Evaluates the given function call for all models
Returns the results of the calls in a list
"""
# !! PART OF ORIGINAL DOCSTRING INCOMPATIBLE WITH CLASS INTERFACE !!
# Example
# -------
# We set up multiple stationary models, one for a reference (ground)
# state, and two for biased states, and group them in a
# MultiStationaryModel.
# >>> from pyemma.thermo import StationaryModel, MEMM
# >>> m_1 = StationaryModel(f=[1.0, 0], label='biased 1')
# >>> m_2 = StationaryModel(f=[2.0, 0], label='biased 2')
# >>> m_mult = MEMM([m_1, m_2], [0, 0], label='unbiased')
# Compute the stationary distribution for the two biased models
# >>> m_mult.meval('stationary_distribution')
# [array([ 0.73105858, 0.26894142]), array([ 0.88079708, 0.11920292])]
# We set up multiple Markov state models for different temperatures
# and group them in a MultiStationaryModel.
# >>> import numpy as np
# >>> from pyemma.msm import MSM
# >>> from pyemma.thermo import MEMM
# >>> b = 20 # transition barrier in kJ / mol
# >>> temps = np.arange(300, 500, 25) # temperatures 300 to 500 K
# >>> p_trans = [np.exp(- b / kT) for kT in 0.00831*temps ]
# >>> # build MSMs for different temperatures
# >>> msms = [MSM(P=np.array([[1.0-p, p], [p, 1.0-p]])) for p in p_trans]
# >>> # build Multi-MSM
# >>> msm_mult = MEMM(pi=msms[0].stationary_distribution, label='300 K', models=msms)
# Compute the timescales and see how they decay with temperature
# Greetings to Arrhenius.
# >>> np.hstack(msm_mult.meval('timescales'))
# array([ 1523.83827932, 821.88040004, 484.06386176, 305.87880068,
# 204.64109413, 143.49286817, 104.62539128, 78.83331598])
# !! END OF INCOMPATIBLE PART !!
return [_call_member(M, f, *args, **kw) for M in self.models] | [
"def",
"meval",
"(",
"self",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# !! PART OF ORIGINAL DOCSTRING INCOMPATIBLE WITH CLASS INTERFACE !!",
"# Example",
"# -------",
"# We set up multiple stationary models, one for a reference (ground)",
"# state, and two fo... | Evaluates the given function call for all models
Returns the results of the calls in a list | [
"Evaluates",
"the",
"given",
"function",
"call",
"for",
"all",
"models",
"Returns",
"the",
"results",
"of",
"the",
"calls",
"in",
"a",
"list"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/models/multi_therm.py#L84-L119 | train | 204,096 |
markovmodel/PyEMMA | pyemma/coordinates/estimation/koopman.py | _KoopmanEstimator.u | def u(self):
'weights in the input basis'
self._check_estimated()
u_mod = self.u_pc_1
N = self._R.shape[0]
u_input = np.zeros(N+1)
u_input[0:N] = self._R.dot(u_mod[0:-1]) # in input basis
u_input[N] = u_mod[-1] - self.mean.dot(self._R.dot(u_mod[0:-1]))
return u_input | python | def u(self):
'weights in the input basis'
self._check_estimated()
u_mod = self.u_pc_1
N = self._R.shape[0]
u_input = np.zeros(N+1)
u_input[0:N] = self._R.dot(u_mod[0:-1]) # in input basis
u_input[N] = u_mod[-1] - self.mean.dot(self._R.dot(u_mod[0:-1]))
return u_input | [
"def",
"u",
"(",
"self",
")",
":",
"self",
".",
"_check_estimated",
"(",
")",
"u_mod",
"=",
"self",
".",
"u_pc_1",
"N",
"=",
"self",
".",
"_R",
".",
"shape",
"[",
"0",
"]",
"u_input",
"=",
"np",
".",
"zeros",
"(",
"N",
"+",
"1",
")",
"u_input",... | weights in the input basis | [
"weights",
"in",
"the",
"input",
"basis"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/estimation/koopman.py#L118-L126 | train | 204,097 |
markovmodel/PyEMMA | pyemma/_base/estimator.py | _estimate_param_scan_worker | def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args,
failfast, return_exceptions):
""" Method that runs estimation for several parameter settings.
Defined as a worker for parallelization
"""
# run estimation
model = None
try: # catch any exception
estimator.estimate(X, **params)
model = estimator.model
except KeyboardInterrupt:
# we want to be able to interactively interrupt the worker, no matter of failfast=False.
raise
except:
e = sys.exc_info()[1]
if isinstance(estimator, Loggable):
estimator.logger.warning("Ignored error during estimation: %s" % e)
if failfast:
raise # re-raise
elif return_exceptions:
model = e
else:
pass # just return model=None
# deal with results
res = []
# deal with result
if evaluate is None: # we want full models
res.append(model)
# we want to evaluate function(s) of the model
elif _types.is_iterable(evaluate):
values = [] # the function values the model
for ieval, name in enumerate(evaluate):
# get method/attribute name and arguments to be evaluated
#name = evaluate[ieval]
args = ()
if evaluate_args is not None:
args = evaluate_args[ieval]
# wrap single arguments in an iterable again to pass them.
if _types.is_string(args):
args = (args, )
# evaluate
try:
# try calling method/property/attribute
value = _call_member(estimator.model, name, failfast, *args)
# couldn't find method/property/attribute
except AttributeError as e:
if failfast:
raise e # raise an AttributeError
else:
value = None # we just ignore it and return None
values.append(value)
# if we only have one value, unpack it
if len(values) == 1:
values = values[0]
res.append(values)
else:
raise ValueError('Invalid setting for evaluate: ' + str(evaluate))
if len(res) == 1:
res = res[0]
return res | python | def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args,
failfast, return_exceptions):
""" Method that runs estimation for several parameter settings.
Defined as a worker for parallelization
"""
# run estimation
model = None
try: # catch any exception
estimator.estimate(X, **params)
model = estimator.model
except KeyboardInterrupt:
# we want to be able to interactively interrupt the worker, no matter of failfast=False.
raise
except:
e = sys.exc_info()[1]
if isinstance(estimator, Loggable):
estimator.logger.warning("Ignored error during estimation: %s" % e)
if failfast:
raise # re-raise
elif return_exceptions:
model = e
else:
pass # just return model=None
# deal with results
res = []
# deal with result
if evaluate is None: # we want full models
res.append(model)
# we want to evaluate function(s) of the model
elif _types.is_iterable(evaluate):
values = [] # the function values the model
for ieval, name in enumerate(evaluate):
# get method/attribute name and arguments to be evaluated
#name = evaluate[ieval]
args = ()
if evaluate_args is not None:
args = evaluate_args[ieval]
# wrap single arguments in an iterable again to pass them.
if _types.is_string(args):
args = (args, )
# evaluate
try:
# try calling method/property/attribute
value = _call_member(estimator.model, name, failfast, *args)
# couldn't find method/property/attribute
except AttributeError as e:
if failfast:
raise e # raise an AttributeError
else:
value = None # we just ignore it and return None
values.append(value)
# if we only have one value, unpack it
if len(values) == 1:
values = values[0]
res.append(values)
else:
raise ValueError('Invalid setting for evaluate: ' + str(evaluate))
if len(res) == 1:
res = res[0]
return res | [
"def",
"_estimate_param_scan_worker",
"(",
"estimator",
",",
"params",
",",
"X",
",",
"evaluate",
",",
"evaluate_args",
",",
"failfast",
",",
"return_exceptions",
")",
":",
"# run estimation",
"model",
"=",
"None",
"try",
":",
"# catch any exception",
"estimator",
... | Method that runs estimation for several parameter settings.
Defined as a worker for parallelization | [
"Method",
"that",
"runs",
"estimation",
"for",
"several",
"parameter",
"settings",
"."
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/estimator.py#L127-L191 | train | 204,098 |
markovmodel/PyEMMA | pyemma/_base/estimator.py | Estimator.estimate | def estimate(self, X, **params):
""" Estimates the model given the data X
Parameters
----------
X : object
A reference to the data from which the model will be estimated
params : dict
New estimation parameter values. The parameters must that have been
announced in the __init__ method of this estimator. The present
settings will overwrite the settings of parameters given in the
__init__ method, i.e. the parameter values after this call will be
those that have been used for this estimation. Use this option if
only one or a few parameters change with respect to
the __init__ settings for this run, and if you don't need to
remember the original settings of these changed parameters.
Returns
-------
estimator : object
The estimated estimator with the model being available.
"""
# set params
if params:
self.set_params(**params)
self._model = self._estimate(X)
# ensure _estimate returned something
assert self._model is not None
self._estimated = True
return self | python | def estimate(self, X, **params):
""" Estimates the model given the data X
Parameters
----------
X : object
A reference to the data from which the model will be estimated
params : dict
New estimation parameter values. The parameters must that have been
announced in the __init__ method of this estimator. The present
settings will overwrite the settings of parameters given in the
__init__ method, i.e. the parameter values after this call will be
those that have been used for this estimation. Use this option if
only one or a few parameters change with respect to
the __init__ settings for this run, and if you don't need to
remember the original settings of these changed parameters.
Returns
-------
estimator : object
The estimated estimator with the model being available.
"""
# set params
if params:
self.set_params(**params)
self._model = self._estimate(X)
# ensure _estimate returned something
assert self._model is not None
self._estimated = True
return self | [
"def",
"estimate",
"(",
"self",
",",
"X",
",",
"*",
"*",
"params",
")",
":",
"# set params",
"if",
"params",
":",
"self",
".",
"set_params",
"(",
"*",
"*",
"params",
")",
"self",
".",
"_model",
"=",
"self",
".",
"_estimate",
"(",
"X",
")",
"# ensur... | Estimates the model given the data X
Parameters
----------
X : object
A reference to the data from which the model will be estimated
params : dict
New estimation parameter values. The parameters must that have been
announced in the __init__ method of this estimator. The present
settings will overwrite the settings of parameters given in the
__init__ method, i.e. the parameter values after this call will be
those that have been used for this estimation. Use this option if
only one or a few parameters change with respect to
the __init__ settings for this run, and if you don't need to
remember the original settings of these changed parameters.
Returns
-------
estimator : object
The estimated estimator with the model being available. | [
"Estimates",
"the",
"model",
"given",
"the",
"data",
"X"
] | 5c3124398217de05ba5ce9c8fb01519222481ab8 | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/estimator.py#L381-L411 | train | 204,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.