code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if atomic_radius_data is None: atomic_radius_data = settings['defaults']['atomic_radius_data'] def complete_calculation(): old_index = self.index self.index = range(len(self)) fragments = self._divide_et_impera(offset=offset) position...
def get_bonds(self, self_bonding_allowed=False, offset=3, modified_properties=None, use_lookup=False, set_lookup=True, atomic_radius_data=None )
Return a dictionary representing the bonds. .. warning:: This function is **not sideeffect free**, since it assigns the output to a variable ``self._metadata['bond_dict']`` if ``set_lookup`` is ``True`` (which is the default). This is necessary for performance reasons. ...
3.413551
3.129488
1.09077
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] exclude = set() if exclude is None else exclude bond_dict = self.get_bonds(use_lookup=use_lookup) i = index_of_atom if n_sphere != 0: visited = set([i]) | exclude t...
def get_coordination_sphere( self, index_of_atom, n_sphere=1, give_only_index=False, only_surface=True, exclude=None, use_lookup=None)
Return a Cartesian of atoms in the n-th coordination sphere. Connected means that a path along covalent bonds exists. Args: index_of_atom (int): give_only_index (bool): If ``True`` a set of indices is returned. Otherwise a new Cartesian instance. n_s...
2.301962
2.119909
1.085877
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] included_atoms_set = set(sliced_cartesian.index) assert included_atoms_set.issubset(set(self.index)), \ 'The sliced Cartesian has to be a subset of the bigger frame' bond_dic = self.g...
def _preserve_bonds(self, sliced_cartesian, use_lookup=None)
Is called after cutting geometric shapes. If you want to change the rules how bonds are preserved, when applying e.g. :meth:`Cartesian.cut_sphere` this is the function you have to modify. It is recommended to inherit from the Cartesian class to tailor it for your pro...
3.324643
3.241673
1.025595
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] molecule = self.get_distance_to(origin) if outside_sliced: ...
def cut_sphere( self, radius=15., origin=None, outside_sliced=True, preserve_bonds=False)
Cut a sphere specified by origin and radius. Args: radius (float): origin (list): Please note that you can also pass an integer. In this case it is interpreted as the index of the atom which is taken as origin. outside_sliced (bool): Atoms out...
2.677031
2.883679
0.928338
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] b = a if b is None else b c = a if c is None else c sides =...
def cut_cuboid( self, a=20, b=None, c=None, origin=None, outside_sliced=True, preserve_bonds=False)
Cut a cuboid specified by edge and radius. Args: a (float): Value of the a edge. b (float): Value of the b edge. Takes value of a if None. c (float): Value of the c edge. Takes value of a if None. origin (list): Please note that you can also pass an ...
2.37371
2.534187
0.936675
try: mass = self['mass'].values except KeyError: mass = self.add_data('mass')['mass'].values pos = self.loc[:, ['x', 'y', 'z']].values return (pos * mass[:, None]).sum(axis=0) / self.get_total_mass()
def get_barycenter(self)
Return the mass weighted average location. Args: None Returns: :class:`numpy.ndarray`:
4.419139
4.922557
0.897732
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values else: indices = np.array(indices) if len(indices.shape) == 1: ...
def get_bond_lengths(self, indices)
Return the distances between given atoms. Calculates the distance between the atoms with indices ``i`` and ``b``. The indices can be given in three ways: * As simple list ``[i, b]`` * As list of lists: ``[[i1, b1], [i2, b2]...]`` * As :class:`pd.DataFrame` where ``i`` i...
2.238218
2.128798
1.0514
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values a_pos = self.loc[indices.loc[:, 'a'], coords].values else: indices = np.arra...
def get_angle_degrees(self, indices)
Return the angles between given atoms. Calculates the angle in degrees between the atoms with indices ``i, b, a``. The indices can be given in three ways: * As simple list ``[i, b, a]`` * As list of lists: ``[[i1, b1, a1], [i2, b2, a2]...]`` * As :class:`pd.DataFrame` w...
1.942099
1.875951
1.035261
coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values a_pos = self.loc[indices.loc[:, 'a'], coords].values d_pos = self.loc[indices.loc[:,...
def get_dihedral_degrees(self, indices, start_row=0)
Return the dihedrals between given atoms. Calculates the dihedral angle in degrees between the atoms with indices ``i, b, a, d``. The indices can be given in three ways: * As simple list ``[i, b, a, d]`` * As list of lists: ``[[i1, b1, a1, d1], [i2, b2, a2, d2]...]`` * ...
2.261529
2.23455
1.012074
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] fragments = [] pending = set(self.index) self.get_bonds(use_lookup=use_lookup) while pending: index = self.get_coordination_sphere( pending.pop(), use_lookup=...
def fragmentate(self, give_only_index=False, use_lookup=None)
Get the indices of non bonded parts in the molecule. Args: give_only_index (bool): If ``True`` a set of indices is returned. Otherwise a new Cartesian instance. use_lookup (bool): Use a lookup variable for :meth:`~chemcoord.Cartesian.get_bonds`. ...
4.047422
3.698124
1.094453
return {j: bond_dict[j] & set(self.index) for j in self.index}
def restrict_bond_dict(self, bond_dict)
Restrict a bond dictionary to self. Args: bond_dict (dict): Look into :meth:`~chemcoord.Cartesian.get_bonds`, to see examples for a bond_dict. Returns: bond dictionary
8.153941
10.68827
0.762887
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] exclude = [tuple[0] for tuple in list_of_indextuples] index_of_atom = list_of_indextuples[0][1] fragment_index = self.get_coordination_sphere( index_of_atom, exclude=set(exclude), n_s...
def get_fragment(self, list_of_indextuples, give_only_index=False, use_lookup=None)
Get the indices of the atoms in a fragment. The list_of_indextuples contains all bondings from the molecule to the fragment. ``[(1,3), (2,4)]`` means for example that the fragment is connected over two bonds. The first bond is from atom 1 in the molecule to atom 3 in the fragment. The s...
3.909871
3.678625
1.062862
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] if pd.api.types.is_list_like(fragments): for fragment in fragments: try: index_of_all_fragments |= fragment.index except NameError: ...
def get_without(self, fragments, use_lookup=None)
Return self without the specified fragments. Args: fragments: Either a list of :class:`~chemcoord.Cartesian` or a :class:`~chemcoord.Cartesian`. use_lookup (bool): Use a lookup variable for :meth:`~chemcoord.Cartesian.get_bonds`. The default is ...
3.38668
3.051641
1.10979
n1 = pos1.shape[0] n2 = pos2.shape[0] D = np.empty((n1, n2)) for i in range(n1): for j in range(n2): D[i, j] = np.sqrt(((pos1[i] - pos2[j])**2).sum()) return D
def _jit_pairwise_distances(pos1, pos2)
Optimized function for calculating the distance between each pair of points in positions1 and positions2. Does use python mode as fallback, if a scalar and not an array is given.
1.752663
1.778145
0.985669
def calculate_inertia_tensor(molecule): masses = molecule.loc[:, 'mass'].values pos = molecule.loc[:, ['x', 'y', 'z']].values inertia = np.sum( masses[:, None, None] * ((pos**2).sum(axis=1)[:, None, None] * np.identi...
def get_inertia(self)
Calculate the inertia tensor and transforms along rotation axes. This function calculates the inertia tensor and returns a 4-tuple. The unit is ``amu * length-unit-of-xyz-file**2`` Args: None Returns: dict: The returned dictionary has four poss...
3.360845
2.745002
1.224351
if old_basis is None: old_basis = np.identity(3) is_rotation_matrix = np.isclose(np.linalg.det(new_basis), 1) if not is_rotation_matrix and orthonormalize: new_basis = xyz_functions.orthonormalize_righthanded(new_basis) is_rotation_matrix = True ...
def basistransform(self, new_basis, old_basis=None, orthonormalize=True)
Transform the frame to a new basis. This function transforms the cartesian coordinates from an old basis to a new one. Please note that old_basis and new_basis are supposed to have full Rank and consist of three linear independent vectors. If rotate_only is True, it is asserted,...
2.551367
2.48156
1.02813
if origin is None: origin = np.zeros(3) elif pd.api.types.is_list_like(origin): origin = np.array(origin, dtype='f8') else: origin = self.loc[origin, ['x', 'y', 'z']] if other_atoms is None: other_atoms = self.index new =...
def get_distance_to(self, origin=None, other_atoms=None, sort=False)
Return a Cartesian with a column for the distance from origin.
2.633684
2.546389
1.034282
output = self if inplace else self.copy() new_index = [rename_dict.get(key, key) for key in self.index] output.index = new_index if not inplace: return output
def change_numbering(self, rename_dict, inplace=False)
Return the reindexed version of Cartesian. Args: rename_dict (dict): A dictionary mapping integers on integers. Returns: Cartesian: A renamed copy according to the dictionary passed.
2.563557
3.018317
0.849333
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] def get_chem_env(self, i, n_sphere): env_index = self.get_coordination_sphere( i, n_sphere=n_sphere, only_surface=False, give_only_index=True, use_lookup=use_lookup) ...
def partition_chem_env(self, n_sphere=4, use_lookup=None)
This function partitions the molecule into subsets of the same chemical environment. A chemical environment is specified by the number of surrounding atoms of a certain kind around an atom with a certain atomic number represented by a tuple of a string and a frozenset of tuples....
3.798836
3.467073
1.09569
m1 = (self - self.get_centroid()).sort_index() m2 = (other - other.get_centroid()).sort_index() if indices is not None and ignore_hydrogens: message = 'Indices != None and ignore_hydrogens == True is invalid' raise IllegalArgumentCombination(message) elif...
def align(self, other, indices=None, ignore_hydrogens=False)
Align two Cartesians. Minimize the RMSD (root mean squared deviation) between ``self`` and ``other``. Returns a tuple of copies of ``self`` and ``other`` where both are centered around their centroid and ``other`` is rotated unto ``self``. The rotation minimises the di...
2.559279
2.340514
1.093469
def make_subset_similar(m1, subset1, m2, subset2, index_dct): coords = ['x', 'y', 'z'] index1 = list(subset1) for m1_i in index1: dist_m2_to_m1_i = m2.get_distance_to(m1.loc[m1_i, coords], ...
def reindex_similar(self, other, n_sphere=4)
Reindex ``other`` to be similarly indexed as ``self``. Returns a reindexed copy of ``other`` that minimizes the distance for each atom to itself in the same chemical environemt from ``self`` to ``other``. Read more about the definition of the chemical environment in :func:`Carte...
2.425978
2.363022
1.026642
if not date_str: return None try: date = ciso8601.parse_datetime(date_str) if not date: date = arrow.get(date_str).datetime except TypeError: date = arrow.get(date_str[0]).datetime return date
def parse_date(date_str)
Parse elastic datetime string.
2.907105
2.7163
1.070245
dates = [config.LAST_UPDATED, config.DATE_CREATED] for field, field_schema in schema.items(): if field_schema['type'] == 'datetime': dates.append(field) return dates
def get_dates(schema)
Return list of datetime fields for given schema.
4.158156
3.472861
1.197329
doc = hit.get('_source', {}) doc.setdefault(config.ID_FIELD, hit.get('_id')) doc.setdefault('_type', hit.get('_type')) if hit.get('highlight'): doc['es_highlight'] = hit.get('highlight') if hit.get('inner_hits'): doc['_inner_hits'] = {} for key, value in hit.get('inner_...
def format_doc(hit, schema, dates)
Format given doc to match given schema.
2.132277
2.140286
0.996258
filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: filters.extend(query_filter['and']) else: filters.append(query_filter) if filters: ...
def set_filters(query, base_filters)
Put together all filters we have and set them as 'and' filter within filtered query. :param query: elastic query being constructed :param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup)
2.203123
2.324559
0.94776
urls = [url] if isinstance(url, str) else url kwargs.setdefault('serializer', ElasticJSONSerializer()) es = elasticsearch.Elasticsearch(urls, **kwargs) return es
def get_es(url, **kwargs)
Create elasticsearch client instance. :param url: elasticsearch url
4.56776
6.656012
0.686261
elastic_query, filters = {"query": {"filtered": {}}}, [] for key in doc.keys(): if key == 'q': elastic_query['query']['filtered']['query'] = _build_query_string(doc['q']) else: _value = doc[key] filters.append({"terms": {key: _value}} if isinstance(_valu...
def build_elastic_query(doc)
Build a query which follows ElasticSearch syntax from doc. 1. Converts {"q":"cricket"} to the below elastic query:: { "query": { "filtered": { "query": { "query_string": { "query": "cricket", ...
2.931299
3.49444
0.838847
def _is_phrase_search(query_string): clean_query = query_string.strip() return clean_query and clean_query.startswith('"') and clean_query.endswith('"') def _get_phrase(query_string): return query_string.strip().strip('"') if _is_phrase_search(q): query = {'match_phras...
def _build_query_string(q, default_field=None, default_operator='AND')
Build ``query_string`` object from ``q``. :param q: q of type String :param default_field: default_field :return: dictionary object.
2.629441
2.645481
0.993937
if isinstance(value, ObjectId): return str(value) return super(ElasticJSONSerializer, self).default(value)
def default(self, value)
Convert mongo.ObjectId.
5.896954
4.206917
1.401728
if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations']
def extra(self, response)
Add extra info to response.
3.471884
2.665884
1.302339
elasticindexes = self._get_indexes() for index, settings in elasticindexes.items(): es = settings['resource'] if not es.indices.exists(index): self.create_index(index, settings.get('index_settings'), es) continue else: ...
def init_index(self, app=None)
Create indexes and put mapping.
4.576737
4.392373
1.041974
indexes = {} for resource in self._get_elastic_resources(): try: index = self._resource_index(resource) except KeyError: # ignore missing continue if index not in indexes: indexes.update({ ...
def _get_indexes(self)
Based on the resource definition calculates the index definition
4.285861
4.008929
1.069079
properties = {} for field, field_schema in schema.items(): field_mapping = self._get_field_mapping(field_schema) if field_mapping: properties[field] = field_mapping return {'properties': properties}
def _get_mapping(self, schema)
Get mapping for given resource or item schema. :param schema: resource or dict/list type item schema
2.638608
3.212946
0.821243
if 'mapping' in schema: return schema['mapping'] elif schema['type'] == 'dict' and 'schema' in schema: return self._get_mapping(schema['schema']) elif schema['type'] == 'list' and 'schema' in schema.get('schema', {}): return self._get_mapping(schema['...
def _get_field_mapping(self, schema)
Get mapping for single field schema. :param schema: field schema
2.235317
2.288811
0.976628
if index is None: index = self.index if es is None: es = self.es try: alias = index index = generate_index_name(alias) args = {'index': index} if settings: args['body'] = settings es.in...
def create_index(self, index=None, settings=None, es=None)
Create new index and ignore if it exists already.
3.023712
2.903253
1.041491
for resource, resource_config in self._get_elastic_resources().items(): datasource = resource_config.get('datasource', {}) if not is_elastic(datasource): continue if datasource.get('source', resource) != resource: # only put mapping for core types ...
def put_mapping(self, app, index=None)
Put mapping for elasticsearch for current schema. It's not called automatically now, but rather left for user to call it whenever it makes sense.
4.496835
4.472085
1.005534
mapping = self.es.indices.get_mapping(index=index, doc_type=doc_type) return next(iter(mapping.values()))
def get_mapping(self, index, doc_type=None)
Get mapping for index. :param index: index name
2.812713
3.948585
0.712334
settings = self.es.indices.get_settings(index=index) return next(iter(settings.values()))
def get_settings(self, index)
Get settings for index. :param index: index name
4.877334
7.054423
0.691387
try: info = self.es.indices.get_alias(name=alias) return next(iter(info.keys())) except elasticsearch.exceptions.NotFoundError: return alias
def get_index_by_alias(self, alias)
Get index name for given alias. If there is no alias assume it's an index. :param alias: alias name
3.213871
3.322171
0.967401
args = getattr(req, 'args', request.args if request else {}) or {} source_config = config.SOURCES[resource] if args.get('source'): query = json.loads(args.get('source')) if 'filtered' not in query.get('query', {}): _query = query.get('query') ...
def find(self, resource, req, sub_resource_lookup)
Find documents for resource.
2.793869
2.75271
1.014952
try: return self.app.config.get('ELASTICSEARCH_AUTO_AGGREGATIONS') or \ bool(req.args and int(req.args.get('aggregations'))) except (AttributeError, TypeError): return False
def should_aggregate(self, req)
Check the environment variable and the given argument parameter to decide if aggregations needed. argument value is expected to be '0' or '1'
4.726035
4.626879
1.02143
try: return bool(req.args and int(req.args.get('es_highlight', 0))) except (AttributeError, TypeError): return False
def should_highlight(self, req)
Check the given argument parameter to decide if highlights needed. argument value is expected to be '0' or '1'
4.842413
5.029122
0.962875
try: return req.args and json.loads(req.args.get('projections', [])) except (AttributeError, TypeError): return False
def should_project(self, req)
Check the given argument parameter to decide if projections needed. argument value is expected to be a list of strings
6.721418
5.519775
1.217698
try: args = getattr(req, 'args', {}) return ','.join(json.loads(args.get('projections'))) except (AttributeError, TypeError): return None
def get_projected_fields(self, req)
Returns the projected fields from request.
5.590727
5.036602
1.11002
if config.ID_FIELD in lookup: return self._find_by_id(resource=resource, _id=lookup[config.ID_FIELD], parent=lookup.get('parent')) else: args = self._es_args(resource) filters = [{'term': {key: val}} for key, val in lookup.items()] query = {'quer...
def find_one(self, resource, req, **lookup)
Find single document, if there is _id in lookup use that, otherwise filter.
3.73696
3.384592
1.104109
def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('found', False) args = self._es_args(resource) try: # set the parent if available if parent: args['parent'] = parent ...
def _find_by_id(self, resource, _id, parent=None)
Find the document by Id. If parent is not provided then on routing exception try to find using search.
3.256015
3.103214
1.04924
return self._find_by_id(resource=resource, _id=_id)
def find_one_raw(self, resource, _id)
Find document by id.
5.621231
4.252763
1.321783
args = self._es_args(resource) return self._parse_hits(self.elastic(resource).mget(body={'ids': ids}, **args), resource)
def find_list_of_ids(self, resource, ids, client_projection=None)
Find documents by ids.
9.006026
7.848624
1.147466
ids = [] kwargs.update(self._es_args(resource)) for doc in doc_or_docs: self._update_parent_args(resource, kwargs, doc) _id = doc.pop('_id', None) res = self.elastic(resource).index(body=doc, id=_id, **kwargs) doc.setdefault('_id', res.get...
def insert(self, resource, doc_or_docs, **kwargs)
Insert document, it must be new if there is ``_id`` in it.
3.724905
3.61272
1.031053
kwargs.update(self._es_args(resource)) parent_type = self._get_parent_type(resource) if parent_type: for doc in docs: if doc.get(parent_type.get('field')): doc['_parent'] = doc.get(parent_type.get('field')) res = bulk(self.elastic...
def bulk_insert(self, resource, docs, **kwargs)
Bulk insert documents.
3.41506
3.411533
1.001034
args = self._es_args(resource, refresh=True) if self._get_retry_on_conflict(): args['retry_on_conflict'] = self._get_retry_on_conflict() updates.pop('_id', None) updates.pop('_type', None) self._update_parent_args(resource, args, updates) return self...
def update(self, resource, id_, updates)
Update document in index.
4.437579
4.158959
1.066993
args = self._es_args(resource, refresh=True) document.pop('_id', None) document.pop('_type', None) self._update_parent_args(resource, args, document) return self.elastic(resource).index(body=document, id=id_, **args)
def replace(self, resource, id_, document)
Replace document in index.
6.030307
5.902105
1.021721
kwargs.update(self._es_args(resource)) if parent: kwargs['parent'] = parent if lookup: if lookup.get('_id'): try: return self.elastic(resource).delete(id=lookup.get('_id'), refresh=True, **kwargs) except elasti...
def remove(self, resource, lookup=None, parent=None, **kwargs)
Remove docs for resource. :param resource: resource name :param lookup: filter :param parent: parent id
5.95393
6.396933
0.930748
args = self._es_args(resource) res = self.elastic(resource).count(body={'query': {'match_all': {}}}, **args) return res.get('count', 0) == 0
def is_empty(self, resource)
Test if there is no document for resource. :param resource: resource name
4.49157
5.317111
0.844739
if not index: index = self.index if not app: app = self.app if not es: es = self.es if not settings: return for alias, old_settings in self.es.indices.get_settings(index=index).items(): try: ...
def put_settings(self, app=None, index=None, settings=None, es=None)
Modify index settings. Index must exist already.
2.569127
2.608585
0.984874
datasource = self.get_datasource(resource) schema = {} schema.update(config.DOMAIN[datasource[0]].get('schema', {})) schema.update(config.DOMAIN[resource].get('schema', {})) dates = get_dates(schema) docs = [] for hit in hits.get('hits', {}).get('hits', [...
def _parse_hits(self, hits, resource)
Parse hits response into documents.
4.59096
4.275062
1.073893
datasource = self.get_datasource(resource) args = { 'index': self._resource_index(resource), 'doc_type': datasource[0], } if source_projections: args['_source'] = source_projections if refresh: args['refresh'] = refresh ...
def _es_args(self, resource, refresh=None, source_projections=None)
Get index and doctype args.
2.851636
2.677012
1.065231
parent_type = self._get_parent_type(resource) if parent_type and document: return document.get(parent_type.get('field')) return None
def get_parent_id(self, resource, document)
Get the Parent Id of the document :param resource: resource name :param document: document containing the parent id
3.6241
4.652437
0.778968
datasource = self.get_datasource(resource) keys = datasource[2].keys() return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED])
def _fields(self, resource)
Get projection fields for given resource.
10.190112
7.949804
1.281807
datasource = self.get_datasource(resource) indexes = self._resource_config(resource, 'INDEXES') or {} default_index = self._resource_config(resource, 'INDEX') return indexes.get(datasource[0], default_index)
def _resource_index(self, resource)
Get index for given resource. by default it will be `self.index`, but it can be overriden via app.config :param resource: resource name
4.624511
4.605023
1.004232
if self._resource_config(resource, 'FORCE_REFRESH', True): self.elastic(resource).indices.refresh(self._resource_index(resource))
def _refresh_resource_index(self, resource)
Refresh index for given resource. :param resource: resource name
9.805661
11.550525
0.848936
px = 'ELASTICSEARCH' if resource and config.DOMAIN[resource].get('elastic_prefix'): px = config.DOMAIN[resource].get('elastic_prefix') return px
def _resource_prefix(self, resource=None)
Get elastic prefix for given resource. Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``.
7.611208
6.065035
1.254932
px = self._resource_prefix(resource) return self.app.config.get('%s_%s' % (px, key), default)
def _resource_config(self, resource=None, key=None, default=None)
Get config using resource elastic prefix (if any).
5.388653
4.134207
1.303431
px = self._resource_prefix(resource) if px not in self.elastics: url = self._resource_config(resource, 'URL') assert url, 'no url for %s' % px self.elastics[px] = get_es(url, **self.kwargs) return self.elastics[px]
def elastic(self, resource=None)
Get ElasticSearch instance for given resource.
4.755963
4.300169
1.105995
def iter_chunks(f): while True: chunk = f.read(chunk_size) if not chunk: break yield chunk sig = hashlib.md5() with open(fname, 'rb') as f: for chunk in iter_chunks(f): sig.update(chunk) # data = f.read() ...
def get_md5sum(fname, chunk_size=1024)
Returns the MD5 checksum of a file. Args: fname (str): Filename chunk_size (Optional[int]): Size (in Bytes) of the chunks that should be read in at once. Increasing chunk size reduces the number of reads required, but increases the memory usage. Defaults to 1024. Return...
2.135809
2.211224
0.965895
# Check if the file exists if not os.path.isfile(fname): # print('File does not exist.') return False # Check file size, withe the given tolerances if size_guess is not None: size = os.path.getsize(fname) tol = atol + rtol * size_guess if abs(size - size_gu...
def h5_file_exists(fname, size_guess=None, rtol=0.1, atol=1., dsets={})
Returns ``True`` if an HDF5 file exists, has the expected file size, and contains (at least) the given datasets, with the correct shapes. Args: fname (str): Filename to check. size_guess (Optional[int]): Expected size (in Bytes) of the file. If ``None`` (the default), then filesize ...
2.114007
2.083591
1.014598
# Determine the filename if fname is None: fname = url.split('/')[-1] # Check if the file already exists on disk if (not clobber) and os.path.isfile(fname): print('Checking existing file to see if MD5 sum matches ...') md5_existing = get_md5sum(fname, chunk_size=chunk_size...
def download_and_verify(url, md5sum, fname=None, chunk_size=1024, clobber=False, verbose=True)
Download a file and verify the MD5 sum. Args: url (str): The URL to download. md5sum (str): The expected MD5 sum. fname (Optional[str]): The filename to store the downloaded file in. If `None`, infer the filename from the URL. Defaults to `None`. chunk_size (Optional[int...
2.032316
2.017071
1.007558
# Determine the filename if fname is None: fname = url.split('/')[-1] # Stream the URL as a file, copying to local disk with contextlib.closing(requests.get(url, stream=True)) as r: try: r.raise_for_status() except requests.exceptions.HTTPError as error: ...
def download(url, fname=None)
Downloads a file. Args: url (str): The URL to download. fname (Optional[str]): The filename to store the downloaded file in. If `None`, take the filename from the URL. Defaults to `None`. Returns: The filename the URL was downloaded to. Raises: requests.excep...
2.467746
2.756084
0.895381
url = '{}/api/datasets/:persistentId?persistentId=doi:{}'.format(dataverse, doi) r = requests.get(url) try: r.raise_for_status() except requests.exceptions.HTTPError as error: print('Error looking up DOI "{}" in the Harvard Dataverse.'.format(doi)) print(r.text) ra...
def dataverse_search_doi(doi)
Fetches metadata pertaining to a Digital Object Identifier (DOI) in the Harvard Dataverse. Args: doi (str): The Digital Object Identifier (DOI) of the entry in the Dataverse. Raises: requests.exceptions.HTTPError: The given DOI does not exist, or there was a problem...
3.183749
2.925423
1.088304
metadata = dataverse_search_doi(doi) def requirements_match(metadata): for key in file_requirements.keys(): if metadata['dataFile'].get(key, None) != file_requirements[key]: return False return True for file_metadata in metadata['data']['latestVersion']['fi...
def dataverse_download_doi(doi, local_fname=None, file_requirements={}, clobber=False)
Downloads a file from the Dataverse, using a DOI and set of metadata parameters to locate the file. Args: doi (str): Digital Object Identifier (DOI) containing the file. local_fname (Optional[str]): Local filename to download the file to. If `None`, then use the filename provided by...
3.106294
3.027181
1.026134
if blockchain == 'bitcoin': return btc_address_reencode(address, **blockchain_opts) else: raise ValueError("Unknown blockchain '{}'".format(blockchain))
def address_reencode(address, blockchain='bitcoin', **blockchain_opts)
Reencode an address
2.691266
2.648604
1.016108
if len(o) == 0: return dict( _type='np.dtype', descr=str(o)) return dict( _type='np.dtype', descr=o.descr)
def serialize_dtype(o)
Serializes a :obj:`numpy.dtype`. Args: o (:obj:`numpy.dtype`): :obj:`dtype` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
4.651078
5.061706
0.918876
if isinstance(d['descr'], six.string_types): return np.dtype(d['descr']) descr = [] for col in d['descr']: col_descr = [] for c in col: if isinstance(c, six.string_types): col_descr.append(str(c)) elif type(c) is list: col_...
def deserialize_dtype(d)
Deserializes a JSONified :obj:`numpy.dtype`. Args: d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object. Returns: A :obj:`dtype` object.
2.042231
2.21901
0.920334
if o.flags['C_CONTIGUOUS']: o_data = o.data else: o_data = np.ascontiguousarray(o).data data_b64 = base64.b64encode(o_data) return dict( _type='np.ndarray', data=data_b64.decode('utf-8'), dtype=o.dtype, shape=o.shape)
def serialize_ndarray_b64(o)
Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are human-readable, but the array data itself is binary64 encoded. Args: o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
2.339761
2.327467
1.005282
if isinstance(o, tuple): return dict(_type='tuple', items=o) elif isinstance(o, list): return [hint_tuples(el) for el in o] else: return o
def hint_tuples(o)
Annotates tuples before JSON serialization, so that they can be reconstructed during deserialization. Each tuple is converted into a dictionary of the form: {'_type': 'tuple', 'items': (...)} This function acts recursively on lists, so that tuples nested inside a list (or doubly nested, triply...
2.996722
2.553802
1.173435
return dict( _type='np.ndarray', dtype=o.dtype, value=hint_tuples(o.tolist()))
def serialize_ndarray_readable(o)
Serializes a :obj:`numpy.ndarray` in a human-readable format. Args: o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
13.331652
17.704573
0.753006
with io.BytesIO() as f: np.save(f, o) f.seek(0) serialized = json.dumps(f.read().decode('latin-1')) return dict( _type='np.ndarray', npy=serialized)
def serialize_ndarray_npy(o)
Serializes a :obj:`numpy.ndarray` using numpy's built-in :obj:`save` function. This produces totally unreadable (and very un-JSON-like) results (in "npy" format), but it's basically guaranteed to work in 100% of cases. Args: o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized. Returns: ...
3.563575
4.193591
0.849767
with io.BytesIO() as f: f.write(json.loads(d['npy']).encode('latin-1')) f.seek(0) return np.load(f)
def deserialize_ndarray_npy(d)
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's :obj:`save` function. Args: d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created using :obj:`numpy.save`. Returns: An :obj:`ndarray` object.
3.597087
4.156221
0.865471
if 'data' in d: x = np.fromstring( base64.b64decode(d['data']), dtype=d['dtype']) x.shape = d['shape'] return x elif 'value' in d: return np.array(d['value'], dtype=d['dtype']) elif 'npy' in d: return deserialize_ndarray_npy(d) else: ...
def deserialize_ndarray(d)
Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`, :obj:`"readable"`. Args: d (`dict`): A dictionary representation of an :obj:`ndarray` object. Returns: An :obj:`ndarray` object.
2.768065
2.869259
0.964732
return dict( _type='astropy.units.Quantity', value=o.value, unit=o.unit.to_string())
def serialize_quantity(o)
Serializes an :obj:`astropy.units.Quantity`, for JSONification. Args: o (:obj:`astropy.units.Quantity`): :obj:`Quantity` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
4.417075
4.16797
1.059767
representation = o.representation.get_name() frame = o.frame.name r = o.represent_as('spherical') d = dict( _type='astropy.coordinates.SkyCoord', frame=frame, representation=representation, lon=r.lon, lat=r.lat) if len(o.distance.unit.to_string()): ...
def serialize_skycoord(o)
Serializes an :obj:`astropy.coordinates.SkyCoord`, for JSONification. Args: o (:obj:`astropy.coordinates.SkyCoord`): :obj:`SkyCoord` to be serialized. Returns: A dictionary that can be passed to :obj:`json.dumps`.
4.017205
4.404915
0.911982
if 'distance' in d: args = (d['lon'], d['lat'], d['distance']) else: args = (d['lon'], d['lat']) return coords.SkyCoord( *args, frame=d['frame'], representation='spherical')
def deserialize_skycoord(d)
Deserializes a JSONified :obj:`astropy.coordinates.SkyCoord`. Args: d (:obj:`dict`): A dictionary representation of a :obj:`SkyCoord` object. Returns: A :obj:`SkyCoord` object.
3.439981
3.999566
0.860089
# Use specified numpy.ndarray serialization mode serialize_fns = { 'b64': serialize_ndarray_b64, 'readable': serialize_ndarray_readable, 'npy': serialize_ndarray_npy} if ndarray_mode not in serialize_fns: raise ValueError('"ndarray_mode" must be one of {}'.format( ...
def get_encoder(ndarray_mode='b64')
Returns a JSON encoder that can handle: * :obj:`numpy.ndarray` * :obj:`numpy.floating` (converted to :obj:`float`) * :obj:`numpy.integer` (converted to :obj:`int`) * :obj:`numpy.dtype` * :obj:`astropy.units.Quantity` * :obj:`astropy.coordinates.SkyCoord` Args: ...
2.238178
2.036832
1.098853
if blockchain == 'bitcoin': return btc_is_multisig(privkey_info, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def is_multisig(privkey_info, blockchain='bitcoin', **blockchain_opts)
Is the given private key bundle a multisig bundle?
2.542762
2.306936
1.102225
if blockchain == 'bitcoin': return btc_is_multisig_address(addr, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def is_multisig_address(addr, blockchain='bitcoin', **blockchain_opts)
Is the given address a multisig address?
2.585922
2.3349
1.107509
if blockchain == 'bitcoin': return btc_is_multisig_script(script, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts)
Is the given script a multisig script?
2.706818
2.460499
1.100109
if blockchain == 'bitcoin': return btc_is_singlesig(privkey_info, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def is_singlesig(privkey_info, blockchain='bitcoin', **blockchain_opts)
Is the given private key bundle a single-sig key bundle?
2.498705
2.294631
1.088935
if blockchain == 'bitcoin': return btc_get_singlesig_privkey(privkey_info, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def get_singlesig_privkey(privkey_info, blockchain='bitcoin', **blockchain_opts)
Given a private key bundle, get the (single) private key
2.386983
2.353256
1.014332
if blockchain == 'bitcoin': return btc_is_singlesig_address(addr, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def is_singlesig_address(addr, blockchain='bitcoin', **blockchain_opts)
Is the given address a single-sig address?
2.596232
2.328458
1.115
if blockchain == 'bitcoin': return btc_get_privkey_address(privkey_info, **blockchain_opts) else: raise ValueError('Unknown blockchain "{}"'.format(blockchain))
def get_privkey_address(privkey_info, blockchain='bitcoin', **blockchain_opts)
Get the address from a private key bundle
2.496941
2.364604
1.055966
columns = ['bond', 'angle', 'dihedral'] C_dist = zmat_dist.loc[:, columns].values.T try: C_dist = C_dist.astype('f8') C_dist[[1, 2], :] = np.radians(C_dist[[1, 2], :]) except (TypeError, AttributeError): C_dist[[1, 2], :] = sympy.rad(C_dist[[1, 2], :]) cart_dist = np.ten...
def apply_grad_cartesian_tensor(grad_X, zmat_dist)
Apply the gradient for transformation to cartesian space onto zmat_dist. Args: grad_X (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array. The mathematical details of the index layout is explained in :meth:`~chemcoord.Cartesian.get_grad_zmat()`. zmat_dist (:class:`~chemcoord....
3.814003
3.52017
1.083471
if hasattr(model, 'id'): class Converter(_ModelConverter): _model = model app.url_map.converters[model.__name__] = Converter
def register_model_converter(model, app)
Add url converter for model Example: class Student(db.model): id = Column(Integer, primary_key=True) name = Column(String(50)) register_model_converter(Student) @route('/classmates/<Student:classmate>') def get_classmate_info(classmate): pass ...
5.055836
4.969754
1.017321
def convert_d(d): r = d % 360 return r - (r // 180) * 360 new = self.copy() new.unsafe_loc[:, 'angle'] = new['angle'] % 360 select = new['angle'] > 180 new.unsafe_loc[select, 'angle'] = new.loc[select, 'angle'] - 180 new.unsafe_loc[selec...
def iupacify(self)
Give the IUPAC conform representation. Mathematically speaking the angles in a zmatrix are representations of an equivalence class. We will denote an equivalence relation with :math:`\\sim` and use :math:`\\alpha` for an angle and :math:`\\delta` for a dihedral angle. Then the f...
3.106185
2.923753
1.062396
r new = self.copy() def convert_d(d): r = d % 360 return r - (r // 180) * 360 new.unsafe_loc[:, 'dihedral'] = convert_d(new.loc[:, 'dihedral']) return new
def minimize_dihedrals(self)
r"""Give a representation of the dihedral with minimized absolute value. Mathematically speaking the angles in a zmatrix are representations of an equivalence class. We will denote an equivalence relation with :math:`\sim` and use :math:`\alpha` for an angle and :math:`\delta` for a dih...
6.082179
7.89196
0.77068
perform_checks = kwargs.pop('perform_checks', True) cols = ['bond', 'angle', 'dihedral'] out = self.copy() def get_subs_f(*args): def subs_function(x): if hasattr(x, 'subs'): x = x.subs(*args) try: ...
def subs(self, *args, **kwargs)
Substitute a symbolic expression in ``['bond', 'angle', 'dihedral']`` This is a wrapper around the substitution mechanism of `sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_. Any symbolic expression in the columns ``['bond', 'angle', 'dihedral']`` of ``self`` will ...
4.169224
3.26798
1.27578
if (new_index is None): new_index = range(len(self)) elif len(new_index) != len(self): raise ValueError('len(new_index) has to be the same as len(self)') c_table = self.loc[:, ['b', 'a', 'd']] # Strange bug in pandas where .replace is transitive for obje...
def change_numbering(self, new_index=None)
Change numbering to a new index. Changes the numbering of index and all dependent numbering (bond_with...) to a new_index. The user has to make sure that the new_index consists of distinct elements. Args: new_index (list): If None the new_index is taken from...
4.138224
4.377575
0.945323
def get_normal_vec(cartesian, reference_labels): b_pos, a_pos, d_pos = cartesian._get_positions(reference_labels) BA = a_pos - b_pos AD = d_pos - a_pos N1 = np.cross(BA, AD) n1 = N1 / np.linalg.norm(N1) return n1 def inser...
def _insert_dummy_cart(self, exception, last_valid_cartesian=None)
Insert dummy atom into the already built cartesian of exception
2.774001
2.629167
1.055087
def insert_row(df, pos, key): if pos < len(df): middle = df.iloc[pos:(pos + 1)] middle.index = [key] start, end = df.iloc[:pos], df.iloc[pos:] return pd.concat([start, middle, end]) elif pos == len(df): ...
def _insert_dummy_zmat(self, exception, inplace=False)
Works INPLACE
3.446606
3.427811
1.005483
zmat = self if inplace else self.copy() if to_remove is None: to_remove = zmat._has_removable_dummies() if not to_remove: if inplace: return None else: return zmat has_dummies = zmat._metadata['has_dummies'] ...
def _remove_dummies(self, to_remove=None, inplace=False)
Works INPLACE
3.568882
3.520992
1.013601
def create_cartesian(positions, row): xyz_frame = pd.DataFrame(columns=['atom', 'x', 'y', 'z'], index=self.index[:row], dtype='f8') xyz_frame['atom'] = self.loc[xyz_frame.index, 'atom'] xyz_frame.loc[:, ['x', 'y', 'z']] = position...
def get_cartesian(self)
Return the molecule in cartesian coordinates. Raises an :class:`~exceptions.InvalidReference` exception, if the reference of the i-th atom is undefined. Args: None Returns: Cartesian: Reindexed version of the zmatrix.
4.427173
4.248594
1.042033