code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self.tagSet: return Set.tagMap.fget(self) else: return self.componentType.tagMapUnique
def tagMap(self)
Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.
12.424328
12.532681
0.991354
if self._currentIdx is None: raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if innerFlag and isinstance(c, Choice): return c.getComponent(innerFlag) else: return c
def getComponent(self, innerFlag=False)
Return currently assigned component of the |ASN.1| object. Returns ------- : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object
4.370122
4.110163
1.063248
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....
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
4.731122
4.671808
1.012696
if self._currentIdx is None: return False componentValue = self._componentValues[self._currentIdx] return componentValue is not noValue and componentValue.isValue
def isValue(self)
Indicate that |ASN.1| object represents ASN.1 value. If *isValue* is `False` then this object represents just ASN.1 schema. If *isValue* is `True` then, in addition to its ASN.1 schema features, this object can also be used like a Python built-in object (e.g. `int`, `str`, `dict` etc.)...
8.279787
13.955416
0.593303
try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap( {self.tagSet: self}, {eoo.endOfOctets.tagSet: eoo.endOfOctets}, self ) return self._tagMap
def tagMap(self)
Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.
5.066679
3.724877
1.360227
path = [(node.x, node.y)] while node.parent: node = node.parent path.append((node.x, node.y)) path.reverse() return path
def backtrace(node)
Backtrace according to the parent records and return the path. (including both start and end nodes)
2.091632
2.009398
1.040925
path_a = backtrace(node_a) path_b = backtrace(node_b) path_b.reverse() return path_a + path_b
def bi_backtrace(node_a, node_b)
Backtrace from start and end node, returns the path for bi-directional A* (including both start and end nodes)
2.314172
2.293479
1.009023
''' Given the start and end coordinates, return all the coordinates lying on the line formed by these coordinates, based on Bresenham's algorithm. http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification ''' line = [] x0, y0 = coords_a x1, y1 = coords_b dx = abs(x1 - x0...
def bresenham(coords_a, coords_b)
Given the start and end coordinates, return all the coordinates lying on the line formed by these coordinates, based on Bresenham's algorithm. http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification
1.816785
1.378484
1.317958
''' Given a compressed path, return a new path that has all the segments in it interpolated. ''' expanded = [] if len(path) < 2: return expanded for i in range(len(path)-1): expanded += bresenham(path[i], path[i + 1]) expanded += [path[:-1]] return expanded
def expand_path(path)
Given a compressed path, return a new path that has all the segments in it interpolated.
5.716147
3.372077
1.695141
if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0: # direct neighbor - distance is 1 ng = 1 else: # not a direct neighbor - diagonal movement ng = SQRT2 # weight for weighted algorithms if self.weighted: ng *= no...
def calc_cost(self, node_a, node_b)
get the distance between current node and the neighbor (cost)
5.39079
4.920439
1.095591
if not heuristic: heuristic = self.heuristic return heuristic( abs(node_a.x - node_b.x), abs(node_a.y - node_b.y))
def apply_heuristic(self, node_a, node_b, heuristic=None)
helper function to apply heuristic
2.389348
2.31184
1.033527
''' find neighbor, same for Djikstra, A*, Bi-A*, IDA* ''' if not diagonal_movement: diagonal_movement = self.diagonal_movement return grid.neighbors(node, diagonal_movement=diagonal_movement)
def find_neighbors(self, grid, node, diagonal_movement=None)
find neighbor, same for Djikstra, A*, Bi-A*, IDA*
6.294263
2.573151
2.446131
if self.runs >= self.max_runs: raise ExecutionRunsException( '{} run into barrier of {} iterations without ' 'finding the destination'.format( self.__class__.__name__, self.max_runs)) if time.time() - self.start_time >= self.time_...
def keep_running(self)
check, if we run into time or iteration constrains. :returns: True if we keep running and False if we run into a constraint
5.00321
4.520209
1.106854
''' we check if the given node is path of the path by calculating its cost and add or remove it from our path :param node: the node we like to test (the neighbor in A* or jump-node in JumpPointSearch) :param parent: the parent node (the current node we like to test) ...
def process_node(self, node, parent, end, open_list, open_value=True)
we check if the given node is path of the path by calculating its cost and add or remove it from our path :param node: the node we like to test (the neighbor in A* or jump-node in JumpPointSearch) :param parent: the parent node (the current node we like to test) :param end: t...
5.149457
2.219295
2.320312
self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start.opened = True open_list = [start] while len(open_list) > 0: self.runs += 1 self.keep_running() path = self.check_neighbors(...
def find_path(self, start, end, grid)
find a path from start to end node on grid by iterating over all neighbors of a node (see check_neighbors) :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
4.603104
4.665949
0.986531
self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start_open_list = [start] start.g = 0 start.f = 0 start.opened = BY_START end_open_list = [end] end.g = 0 end.f = 0 end.opened...
def find_path(self, start, end, grid)
find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
2.738265
2.77754
0.98586
# 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 ...
def cleanup(self)
reset all calculated values, fresh start for pathfinding
7.001456
6.191681
1.130784
nodes = [] use_matrix = (isinstance(matrix, (tuple, list))) or \ (USE_NUMPY and isinstance(matrix, np.ndarray) and matrix.size > 0) for y in range(height): nodes.append([]) for x in range(width): # 1, '1', True will be walkable # while others will be obs...
def build_nodes(width, height, matrix=None, inverse=False)
create nodes according to grid size. If a matrix is given it will be used to determine what nodes are walkable. :rtype : list
4.421399
4.524248
0.977267
return 0 <= x < self.width and 0 <= y < self.height
def inside(self, x, y)
check, if field position is inside map :param x: x pos :param y: y pos :return:
3.125722
6.798526
0.459765
return self.inside(x, y) and self.nodes[y][x].walkable
def walkable(self, x, y)
check, if the tile is inside grid and if it is set as walkable
5.485169
5.041224
1.088063
x = node.x y = node.y neighbors = [] s0 = d0 = s1 = d1 = s2 = d2 = s3 = d3 = False # ↑ if self.walkable(x, y - 1): neighbors.append(self.nodes[y - 1][x]) s0 = True # → if self.walkable(x + 1, y): neighbors.appe...
def neighbors(self, node, diagonal_movement=DiagonalMovement.never)
get all neighbors of one node :param node: node
1.4205
1.425993
0.996148
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 += star...
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_ch...
2.413416
2.315018
1.042504
# pop node with minimum 'f' value node = heapq.nsmallest(1, open_list)[0] open_list.remove(node) node.closed = True # if reached the end position, construct the path and return it # (ignored for bi-directional a*, there we look for a neighbor that is # ...
def check_neighbors(self, start, end, grid, open_list, open_value=True, backtrace_by=None)
find next path segment based on given node (or return path if we found the end)
5.238799
5.186945
1.009997
start.g = 0 start.f = 0 return super(AStarFinder, self).find_path(start, end, grid)
def find_path(self, start, end, grid)
find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return:
4.165177
4.986845
0.835233
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 pack...
def load()
Loads the libzar shared library and its dependencies.
4.827124
4.564956
1.057431
global LIBZBAR global EXTERNAL_DEPENDENCIES if not LIBZBAR: libzbar, dependencies = zbar_library.load() LIBZBAR = libzbar EXTERNAL_DEPENDENCIES = [LIBZBAR] + dependencies return LIBZBAR
def load_libzbar()
Loads the zbar shared library and its dependencies. Populates the globals LIBZBAR and EXTERNAL_DEPENDENCIES.
4.121302
3.316157
1.242794
prototype = CFUNCTYPE(restype, *args) return prototype((fname, load_libzbar()))
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.C...
7.956183
20.24975
0.392903
x_values = list(map(itemgetter(0), locations)) x_min, x_max = min(x_values), max(x_values) y_values = list(map(itemgetter(1), locations)) y_min, y_max = min(y_values), max(y_values) return Rect(x_min, y_min, x_max - x_min, y_max - y_min)
def bounding_box(locations)
Computes the bounding box of an iterable of (x, y) coordinates. Args: locations: iterable of (x, y) tuples. Returns: `Rect`: Coordinates of the bounding box.
1.632531
1.673715
0.975394
def is_not_clockwise(p0, p1, p2): return 0 <= ( (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p1[1] - p0[1]) * (p2[0] - p0[0]) ) def go(points_): res = [] for p in points_: while 1 < len(res) and is_not_clockwise(res[-2], res[-1], p): ...
def convex_hull(points)
Computes the convex hull of an iterable of (x, y) coordinates. Args: points: iterable of (x, y) tuples. Returns: `list`: instances of `Point` - vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. ...
2.998483
2.961879
1.012359
symbol = zbar_image_first_symbol(image) while symbol: yield symbol symbol = zbar_symbol_next(symbol)
def _symbols_for_image(image)
Generator of symbols. Args: image: `zbar_image` Yields: POINTER(zbar_symbol): Symbol
5.704738
5.385296
1.059317
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), ...
def _decode_symbols(symbols)
Generator of decoded symbol information. Args: symbols: iterable of instances of `POINTER(zbar_symbol)` Yields: Decoded: decoded symbol
6.045151
5.034648
1.20071
# Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL # are installed. if 'PIL.' in str(type(image)): if 'L' != image.mode: image = image.convert('L') pixels = image.tobytes() width, height = image.size elif 'numpy.ndarray' in str(type(image)):...
def _pixel_data(image)
Returns (pixels, width, height) Returns: :obj: `tuple` (pixels, width, height)
3.143419
3.063676
1.026029
pixels, width, height = _pixel_data(image) results = [] with _image_scanner() as scanner: if symbols: # Disable all but the symbols of interest disable = set(ZBarSymbol).difference(symbols) for symbol in disable: zbar_image_scanner_set_config...
def decode(image, symbols=None)
Decodes datamatrix barcodes in `image`. Args: image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height) symbols: iter(ZBarSymbol) the symbol types to decode; if `None`, uses `zbar`'s default behaviour, which is to decode all symbol types. Returns: :obj:`list` of ...
4.831805
4.955468
0.975045
output = "" i18 = getattr(settings, 'USE_I18N', False) if i18: template = "admin/language_selector.html" context['i18n_is_set'] = True try: output = render_to_string(template, context) except: pass return output
def language_selector(context)
displays a language selector dropdown in the admin, based on Django "LANGUAGES" context. requires: * USE_I18N = True / settings.py * LANGUAGES specified / settings.py (otherwise all Django locales will be displayed) * "set_language" url configured (see https://docs.djangoproj...
3.279875
3.088983
1.061798
try: template = app['app_label'] + template text = render_to_string(template, context) except: text = app['name'] return text
def render_app_name(context, app, template="/admin_app_name.html")
Render the application name using the default template name. If it cannot find a template matching the given path, fallback to the application name.
4.142612
4.143261
0.999843
try: text = app['app_label'] except KeyError: text = fallback except TypeError: text = app return text
def render_app_label(context, app, fallback="")
Render the application label.
4.39467
3.953311
1.111643
try: template = app['app_label'] + template text = render_to_string(template, context) except: text = fallback return text
def render_app_description(context, app, fallback="", template="/admin_app_description.html")
Render the application description using the default template name. If it cannot find a template matching the given path, fallback to the fallback argument.
3.819505
4.096736
0.932329
if CUSTOM_FIELD_RENDERER: mod, cls = CUSTOM_FIELD_RENDERER.rsplit(".", 1) field_renderer = getattr(import_module(mod), cls) if field_renderer: return field_renderer(field, **kwargs).render() return field
def custom_field_rendering(context, field, *args, **kwargs)
Wrapper for rendering the field via an external renderer
3.144628
3.045334
1.032605
if self._is_reader: assert self._filenames is not None return self._filenames else: return self.data_producer.filenames
def filenames(self)
list of file names the data is originally being read from. Returns ------- names : list of str list of file names at the beginning of the input chain.
6.482656
7.323347
0.885204
if self.data_producer is None: return [] res = [] ds = self.data_producer while not ds.is_reader: res.append(ds) ds = ds.data_producer res.append(ds) res = res[::-1] return res
def _data_flow_chain(self)
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
3.845717
3.603694
1.06716
r if not IteratorState.is_uniform_stride(stride): n = len(np.unique(stride[:, 0])) else: n = self.ntraj return n
def number_of_trajectories(self, stride=None)
r""" Returns the number of trajectories. Parameters ---------- stride: None (default) or np.ndarray Returns ------- int : number of trajectories
13.075029
13.3582
0.978802
r 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] ...
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...
6.749254
6.834966
0.98746
if chunksize != 0: chunksize = float(chunksize) chunks = int(sum((ceil(l / chunksize) for l in self.trajectory_lengths(stride=stride, skip=skip)))) else: chunks = self.number_of_trajectories(stride) return chunks
def n_chunks(self, chunksize, stride=1, skip=0)
how many chunks an iterator of this sourcde will output, starting (eg. after calling reset()) Parameters ---------- chunksize stride skip
4.323742
5.076293
0.851752
r 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.tr...
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 ------- ...
3.869714
4.231728
0.914453
r if not IteratorState.is_uniform_stride(stride): return len(stride) return sum(self.trajectory_lengths(stride=stride, skip=skip))
def n_frames_total(self, stride=1, skip=0)
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. ...
15.03886
17.964901
0.837125
if isinstance(dimensions, int): ndim = 1 dimensions = slice(dimensions, dimensions + 1) elif isinstance(dimensions, (list, np.ndarray, tuple, slice)): if hasattr(dimensions, 'ndim') and dimensions.ndim > 1: raise ValueError('dimension indices ...
def get_output(self, dimensions=slice(0, None), stride=1, skip=0, chunk=None)
Maps all input data of this transformer and returns it as an array or list of arrays Parameters ---------- dimensions : list-like of indexes or slice, default=all indices of dimensions you like to keep. stride : int, default=1 only take every n'th frame. sk...
4.36121
4.376737
0.996452
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 + ext...
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 ...
3.607023
3.50865
1.028037
assert not self.uniform_stride, "requested random access indices, but is in uniform stride mode" if traj in self.traj_keys: return self.ra_indices_for_traj_dict[traj] else: return np.array([])
def ra_indices_for_traj(self, traj)
Gives the indices for a trajectory file index (without changing the order within the trajectory itself). :param traj: a trajectory file index :return: a Nx1 - np.array of the indices corresponding to the trajectory index
7.312238
7.694477
0.950323
return self._data_source.n_chunks(self.chunksize, stride=self.stride, skip=self.skip)
def n_chunks(self)
rough estimate of how many chunks will be processed
7.659755
6.792891
1.127613
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_itra...
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.
3.782432
3.591245
1.053237
if value != self._selected_itraj: self.state.itraj = value # TODO: this side effect is unexpected. self.state.t = 0
def _itraj(self, value)
Reader-internal property that tracks the upcoming trajectory index. Should not be used within iterator loop. Parameters ---------- value : int The upcoming trajectory index.
9.15722
10.302544
0.888831
try: return self._name except AttributeError: self._name = "%s.%s[%i]" % (self.__module__, self.__class__.__name__, next(Loggable.__ids)) return self._name
def name(self)
The name of this instance
4.681006
4.467106
1.047883
r # 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: ...
def _get_model_param_names(cls)
r"""Get parameter names for the model
5.572628
5.537081
1.00642
r 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. eli...
def update_model_params(self, **params)
r"""Update given model parameter if they are set to specific values
3.751834
3.699182
1.014234
r 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. ...
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 Pa...
2.864831
2.465394
1.162018
r self._check_samples_available() # TODO: can we use np.fromiter here? We would ne the same shape of every member for this! return [call_member(M, f, *args, **kwargs) for M in self.samples]
def sample_f(self, f, *args, **kwargs)
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 met...
20.405672
25.129276
0.812028
r vals = self.sample_f(f, *args, **kwargs) return _np.mean(vals, axis=0)
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 mod...
5.783718
8.908569
0.649231
r vals = self.sample_f(f, *args, **kwargs) return _np.std(vals, axis=0)
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 ...
6.346447
9.825319
0.645928
r vals = self.sample_f(f, *args, **kwargs) return confidence_interval(vals, conf=self.conf)
def sample_conf(self, f, *args, **kwargs)
r"""Sample confidence interval of numerical method f over all samples Calls f(\*args, \*\*kwargs) on all samples and computes the confidence interval. Size of confidence interval is given in the construction of the SampledModel. f must return a numerical value or an ndarray. Parameters...
7.552243
12.014211
0.628609
all_labels = [] for f in self.active_features: all_labels += f.describe() return all_labels
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.
6.82656
5.136455
1.329041
if exclude_symmetry_related: exclusions = [] exclusions.append("mass < 2") exclusions.append("(resname == VAL and name == CG)") exclusions.append("(resname == LEU and name == CD)") exclusions.append("(resname == PHE and name == CD) or (resnam...
def select_Heavy(self, exclude_symmetry_related=False)
Returns the indexes of all heavy atoms (Mass >= 2), optionally excluding symmetry-related heavy atoms. Parameters ---------- exclude_symmetry_related : boolean, default=False if True, exclude symmetry-related heavy atoms. Returns ------- indexes : nd...
2.05199
2.017084
1.017305
assert isinstance(excluded_neighbors,int) p = [] for i in range(len(sel)): for j in range(i + 1, len(sel)): # get ordered pair I = sel[i] J = sel[j] if (I > J): I = sel[j] ...
def pairs(sel, excluded_neighbors=0)
Creates all pairs between indexes. Will exclude closest neighbors up to :py:obj:`excluded_neighbors` The self-pair (i,i) is always excluded Parameters ---------- sel : ndarray((n), dtype=int) array with selected atom indexes excluded_neighbors: int, default = 0 ...
3.078712
2.925647
1.052318
pair_inds = np.array(pair_inds).astype(dtype=np.int, casting='safe') if pair_inds.ndim != 2: raise ValueError("pair indices has to be a matrix.") if pair_inds.shape[1] != pair_n: raise ValueError("pair indices shape has to be (x, %i)." % pair_n) if pa...
def _check_indices(self, pair_inds, pair_n=2)
ensure pairs are valid (shapes, all atom indices available?, etc.)
2.920023
2.657551
1.098765
self.add_selection(list(range(self.topology.n_atoms)), reference=reference, atom_indices=atom_indices, ref_atom_indices=ref_atom_indices)
def add_all(self, reference=None, atom_indices=None, ref_atom_indices=None)
Adds all atom coordinates to the feature list. The coordinates are flattened as follows: [x1, y1, z1, x2, y2, z2, ...] Parameters ---------- reference: mdtraj.Trajectory or None, default=None if given, all data is being aligned to the given reference with Trajectory.superpos...
2.766915
3.560427
0.77713
from .misc import SelectionFeature, AlignFeature if reference is None: f = SelectionFeature(self.topology, indexes) else: if not isinstance(reference, mdtraj.Trajectory): raise ValueError('reference is not a mdtraj.Trajectory object, but {}'.forma...
def add_selection(self, indexes, reference=None, atom_indices=None, ref_atom_indices=None)
Adds the coordinates of the selected atom indexes to the feature list. The coordinates of the selection [1, 2, ...] are flattened as follows: [x1, y1, z1, x2, y2, z2, ...] Parameters ---------- indexes : ndarray((n), dtype=int) array with selected atom indexes refere...
3.631353
3.446637
1.053593
r 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_fe...
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...
7.835314
7.138121
1.097672
# 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...
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 pai...
3.742072
3.659132
1.022667
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) ...
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...
6.217185
6.597256
0.94239
r 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) ...
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 (eithe...
7.540759
7.855439
0.959941
r from .distances import ResidueMinDistanceFeature if scheme != 'ca' and is_string(residue_pairs): if residue_pairs == 'all': self.logger.warning("Using all residue pairs with schemes like closest or closest-heavy is " "very time c...
def add_residue_mindist(self, residue_pairs='all', scheme='closest-heavy', ignore_nonprotein=True, threshold=None, periodic=True)
r""" Adds the minimum distance between residues to the feature list. See below how the minimum distance can be defined. If the topology generated out of :py:obj:`topfile` contains information on periodic boundary conditions, the minimum image convention will be used when computing distan...
6.516649
6.109779
1.066593
r from .misc import GroupCOMFeature f = GroupCOMFeature(self.topology, group_definitions , ref_geom=ref_geom, image_molecules=image_molecules, mass_weighted=mass_weighted) self.__add_feature(f)
def add_group_COM(self, group_definitions, ref_geom=None, image_molecules=False, mass_weighted=True,)
r""" Adds the centers of mass (COM) in cartesian coordinates of a group or groups of atoms. If these group definitions coincide directly with residues, use :obj:`add_residue_COM` instead. No periodic boundaries are taken into account. Parameters ---------- group_definit...
5.315385
5.687413
0.934588
r from .misc import ResidueCOMFeature from pyemma.coordinates.data.featurization.util import _atoms_in_residues assert scheme in ['all', 'backbone', 'sidechain'] residue_atoms = _atoms_in_residues(self.topology, residue_indices, subset_of_atom_idxs=self.topology.select(scheme),...
def add_residue_COM(self, residue_indices, scheme='all', ref_geom=None, image_molecules=False, mass_weighted=True,)
r""" Adds a per-residue center of mass (COM) in cartesian coordinates. No periodic boundaries are taken into account. Parameters ---------- residue_indices : iterable of integers The residue indices for which the COM will be computed. These are always zero-indexed t...
4.905323
4.481821
1.094493
r from .distances import GroupMinDistanceFeature # Some thorough input checking and reformatting group_definitions, group_pairs, distance_list, group_identifiers = \ _parse_groupwise_input(group_definitions, group_pairs, self.logger, 'add_group_mindist') distance_list...
def add_group_mindist(self, group_definitions, group_pairs='all', threshold=None, periodic=True)
r""" Adds the minimum distance between groups of atoms to the feature list. If the groups of atoms are identical to residues, use :py:obj:`add_residue_mindist <pyemma.coordinates.data.featurizer.MDFeaturizer.add_residue_mindist>`. Parameters ---------- group_definitions : list ...
6.183005
6.666205
0.927515
from .angles import AngleFeature indexes = self._check_indices(indexes, pair_n=3) f = AngleFeature(self.topology, indexes, deg=deg, cossin=cossin, periodic=periodic) self.__add_feature(f)
def add_angles(self, indexes, deg=False, cossin=False, periodic=True)
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. ...
5.736354
6.420563
0.893435
from .angles import DihedralFeature indexes = self._check_indices(indexes, pair_n=4) f = DihedralFeature(self.topology, indexes, deg=deg, cossin=cossin, periodic=periodic) self.__add_feature(f)
def add_dihedrals(self, indexes, deg=False, cossin=False, periodic=True)
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. ...
5.013339
6.149021
0.815307
from .angles import BackboneTorsionFeature f = BackboneTorsionFeature( self.topology, selstr=selstr, deg=deg, cossin=cossin, periodic=periodic) self.__add_feature(f)
def add_backbone_torsions(self, selstr=None, deg=False, cossin=False, periodic=True)
Adds all backbone phi/psi angles or the ones specified in :obj:`selstr` to the feature list. Parameters ---------- selstr : str, optional, default = "" selection string specifying the atom selection used to specify a specific set of backbone angles If "" (default), all ...
3.705222
4.56845
0.811046
from .angles import SideChainTorsions f = SideChainTorsions( self.topology, selstr=selstr, deg=deg, cossin=cossin, periodic=periodic, which=['chi1']) self.__add_feature(f)
def add_chi1_torsions(self, selstr="", deg=False, cossin=False, periodic=True)
Adds all chi1 angles or the ones specified in :obj:`selstr` to the feature list. Parameters ---------- selstr : str, optional, default = "" selection string specifying the atom selection used to specify a specific set of backbone angles If "" (default), all chi1 angles ...
5.030628
5.70496
0.881799
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...
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)
5.900913
6.267822
0.941462
r from .misc import MinRmsdFeature f = MinRmsdFeature(ref, ref_frame=ref_frame, atom_indices=atom_indices, topology=self.topology, precentered=precentered) self.__add_feature(f)
def add_minrmsd_to_ref(self, ref, ref_frame=0, atom_indices=None, precentered=False)
r""" Adds the minimum root-mean-square-deviation (minrmsd) with respect to a reference structure to the feature list. Parameters ---------- ref: Reference structure for computing the minrmsd. Can be of two types: 1. :py:obj:`mdtraj.Trajectory` object ...
4.331598
4.835542
0.895783
description = kwargs.pop('description', None) f = CustomFeature(func, dim=dim, description=description, fun_args=args, fun_kwargs=kwargs) self.add_custom_feature(f)
def add_custom_func(self, func, dim, *args, **kwargs)
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...
4.166166
4.03796
1.03175
custom_feats = [f for f in self.active_features if isinstance(f, CustomFeature)] for f in custom_feats: self.active_features.remove(f)
def remove_all_custom_funcs(self)
Remove all instances of CustomFeature from the active feature list.
3.72518
2.301425
1.61864
dim = sum(f.dimension for f in self.active_features) return dim
def dimension(self)
current dimension due to selected features Returns ------- dim : int total dimension due to all selection features
10.949175
8.672123
1.262571
# 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. ...
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 t...
3.929763
3.983519
0.986505
# 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 = [] sta...
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...
2.927485
2.746864
1.065755
# 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...
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,)...
3.207072
2.964455
1.081842
# 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(c...
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-m...
4.216394
4.139594
1.018553
import msmtools.estimation as me # Decompose count matrix by SVD: if lcc is not None: Ct_svd = me.largest_connected_submatrix(Ct, lcc=lcc) N1 = Ct.shape[0] else: Ct_svd = Ct V, s, W = scl.svd(Ct_svd, full_matrices=False) # Make rank decision: if rank_ind is None:...
def oom_components(Ct, C2t, rank_ind=None, lcc=None, tol_one=1e-2)
Compute OOM components and eigenvalues from count matrices: Parameters ---------- Ct : ndarray(N, N) count matrix from data C2t : sparse csc-matrix (N*N, N) two-step count matrix from data for all states, columns enumerate intermediate steps. rank_ind : ndarray(N, dtype=bool...
2.812691
2.606171
1.079243
import msmtools.estimation as me # Compute equilibrium transition matrix: Ct_Eq = np.einsum('j,jkl,lmn,n->km', omega, Xi, Xi, sigma) # Remove negative entries: Ct_Eq[Ct_Eq < 0.0] = 0.0 # Compute transition matrix after symmetrization: pi_r = np.sum(Ct_Eq, axis=1) if reversible: ...
def equilibrium_transition_matrix(Xi, omega, sigma, reversible=True, return_lcc=True)
Compute equilibrium transition matrix from OOM components: Parameters ---------- Xi : ndarray(M, N, M) matrix of set-observable operators omega: ndarray(M,) information state vector of OOM sigma : ndarray(M,) evaluator of OOM reversible : bool, optional, default=True ...
2.801619
2.600765
1.077229
r from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer return MDFeaturizer(topfile)
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>` ...
7.235846
4.348847
1.663854
r from pyemma.coordinates.data.sources_merger import SourcesMerger return SourcesMerger(sources, chunk=chunksize)
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. Al...
10.390482
6.48841
1.601391
r from pyemma.coordinates.pipelines import Pipeline if not isinstance(stages, list): stages = [stages] p = Pipeline(stages, param_stride=stride, chunksize=chunksize) if run: p.parametrize() return p
def pipeline(stages, run=True, stride=1, chunksize=None)
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 ...
5.319258
5.021873
1.059218
r from pyemma.coordinates.clustering.kmeans import KmeansClustering from pyemma.coordinates.pipelines import Discretizer if cluster is None: _logger.warning('You did not specify a cluster algorithm.' ' Defaulting to kmeans(k=100)') cluster = KmeansClustering(n_clu...
def discretizer(reader, transform=None, cluster=None, run=True, stride=1, chunksize=None)
r""" Specialized pipeline: From trajectories to clustering. Constructs a pipeline that consists of three stages: 1. an input stage (mandatory) 2. a transformer stage (optional) 3. a clustering stage (mandatory) This function is identical to calling :func:`pipeline` with the three sta...
4.491028
4.638268
0.968255
r 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) fr...
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 :...
3.093055
3.454566
0.895353
r 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)['c...
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 dis...
4.253924
4.695833
0.905894
r 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, ...
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 returne...
5.425477
4.916599
1.103502
disc = np.zeros(100, dtype=int) divides = np.concatenate([divides, [100]]) for i in range(len(divides)-1): disc[divides[i]:divides[i+1]] = i+1 return disc[self.dtraj_T100K_dt10]
def dtraj_T100K_dt10_n(self, divides)
100K frames trajectory at timestep 10, arbitrary n-state discretization.
2.446596
2.433502
1.005381
from msmtools.generation import generate_traj return generate_traj(self._P, N, start=start, stop=stop, dt=dt)
def generate_traj(self, N, start=None, stop=None, dt=1)
Generates a random trajectory of length N with time step dt
5.335963
5.459531
0.977367
from msmtools.generation import generate_trajs return generate_trajs(self._P, M, N, start=start, stop=stop, dt=dt)
def generate_trajs(self, M, N, start=None, stop=None, dt=1)
Generates M random trajectories of length N each with time step dt
4.525696
4.525112
1.000129
# norms evnorms = _np.abs(evals) # sort I = _np.argsort(evnorms)[::-1] # permute evals2 = evals[I] evecs2 = evecs[:, I] # done return evals2, evecs2
def sort_by_norm(evals, evecs)
Sorts the eigenvalues and eigenvectors by descending norm of the eigenvalues Parameters ---------- evals: ndarray(n) eigenvalues evecs: ndarray(n,n) eigenvectors in a column matrix Returns ------- (evals, evecs) : ndarray(m), ndarray(n,m) the sorted eigenvalues and ...
3.250965
3.61049
0.900422
# 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 schu...
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...
4.761008
4.566274
1.042646