openmodels 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,329 @@
1
+ """
2
+ Mixins for extensible serialization of Python, NumPy, and SciPy objects.
3
+
4
+ This module provides a flexible mixin-based architecture for converting complex objects
5
+ (such as slices, types, NumPy arrays, and SciPy structures) into JSON-serializable formats.
6
+ Each mixin implements handlers for specific types, allowing easy extension and modular
7
+ support for new serialization targets.
8
+ """
9
+
10
+ import numpy as np
11
+ from scipy.sparse import csr_matrix, csc_matrix, csr_array, csc_array # type: ignore
12
+ from scipy.interpolate import interp1d, BSpline # type: ignore
13
+ from scipy.stats._distn_infrastructure import rv_continuous_frozen # type: ignore
14
+ import scipy.stats # type: ignore
15
+
16
+ from typing import Any, Optional, Callable, Dict
17
+
18
+
19
+ class SerializerMixin:
20
+ """
21
+ Base mixin providing recursive serialization and native Python object
22
+ serialization with a dispatch mechanism. Other mixins only need to implement
23
+ `_get_handlers()` and serialization helpers.
24
+ """
25
+
26
+ def convert_to_serializable(self, value):
27
+ """Recursively convert values into JSON-serializable types."""
28
+ # First check custom handlers
29
+ for typ, handler in self._get_serializer_handlers():
30
+ if isinstance(value, typ):
31
+ return handler(value)
32
+
33
+ # Recursive case: dict, list, tuple
34
+ if isinstance(value, dict):
35
+ if all(isinstance(k, str) for k in value):
36
+ return {k: self.convert_to_serializable(v) for k, v in value.items()}
37
+ # Non-string keys (e.g. int) can't be represented as JSON object keys without
38
+ # losing their type, so fall back to a self-describing keys/values envelope that
39
+ # _deserialize_dict can reconstruct exactly.
40
+ return {
41
+ "__openmodels_dict__": True,
42
+ "keys": [self.convert_to_serializable(k) for k in value.keys()],
43
+ "key_types": [type(k).__name__ for k in value.keys()],
44
+ "values": [self.convert_to_serializable(v) for v in value.values()],
45
+ }
46
+
47
+ if isinstance(value, (list, tuple)):
48
+ return [self.convert_to_serializable(v) for v in value]
49
+
50
+ return value
51
+
52
+ def convert_from_serializable(
53
+ self, value: Any, value_type: Any = "none", value_dtype: Optional[str] = None
54
+ ) -> Any:
55
+
56
+ if isinstance(value_type, list) and isinstance(value, list):
57
+ return [
58
+ self.convert_from_serializable(v, t, value_dtype)
59
+ for v, t in zip(value, value_type)
60
+ ]
61
+
62
+ if isinstance(value_type, str):
63
+ for typ_name, handler in self._get_deserializer_handlers():
64
+ if typ_name == value_type:
65
+ if value_type == "ndarray":
66
+ return handler(value, value_dtype)
67
+ return handler(value)
68
+
69
+ return value
70
+
71
+ # --- Python-native specific serializers/deserializers ---
72
+ def _serialize_slice(self, value: slice):
73
+ return {"start": value.start, "stop": value.stop, "step": value.step}
74
+
75
+ def _deserialize_slice(self, value):
76
+ return slice(
77
+ start=value.get("start"),
78
+ stop=value.get("stop"),
79
+ step=value.get("step"),
80
+ )
81
+
82
+ def _serialize_type(self, value: type):
83
+ return {"type_name": value.__name__}
84
+
85
+ def _deserialize_type(self, value):
86
+ # Deserialize Python type objects from their string name
87
+ # Only allow a safe whitelist of types; default to float if not found
88
+ allowed_types = {
89
+ "int": int,
90
+ "float": float,
91
+ "str": str,
92
+ "bool": bool,
93
+ "tuple": tuple,
94
+ "list": list,
95
+ "dict": dict,
96
+ }
97
+ return allowed_types.get(value["type_name"], float)
98
+
99
+ def _serialize_function(self, func: Callable) -> Dict[str, str]:
100
+ """Serialize a Python function by its module and name."""
101
+ return {
102
+ "module": func.__module__,
103
+ "name": func.__name__,
104
+ }
105
+
106
+ def _deserialize_function(self, data: Dict[str, str]) -> Callable:
107
+ """Deserialize a Python function from its module and name."""
108
+ module = __import__(data["module"], fromlist=[data["name"]])
109
+ return getattr(module, data["name"])
110
+
111
+ def _deserialize_dict(self, value: Any) -> Any:
112
+ """Deserialize a dict, restoring non-string key types for the envelope produced by
113
+ convert_to_serializable's dict branch. Plain string-keyed dicts (the common case,
114
+ including dicts produced by older openmodels versions) pass through unchanged.
115
+ """
116
+ if isinstance(value, dict) and value.get("__openmodels_dict__"):
117
+ allowed_key_types = {"int": int, "float": float, "bool": bool, "str": str}
118
+ return {
119
+ allowed_key_types.get(kt, lambda x: x)(
120
+ k
121
+ ): self.convert_from_serializable(v)
122
+ for k, kt, v in zip(value["keys"], value["key_types"], value["values"])
123
+ }
124
+ return value
125
+
126
+ # --- Handlers ---
127
+ def _get_serializer_handlers(self):
128
+ """Each mixin extends this list."""
129
+ return [
130
+ (slice, self._serialize_slice),
131
+ (type, self._serialize_type),
132
+ (Callable, self._serialize_function),
133
+ ]
134
+
135
+ def _get_deserializer_handlers(self):
136
+ return [
137
+ ("bool", bool),
138
+ ("float", float),
139
+ ("int", int),
140
+ ("slice", self._deserialize_slice),
141
+ ("str", str),
142
+ ("type", self._deserialize_type),
143
+ ("tuple", tuple),
144
+ ("dict", self._deserialize_dict),
145
+ ("function", self._deserialize_function),
146
+ ]
147
+
148
+
149
+ class NumpySerializerMixin(SerializerMixin):
150
+ # --- Helpers ---
151
+ def _get_dtype(self, value: Any) -> str:
152
+ """
153
+ Get the dtype of a numpy array, otherwise return empty string.
154
+ """
155
+ if isinstance(value, np.ndarray):
156
+ return str(value.dtype) # Get the actual numpy dtype
157
+ elif isinstance(value, (list, tuple)) and value:
158
+ # If it's a list/tuple that will become an ndarray, check its elements
159
+ first_elem = value[0]
160
+ if isinstance(first_elem, (int, np.integer)):
161
+ return "int32" # Use int32 for integer lists
162
+ elif isinstance(first_elem, (float, np.floating)):
163
+ return "float64" # Use float64 for float lists
164
+ return ""
165
+
166
+ _POOLING_FUNC_REGISTRY = {
167
+ "mean": np.mean,
168
+ "median": np.median,
169
+ "max": np.max,
170
+ "min": np.min,
171
+ "sum": np.sum,
172
+ }
173
+
174
+ # --- NumPy specific serializers/deserializers ---
175
+ def _serialize_ndarray(self, value: np.ndarray):
176
+ return self.convert_to_serializable(value.tolist())
177
+
178
+ def _serialize_generic(self, value: np.generic):
179
+ return value.item()
180
+
181
+ def _deserialize_randomstate(self, value):
182
+ rs = np.random.RandomState()
183
+ rs.set_state(tuple(value))
184
+ return rs
185
+
186
+ def _serialize_numpy_function(self, value):
187
+ # Only handle known numpy functions
188
+ for name, func in self._POOLING_FUNC_REGISTRY.items():
189
+ if value is func:
190
+ return {"numpy_function": name}
191
+ # fallback: use __name__ if possible
192
+ return {"numpy_function": getattr(value, "__name__", None)}
193
+
194
+ def _deserialize_numpy_function(self, value, value_dtype=None):
195
+ name = value.get("numpy_function")
196
+ if name in self._POOLING_FUNC_REGISTRY:
197
+ return self._POOLING_FUNC_REGISTRY[name]
198
+ raise ValueError(f"Unknown numpy function: {name}")
199
+
200
+ # --- Handlers ---
201
+ def _get_serializer_handlers(self):
202
+ return [
203
+ (np.ndarray, self._serialize_ndarray),
204
+ (np.generic, self._serialize_generic),
205
+ (np.dtype, str),
206
+ (type(np.dtype("float64")), str),
207
+ (
208
+ np.random.RandomState,
209
+ lambda v: [self.convert_to_serializable(x) for x in v.get_state()],
210
+ ),
211
+ (type(np.mean), self._serialize_numpy_function),
212
+ ] + super()._get_serializer_handlers()
213
+
214
+ def _get_deserializer_handlers(self):
215
+ return [
216
+ ("ndarray", lambda v, dt=None: np.array(v, dtype=(dt or None))),
217
+ ("generic", lambda v: np.array(v).item()),
218
+ ("float64", np.float64),
219
+ ("int32", int),
220
+ ("int64", int),
221
+ ("dtype", np.dtype),
222
+ ("Float64DType", np.dtype),
223
+ ("RandomState", self._deserialize_randomstate),
224
+ ("_ArrayFunctionDispatcher", self._deserialize_numpy_function),
225
+ ] + super()._get_deserializer_handlers()
226
+
227
+
228
+ class ScipySerializerMixin(SerializerMixin):
229
+ # --- SciPy specific serializers/deserializers ---
230
+ def _serialize_csr_matrix(self, value: csr_matrix):
231
+ csr_value = csr_matrix(value)
232
+ return {
233
+ "data": self.convert_to_serializable(csr_value.data),
234
+ "indptr": self.convert_to_serializable(csr_value.indptr.astype(np.int32)),
235
+ "indices": self.convert_to_serializable(csr_value.indices.astype(np.int32)),
236
+ "shape": self.convert_to_serializable(csr_value.shape),
237
+ "dtype": str(csr_value.data.dtype),
238
+ }
239
+
240
+ def _deserialize_csr_matrix(self, value, value_dtype=None):
241
+ dtype = value.get("dtype", None) or value_dtype or np.float64
242
+ return csr_matrix(
243
+ (
244
+ np.array(value["data"], dtype=dtype),
245
+ np.array(value["indices"], dtype=np.int32),
246
+ np.array(value["indptr"], dtype=np.int32),
247
+ ),
248
+ shape=tuple(value["shape"]),
249
+ )
250
+
251
+ def _serialize_interp1d(self, value: interp1d):
252
+ fill_value = getattr(value, "fill_value", np.nan)
253
+ if isinstance(fill_value, np.ndarray):
254
+ fill_value = self.convert_to_serializable(fill_value)
255
+ return {
256
+ "x": self.convert_to_serializable(value.x),
257
+ "y": self.convert_to_serializable(value.y),
258
+ "kind": getattr(value, "_kind", "linear"),
259
+ "fill_value": fill_value,
260
+ "bounds_error": getattr(value, "bounds_error", None),
261
+ "assume_sorted": getattr(value, "assume_sorted", False),
262
+ "axis": getattr(value, "axis", -1),
263
+ "copy": getattr(value, "copy", True),
264
+ }
265
+
266
+ def _deserialize_interp1d(self, value, value_dtype=None):
267
+ return interp1d(
268
+ x=value["x"],
269
+ y=value["y"],
270
+ kind=value["kind"],
271
+ fill_value=value["fill_value"],
272
+ bounds_error=value["bounds_error"],
273
+ assume_sorted=value["assume_sorted"],
274
+ axis=value["axis"],
275
+ copy=value["copy"],
276
+ )
277
+
278
+ def _serialize_scipy_dist(self, value: rv_continuous_frozen):
279
+ return {"dist_name": value.dist.name, "args": value.args, "kwargs": value.kwds}
280
+
281
+ def _deserialize_scipy_dist(self, value, value_dtype=None):
282
+ dist = getattr(scipy.stats, value["dist_name"])
283
+ return dist(*value["args"], **value["kwargs"])
284
+
285
+ def _serialize_bspline(self, spline: BSpline) -> Dict[str, Any]:
286
+ """
287
+ Serialize a scipy.interpolate.BSpline object.
288
+ """
289
+ return {
290
+ "t": spline.t.tolist(), # Knots
291
+ "c": spline.c.tolist(), # Coefficients
292
+ "k": spline.k, # Degree
293
+ "extrapolate": spline.extrapolate,
294
+ }
295
+
296
+ def _deserialize_bspline(self, data: Dict[str, Any]) -> BSpline:
297
+ """
298
+ Deserialize a dictionary back into a scipy.interpolate.BSpline object.
299
+ """
300
+ return BSpline(
301
+ t=np.array(data["t"]),
302
+ c=np.array(data["c"]),
303
+ k=data["k"],
304
+ extrapolate=data["extrapolate"],
305
+ )
306
+
307
+ # --- Handlers ---
308
+ def _get_serializer_handlers(self):
309
+ return [
310
+ (BSpline, self._serialize_bspline),
311
+ # csr_matrix is the only sparse container openmodels round-trips on the wire, but
312
+ # any scipy sparse container (the older *_matrix family or the newer array-API
313
+ # *_array family) is accepted here - _serialize_csr_matrix normalizes it to csr via
314
+ # the csr_matrix(value) constructor, which accepts any sparse-like input.
315
+ (
316
+ (csr_matrix, csc_matrix, csr_array, csc_array),
317
+ self._serialize_csr_matrix,
318
+ ),
319
+ (interp1d, self._serialize_interp1d),
320
+ (rv_continuous_frozen, self._serialize_scipy_dist),
321
+ ] + super()._get_serializer_handlers()
322
+
323
+ def _get_deserializer_handlers(self):
324
+ return [
325
+ ("BSpline", self._deserialize_bspline),
326
+ ("csr_matrix", self._deserialize_csr_matrix),
327
+ ("interp1d", self._deserialize_interp1d),
328
+ ("scipy_dist", self._deserialize_scipy_dist),
329
+ ] + super()._get_deserializer_handlers()
File without changes
@@ -0,0 +1,73 @@
1
+ import inspect
2
+ import warnings
3
+ from typing import Any, Callable, Dict, List, Tuple, Type, Union
4
+
5
+
6
+ def is_valid_estimator(name: str, cls: Any) -> bool:
7
+ """Check whether (name, cls) represents a valid sklearn estimator."""
8
+
9
+ if not isinstance(name, str):
10
+ return False
11
+ if not inspect.isclass(cls):
12
+ return False
13
+ try:
14
+ from sklearn.base import BaseEstimator
15
+
16
+ return issubclass(cls, BaseEstimator)
17
+ except TypeError:
18
+ return False
19
+
20
+
21
+ def normalize_estimators(
22
+ estimators: Union[Callable[..., Any], List[Any], Tuple[Any, ...], Dict[str, Any]],
23
+ ) -> List[Any]:
24
+ """Normalize input into a flat list of estimators or (name, class) items."""
25
+ if not isinstance(estimators, (list, tuple, set)):
26
+ return [estimators]
27
+ return list(estimators)
28
+
29
+
30
+ def load_custom_estimators(
31
+ custom_estimators: Union[
32
+ Callable[..., Any], List[Any], Tuple[Any, ...], Dict[str, Any]
33
+ ],
34
+ all_estimators: Dict[str, Type],
35
+ ) -> Dict[str, Type]:
36
+ """Convert user-provided estimators into a dictionary of valid ones."""
37
+ extra = {}
38
+ for est in normalize_estimators(custom_estimators):
39
+ try:
40
+ items = est() if callable(est) else est
41
+ except Exception:
42
+ warnings.warn("Failed to call custom_estimator(); skipping.", UserWarning)
43
+ continue
44
+
45
+ if items is None:
46
+ continue
47
+
48
+ if isinstance(items, dict):
49
+ iterator = items.items()
50
+ else:
51
+ iterator = items
52
+
53
+ for item in iterator:
54
+ try:
55
+ name, cls = item
56
+ except Exception:
57
+ warnings.warn(
58
+ "Unexpected custom_estimator format; skipping.", UserWarning
59
+ )
60
+ continue
61
+
62
+ if not is_valid_estimator(name, cls):
63
+ continue
64
+
65
+ if name in all_estimators and all_estimators[name] is not cls:
66
+ warnings.warn(
67
+ f"Estimator '{name}' conflicts with built-in one; preferring custom version.",
68
+ UserWarning,
69
+ )
70
+
71
+ extra[name] = cls
72
+
73
+ return extra