Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SharedMemory and ndarray serialization #1

Merged
merged 18 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dev-environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ name: appose-dev
channels:
- conda-forge
- defaults
- forklift
dependencies:
- python >= 3.10
# Developer tools
Expand Down
41 changes: 40 additions & 1 deletion src/appose/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
###

import json
from multiprocessing import shared_memory
from typing import Any, Dict

Args = Dict[str, Any]
Expand All @@ -38,4 +39,42 @@ def encode(data: Args) -> str:


def decode(the_json: str) -> Args:
return json.loads(the_json)
return json.loads(the_json, object_hook=_appose_object_hook)


class ShmNDArray:
def __init__(self, shm: shared_memory.SharedMemory, dtype: str, shape):
self.shm = shm
self.dtype = dtype
self.shape = shape

def __str__(self):
return (
f"ShmNDArray("
f"shm='{self.shm.name}' ({self.shm.size}), "
f"dtype='{self.dtype}', "
f"shape={self.shape})"
)

def ndarray(self):
try:
import math

import numpy

num_elements = math.prod(self.shape)
return numpy.ndarray(
num_elements, dtype=self.dtype, buffer=self.shm.buf
).reshape(self.shape)
except ModuleNotFoundError:
raise ImportError("NumPy is not available.")


def _appose_object_hook(obj: Dict):
type = obj.get("appose_type")
if type == "shm":
return shared_memory.SharedMemory(name=(obj["name"]), size=(obj["size"]))
elif type == "ndarray":
return ShmNDArray(obj["shm"], obj["dtype"], obj["shape"])
else:
return obj
Loading