Created
August 17, 2022 18:30
-
-
Save SamWolski/1341996434efc403cedb1d478b51d44f to your computer and use it in GitHub Desktop.
Qutip object serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import msgpack | |
import msgpack_numpy | |
import pandas as pd | |
import qutip | |
from scipy.sparse import csr_matrix | |
def serialize_csr(arr): | |
## Switch to coo format | |
coo = arr.tocoo() | |
## Separate into the components we need to reconstruct it | |
out_dict = {"data": coo.data, | |
"col": coo.col, | |
"row": coo.row, | |
"shape": coo.shape} | |
## Return serialized string | |
return msgpack.packb(out_dict, default=msgpack_numpy.encode) | |
def deserialize_csr(bstr): | |
## Unpack into dict with components | |
coo_dict = msgpack.unpackb(bstr, object_hook=msgpack_numpy.decode) | |
## Re-create array with components | |
out_arr = csr_matrix((coo_dict["data"], | |
(coo_dict["row"], coo_dict["col"])), | |
shape=coo_dict["shape"]) | |
return out_arr | |
def serialize_qobj(qobj): | |
""" | |
Serialize a qutip Qobj instance | |
""" | |
data = serialize_csr(qobj.data) | |
dims = qobj.dims | |
## Construct a dict | |
out_dict = {"data": data, "dims": dims} | |
## Serialize the dict | |
serial_dict = msgpack.packb(out_dict) | |
return serial_dict | |
def deserialize_qobj(bstr): | |
## Unpack bitstring | |
in_dict = msgpack.unpackb(bstr) | |
## Assign components | |
data = deserialize_csr(in_dict["data"]) | |
dims = in_dict["dims"] | |
## Reconstruct qobj | |
qobj = qutip.Qobj(inpt=data, dims=dims) | |
return qobj | |
def serialize_df_numeric(data_df): | |
"""Serialize a DataFrame containing only numeric dtypes""" | |
return msgpack.packb(data_df.to_dict(orient="split")) | |
def deserialize_df_numeric(bstr): | |
"""Deserialize a DataFrame containing only numeric dtypes""" | |
return pd.DataFrame(**msgpack.unpackb(bstr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment