nosj 0.1.1__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,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: nosj
3
+ Version: 0.1.1
4
+ Summary: JSON encoding/decoding for Numpy arrays and scalars
5
+ Author-email: mpgriff <mpg@geo.au.dk>
6
+ Maintainer-email: mpgriff <mpg@geo.au.dk>
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Matthew Griffiths <mpg@geo.au.dk>
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Project-URL: Homepage, https://github.com/mpgriff/nosj
30
+ Project-URL: Repository, https://github.com/mpgriff/nosj.git
31
+ Project-URL: Issues, https://github.com/mpgriff/nosj/issues
32
+ Requires-Python: >=3.8
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE.txt
35
+ Requires-Dist: json-numpy
36
+ Requires-Dist: numpy
37
+ Provides-Extra: torch
38
+ Requires-Dist: torch; extra == "torch"
39
+ Dynamic: license-file
40
+
41
+ Nosj allows you to create and save dataclasses to json and reload them easily.
@@ -0,0 +1,6 @@
1
+ nosj.py,sha256=SJVhsZ-ReMn4BHpQ2uNWCqkGzrr4PGPFGkzBYHc4Erg,10914
2
+ nosj-0.1.1.dist-info/licenses/LICENSE.txt,sha256=sz5oSAlvcLttj9UKMz1Fjwz-Uoym71aW7mT3wx1l3yg,1111
3
+ nosj-0.1.1.dist-info/METADATA,sha256=BKUpgoxKRgTyXIg9Gm38uebVDp3EpjZdMaalkC51hfc,1973
4
+ nosj-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ nosj-0.1.1.dist-info/top_level.txt,sha256=jvQH-oXM9XBZ0XMCOhFD4wOsHoSU7f5EHN032dauIKQ,5
6
+ nosj-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthew Griffiths <mpg@geo.au.dk>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ nosj
nosj.py ADDED
@@ -0,0 +1,275 @@
1
+ __version__ = "0.1.1"
2
+
3
+ __all__ = ['nosj']
4
+
5
+
6
+ from dataclasses import dataclass, replace, asdict as dataclass2dict
7
+ from typing import List, _GenericAlias
8
+ import json
9
+ import json_numpy
10
+ json_numpy.patch()
11
+
12
+ from numpy import ndarray, allclose, array
13
+ from numpy.lib.format import descr_to_dtype, dtype_to_descr
14
+
15
+
16
+ def update(self, **kwargs):
17
+ return replace(self, **kwargs)
18
+
19
+ def _to_nosj(self, binary_threshold=100):
20
+ if self.extension is not None and '.' not in fname:
21
+ fname = fname + '.' + self.extension
22
+ if self.extension is not None:
23
+ assert fname.endswith('.' + self.extension), 'File extension does not match class extension'
24
+
25
+
26
+ other = self.copy()
27
+
28
+ for key,val in other.__dict__.items():
29
+ if (hasattr(val, '_description') and val._description is not None) and (hasattr(val, 'extension') and val.extension is not None):
30
+ if val._description.endswith(val.extension):
31
+ exec(f'other.{key} = val._description')
32
+ elif hasattr(val, '_to_nosj'):
33
+ exec(f'other.{key} = val._to_nosj(binary_threshold=binary_threshold)')
34
+ elif isinstance(val, List) and len(val)>0:
35
+ new_list = [x if not hasattr(x, '_to_nosj') else x._to_nosj(binary_threshold=binary_threshold) for x in val]
36
+ exec(f'other.{key} = new_list')
37
+ elif isinstance(val, ndarray) and val.size<=binary_threshold:
38
+ descr = dtype_to_descr(val.dtype)
39
+ array_dict = {
40
+ '__numpy_str__': ' '.join(val.__repr__().replace('\n', '').split()),
41
+ 'dtype': descr,
42
+ 'shape': val.shape,
43
+ }
44
+ exec(f'other.{key} = array_dict')
45
+
46
+ if not hasattr(other, '_description'):
47
+ other._description = fname
48
+
49
+ return dataclass2dict(other)
50
+
51
+
52
+ def save(self, fname, binary_threshold=100):
53
+ res = json.dumps(self._to_nosj(binary_threshold=binary_threshold), indent=4)
54
+ with open(fname, 'wt') as f:
55
+ f.write(res)
56
+
57
+ @classmethod
58
+ def load(cls, fname, load_subclasses=False):
59
+ with open(fname, 'rb') as f:
60
+ res = json.loads(f.read())
61
+ res = cls._reinstantiate_subclasses(cls, res, load_subclasses=load_subclasses)
62
+ return res
63
+
64
+ def __hash__(self):
65
+ descript = self._description
66
+ self._description = 'hash'
67
+ res = hash(self.__repr__())
68
+ self._description = descript
69
+ return res
70
+
71
+ def __eq__(self, other):
72
+ is_equal = hash(self) == hash(other)
73
+ if is_equal:
74
+ for x in self.__class__.__annotations__.keys():
75
+ cvar = vars(self)[x]
76
+ ovar = vars(other)[x]
77
+
78
+ if x == '_description':
79
+ continue
80
+ elif isinstance(cvar, ndarray):
81
+ var_equal = allclose(cvar, ovar)
82
+ else:
83
+ var_equal = (cvar == ovar)
84
+ is_equal = is_equal and var_equal
85
+ return is_equal
86
+
87
+ def reinstantiate_subclasses(cls, d, load_subclasses=False):
88
+ """recursive function to get attributes back into their right classes"""
89
+ if not hasattr(cls, '__annotations__') and '__numpy_str__' in d:
90
+ return eval(d['__numpy_str__']).astype(d.pop('dtype')).reshape(d.pop('shape'))
91
+
92
+ if cls.__base__ != (object, str) and hasattr(cls.__base__, '__annotations__'):
93
+ class_dict = cls.__annotations__ | cls.__base__.__annotations__
94
+ else:
95
+ class_dict = cls.__annotations__
96
+
97
+ if hasattr(d, 'keys'):
98
+ for key in d.keys():
99
+
100
+ if class_dict[key] != type(d[key]) and type(d[key]) == dict:
101
+ d[key] = reinstantiate_subclasses(class_dict[key], d[key])
102
+ elif isinstance(class_dict[key], _GenericAlias):
103
+ subclass = [x for x in class_dict[key].__args__]
104
+ if len(subclass) < len(d[key]):
105
+ subclass = subclass * len(d[key])
106
+ if hasattr(subclass[0], '__annotations__'):
107
+ d[key] = [reinstantiate_subclasses(const, x, load_subclasses=load_subclasses) for const, x in zip(subclass,d[key])]
108
+ else:
109
+ d[key] = [x for const, x in zip(subclass,d[key])]
110
+
111
+ elif class_dict[key] == ndarray:
112
+ pass
113
+ elif class_dict[key] != type(d[key]) and type(d[key]) == str and '.' in d[key] and load_subclasses:
114
+ d[key] = class_dict[key].load(d[key])
115
+ elif class_dict[key] != type(d[key]) and load_subclasses:
116
+ if d[key] is not None:
117
+ d[key] = class_dict[key](**d[key])
118
+
119
+ return cls(**d)
120
+ elif isinstance(d, str) and load_subclasses:
121
+ return cls.load(d)
122
+ else:
123
+ return d
124
+
125
+ def copy(self):
126
+ return replace(self)
127
+
128
+ try:
129
+ from torch import allclose as torch_allclose, Tensor, from_numpy
130
+ TORCH_ENABLED = True
131
+ print('torch detected, enabling torch tensor support in nosj')
132
+ except ImportError:
133
+ TORCH_ENABLED = False
134
+ print('torch not detected, skipping torch tensor support in nosj')
135
+
136
+ if TORCH_ENABLED:
137
+
138
+ def _to_nosj(self, binary_threshold=100):
139
+ if self.extension is not None and '.' not in fname:
140
+ fname = fname + '.' + self.extension
141
+ if self.extension is not None:
142
+ assert fname.endswith('.' + self.extension), 'File extension does not match class extension'
143
+
144
+
145
+ other = self.copy()
146
+ torch_keys = []
147
+ for key,val in other.__dict__.items():
148
+ if isinstance(val, Tensor):
149
+ exec(f'other.{key} = val.numpy()')
150
+ if key in other.__annotations__:
151
+ torch_keys.append(key)
152
+
153
+ for key,val in other.__dict__.items():
154
+ if (hasattr(val, '_description') and val._description is not None) and (hasattr(val, 'extension') and val.extension is not None):
155
+ if val._description.endswith(val.extension):
156
+ exec(f'other.{key} = val._description')
157
+ elif isinstance(val, ndarray) and val.size<=binary_threshold:
158
+ descr = dtype_to_descr(val.dtype)
159
+ array_dict = {
160
+ '__numpy_str__': ' '.join(val.__repr__().replace('\n', '').split()),
161
+ 'dtype': descr,
162
+ 'shape': val.shape,
163
+ }
164
+ exec(f'other.{key} = array_dict')
165
+ elif hasattr(val, '_to_nosj'):
166
+ exec(f'other.{key} = val._to_nosj(binary_threshold=binary_threshold)')
167
+
168
+ if not hasattr(other, '_description'):
169
+ other._description = fname
170
+
171
+ dictionary_rep = dataclass2dict(other)
172
+ if len(torch_keys)>0: dictionary_rep['_torch_keys'] = torch_keys
173
+ return dictionary_rep
174
+
175
+ def reinstantiate_subclasses(cls, d, load_subclasses=False):
176
+ """recursive function to get attributes back into their right classes"""
177
+ if '_torch_keys' in d:
178
+ torch_keys = d.pop('_torch_keys')
179
+ else:
180
+ torch_keys = []
181
+
182
+ if '__numpy_str__' in d:
183
+ cdata = eval(d['__numpy_str__']).astype(d.pop('dtype')).reshape(d.pop('shape'))
184
+ if cls == Tensor: cdata = from_numpy(cdata)
185
+ return cdata
186
+
187
+ if cls.__base__ != (object, str) and hasattr(cls.__base__, '__annotations__'):
188
+ class_dict = cls.__annotations__ | cls.__base__.__annotations__
189
+ else:
190
+ class_dict = cls.__annotations__
191
+
192
+ if hasattr(d, 'keys'):
193
+ for key in d.keys():
194
+ if class_dict[key] != type(d[key]) and type(d[key]) == dict:
195
+ d[key] = reinstantiate_subclasses(class_dict[key], d[key])
196
+ elif isinstance(class_dict[key], _GenericAlias):
197
+ subclass = [x for x in class_dict[key].__args__]
198
+ if len(subclass) < len(d[key]):
199
+ subclass = subclass * len(d[key])
200
+ if hasattr(subclass[0], '__annotations__'):
201
+ d[key] = [reinstantiate_subclasses(const, x, load_subclasses=load_subclasses) for const, x in zip(subclass,d[key])]
202
+ else:
203
+ d[key] = [x for const, x in zip(subclass,d[key])]
204
+
205
+ elif class_dict[key] == ndarray or class_dict[key] == Tensor:
206
+ pass
207
+
208
+ elif class_dict[key] != type(d[key]) and type(d[key]) == str and '.' in d[key] and load_subclasses:
209
+ d[key] = class_dict[key].load(d[key])
210
+ elif class_dict[key] != type(d[key]) and load_subclasses:
211
+ if d[key] is not None:
212
+ d[key] = class_dict[key](**d[key])
213
+ if len(torch_keys)>0:
214
+ for key in torch_keys:
215
+ if isinstance(d[key], ndarray):
216
+ d[key] = from_numpy(array(d[key]))
217
+ return cls(**d)
218
+
219
+ elif isinstance(d, str) and load_subclasses:
220
+ return cls.load(d)
221
+ else:
222
+ return d
223
+
224
+ # @classmethod
225
+ # def load(cls, fname, load_subclasses=False):
226
+ # with open(fname, 'rb') as f:
227
+ # res = json.loads(f.read())
228
+ # if '_torch_keys' in res:
229
+ # torch_keys = res.pop('_torch_keys')
230
+ # for key in torch_keys:
231
+ # if isinstance(res[key], dict) and '__numpy_str__' in res[key]:
232
+ # res[key] = eval(res[key]['__numpy_str__']).astype(res[key]['dtype']).reshape(res[key]['shape'])
233
+ # res[key] = from_numpy(res[key])
234
+ # res = cls._reinstantiate_subclasses(cls, res, load_subclasses=load_subclasses)
235
+ # return res
236
+
237
+
238
+
239
+
240
+ def __eq__(self, other):
241
+ is_equal = hash(self) == hash(other)
242
+ if is_equal:
243
+ for x in self.__class__.__annotations__.keys():
244
+ cvar = vars(self)[x]
245
+ ovar = vars(other)[x]
246
+
247
+ if x == '_description':
248
+ continue
249
+ elif isinstance(cvar, ndarray):
250
+ var_equal = allclose(cvar, ovar)
251
+ elif isinstance(cvar, Tensor):
252
+ var_equal = torch_allclose(cvar, ovar)
253
+ else:
254
+ var_equal = (cvar == ovar)
255
+ is_equal = is_equal and var_equal
256
+ return is_equal
257
+
258
+
259
+
260
+
261
+ def nosj(cls):
262
+ cls._description = cls.__name__.split('.')[-1]
263
+ if 'extension' not in cls.__dict__:
264
+ cls.extension = None
265
+ cls.update = update
266
+ cls._to_nosj = _to_nosj
267
+ cls.__hash__ = __hash__
268
+ cls.__eq__ = __eq__
269
+ cls.save = save
270
+ cls.load = load
271
+ cls._reinstantiate_subclasses = reinstantiate_subclasses
272
+ cls.copy = copy
273
+
274
+
275
+ return dataclass(cls)