Skip to content

easyscience.Utils

classUtils

cached_class(klass)

Decorator to cache class instances by constructor arguments. This results in a class that behaves like a singleton for each set of constructor arguments, ensuring efficiency.

Note that this should be used for immutable classes only. Having a cached mutable class makes very little sense. For efficiency, avoid using this decorator for situations where there are many constructor arguments permutations.

The keywords argument dictionary is converted to a tuple because dicts are mutable; keywords themselves are strings and so are always hashable, but if any arguments (keyword or positional) are non-hashable, that set of arguments is not cached.

singleton(cls)

This decorator can be used to create a singleton out of a class.

Usage::

@singleton
class MySingleton():

    def __init__():
        pass

decorators

memoized

Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated).

__get__(obj, objtype)

Support instance methods.

__repr__()

Return the function's docstring.

counted(func)

Counts how many times a function has been called and adds a func.calls to it's properties :param func: Function to be counted :return: Results from function call

deprecated(func)

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

time_it(func)

Times a function and reports the time either to the class' log or the base logger :param func: function to be timed :return: callable function with timer

io

dict

DataDictSerializer

Bases: DictSerializer

This is a serializer that can encode the data in an EasyScience object to a JSON encoded dictionary.

decode(d) classmethod

This function is not implemented as a data dictionary does not contain the necessary information to re-form an EasyScience object.

encode(obj, skip=None, full_encode=False, **kwargs)

Convert an EasyScience object to a JSON encoded data dictionary

:param obj: Object to be encoded. :param skip: List of field names as strings to skip when forming the encoded object :param full_encode: Should the data also be JSON encoded (default False) :param kwargs: Any additional key word arguments to be passed to the encoder :return: object encoded to data dictionary.

DictSerializer

Bases: BaseEncoderDecoder

This is a serializer that can encode and decode EasyScience objects to a JSON encoded dictionary.

decode(d) classmethod

:param d: Dict representation. :return: ComponentSerializer class.

encode(obj, skip=None, full_encode=False, **kwargs)

Convert an EasyScience object to a JSON encoded dictionary

:param obj: Object to be encoded. :param skip: List of field names as strings to skip when forming the encoded object :param full_encode: Should the data also be JSON encoded (default False) :param kwargs: Any additional key word arguments to be passed to the encoder :return: object encoded to dictionary containing all information to reform an EasyScience object.

from_dict(d) classmethod

:param d: Dict representation. :return: ComponentSerializer class.

json

JsonDataSerializer

Bases: BaseEncoderDecoder

encode(obj, skip=[])

Returns a json string representation of the ComponentSerializer object.

JsonDecoderTemplate

Bases: JSONDecoder

A Json Decoder which supports the ComponentSerializer API. By default, the decoder attempts to find a module and name associated with a dict. If found, the decoder will generate a Pymatgen as a priority. If that fails, the original decoded dictionary from the string is returned. Note that nested lists and dicts containing pymatgen object will be decoded correctly as well.

Usage:

# Add it as a *cls* keyword when using json.load
json.loads(json_string, cls=MontyDecoder)
decode(s)

Overrides decode from JSONDecoder.

:param s: string :return: Object.

JsonEncoderTemplate

Bases: JSONEncoder

A Json Encoder which supports the ComponentSerializer API, plus adds support for numpy arrays, datetime objects, bson ObjectIds (requires bson).

Usage::

# Add it as a *cls* keyword when using json.dump
json.dumps(object, cls=MontyEncoder)
default(o)

Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object has no to_dict property, the default Python json encoder default method is called.

Parameters:

Name Type Description Default
o

Python object.

required
Return

Python dict representation.

JsonSerializer

Bases: BaseEncoderDecoder

encode(obj, skip=[])

Returns a json string representation of the ComponentSerializer object.

jsanitize(obj, strict=False, allow_bson=False)

This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's as_dict() protocol.

Parameters:

Name Type Description Default
obj

input json-like object.

required
strict bool

This parameters sets the behavior when jsanitize encounters an object it does not understand. If strict is True, jsanitize will try to get the as_dict() attribute of the object. If no such attribute is found, an attribute error will be thrown. If strict is False, jsanitize will simply call str(object) to convert the object to a string representation.

False
allow_bson bool

This parameters sets the behavior when jsanitize encounters an bson supported type such as objectid and datetime. If True, such bson types will be ignored, allowing for proper insertion into MongoDb databases.

False

Returns:

Type Description

Sanitized dict that can be json serialized.

template

BaseEncoderDecoder

This is the base class for creating an encoder/decoder which can convert EasyScience objects. encode and decode are abstract methods to be implemented for each serializer. It is expected that the helper function _convert_to_dict will be used as a base for encoding (or the DictSerializer as it's more flexible).

decode(obj) abstractmethod classmethod

Re-create an EasyScience object from the output of an encoder. The default decoder is DictSerializer.

:param obj: encoded EasyScience object :return: Reformed EasyScience object

encode(obj, skip=None, **kwargs) abstractmethod

Abstract implementation of an encoder.

:param obj: Object to be encoded. :param skip: List of field names as strings to skip when forming the encoded object :param kwargs: Any additional key word arguments to be passed to the encoder :return: encoded object containing all information to reform an EasyScience object.

get_arg_spec(func) staticmethod

Get the full argument specification of a function (typically __init__)

:param func: Function to be inspected :return: Tuple of argument spec and arguments

get_class_module(obj)

Returns the REAL module of the class of the object.

recursive_encoder(obj, skip=[], encoder=None, full_encode=False, **kwargs)

Walk through an object encoding it

xml

XMLSerializer

Bases: BaseEncoderDecoder

This is a serializer that can encode and decode EasyScience objects to a basic xml format.

decode(data) classmethod

Decode an EasyScience object which has been encoded in XML format.

:param data: String containing XML encoded data. :return: Reformed EasyScience object.

encode(obj, skip=None, data_only=False, fast=False, use_header=False, **kwargs)

Convert an EasyScience object to an XML encoded string. Note that for speed the fast setting can be changed to True. An XML document with initial block data is returned.

:param obj: Object to be encoded. :param skip: List of field names as strings to skip when forming the encoded object :param data_only: Should only the object's data be encoded. :param fast: Should the returned string be pretty? This can be turned off for speed. :param use_header: Should a header of '?xml version="1.0" encoding="UTF-8"?' be included? :param kwargs: Any additional key-words to pass to the Dictionary Serializer. :return: string containing the XML encoded object

string_to_variable(in_string) staticmethod

Convert an XML encoded string to JSON form.

string

__version__ = '0.1.0' module-attribute

This module provides utility classes for string operations.

transformation_to_string(matrix, translation_vec=(0, 0, 0), components=('x', 'y', 'z'), c='', delim=',')

Convenience method. Given matrix returns string, e.g. x+2y+1/4 :param matrix :param translation_vec :param components: either ('x', 'y', 'z') or ('a', 'b', 'c') :param c: optional additional character to print (used for magmoms) :param delim: delimiter :return: xyz string