code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def ensure_row_dep_constraint(
self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None,
max_iter=100, force=False):
X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D)
if force:
raise NotImplementedError
else:
kernel_... | Ensures dependencey or indepdendency between rows with respect to
columns. |
def parse_format_specifier(specification):
m = _parse_format_specifier_regex.match(specification)
if m is None:
raise ValueError(
"Invalid format specifier: {!r}".format(specification))
format_dict = m.groupdict('')
# Convert zero-padding into fill and alignment.
zeropad = ... | Parse the given format specification and return a dictionary
containing relevant values. |
def format_align(sign, body, spec):
padding = spec['fill'] * (spec['minimumwidth'] - len(sign) - len(body))
align = spec['align']
if align == '<':
result = sign + body + padding
elif align == '>':
result = padding + sign + body
elif align == '=':
result = sign + padding ... | Given an unpadded, non-aligned numeric string 'body' and sign
string 'sign', add padding and alignment conforming to the given
format specifier dictionary 'spec' (as produced by
parse_format_specifier). |
def subs(self, *args):
cols = ['x', 'y', 'z']
out = self.copy()
def get_subs_f(*args):
def subs_function(x):
if hasattr(x, 'subs'):
x = x.subs(*args)
try:
x = float(x)
except... | Substitute a symbolic expression in ``['x', 'y', 'z']``
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
``['x', 'y', 'z']`` of ``self`` will be substituted
with ... |
def _jit_give_bond_array(pos, bond_radii, self_bonding_allowed=False):
n = pos.shape[0]
bond_array = np.empty((n, n), dtype=nb.boolean)
for i in range(n):
for j in range(i, n):
D = 0
for h in range(3):
D += (pos[i, h] - po... | Calculate a boolean array where ``A[i,j] is True`` indicates a
bond between the i-th and j-th atom. |
def _update_bond_dict(self, fragment_indices,
positions,
bond_radii,
bond_dict=None,
self_bonding_allowed=False,
convert_index=None):
assert (isinstance(bond_dict, collectio... | If bond_dict is provided, this function is not side effect free
bond_dict has to be a collections.defaultdict(set) |
def _preserve_bonds(self, sliced_cartesian,
use_lookup=None):
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)), \
'... | 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... |
def cut_sphere(
self,
radius=15.,
origin=None,
outside_sliced=True,
preserve_bonds=False):
if origin is None:
origin = np.zeros(3)
elif pd.api.types.is_list_like(origin):
origin = np.array(origin, dtype='f8')
... | 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... |
def cut_cuboid(
self,
a=20,
b=None,
c=None,
origin=None,
outside_sliced=True,
preserve_bonds=False):
if origin is None:
origin = np.zeros(3)
elif pd.api.types.is_list_like(origin):
origin... | 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
... |
def get_barycenter(self):
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() | Return the mass weighted average location.
Args:
None
Returns:
:class:`numpy.ndarray`: |
def get_bond_lengths(self, indices):
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 le... | 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... |
def get_angle_degrees(self, indices):
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
... | 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... |
def fragmentate(self, give_only_index=False,
use_lookup=None):
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:
... | 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`.
... |
def restrict_bond_dict(self, bond_dict):
return {j: bond_dict[j] & set(self.index) for j in self.index} | 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 |
def get_fragment(self, list_of_indextuples, give_only_index=False,
use_lookup=None):
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]
... | 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... |
def get_without(self, fragments,
use_lookup=None):
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_fragme... | 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
... |
def _jit_pairwise_distances(pos1, pos2):
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 | 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. |
def basistransform(self, new_basis, old_basis=None,
orthonormalize=True):
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... | 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,... |
def get_distance_to(self, origin=None, other_atoms=None, sort=False):
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 ot... | Return a Cartesian with a column for the distance from origin. |
def change_numbering(self, rename_dict, inplace=False):
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 | 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. |
def parse_date(date_str):
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 | Parse elastic datetime string. |
def get_dates(schema):
dates = [config.LAST_UPDATED, config.DATE_CREATED]
for field, field_schema in schema.items():
if field_schema['type'] == 'datetime':
dates.append(field)
return dates | Return list of datetime fields for given schema. |
def format_doc(hit, schema, dates):
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'] = {}
... | Format given doc to match given schema. |
def set_filters(query, base_filters):
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.appen... | 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) |
def get_es(url, **kwargs):
urls = [url] if isinstance(url, str) else url
kwargs.setdefault('serializer', ElasticJSONSerializer())
es = elasticsearch.Elasticsearch(urls, **kwargs)
return es | Create elasticsearch client instance.
:param url: elasticsearch url |
def build_elastic_query(doc):
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... | 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",
... |
def _build_query_string(q, default_field=None, default_operator='AND'):
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(... | Build ``query_string`` object from ``q``.
:param q: q of type String
:param default_field: default_field
:return: dictionary object. |
def default(self, value):
if isinstance(value, ObjectId):
return str(value)
return super(ElasticJSONSerializer, self).default(value) | Convert mongo.ObjectId. |
def extra(self, response):
if 'facets' in self.hits:
response['_facets'] = self.hits['facets']
if 'aggregations' in self.hits:
response['_aggregations'] = self.hits['aggregations'] | Add extra info to response. |
def init_index(self, app=None):
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)
co... | Create indexes and put mapping. |
def _get_indexes(self):
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.upda... | Based on the resource definition calculates the index definition |
def _get_mapping(self, schema):
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} | Get mapping for given resource or item schema.
:param schema: resource or dict/list type item schema |
def _get_field_mapping(self, schema):
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', {}):
... | Get mapping for single field schema.
:param schema: field schema |
def create_index(self, index=None, settings=None, es=None):
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... | Create new index and ignore if it exists already. |
def put_mapping(self, app, index=None):
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) != resou... | 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. |
def get_mapping(self, index, doc_type=None):
mapping = self.es.indices.get_mapping(index=index, doc_type=doc_type)
return next(iter(mapping.values())) | Get mapping for index.
:param index: index name |
def get_settings(self, index):
settings = self.es.indices.get_settings(index=index)
return next(iter(settings.values())) | Get settings for index.
:param index: index name |
def get_index_by_alias(self, alias):
try:
info = self.es.indices.get_alias(name=alias)
return next(iter(info.keys()))
except elasticsearch.exceptions.NotFoundError:
return alias | Get index name for given alias.
If there is no alias assume it's an index.
:param alias: alias name |
def should_aggregate(self, req):
try:
return self.app.config.get('ELASTICSEARCH_AUTO_AGGREGATIONS') or \
bool(req.args and int(req.args.get('aggregations')))
except (AttributeError, TypeError):
return False | Check the environment variable and the given argument parameter to decide if aggregations needed.
argument value is expected to be '0' or '1' |
def should_highlight(self, req):
try:
return bool(req.args and int(req.args.get('es_highlight', 0)))
except (AttributeError, TypeError):
return False | Check the given argument parameter to decide if highlights needed.
argument value is expected to be '0' or '1' |
def should_project(self, req):
try:
return req.args and json.loads(req.args.get('projections', []))
except (AttributeError, TypeError):
return False | Check the given argument parameter to decide if projections needed.
argument value is expected to be a list of strings |
def get_projected_fields(self, req):
try:
args = getattr(req, 'args', {})
return ','.join(json.loads(args.get('projections')))
except (AttributeError, TypeError):
return None | Returns the projected fields from request. |
def find_one(self, resource, req, **lookup):
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 ... | Find single document, if there is _id in lookup use that, otherwise filter. |
def _find_by_id(self, resource, _id, parent=None):
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 par... | Find the document by Id. If parent is not provided then on
routing exception try to find using search. |
def find_one_raw(self, resource, _id):
return self._find_by_id(resource=resource, _id=_id) | Find document by id. |
def find_list_of_ids(self, resource, ids, client_projection=None):
args = self._es_args(resource)
return self._parse_hits(self.elastic(resource).mget(body={'ids': ids}, **args), resource) | Find documents by ids. |
def insert(self, resource, doc_or_docs, **kwargs):
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, ... | Insert document, it must be new if there is ``_id`` in it. |
def bulk_insert(self, resource, docs, **kwargs):
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_ty... | Bulk insert documents. |
def update(self, resource, id_, updates):
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(re... | Update document in index. |
def replace(self, resource, id_, document):
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) | Replace document in index. |
def remove(self, resource, lookup=None, parent=None, **kwargs):
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.g... | Remove docs for resource.
:param resource: resource name
:param lookup: filter
:param parent: parent id |
def is_empty(self, resource):
args = self._es_args(resource)
res = self.elastic(resource).count(body={'query': {'match_all': {}}}, **args)
return res.get('count', 0) == 0 | Test if there is no document for resource.
:param resource: resource name |
def put_settings(self, app=None, index=None, settings=None, es=None):
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.indice... | Modify index settings.
Index must exist already. |
def _parse_hits(self, hits, resource):
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 hi... | Parse hits response into documents. |
def _es_args(self, resource, refresh=None, source_projections=None):
datasource = self.get_datasource(resource)
args = {
'index': self._resource_index(resource),
'doc_type': datasource[0],
}
if source_projections:
args['_source'] = source_proj... | Get index and doctype args. |
def get_parent_id(self, resource, document):
parent_type = self._get_parent_type(resource)
if parent_type and document:
return document.get(parent_type.get('field'))
return None | Get the Parent Id of the document
:param resource: resource name
:param document: document containing the parent id |
def _fields(self, resource):
datasource = self.get_datasource(resource)
keys = datasource[2].keys()
return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED]) | Get projection fields for given resource. |
def _resource_index(self, resource):
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) | Get index for given resource.
by default it will be `self.index`, but it can be overriden via app.config
:param resource: resource name |
def _refresh_resource_index(self, resource):
if self._resource_config(resource, 'FORCE_REFRESH', True):
self.elastic(resource).indices.refresh(self._resource_index(resource)) | Refresh index for given resource.
:param resource: resource name |
def _resource_prefix(self, resource=None):
px = 'ELASTICSEARCH'
if resource and config.DOMAIN[resource].get('elastic_prefix'):
px = config.DOMAIN[resource].get('elastic_prefix')
return px | Get elastic prefix for given resource.
Resource can specify ``elastic_prefix`` which behaves same like ``mongo_prefix``. |
def _resource_config(self, resource=None, key=None, default=None):
px = self._resource_prefix(resource)
return self.app.config.get('%s_%s' % (px, key), default) | Get config using resource elastic prefix (if any). |
def elastic(self, resource=None):
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] | Get ElasticSearch instance for given resource. |
def get_md5sum(fname, chunk_size=1024):
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(... | 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... |
def download(url, fname=None):
# 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.excepti... | 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... |
def dataverse_search_doi(doi):
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))
... | 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... |
def address_reencode(address, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_address_reencode(address, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) | Reencode an address |
def serialize_dtype(o):
if len(o) == 0:
return dict(
_type='np.dtype',
descr=str(o))
return dict(
_type='np.dtype',
descr=o.descr) | 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`. |
def deserialize_dtype(d):
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 ... | Deserializes a JSONified :obj:`numpy.dtype`.
Args:
d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object.
Returns:
A :obj:`dtype` object. |
def serialize_ndarray_b64(o):
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) | 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`. |
def hint_tuples(o):
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 | 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... |
def serialize_ndarray_readable(o):
return dict(
_type='np.ndarray',
dtype=o.dtype,
value=hint_tuples(o.tolist())) | 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`. |
def serialize_ndarray_npy(o):
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) | 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:
... |
def deserialize_ndarray_npy(d):
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f) | 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. |
def deserialize_ndarray(d):
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 deserializ... | 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. |
def serialize_quantity(o):
return dict(
_type='astropy.units.Quantity',
value=o.value,
unit=o.unit.to_string()) | 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`. |
def serialize_skycoord(o):
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.dist... | 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`. |
def deserialize_skycoord(d):
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') | Deserializes a JSONified :obj:`astropy.coordinates.SkyCoord`.
Args:
d (:obj:`dict`): A dictionary representation of a :obj:`SkyCoord` object.
Returns:
A :obj:`SkyCoord` object. |
def is_multisig(privkey_info, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_is_multisig(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Is the given private key bundle a multisig bundle? |
def is_multisig_address(addr, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_is_multisig_address(addr, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Is the given address a multisig address? |
def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_is_multisig_script(script, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Is the given script a multisig script? |
def is_singlesig(privkey_info, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_is_singlesig(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Is the given private key bundle a single-sig key bundle? |
def get_singlesig_privkey(privkey_info, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_get_singlesig_privkey(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Given a private key bundle, get the (single) private key |
def is_singlesig_address(addr, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_is_singlesig_address(addr, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Is the given address a single-sig address? |
def get_privkey_address(privkey_info, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_get_privkey_address(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Get the address from a private key bundle |
def apply_grad_cartesian_tensor(grad_X, zmat_dist):
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], :] =... | 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.... |
def register_model_converter(model, app):
if hasattr(model, 'id'):
class Converter(_ModelConverter):
_model = model
app.url_map.converters[model.__name__] = Converter | 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
... |
def iupacify(self):
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
... | 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... |
def minimize_dihedrals(self):
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 | 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... |
def change_numbering(self, new_index=None):
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 ... | 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... |
def _insert_dummy_cart(self, exception, last_valid_cartesian=None):
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)
n... | Insert dummy atom into the already built cartesian of exception |
def _remove_dummies(self, to_remove=None, inplace=False):
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 zm... | Works INPLACE |
def get_cartesian(self):
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[:, ['... | 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. |
def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints):
if blockchain_name == 'bitcoin':
return get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=tx_filter, **hints)
else:
... | Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights.
Returns a list of tuples in the format of [(block height, [txs])], where
each tx in [txs] is the parsed transaction. The parsed transaction will conform to... # TODO write a spec for this
Ea... |
def tx_parse(raw_tx, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_deserialize(raw_tx, **blockchain_opts)
else:
raise ValueError("Unknown blockchain {}".format(blockchain)) | Parse a raw transaction, based on the type of blockchain it's from
Returns a tx dict on success (see get_virtual_transactions)
Raise ValueError for unknown blockchain
Raise some other exception for invalid raw_tx (implementation-specific) |
def tx_output_has_data(output, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_output_has_data(output, **blockchain_opts)
else:
return ValueError('Unknown blockchain "{}"'.format(blockchain)) | Give a blockchain name and a tx output, determine whether or not it is a
data-bearing script--i.e. one with data for the state engine.
Return True if so
Return False if not |
def tx_is_data_script(out_script, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_output_script_has_data(out_script, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Given a blockchain name and an output script (tx['outs'][x]['script']),
determine whether or not it is a data-bearing script---i.e. one with data for the state engine.
Return True if so
Reurn False if not |
def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts)
else:
raise ValueError('Unknown blockchain "{}"'.format(blockchain)) | Add a set of inputs and outputs to a tx.
Return the new tx on success
Raise on error |
def tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, **blockchain_opts)
else:
raise ValueError('Unknown b... | Sign a given input in a transaction, given the previous output script and previous output amount.
Different blockchains can require additional fields; pass thse in **blockchain_opts.
Return the serialized tx with the given input signed on success
Raise on error |
def tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, blockchain='bitcoin', **blockchain_opts):
if blockchain == 'bitcoin':
return btc_tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, **blockchain_opts)
else:
raise ValueError('Unknown blockchai... | Sign all unsigned inputs to a given transaction with the given private key. Also, pass in the list of previous outputs to the transaction so they
can be paired with the right input (i.e. prev_outputs is a list of tx outputs that are in 1-to-1 correspondance with the inputs in the serialized tx)
Different ... |
def fetch():
url = 'http://pla.esac.esa.int/pla/aio/product-action?MAP.MAP_ID=HFI_CompMap_ThermalDustModel_2048_R1.20.fits'
md5 = '8d804f4e64e709f476a63f0dfed1fd11'
fname = os.path.join(
data_dir(),
'planck',
'HFI_CompMap_ThermalDustModel_2048_R1.20.fits')
fetch_utils.downlo... | Downloads the Planck Collaboration (2013) dust map, placing it in the
default ``dustmaps`` data directory. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.