text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: ['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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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` or .. 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.: 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 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 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.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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.: 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: Create a reader for trajectory files and select some distance as feature: create a reader for a csv file: Create a reader for huge NumPy in-memory arrays to process them in huge chunks to avoid memory issues: 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 -------- Create some random data and cluster centers: Define a TICA transformation with lag time 10: Assign any input to given centers: .. 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 -------- .. 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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' Generate some random data and choose 10 random centers: .. 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unregister_signal_handlers():
""" set signal handlers to default """ |
signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN)
signal.signal(SIGNAL_PDB, signal.SIG_IGN) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selection_strategy(oasis_obj, strategy='spectral-oasis', nsel=1, neig=None):
""" Factory for selection strategy object Returns ------- selstr : SelectionStrategy Selection strategy object """ |
strategy = strategy.lower()
if strategy == 'random':
return SelectionStrategyRandom(oasis_obj, strategy, nsel=nsel, neig=neig)
elif strategy == 'oasis':
return SelectionStrategyOasis(oasis_obj, strategy, nsel=nsel, neig=neig)
elif strategy == 'spectral-oasis':
return SelectionStrategySpectralOasis(oasis_obj, strategy, nsel=nsel, neig=neig)
else:
raise ValueError('Selected strategy is unknown: '+str(strategy)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_error(self):
""" Evaluate the absolute error of the Nystroem approximation for each column """ |
# err_i = sum_j R_{k,ij} A_{k,ji} - d_i
self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None):
""" Defines the column selection strategy Parameters strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` spectral-oasis : selects the nsel columns that are most distanced in the oASIS-error-scaled dominant eigenspace nsel : int number of columns to be selected in each round neig : int or None, optional, default None Number of eigenvalues to be optimized by the selection process. If None, use the whole available eigenspace """ |
self._selection_strategy = selection_strategy(self, strategy, nsel, neig) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_inverse(self):
""" Recomputes W_k_inv and R_k given the current column selection When computed, the block matrix inverse W_k_inv will be updated. This is useful when you want to compute eigenvalues or get an approximation for the full matrix or individual columns. Calling this function is not strictly necessary, but then you rely on the fact that the updates did not accumulate large errors. That depends very much on how columns were added. Adding columns with very small Schur complement causes accumulation of errors and is more likely to make it necessary to update the inverse. """ |
# compute R_k and W_k_inv
Wk = self._C_k[self._columns, :]
self._W_k_inv = np.linalg.pinv(Wk)
self._R_k = np.dot(self._W_k_inv, self._C_k.T) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def approximate_cholesky(self, epsilon=1e-6):
r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- L : ndarray((n,m), dtype=float) Cholesky matrix such that `A \approx L L^{\top}`. Number of columns :math:`m` is most at the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ |
# compute the Eigenvalues of C0 using Schur factorization
Wk = self._C_k[self._columns, :]
L0 = spd_inv_split(Wk, epsilon=epsilon)
L = np.dot(self._C_k, L0)
return L |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def approximate_eig(self, epsilon=1e-6):
""" Compute low-rank approximation of the eigenvalue decomposition of target matrix. If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- s : ndarray((m,), dtype=float) approximated eigenvalues. Number of eigenvalues returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. W : ndarray((n,m), dtype=float) approximated eigenvectors in columns. Number of eigenvectors returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ |
L = self.approximate_cholesky(epsilon=epsilon)
LL = np.dot(L.T, L)
s, V = np.linalg.eigh(LL)
# sort
s, V = sort_by_norm(s, V)
# back-transform eigenvectors
Linv = np.linalg.pinv(L.T)
V = np.dot(Linv, V)
# normalize eigenvectors
ncol = V.shape[1]
for i in range(ncol):
if not np.allclose(V[:, i], 0):
V[:, i] /= np.sqrt(np.dot(V[:, i], V[:, i]))
return s, V |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self):
""" Selects next column indexes according to defined strategy Returns ------- cols : ndarray((nsel,), dtype=int) selected columns """ |
err = self._oasis_obj.error
if np.allclose(err, 0):
return None
nsel = self._check_nsel()
if nsel is None:
return None
return self._select(nsel, err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, name):
""" deletes model with given name """ |
if name not in self._parent:
raise KeyError('model "{}" not present'.format(name))
del self._parent[name]
if self._current_model_group == name:
self._current_model_group = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_model(self, name):
""" choose an existing model """ |
if name not in self._parent:
raise KeyError('model "{}" not present'.format(name))
self._current_model_group = name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def models_descriptive(self):
""" list all stored models in given file. Returns ------- """ |
f = self._parent
return {name: {a: f[name].attrs[a]
for a in H5File.stored_attributes}
for name in f.keys()} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_progress(self):
""" whether to show the progress of heavy calculations on this object. """ |
from pyemma import config
# no value yet, obtain from config
if not hasattr(self, "_show_progress"):
val = config.show_progress_bars
self._show_progress = val
# config disabled progress?
elif not config.show_progress_bars:
return False
return self._show_progress |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _progress_set_description(self, stage, description):
""" set description of an already existing progress """ |
self.__check_stage_registered(stage)
self._prog_rep_descriptions[stage] = description
if self._prog_rep_progressbars[stage]:
self._prog_rep_progressbars[stage].set_description(description, refresh=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw):
""" Updates the progress. Will update progress bars or other progress output. Parameters numerator : int numerator of partial work done already in current stage stage : int, nonnegative, default=0 Current stage of the algorithm, 0 or greater """ |
if not self.show_progress:
return
self.__check_stage_registered(stage)
if not self._prog_rep_progressbars[stage]:
return
pg = self._prog_rep_progressbars[stage]
pg.update(int(numerator_increment)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _progress_force_finish(self, stage=0, description=None):
""" forcefully finish the progress for given stage """ |
if not self.show_progress:
return
self.__check_stage_registered(stage)
if not self._prog_rep_progressbars[stage]:
return
pg = self._prog_rep_progressbars[stage]
pg.desc = description
increment = int(pg.total - pg.n)
if increment > 0:
pg.update(increment)
pg.refresh(nolock=True)
pg.close()
self._prog_rep_progressbars.pop(stage, None)
self._prog_rep_descriptions.pop(stage, None)
self._prog_rep_callbacks.pop(stage, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_feature_histograms(xyzall, feature_labels=None, ax=None, ylog=False, outfile=None, n_bins=50, ignore_dim_warning=False, **kwargs):
r"""Feature histogram plot Parameters xyzall : np.ndarray(T, d) (Concatenated list of) input features; containing time series data to be plotted. Array of T data points in d dimensions (features). feature_labels : iterable of str or pyemma.Featurizer, optional, default=None Labels of histogramed features, defaults to feature index. ax : matplotlib.Axes object, optional, default=None. The ax to plot to; if ax=None, a new ax (and fig) is created. ylog : boolean, default=False If True, plot logarithm of histogram values. n_bins : int, default=50 Number of bins the histogram uses. outfile : str, default=None If not None, saves plot to this file. ignore_dim_warning : boolean, default=False Enable plotting for more than 50 dimensions (on your own risk). **kwargs: kwargs passed to pyplot.fill_between. See the doc of pyplot for options. Returns ------- fig : matplotlib.Figure object The figure in which the used ax resides. ax : matplotlib.Axes object The ax in which the historams were plotted. """ |
if not isinstance(xyzall, _np.ndarray):
raise ValueError('Input data hast to be a numpy array. Did you concatenate your data?')
if xyzall.shape[1] > 50 and not ignore_dim_warning:
raise RuntimeError('This function is only useful for less than 50 dimensions. Turn-off this warning '
'at your own risk with ignore_dim_warning=True.')
if feature_labels is not None:
if not isinstance(feature_labels, list):
from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer as _MDFeaturizer
if isinstance(feature_labels, _MDFeaturizer):
feature_labels = feature_labels.describe()
else:
raise ValueError('feature_labels must be a list of feature labels, '
'a pyemma featurizer object or None.')
if not xyzall.shape[1] == len(feature_labels):
raise ValueError('feature_labels must have the same dimension as the input data xyzall.')
# make nice plots if user does not decide on color and transparency
if 'color' not in kwargs.keys():
kwargs['color'] = 'b'
if 'alpha' not in kwargs.keys():
kwargs['alpha'] = .25
import matplotlib.pyplot as _plt
# check input
if ax is None:
fig, ax = _plt.subplots()
else:
fig = ax.get_figure()
hist_offset = -.2
for h, coordinate in enumerate(reversed(xyzall.T)):
hist, edges = _np.histogram(coordinate, bins=n_bins)
if not ylog:
y = hist / hist.max()
else:
y = _np.zeros_like(hist) + _np.NaN
pos_idx = hist > 0
y[pos_idx] = _np.log(hist[pos_idx]) / _np.log(hist[pos_idx]).max()
ax.fill_between(edges[:-1], y + h + hist_offset, y2=h + hist_offset, **kwargs)
ax.axhline(y=h + hist_offset, xmin=0, xmax=1, color='k', linewidth=.2)
ax.set_ylim(hist_offset, h + hist_offset + 1)
# formatting
if feature_labels is None:
feature_labels = [str(n) for n in range(xyzall.shape[1])]
ax.set_ylabel('Feature histograms')
ax.set_yticks(_np.array(range(len(feature_labels))) + .3)
ax.set_yticklabels(feature_labels[::-1])
ax.set_xlabel('Feature values')
# save
if outfile is not None:
fig.savefig(outfile)
return fig, ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_memory(self, op_in_mem):
r""" If set to True, the output will be stored in memory. """ |
old_state = self.in_memory
if not old_state and op_in_mem:
self._map_to_memory()
elif not op_in_mem and old_state:
self._clear_in_memory() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expectation(self, observables, statistics, lag_multiple=1, observables_mean_free=False, statistics_mean_free=False):
r"""Compute future expectation of observable or covariance using the approximated Koopman operator. Parameters observables : np.ndarray((input_dimension, n_observables)) Coefficients that express one or multiple observables in the basis of the input features. statistics : np.ndarray((input_dimension, n_statistics)), optional Coefficients that express one or multiple statistics in the basis of the input features. This parameter can be None. In that case, this method returns the future expectation value of the observable(s). lag_multiple : int If > 1, extrapolate to a multiple of the estimator's lag time by assuming Markovianity of the approximated Koopman operator. observables_mean_free : bool, default=False If true, coefficients in `observables` refer to the input features with feature means removed. If false, coefficients in `observables` refer to the unmodified input features. statistics_mean_free : bool, default=False If true, coefficients in `statistics` refer to the input features with feature means removed. If false, coefficients in `statistics` refer to the unmodified input features. Notes ----- A "future expectation" of a observable g is the average of g computed over a time window that has the same total length as the input data from which the Koopman operator was estimated but is shifted by lag_multiple*tau time steps into the future (where tau is the lag time). It is computed with the equation: .. math:: \mathbb{E}[g]_{\rho_{n}}=\mathbf{q}^{T}\mathbf{P}^{n-1}\mathbf{e}_{1} where .. math:: P_{ij}=\sigma_{i}\langle\psi_{i},\phi_{j}\rangle_{\rho_{1}} and .. math:: q_{i}=\langle g,\phi_{i}\rangle_{\rho_{1}} and :math:`\mathbf{e}_{1}` is the first canonical unit vector. A model prediction of time-lagged covariances between the observable f and the statistic g at a lag-time of lag_multiple*tau is computed with the equation: .. math:: \mathrm{cov}[g,\,f;n\tau]=\mathbf{q}^{T}\mathbf{P}^{n-1}\boldsymbol{\Sigma}\mathbf{r} where :math:`r_{i}=\langle\psi_{i},f\rangle_{\rho_{0}}` and :math:`\boldsymbol{\Sigma}=\mathrm{diag(\boldsymbol{\sigma})}` . """ |
# TODO: implement the case lag_multiple=0
dim = self.dimension()
S = np.diag(np.concatenate(([1.0], self.singular_values[0:dim])))
V = self.V[:, 0:dim]
U = self.U[:, 0:dim]
m_0 = self.mean_0
m_t = self.mean_t
assert lag_multiple >= 1, 'lag_multiple = 0 not implemented'
if lag_multiple == 1:
P = S
else:
p = np.zeros((dim + 1, dim + 1))
p[0, 0] = 1.0
p[1:, 0] = U.T.dot(m_t - m_0)
p[1:, 1:] = U.T.dot(self.Ctt).dot(V)
P = np.linalg.matrix_power(S.dot(p), lag_multiple - 1).dot(S)
Q = np.zeros((observables.shape[1], dim + 1))
if not observables_mean_free:
Q[:, 0] = observables.T.dot(m_t)
Q[:, 1:] = observables.T.dot(self.Ctt).dot(V)
if statistics is not None:
# compute covariance
R = np.zeros((statistics.shape[1], dim + 1))
if not statistics_mean_free:
R[:, 0] = statistics.T.dot(m_0)
R[:, 1:] = statistics.T.dot(self.C00).dot(U)
if statistics is not None:
# compute lagged covariance
return Q.dot(P).dot(R.T)
# TODO: discuss whether we want to return this or the transpose
# TODO: from MSMs one might expect to first index to refer to the statistics, here it is the other way round
else:
# compute future expectation
return Q.dot(P)[:, 0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _diagonalize(self):
"""Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the singular functions is 1 * 'kinetic map' or 'km': singular functions are scaled by singular value. Note that only the left singular functions induce a kinetic map. """ |
L0 = spd_inv_split(self.C00, epsilon=self.epsilon)
self._rank0 = L0.shape[1] if L0.ndim == 2 else 1
Lt = spd_inv_split(self.Ctt, epsilon=self.epsilon)
self._rankt = Lt.shape[1] if Lt.ndim == 2 else 1
W = np.dot(L0.T, self.C0t).dot(Lt)
from scipy.linalg import svd
A, s, BT = svd(W, compute_uv=True, lapack_driver='gesvd')
self._singular_values = s
# don't pass any values in the argument list that call _diagonalize again!!!
m = VAMPModel._dimension(self._rank0, self._rankt, self.dim, self._singular_values)
U = np.dot(L0, A[:, :m])
V = np.dot(Lt, BT[:m, :].T)
# scale vectors
if self.scaling is not None:
U *= s[np.newaxis, 0:m] # scaled left singular functions induce a kinetic map
V *= s[np.newaxis, 0:m] # scaled right singular functions induce a kinetic map wrt. backward propagator
self._U = U
self._V = V
self._svd_performed = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(self, test_model=None, score_method='VAMP2'):
"""Compute the VAMP score for this model or the cross-validation score between self and a second model. Parameters test_model : VAMPModel, optional, default=None If `test_model` is not None, this method computes the cross-validation score between self and `test_model`. It is assumed that self was estimated from the "training" data and `test_model` was estimated from the "test" data. The score is computed for one realization of self and `test_model`. Estimation of the average cross-validation score and partitioning of data into test and training part is not performed by this method. If `test_model` is None, this method computes the VAMP score for the model contained in self. score_method : str, optional, default='VAMP2' Available scores are based on the variational approach for Markov processes [1]_: * 'VAMP1' Sum of singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the sum of Koopman matrix eigenvalues, also called Rayleigh quotient [1]_. * 'VAMP2' Sum of squared singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the kinetic variance [2]_ . * 'VAMPE' Approximation error of the estimated Koopman operator with respect to the true Koopman operator up to an additive constant [1]_ . Returns ------- score : float If `test_model` is not None, returns the cross-validation VAMP score between self and `test_model`. Otherwise return the selected VAMP-score of self. References .. [1] Wu, H. and Noe, F. 2017. Variational approach for learning Markov processes from time series data. arXiv:1707.04659v1 .. [2] Noe, F. and Clementi, C. 2015. Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory. Comput. doi:10.1021/acs.jctc.5b00553 """ |
# TODO: implement for TICA too
if test_model is None:
test_model = self
Uk = self.U[:, 0:self.dimension()]
Vk = self.V[:, 0:self.dimension()]
res = None
if score_method == 'VAMP1' or score_method == 'VAMP2':
A = spd_inv_sqrt(Uk.T.dot(test_model.C00).dot(Uk))
B = Uk.T.dot(test_model.C0t).dot(Vk)
C = spd_inv_sqrt(Vk.T.dot(test_model.Ctt).dot(Vk))
ABC = mdot(A, B, C)
if score_method == 'VAMP1':
res = np.linalg.norm(ABC, ord='nuc')
elif score_method == 'VAMP2':
res = np.linalg.norm(ABC, ord='fro')**2
elif score_method == 'VAMPE':
Sk = np.diag(self.singular_values[0:self.dimension()])
res = np.trace(2.0 * mdot(Vk, Sk, Uk.T, test_model.C0t) - mdot(Vk, Sk, Uk.T, test_model.C00, Uk, Sk, Vk.T, test_model.Ctt))
else:
raise ValueError('"score" should be one of VAMP1, VAMP2 or VAMPE')
# add the contribution (+1) of the constant singular functions to the result
assert res
return res + 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20):
""" Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional, default=500 Length in steps of each umbrella trajectory. md_length: int, optional, default=1000 Length in steps of each unbiased trajectory. nmd: int, optional, default=20 Number of unbiased trajectories. Returns ------- dict - keys shown below in brackets Trajectory data from umbrella sampling (us_trajs) and unbiased (md_trajs) MCMC runs and their discretised counterparts (us_dtrajs + md_dtrajs + centers). The umbrella sampling parameters (us_centers + us_force_constants) are in the same order as the umbrella sampling trajectories. Energies are given in kT, lengths in arbitrary units. """ |
dws = _DWS()
us_data = dws.us_sample(
ntherm=ntherm, us_fc=us_fc, us_length=us_length, md_length=md_length, nmd=nmd)
us_data.update(centers=dws.centers)
return us_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_multi_temperature_data(kt0=1.0, kt1=5.0, length0=10000, length1=10000, n0=10, n1=10):
""" Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state. length0: int, optional, default=10000 Trajectory length in steps for the first thermodynamic state. length1: int, optional, default=10000 Trajectory length in steps for the second thermodynamic state. n0: int, optional, default=10 Number of trajectories in the first thermodynamic state. n1: int, optional, default=10 Number of trajectories in the second thermodynamic state. Returns ------- dict - keys shown below in brackets Trajectory (trajs), energy (energy_trajs), and temperature (temp_trajs) data from the MCMC runs as well as the discretised version (dtrajs + centers). Energies and temperatures are given in kT, lengths in arbitrary units. """ |
dws = _DWS()
mt_data = dws.mt_sample(
kt0=kt0, kt1=kt1, length0=length0, length1=length1, n0=n0, n1=n1)
mt_data.update(centers=dws.centers)
return mt_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_scaled(self, factor):
""" Get a new time unit, scaled by the given factor """ |
res = TimeUnit(self)
res._factor = self._factor * factor
res._unit = self._unit
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rescale_around1(self, times):
""" Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1. Parameters times : float array array of times in multiple of the present elementary unit """ |
if self._unit == self._UNIT_STEP:
return times, 'step' # nothing to do
m = np.mean(times)
mult = 1.0
cur_unit = self._unit
# numbers are too small. Making them larger and reducing the unit:
if (m < 0.001):
while mult*m < 0.001 and cur_unit >= 0:
mult *= 1000
cur_unit -= 1
return mult*times, self._unit_names[cur_unit]
# numbers are too large. Making them smaller and increasing the unit:
if (m > 1000):
while mult*m > 1000 and cur_unit <= 5:
mult /= 1000
cur_unit += 1
return mult*times, self._unit_names[cur_unit]
# nothing to do
return times, self._unit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.