qrunch.storage.serializers

Contains class to serialize and deserialize dataclass instances using pickle.

Module Attributes

MODULE_PATHS

Map of class names to the path to the module where they are defined.

WrappedBytesDict

Keys 'metadata' and 'data' both map to raw bytes.

Functions

check_module_path_is_in_map(obj_type)

Check that the path to the module defining the class is in the MODULE_PATHS map.

Classes

DataClassJSONSerializer

Class to serialize and deserialize instances using JSON.

NestedStrDictJSONSerializer

Class to serialize and deserialize instances using JSON.

PickleSerializer

Class to serialize and deserialize instances using Python pickle.

class DataClassJSONSerializer

Bases: SerializerProtocol

Class to serialize and deserialize instances using JSON.

__init__(*args, **kwargs)
from_bytes(serialized_data: bytes, cls: type[T]) T

Deserialize bytes back into a dataclass instance of the given type.

Parameters:
  • serialized_data (bytes) – Serialized byte data.

  • cls (type[T]) – The expected dataclass type.

Return type:

T

to_bytes(instance: Any) bytes

Serialize a dataclass instance into bytes.

Parameters:

instance (Any) – The dataclass instance to serialize.

Return type:

bytes

MODULE_PATHS: dict[str, str] = {'ChemistryFermionHermitianSum': 'qrunch.chemistry.ground_state_problem.calculators.tools.second_quantized_hamiltonian_creators.chemistry_fermion_hermitian_sum', 'ChemistryPairedHardcoreBosonHermitianSum': 'qrunch.chemistry.ground_state_problem.calculators.tools.second_quantized_hamiltonian_creators.chemistry_boson_hermitian_sum', 'Circuit': 'qrunch.quantum.circuits.circuit', 'DenseArray': 'qrunch.common.arrays.dense_array', 'DoubleExcitationGate': 'qrunch.quantum.gates.composite_gates', 'DoubleExcitationsArray': 'qrunch.common.arrays.double_excitations_array', 'ExpectationValue': 'qrunch.quantum.measurement.expectation_value', 'FermionHermitianSum': 'qrunch.quantum.operators.second_quantization.fermion.sums', 'MolecularElectronConfiguration': 'qrunch.chemistry.molecule.molecular_electron_configuration', 'MolecularEnergyContributions': 'qrunch.chemistry.molecule.molecular_energy_contributions', 'PairedHardcoreBosonHermitianSum': 'qrunch.quantum.operators.second_quantization.hardcore_boson.sums', 'Parameter': 'qrunch.core.expressions.parameter', 'RXGate': 'qrunch.quantum.gates.universal_gates', 'RYGate': 'qrunch.quantum.gates.universal_gates', 'RestrictedElectronicStructureIntegrals': 'qrunch.chemistry._integral_tools.integral_protocols', 'RestrictedGroundStateProblem': 'qrunch.chemistry.ground_state_problem.builders.builders_protocols', 'RestrictedMolecularOrbitalCalculatorResult': 'qrunch.chemistry.molecular_orbital_calculators.molecular_orbital_calculators_protocols', 'RestrictedMolecularOrbitals': 'qrunch.chemistry.molecule.molecular_orbitals', 'RestrictedOccupiedMolecularOrbitals': 'qrunch.chemistry.ground_state_problem.builders.tools.localization.localization_protocols', 'RestrictedOneBodyCoreHamiltonian': 'qrunch.chemistry._integral_tools.integral_protocols', 'RestrictedTwoBodyElectronRepulsionIntegrals': 'qrunch.chemistry._integral_tools.integral_protocols', 'SingleExcitationGate': 'qrunch.quantum.gates.composite_gates', 'SingleExcitationsArray': 'qrunch.common.arrays.single_excitations_array', 'SparseArray': 'qrunch.common.arrays.sparse_array', 'TwoBodyElectronRepulsionIntegralsProtocol': 'qrunch.chemistry._integral_tools.integral_protocols', 'UnrestrictedElectronicStructureIntegrals': 'qrunch.chemistry._integral_tools.integral_protocols', 'UnrestrictedGroundStateProblem': 'qrunch.chemistry.ground_state_problem.builders.builders_protocols', 'UnrestrictedMolecularOrbitalCalculatorResult': 'qrunch.chemistry.molecular_orbital_calculators.molecular_orbital_calculators_protocols', 'UnrestrictedMolecularOrbitals': 'qrunch.chemistry.molecule.molecular_orbitals', 'UnrestrictedOccupiedMolecularOrbitals': 'qrunch.chemistry.ground_state_problem.builders.tools.localization.localization_protocols', 'UnrestrictedOneBodyCoreHamiltonian': 'qrunch.chemistry._integral_tools.integral_protocols', 'UnrestrictedTwoBodyElectronRepulsionIntegrals': 'qrunch.chemistry._integral_tools.integral_protocols', '_SerializablePauliAdaptiveVqeResult': 'qrunch.quantum.algorithms.pauli.vqes.adaptive_vqe'}

Map of class names to the path to the module where they are defined.

Having this allows us to not hard-code the module paths into the serialized data, thus allowing us the flexibility to move stuff around when desired.

class NestedStrDictJSONSerializer

Bases: object

Class to serialize and deserialize instances using JSON.

static from_bytes(serialized_data: bytes) Mapping[str, str | Mapping[str, str | NestedStrDict]]

Deserialize bytes back into a dataclass instance of the given type.

Parameters:
  • serialized_data (bytes) – Serialized byte data.

  • cls – The expected dataclass type.

Return type:

Mapping[str, str | Mapping[str, str | NestedStrDict]]

static to_bytes(instance: Mapping[str, str | Mapping[str, str | NestedStrDict]]) bytes

Serialize a dataclass instance into bytes.

Parameters:

instance (Mapping[str, str | Mapping[str, str | NestedStrDict]]) – The dataclass instance to serialize.

Return type:

bytes

class PickleSerializer

Bases: SerializerProtocol

Class to serialize and deserialize instances using Python pickle.

class CustomEncodingPickler

Bases: Pickler

Pickler which uses the encode-decode methods on classes if they implement the HasCustomEncoding Protocol.

__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)
bin
clear_memo()

Clears the pickler’s “memo”.

The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers.

dispatch_table
dump(obj, /)

Write a pickled representation of the given object to the open file.

fast
memo
persistent_id
reducer_override(obj: Any) tuple[Callable[[dict[str, Any]], Any], tuple[dict[str, Any]]]

Reduces HasCustomEncoding classes using the encode-decode scheme.

Parameters:

obj (Any)

Return type:

tuple[Callable[[dict[str, Any]], Any], tuple[dict[str, Any]]]

class ModulePathLookupUnpickler

Bases: Unpickler

Unpickler which looks for the modules in MODULE_PATHS for classes, ensuring backwards compatibility.

__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)
find_class(module_name: str, cls_name: str) type

Find the cls_name by first looking in the MODULE_PATHS, falling back to the default if not found.

Parameters:
  • module_name (str) – The name of the module to search in (in absolute style), if not found in MODULE_PATHS.

  • cls_name (str) – the name of the class to find.

Return type:

type

load()

Load a pickle.

Read a pickled object representation from the open file object given in the constructor, and return the reconstituted object hierarchy specified therein.

memo
persistent_load
safe_builtins: ClassVar[set[str]] = {'complex', 'float', 'frozenset', 'getattr', 'int', 'list', 'range', 'set', 'slice'}

Adds extra safety to the unpickling by only allowing some builtins (and thus not allowing e.g. eval).

__init__(*args, **kwargs)
from_bytes(serialized_data: bytes, cls: type[T]) T

Deserialize bytes back into a dataclass instance of the given type.

Parameters:
  • serialized_data (bytes) – Serialized byte data.

  • cls (type[T]) – The expected dataclass type.

Return type:

T

to_bytes(instance: Any) bytes

Serialize a dataclass instance into bytes.

Parameters:

instance (Any) – The dataclass instance to serialize.

Return type:

bytes

WrappedBytesDict

Keys ‘metadata’ and ‘data’ both map to raw bytes.

alias of dict[Literal[‘metadata’] | Literal[‘data’], bytes]

check_module_path_is_in_map(obj_type: type) None

Check that the path to the module defining the class is in the MODULE_PATHS map.

Parameters:

obj_type (type) – The class to ensure is in the MODULE_MAP

Return type:

None