Module ARgorithmToolkit.encoders

For support of nested ARgorithm Classes, this module provides with a Encoder that stores the reference to ARgorithm Object whenever an ARgorithm Class object is serialized in the StateSet (which only happens when we nest one ARgorithm Class in another)

Expand source code
"""For support of nested ARgorithm Classes, this module provides with a Encoder
that stores the reference to ARgorithm Object whenever an ARgorithm Class
object is serialized in the StateSet (which only happens when we nest one
ARgorithm Class in another)"""
import inspect
from json import JSONEncoder
import numpy as np
import ARgorithmToolkit

def serialize(cls):
    """Decorator to make classes serializable."""
    def to_json(self):
        """Creates a string representing a reference to ARgorithmObject for use
        in application."""
        class_name = type(self).__name__
        obj_id = id(self)
        return f"$ARgorithmToolkit.{class_name}:{obj_id}"
    setattr(cls,'to_json',to_json)
    return cls

class StateEncoder(JSONEncoder):
    """The custon Encoder to be used to convert StateSet into JSON.

    Supports ARgorithm Classes as well
    """
    def default(self, o):
        """The function called when an object has to be serialized.

        Args:
            o ([type]): The object to be serialized
        """
        classes = inspect.getmembers(ARgorithmToolkit,inspect.isclass)
        classes = tuple([x for _,x in classes])
        if isinstance(ARgorithmToolkit.Variable,classes) :
            return super().default(o.value)
        if isinstance(o, classes):
            try:
                return o.to_json()
            except Exception as ex:
                raise TypeError("Unserializable ARgorithm class",) from ex
        if isinstance(o, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(o)
        if isinstance(o, (np.float_, np.float16, np.float32, np.float64)):
            return float(o)
        if isinstance(o, (np.complex_, np.complex64, np.complex128)):
            return {'real': o.real, 'imag': o.imag}
        if isinstance(o, (np.ndarray,)):
            return o.tolist()
        if isinstance(o, (np.bool_)):
            return bool(o)
        if isinstance(o, (np.void)):
            return None
        return super().default(o)

Functions

def serialize(cls)

Decorator to make classes serializable.

Expand source code
def serialize(cls):
    """Decorator to make classes serializable."""
    def to_json(self):
        """Creates a string representing a reference to ARgorithmObject for use
        in application."""
        class_name = type(self).__name__
        obj_id = id(self)
        return f"$ARgorithmToolkit.{class_name}:{obj_id}"
    setattr(cls,'to_json',to_json)
    return cls

Classes

class StateEncoder (*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

The custon Encoder to be used to convert StateSet into JSON.

Supports ARgorithm Classes as well

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

If specified, default is a function that gets called for objects that can't otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

Expand source code
class StateEncoder(JSONEncoder):
    """The custon Encoder to be used to convert StateSet into JSON.

    Supports ARgorithm Classes as well
    """
    def default(self, o):
        """The function called when an object has to be serialized.

        Args:
            o ([type]): The object to be serialized
        """
        classes = inspect.getmembers(ARgorithmToolkit,inspect.isclass)
        classes = tuple([x for _,x in classes])
        if isinstance(ARgorithmToolkit.Variable,classes) :
            return super().default(o.value)
        if isinstance(o, classes):
            try:
                return o.to_json()
            except Exception as ex:
                raise TypeError("Unserializable ARgorithm class",) from ex
        if isinstance(o, (np.int_, np.intc, np.intp, np.int8,
                            np.int16, np.int32, np.int64, np.uint8,
                            np.uint16, np.uint32, np.uint64)):
            return int(o)
        if isinstance(o, (np.float_, np.float16, np.float32, np.float64)):
            return float(o)
        if isinstance(o, (np.complex_, np.complex64, np.complex128)):
            return {'real': o.real, 'imag': o.imag}
        if isinstance(o, (np.ndarray,)):
            return o.tolist()
        if isinstance(o, (np.bool_)):
            return bool(o)
        if isinstance(o, (np.void)):
            return None
        return super().default(o)

Ancestors

  • json.encoder.JSONEncoder

Methods

def default(self, o)

The function called when an object has to be serialized.

Args

o : [type]
The object to be serialized
Expand source code
def default(self, o):
    """The function called when an object has to be serialized.

    Args:
        o ([type]): The object to be serialized
    """
    classes = inspect.getmembers(ARgorithmToolkit,inspect.isclass)
    classes = tuple([x for _,x in classes])
    if isinstance(ARgorithmToolkit.Variable,classes) :
        return super().default(o.value)
    if isinstance(o, classes):
        try:
            return o.to_json()
        except Exception as ex:
            raise TypeError("Unserializable ARgorithm class",) from ex
    if isinstance(o, (np.int_, np.intc, np.intp, np.int8,
                        np.int16, np.int32, np.int64, np.uint8,
                        np.uint16, np.uint32, np.uint64)):
        return int(o)
    if isinstance(o, (np.float_, np.float16, np.float32, np.float64)):
        return float(o)
    if isinstance(o, (np.complex_, np.complex64, np.complex128)):
        return {'real': o.real, 'imag': o.imag}
    if isinstance(o, (np.ndarray,)):
        return o.tolist()
    if isinstance(o, (np.bool_)):
        return bool(o)
    if isinstance(o, (np.void)):
        return None
    return super().default(o)