numcodecs-random-projection 0.1.0a1__tar.gz
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.
- numcodecs_random_projection-0.1.0a1/.gitignore +14 -0
- numcodecs_random_projection-0.1.0a1/LICENSE +375 -0
- numcodecs_random_projection-0.1.0a1/PKG-INFO +64 -0
- numcodecs_random_projection-0.1.0a1/README.md +22 -0
- numcodecs_random_projection-0.1.0a1/pyproject.toml +78 -0
- numcodecs_random_projection-0.1.0a1/src/numcodecs_random_projection/__init__.py +629 -0
- numcodecs_random_projection-0.1.0a1/src/numcodecs_random_projection/mt_rng.py +88 -0
- numcodecs_random_projection-0.1.0a1/src/numcodecs_random_projection/py.typed +0 -0
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
Copyright (c) 2025-2026, Sami Sidoroff and Juniper Tyree
|
|
2
|
+
|
|
3
|
+
Mozilla Public License Version 2.0
|
|
4
|
+
==================================
|
|
5
|
+
|
|
6
|
+
1. Definitions
|
|
7
|
+
--------------
|
|
8
|
+
|
|
9
|
+
1.1. "Contributor"
|
|
10
|
+
means each individual or legal entity that creates, contributes to
|
|
11
|
+
the creation of, or owns Covered Software.
|
|
12
|
+
|
|
13
|
+
1.2. "Contributor Version"
|
|
14
|
+
means the combination of the Contributions of others (if any) used
|
|
15
|
+
by a Contributor and that particular Contributor's Contribution.
|
|
16
|
+
|
|
17
|
+
1.3. "Contribution"
|
|
18
|
+
means Covered Software of a particular Contributor.
|
|
19
|
+
|
|
20
|
+
1.4. "Covered Software"
|
|
21
|
+
means Source Code Form to which the initial Contributor has attached
|
|
22
|
+
the notice in Exhibit A, the Executable Form of such Source Code
|
|
23
|
+
Form, and Modifications of such Source Code Form, in each case
|
|
24
|
+
including portions thereof.
|
|
25
|
+
|
|
26
|
+
1.5. "Incompatible With Secondary Licenses"
|
|
27
|
+
means
|
|
28
|
+
|
|
29
|
+
(a) that the initial Contributor has attached the notice described
|
|
30
|
+
in Exhibit B to the Covered Software; or
|
|
31
|
+
|
|
32
|
+
(b) that the Covered Software was made available under the terms of
|
|
33
|
+
version 1.1 or earlier of the License, but not also under the
|
|
34
|
+
terms of a Secondary License.
|
|
35
|
+
|
|
36
|
+
1.6. "Executable Form"
|
|
37
|
+
means any form of the work other than Source Code Form.
|
|
38
|
+
|
|
39
|
+
1.7. "Larger Work"
|
|
40
|
+
means a work that combines Covered Software with other material, in
|
|
41
|
+
a separate file or files, that is not Covered Software.
|
|
42
|
+
|
|
43
|
+
1.8. "License"
|
|
44
|
+
means this document.
|
|
45
|
+
|
|
46
|
+
1.9. "Licensable"
|
|
47
|
+
means having the right to grant, to the maximum extent possible,
|
|
48
|
+
whether at the time of the initial grant or subsequently, any and
|
|
49
|
+
all of the rights conveyed by this License.
|
|
50
|
+
|
|
51
|
+
1.10. "Modifications"
|
|
52
|
+
means any of the following:
|
|
53
|
+
|
|
54
|
+
(a) any file in Source Code Form that results from an addition to,
|
|
55
|
+
deletion from, or modification of the contents of Covered
|
|
56
|
+
Software; or
|
|
57
|
+
|
|
58
|
+
(b) any new file in Source Code Form that contains any Covered
|
|
59
|
+
Software.
|
|
60
|
+
|
|
61
|
+
1.11. "Patent Claims" of a Contributor
|
|
62
|
+
means any patent claim(s), including without limitation, method,
|
|
63
|
+
process, and apparatus claims, in any patent Licensable by such
|
|
64
|
+
Contributor that would be infringed, but for the grant of the
|
|
65
|
+
License, by the making, using, selling, offering for sale, having
|
|
66
|
+
made, import, or transfer of either its Contributions or its
|
|
67
|
+
Contributor Version.
|
|
68
|
+
|
|
69
|
+
1.12. "Secondary License"
|
|
70
|
+
means either the GNU General Public License, Version 2.0, the GNU
|
|
71
|
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
|
72
|
+
Public License, Version 3.0, or any later versions of those
|
|
73
|
+
licenses.
|
|
74
|
+
|
|
75
|
+
1.13. "Source Code Form"
|
|
76
|
+
means the form of the work preferred for making modifications.
|
|
77
|
+
|
|
78
|
+
1.14. "You" (or "Your")
|
|
79
|
+
means an individual or a legal entity exercising rights under this
|
|
80
|
+
License. For legal entities, "You" includes any entity that
|
|
81
|
+
controls, is controlled by, or is under common control with You. For
|
|
82
|
+
purposes of this definition, "control" means (a) the power, direct
|
|
83
|
+
or indirect, to cause the direction or management of such entity,
|
|
84
|
+
whether by contract or otherwise, or (b) ownership of more than
|
|
85
|
+
fifty percent (50%) of the outstanding shares or beneficial
|
|
86
|
+
ownership of such entity.
|
|
87
|
+
|
|
88
|
+
2. License Grants and Conditions
|
|
89
|
+
--------------------------------
|
|
90
|
+
|
|
91
|
+
2.1. Grants
|
|
92
|
+
|
|
93
|
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
|
94
|
+
non-exclusive license:
|
|
95
|
+
|
|
96
|
+
(a) under intellectual property rights (other than patent or trademark)
|
|
97
|
+
Licensable by such Contributor to use, reproduce, make available,
|
|
98
|
+
modify, display, perform, distribute, and otherwise exploit its
|
|
99
|
+
Contributions, either on an unmodified basis, with Modifications, or
|
|
100
|
+
as part of a Larger Work; and
|
|
101
|
+
|
|
102
|
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
|
103
|
+
for sale, have made, import, and otherwise transfer either its
|
|
104
|
+
Contributions or its Contributor Version.
|
|
105
|
+
|
|
106
|
+
2.2. Effective Date
|
|
107
|
+
|
|
108
|
+
The licenses granted in Section 2.1 with respect to any Contribution
|
|
109
|
+
become effective for each Contribution on the date the Contributor first
|
|
110
|
+
distributes such Contribution.
|
|
111
|
+
|
|
112
|
+
2.3. Limitations on Grant Scope
|
|
113
|
+
|
|
114
|
+
The licenses granted in this Section 2 are the only rights granted under
|
|
115
|
+
this License. No additional rights or licenses will be implied from the
|
|
116
|
+
distribution or licensing of Covered Software under this License.
|
|
117
|
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
|
118
|
+
Contributor:
|
|
119
|
+
|
|
120
|
+
(a) for any code that a Contributor has removed from Covered Software;
|
|
121
|
+
or
|
|
122
|
+
|
|
123
|
+
(b) for infringements caused by: (i) Your and any other third party's
|
|
124
|
+
modifications of Covered Software, or (ii) the combination of its
|
|
125
|
+
Contributions with other software (except as part of its Contributor
|
|
126
|
+
Version); or
|
|
127
|
+
|
|
128
|
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
|
129
|
+
its Contributions.
|
|
130
|
+
|
|
131
|
+
This License does not grant any rights in the trademarks, service marks,
|
|
132
|
+
or logos of any Contributor (except as may be necessary to comply with
|
|
133
|
+
the notice requirements in Section 3.4).
|
|
134
|
+
|
|
135
|
+
2.4. Subsequent Licenses
|
|
136
|
+
|
|
137
|
+
No Contributor makes additional grants as a result of Your choice to
|
|
138
|
+
distribute the Covered Software under a subsequent version of this
|
|
139
|
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
|
140
|
+
permitted under the terms of Section 3.3).
|
|
141
|
+
|
|
142
|
+
2.5. Representation
|
|
143
|
+
|
|
144
|
+
Each Contributor represents that the Contributor believes its
|
|
145
|
+
Contributions are its original creation(s) or it has sufficient rights
|
|
146
|
+
to grant the rights to its Contributions conveyed by this License.
|
|
147
|
+
|
|
148
|
+
2.6. Fair Use
|
|
149
|
+
|
|
150
|
+
This License is not intended to limit any rights You have under
|
|
151
|
+
applicable copyright doctrines of fair use, fair dealing, or other
|
|
152
|
+
equivalents.
|
|
153
|
+
|
|
154
|
+
2.7. Conditions
|
|
155
|
+
|
|
156
|
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
|
157
|
+
in Section 2.1.
|
|
158
|
+
|
|
159
|
+
3. Responsibilities
|
|
160
|
+
-------------------
|
|
161
|
+
|
|
162
|
+
3.1. Distribution of Source Form
|
|
163
|
+
|
|
164
|
+
All distribution of Covered Software in Source Code Form, including any
|
|
165
|
+
Modifications that You create or to which You contribute, must be under
|
|
166
|
+
the terms of this License. You must inform recipients that the Source
|
|
167
|
+
Code Form of the Covered Software is governed by the terms of this
|
|
168
|
+
License, and how they can obtain a copy of this License. You may not
|
|
169
|
+
attempt to alter or restrict the recipients' rights in the Source Code
|
|
170
|
+
Form.
|
|
171
|
+
|
|
172
|
+
3.2. Distribution of Executable Form
|
|
173
|
+
|
|
174
|
+
If You distribute Covered Software in Executable Form then:
|
|
175
|
+
|
|
176
|
+
(a) such Covered Software must also be made available in Source Code
|
|
177
|
+
Form, as described in Section 3.1, and You must inform recipients of
|
|
178
|
+
the Executable Form how they can obtain a copy of such Source Code
|
|
179
|
+
Form by reasonable means in a timely manner, at a charge no more
|
|
180
|
+
than the cost of distribution to the recipient; and
|
|
181
|
+
|
|
182
|
+
(b) You may distribute such Executable Form under the terms of this
|
|
183
|
+
License, or sublicense it under different terms, provided that the
|
|
184
|
+
license for the Executable Form does not attempt to limit or alter
|
|
185
|
+
the recipients' rights in the Source Code Form under this License.
|
|
186
|
+
|
|
187
|
+
3.3. Distribution of a Larger Work
|
|
188
|
+
|
|
189
|
+
You may create and distribute a Larger Work under terms of Your choice,
|
|
190
|
+
provided that You also comply with the requirements of this License for
|
|
191
|
+
the Covered Software. If the Larger Work is a combination of Covered
|
|
192
|
+
Software with a work governed by one or more Secondary Licenses, and the
|
|
193
|
+
Covered Software is not Incompatible With Secondary Licenses, this
|
|
194
|
+
License permits You to additionally distribute such Covered Software
|
|
195
|
+
under the terms of such Secondary License(s), so that the recipient of
|
|
196
|
+
the Larger Work may, at their option, further distribute the Covered
|
|
197
|
+
Software under the terms of either this License or such Secondary
|
|
198
|
+
License(s).
|
|
199
|
+
|
|
200
|
+
3.4. Notices
|
|
201
|
+
|
|
202
|
+
You may not remove or alter the substance of any license notices
|
|
203
|
+
(including copyright notices, patent notices, disclaimers of warranty,
|
|
204
|
+
or limitations of liability) contained within the Source Code Form of
|
|
205
|
+
the Covered Software, except that You may alter any license notices to
|
|
206
|
+
the extent required to remedy known factual inaccuracies.
|
|
207
|
+
|
|
208
|
+
3.5. Application of Additional Terms
|
|
209
|
+
|
|
210
|
+
You may choose to offer, and to charge a fee for, warranty, support,
|
|
211
|
+
indemnity or liability obligations to one or more recipients of Covered
|
|
212
|
+
Software. However, You may do so only on Your own behalf, and not on
|
|
213
|
+
behalf of any Contributor. You must make it absolutely clear that any
|
|
214
|
+
such warranty, support, indemnity, or liability obligation is offered by
|
|
215
|
+
You alone, and You hereby agree to indemnify every Contributor for any
|
|
216
|
+
liability incurred by such Contributor as a result of warranty, support,
|
|
217
|
+
indemnity or liability terms You offer. You may include additional
|
|
218
|
+
disclaimers of warranty and limitations of liability specific to any
|
|
219
|
+
jurisdiction.
|
|
220
|
+
|
|
221
|
+
4. Inability to Comply Due to Statute or Regulation
|
|
222
|
+
---------------------------------------------------
|
|
223
|
+
|
|
224
|
+
If it is impossible for You to comply with any of the terms of this
|
|
225
|
+
License with respect to some or all of the Covered Software due to
|
|
226
|
+
statute, judicial order, or regulation then You must: (a) comply with
|
|
227
|
+
the terms of this License to the maximum extent possible; and (b)
|
|
228
|
+
describe the limitations and the code they affect. Such description must
|
|
229
|
+
be placed in a text file included with all distributions of the Covered
|
|
230
|
+
Software under this License. Except to the extent prohibited by statute
|
|
231
|
+
or regulation, such description must be sufficiently detailed for a
|
|
232
|
+
recipient of ordinary skill to be able to understand it.
|
|
233
|
+
|
|
234
|
+
5. Termination
|
|
235
|
+
--------------
|
|
236
|
+
|
|
237
|
+
5.1. The rights granted under this License will terminate automatically
|
|
238
|
+
if You fail to comply with any of its terms. However, if You become
|
|
239
|
+
compliant, then the rights granted under this License from a particular
|
|
240
|
+
Contributor are reinstated (a) provisionally, unless and until such
|
|
241
|
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
|
242
|
+
ongoing basis, if such Contributor fails to notify You of the
|
|
243
|
+
non-compliance by some reasonable means prior to 60 days after You have
|
|
244
|
+
come back into compliance. Moreover, Your grants from a particular
|
|
245
|
+
Contributor are reinstated on an ongoing basis if such Contributor
|
|
246
|
+
notifies You of the non-compliance by some reasonable means, this is the
|
|
247
|
+
first time You have received notice of non-compliance with this License
|
|
248
|
+
from such Contributor, and You become compliant prior to 30 days after
|
|
249
|
+
Your receipt of the notice.
|
|
250
|
+
|
|
251
|
+
5.2. If You initiate litigation against any entity by asserting a patent
|
|
252
|
+
infringement claim (excluding declaratory judgment actions,
|
|
253
|
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
|
254
|
+
directly or indirectly infringes any patent, then the rights granted to
|
|
255
|
+
You by any and all Contributors for the Covered Software under Section
|
|
256
|
+
2.1 of this License shall terminate.
|
|
257
|
+
|
|
258
|
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
|
259
|
+
end user license agreements (excluding distributors and resellers) which
|
|
260
|
+
have been validly granted by You or Your distributors under this License
|
|
261
|
+
prior to termination shall survive termination.
|
|
262
|
+
|
|
263
|
+
************************************************************************
|
|
264
|
+
* *
|
|
265
|
+
* 6. Disclaimer of Warranty *
|
|
266
|
+
* ------------------------- *
|
|
267
|
+
* *
|
|
268
|
+
* Covered Software is provided under this License on an "as is" *
|
|
269
|
+
* basis, without warranty of any kind, either expressed, implied, or *
|
|
270
|
+
* statutory, including, without limitation, warranties that the *
|
|
271
|
+
* Covered Software is free of defects, merchantable, fit for a *
|
|
272
|
+
* particular purpose or non-infringing. The entire risk as to the *
|
|
273
|
+
* quality and performance of the Covered Software is with You. *
|
|
274
|
+
* Should any Covered Software prove defective in any respect, You *
|
|
275
|
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
|
276
|
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
|
277
|
+
* essential part of this License. No use of any Covered Software is *
|
|
278
|
+
* authorized under this License except under this disclaimer. *
|
|
279
|
+
* *
|
|
280
|
+
************************************************************************
|
|
281
|
+
|
|
282
|
+
************************************************************************
|
|
283
|
+
* *
|
|
284
|
+
* 7. Limitation of Liability *
|
|
285
|
+
* -------------------------- *
|
|
286
|
+
* *
|
|
287
|
+
* Under no circumstances and under no legal theory, whether tort *
|
|
288
|
+
* (including negligence), contract, or otherwise, shall any *
|
|
289
|
+
* Contributor, or anyone who distributes Covered Software as *
|
|
290
|
+
* permitted above, be liable to You for any direct, indirect, *
|
|
291
|
+
* special, incidental, or consequential damages of any character *
|
|
292
|
+
* including, without limitation, damages for lost profits, loss of *
|
|
293
|
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
|
294
|
+
* and all other commercial damages or losses, even if such party *
|
|
295
|
+
* shall have been informed of the possibility of such damages. This *
|
|
296
|
+
* limitation of liability shall not apply to liability for death or *
|
|
297
|
+
* personal injury resulting from such party's negligence to the *
|
|
298
|
+
* extent applicable law prohibits such limitation. Some *
|
|
299
|
+
* jurisdictions do not allow the exclusion or limitation of *
|
|
300
|
+
* incidental or consequential damages, so this exclusion and *
|
|
301
|
+
* limitation may not apply to You. *
|
|
302
|
+
* *
|
|
303
|
+
************************************************************************
|
|
304
|
+
|
|
305
|
+
8. Litigation
|
|
306
|
+
-------------
|
|
307
|
+
|
|
308
|
+
Any litigation relating to this License may be brought only in the
|
|
309
|
+
courts of a jurisdiction where the defendant maintains its principal
|
|
310
|
+
place of business and such litigation shall be governed by laws of that
|
|
311
|
+
jurisdiction, without reference to its conflict-of-law provisions.
|
|
312
|
+
Nothing in this Section shall prevent a party's ability to bring
|
|
313
|
+
cross-claims or counter-claims.
|
|
314
|
+
|
|
315
|
+
9. Miscellaneous
|
|
316
|
+
----------------
|
|
317
|
+
|
|
318
|
+
This License represents the complete agreement concerning the subject
|
|
319
|
+
matter hereof. If any provision of this License is held to be
|
|
320
|
+
unenforceable, such provision shall be reformed only to the extent
|
|
321
|
+
necessary to make it enforceable. Any law or regulation which provides
|
|
322
|
+
that the language of a contract shall be construed against the drafter
|
|
323
|
+
shall not be used to construe this License against a Contributor.
|
|
324
|
+
|
|
325
|
+
10. Versions of the License
|
|
326
|
+
---------------------------
|
|
327
|
+
|
|
328
|
+
10.1. New Versions
|
|
329
|
+
|
|
330
|
+
Mozilla Foundation is the license steward. Except as provided in Section
|
|
331
|
+
10.3, no one other than the license steward has the right to modify or
|
|
332
|
+
publish new versions of this License. Each version will be given a
|
|
333
|
+
distinguishing version number.
|
|
334
|
+
|
|
335
|
+
10.2. Effect of New Versions
|
|
336
|
+
|
|
337
|
+
You may distribute the Covered Software under the terms of the version
|
|
338
|
+
of the License under which You originally received the Covered Software,
|
|
339
|
+
or under the terms of any subsequent version published by the license
|
|
340
|
+
steward.
|
|
341
|
+
|
|
342
|
+
10.3. Modified Versions
|
|
343
|
+
|
|
344
|
+
If you create software not governed by this License, and you want to
|
|
345
|
+
create a new license for such software, you may create and use a
|
|
346
|
+
modified version of this License if you rename the license and remove
|
|
347
|
+
any references to the name of the license steward (except to note that
|
|
348
|
+
such modified license differs from this License).
|
|
349
|
+
|
|
350
|
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
|
351
|
+
Licenses
|
|
352
|
+
|
|
353
|
+
If You choose to distribute Source Code Form that is Incompatible With
|
|
354
|
+
Secondary Licenses under the terms of this version of the License, the
|
|
355
|
+
notice described in Exhibit B of this License must be attached.
|
|
356
|
+
|
|
357
|
+
Exhibit A - Source Code Form License Notice
|
|
358
|
+
-------------------------------------------
|
|
359
|
+
|
|
360
|
+
This Source Code Form is subject to the terms of the Mozilla Public
|
|
361
|
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
362
|
+
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
363
|
+
|
|
364
|
+
If it is not possible or desirable to put the notice in a particular
|
|
365
|
+
file, then You may include the notice in a location (such as a LICENSE
|
|
366
|
+
file in a relevant directory) where a recipient would be likely to look
|
|
367
|
+
for such a notice.
|
|
368
|
+
|
|
369
|
+
You may add additional accurate notices of copyright ownership.
|
|
370
|
+
|
|
371
|
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
|
372
|
+
---------------------------------------------------------
|
|
373
|
+
|
|
374
|
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
|
375
|
+
defined by the Mozilla Public License, v. 2.0.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: numcodecs-random-projection
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Random projection codec for the `numcodecs` buffer compression API
|
|
5
|
+
Project-URL: Documentation, https://sidorow.github.io/numcodecs-random-projection/
|
|
6
|
+
Project-URL: Repository, https://github.com/Sidorow/numcodecs-random-projection.git
|
|
7
|
+
Project-URL: Issues, https://github.com/Sidorow/numcodecs-random-projection/issues
|
|
8
|
+
Author-email: Sami Sidoroff <sami.sidoroff@helsinki.fi>, Juniper Tyree <juniper.tyree@helsinki.fi>
|
|
9
|
+
Maintainer-email: Sami Sidoroff <sami.sidoroff@helsinki.fi>, Juniper Tyree <juniper.tyree@helsinki.fi>
|
|
10
|
+
License-Expression: MPL-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: compression,lossy-compression,numcodecs,random-projection
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
|
|
17
|
+
Classifier: Natural Language :: English
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering
|
|
26
|
+
Classifier: Topic :: System :: Archiving :: Compression
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Requires-Dist: leb128~=1.0.8
|
|
30
|
+
Requires-Dist: numcodecs<0.17,>=0.13.0
|
|
31
|
+
Requires-Dist: numpy~=2.0
|
|
32
|
+
Requires-Dist: tqdm~=4.60
|
|
33
|
+
Requires-Dist: types-tqdm~=4.60
|
|
34
|
+
Requires-Dist: typing-extensions~=4.6
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Requires-Dist: mypy~=1.14; extra == 'dev'
|
|
37
|
+
Requires-Dist: pytest~=8.3; extra == 'dev'
|
|
38
|
+
Provides-Extra: test
|
|
39
|
+
Requires-Dist: scipy>=1.15.3; extra == 'test'
|
|
40
|
+
Requires-Dist: xarray>=2025.6.1; extra == 'test'
|
|
41
|
+
Description-Content-Type: text/markdown
|
|
42
|
+
|
|
43
|
+
[](https://github.com/Sidorow/numcodecs-random-projection/actions/workflows/ci.yml?query=branch%3Amain)
|
|
44
|
+
[](https://pypi.python.org/pypi/numcodecs-random-projection)
|
|
45
|
+
[](https://github.com/Sidorow/numcodecs-random-projection/blob/main/LICENSE)
|
|
46
|
+
[](https://pypi.python.org/pypi/numcodecs-random-projection)
|
|
47
|
+
[](https://sidorow.github.io/numcodecs-random-projection/)
|
|
48
|
+
|
|
49
|
+
# numcodecs-random-projection
|
|
50
|
+
|
|
51
|
+
`RPCodec` for the [`numcodecs`] buffer compression API.
|
|
52
|
+
|
|
53
|
+
[`numcodecs`]: https://numcodecs.readthedocs.io/en/stable/
|
|
54
|
+
|
|
55
|
+
## License
|
|
56
|
+
|
|
57
|
+
Licensed under the Mozilla Public License, Version 2.0 ([LICENSE](LICENSE) or https://www.mozilla.org/en-US/MPL/2.0/).
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
## Funding
|
|
61
|
+
|
|
62
|
+
The `numcodecs-random-projection` package has been developed as part of [ESiWACE3](https://www.esiwace.eu), the third phase of the Centre of Excellence in Simulation of Weather and Climate in Europe.
|
|
63
|
+
|
|
64
|
+
Funded by the European Union. This work has received funding from the European High Performance Computing Joint Undertaking (JU) under grant agreement No 101093054.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[](https://github.com/Sidorow/numcodecs-random-projection/actions/workflows/ci.yml?query=branch%3Amain)
|
|
2
|
+
[](https://pypi.python.org/pypi/numcodecs-random-projection)
|
|
3
|
+
[](https://github.com/Sidorow/numcodecs-random-projection/blob/main/LICENSE)
|
|
4
|
+
[](https://pypi.python.org/pypi/numcodecs-random-projection)
|
|
5
|
+
[](https://sidorow.github.io/numcodecs-random-projection/)
|
|
6
|
+
|
|
7
|
+
# numcodecs-random-projection
|
|
8
|
+
|
|
9
|
+
`RPCodec` for the [`numcodecs`] buffer compression API.
|
|
10
|
+
|
|
11
|
+
[`numcodecs`]: https://numcodecs.readthedocs.io/en/stable/
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
Licensed under the Mozilla Public License, Version 2.0 ([LICENSE](LICENSE) or https://www.mozilla.org/en-US/MPL/2.0/).
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Funding
|
|
19
|
+
|
|
20
|
+
The `numcodecs-random-projection` package has been developed as part of [ESiWACE3](https://www.esiwace.eu), the third phase of the Centre of Excellence in Simulation of Weather and Climate in Europe.
|
|
21
|
+
|
|
22
|
+
Funded by the European Union. This work has received funding from the European High Performance Computing Joint Undertaking (JU) under grant agreement No 101093054.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "numcodecs-random-projection"
|
|
7
|
+
version = "0.1.0a1"
|
|
8
|
+
dependencies = [
|
|
9
|
+
"leb128~=1.0.8",
|
|
10
|
+
"numcodecs>=0.13.0,<0.17",
|
|
11
|
+
"numpy~=2.0",
|
|
12
|
+
"typing-extensions~=4.6",
|
|
13
|
+
"tqdm~=4.60",
|
|
14
|
+
"types-tqdm~=4.60",
|
|
15
|
+
]
|
|
16
|
+
requires-python = ">=3.10"
|
|
17
|
+
authors = [{ name = "Sami Sidoroff", email = "sami.sidoroff@helsinki.fi" }, { name = "Juniper Tyree", email = "juniper.tyree@helsinki.fi" }]
|
|
18
|
+
maintainers = [{ name = "Sami Sidoroff", email = "sami.sidoroff@helsinki.fi" }, { name = "Juniper Tyree", email = "juniper.tyree@helsinki.fi" }]
|
|
19
|
+
description = "Random projection codec for the `numcodecs` buffer compression API"
|
|
20
|
+
readme = "README.md"
|
|
21
|
+
license = "MPL-2.0"
|
|
22
|
+
keywords = ["random-projection", "compression", "lossy-compression", "numcodecs"]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 3 - Alpha",
|
|
25
|
+
"Intended Audience :: Science/Research",
|
|
26
|
+
"Intended Audience :: End Users/Desktop",
|
|
27
|
+
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
|
|
28
|
+
"Natural Language :: English",
|
|
29
|
+
"Operating System :: OS Independent",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Programming Language :: Python :: 3.10",
|
|
32
|
+
"Programming Language :: Python :: 3.11",
|
|
33
|
+
"Programming Language :: Python :: 3.12",
|
|
34
|
+
"Programming Language :: Python :: 3.13",
|
|
35
|
+
"Programming Language :: Python :: 3.14",
|
|
36
|
+
"Topic :: Scientific/Engineering",
|
|
37
|
+
"Topic :: System :: Archiving :: Compression",
|
|
38
|
+
"Typing :: Typed",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Documentation = "https://sidorow.github.io/numcodecs-random-projection/"
|
|
43
|
+
Repository = "https://github.com/Sidorow/numcodecs-random-projection.git"
|
|
44
|
+
Issues = "https://github.com/Sidorow/numcodecs-random-projection/issues"
|
|
45
|
+
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
dev = [
|
|
48
|
+
"mypy~=1.14",
|
|
49
|
+
"pytest~=8.3",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
test = [
|
|
53
|
+
"scipy>=1.15.3",
|
|
54
|
+
"xarray>=2025.6.1",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
[project.entry-points."numcodecs.codecs"]
|
|
58
|
+
"rp" = "numcodecs_random_projection:RPCodec"
|
|
59
|
+
|
|
60
|
+
[tool.setuptools.packages.find]
|
|
61
|
+
where = ["src"]
|
|
62
|
+
|
|
63
|
+
[tool.setuptools.package-data]
|
|
64
|
+
"numcodecs_random_projection" = ["py.typed"]
|
|
65
|
+
|
|
66
|
+
[tool.ruff.lint]
|
|
67
|
+
select = ["E4", "E7", "E9", "F", "I"]
|
|
68
|
+
|
|
69
|
+
[tool.pytest.ini_options]
|
|
70
|
+
addopts = ["--import-mode=importlib"]
|
|
71
|
+
xfail_strict = true
|
|
72
|
+
|
|
73
|
+
[[tool.mypy.overrides]]
|
|
74
|
+
module = ["leb128.*", "numcodecs.*"]
|
|
75
|
+
follow_untyped_imports = true
|
|
76
|
+
|
|
77
|
+
[tool.hatch.build.targets.sdist]
|
|
78
|
+
include = ["/src", "/LICENSE", "/pyproject.toml", "/README.md"]
|
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
"""
|
|
2
|
+
[`RPCodec`][numcodecs_random_projection.RPCodec] for the [`numcodecs`][numcodecs] buffer compression API.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__all__ = ["RPCodec", "RPMethod"]
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import time
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from io import BytesIO
|
|
12
|
+
from math import ceil
|
|
13
|
+
from sys import byteorder
|
|
14
|
+
|
|
15
|
+
import leb128
|
|
16
|
+
import numcodecs.compat
|
|
17
|
+
import numcodecs.registry
|
|
18
|
+
import numpy as np
|
|
19
|
+
import tqdm
|
|
20
|
+
from numcodecs.abc import Codec
|
|
21
|
+
from typing_extensions import (
|
|
22
|
+
Buffer, # MSPV 3.12
|
|
23
|
+
assert_never, # MSPV 3.11
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
from .mt_rng import MultithreadedRNG
|
|
27
|
+
|
|
28
|
+
LOG = logging.getLogger(__name__)
|
|
29
|
+
|
|
30
|
+
_BLOCK_THRESHOLD = 1000
|
|
31
|
+
_BLOCK_SIZE = 512
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RPMethod(Enum):
|
|
35
|
+
"""Random projection method."""
|
|
36
|
+
|
|
37
|
+
dct = "dct"
|
|
38
|
+
"""
|
|
39
|
+
Discrete Cosine Transform (DCT).
|
|
40
|
+
|
|
41
|
+
Generate DxK projection matrix R using Type II Discrete Cosine Transform (DCT) basis ¹.
|
|
42
|
+
"""
|
|
43
|
+
gaussian = "gaussian"
|
|
44
|
+
"""
|
|
45
|
+
Gaussian random projection.
|
|
46
|
+
|
|
47
|
+
Generate random DxK matrix R with entries drawn from N(0, 1/√K) distribution,
|
|
48
|
+
which preserves expected distances according to Johnson-Lindenstrauss lemma.
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
[^1]: José J. Amador,
|
|
52
|
+
Random projection and orthonormality for lossy image compression, Image and Vision Computing, Volume 25, Issue 5, 2007, Pages 754-766, ISSN 0262-8856, Available from:
|
|
53
|
+
[https://doi.org/10.1016/j.imavis.2006.05.018](https://doi.org/10.1016/j.imavis.2006.05.018)
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class RPCodec(Codec):
|
|
58
|
+
"""
|
|
59
|
+
Random projection codec for lossy compression of numerical data.
|
|
60
|
+
|
|
61
|
+
Compresses 2D finite floating point data by projecting it onto a lower-dimensional subspace using a specified method.
|
|
62
|
+
Discrete Cosine Transform (DCT) is used by default.
|
|
63
|
+
|
|
64
|
+
A two-dimensional array of shape N x D is encoded as an array of
|
|
65
|
+
shape N x K, where `k` is either set explicitly or chosen with compression ratio `cr`.
|
|
66
|
+
Alternatively, `k` can be estimated from the data during encoding by giving a specified Mean Absolute Error (MAE) during initialization.
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
__slots__ = ("_mae", "_cr", "_k", "_method", "_seed", "_debug")
|
|
71
|
+
_mae: None | float
|
|
72
|
+
_cr: None | float
|
|
73
|
+
_k: None | int
|
|
74
|
+
_method: RPMethod
|
|
75
|
+
_seed: int
|
|
76
|
+
_debug: bool
|
|
77
|
+
|
|
78
|
+
codec_id: str = "rp" # type: ignore
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
mae: None | float = None,
|
|
83
|
+
cr: None | float = None,
|
|
84
|
+
k: None | int = None,
|
|
85
|
+
method: str | RPMethod = RPMethod.dct,
|
|
86
|
+
seed: int | None = None,
|
|
87
|
+
debug: bool = False,
|
|
88
|
+
) -> None:
|
|
89
|
+
"""
|
|
90
|
+
Initialize Random Projection codec.
|
|
91
|
+
|
|
92
|
+
Parameters
|
|
93
|
+
----------
|
|
94
|
+
mae : float
|
|
95
|
+
Target mean absolute error. If specified, `k` will be estimated from
|
|
96
|
+
data during encoding. Note that the bound is *not* guaranteed to be
|
|
97
|
+
met.
|
|
98
|
+
cr : float
|
|
99
|
+
Target compression ratio. If specified, `k` will be calculated as D/`cr`
|
|
100
|
+
where D is the number of features in the input data.
|
|
101
|
+
k : int
|
|
102
|
+
Number of dimensions in the projected space. Will be used over `cr` if
|
|
103
|
+
both are specified. Estimated if `mae` is specified.
|
|
104
|
+
method : str | RPMethod
|
|
105
|
+
Method for generating the projection matrix. Please refer to the
|
|
106
|
+
[`RPMethod`][numcodecs_random_projection.RPMethod] enumeration for
|
|
107
|
+
all supported methods.
|
|
108
|
+
seed : int
|
|
109
|
+
Random seed for reproducible results. If None, results will be
|
|
110
|
+
non-deterministic when using the Gaussian method.
|
|
111
|
+
debug : bool
|
|
112
|
+
Whether debug information should be printed during encoding and
|
|
113
|
+
decoding.
|
|
114
|
+
|
|
115
|
+
Raises
|
|
116
|
+
------
|
|
117
|
+
ValueError
|
|
118
|
+
If not exactly one of `mae`, `cr`, or `k` is set.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
if sum([(mae is not None), (cr is not None), (k is not None)]) != 1:
|
|
122
|
+
raise ValueError("exactly one of `mae`, `cr` or `k` must be set")
|
|
123
|
+
|
|
124
|
+
self._mae = mae
|
|
125
|
+
self._cr = cr
|
|
126
|
+
self._k = k
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
self._method = method if isinstance(method, RPMethod) else RPMethod[method]
|
|
130
|
+
except KeyError:
|
|
131
|
+
hy = "'"
|
|
132
|
+
raise ValueError(
|
|
133
|
+
f"unknown method '{method}', expected one of {', '.join(f'{hy}{m.name}{hy}' for m in RPMethod)}."
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if seed is None:
|
|
137
|
+
self._seed = np.random.randint(0, 2**31 - 1)
|
|
138
|
+
else:
|
|
139
|
+
self._seed = seed
|
|
140
|
+
|
|
141
|
+
self._debug = debug
|
|
142
|
+
|
|
143
|
+
def encode(self, buf: Buffer) -> Buffer:
|
|
144
|
+
"""
|
|
145
|
+
Encode data using random projection.
|
|
146
|
+
|
|
147
|
+
During encode, the input data is standardized (mean=0, std=1) before projection.
|
|
148
|
+
|
|
149
|
+
If `mae` is specified, the number of projected dimensions `k` is estimated based on the standardized data.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
buf : Buffer
|
|
154
|
+
Input data buffer. Must be a 2D array with shape (n_samples, d_features).
|
|
155
|
+
|
|
156
|
+
Returns
|
|
157
|
+
-------
|
|
158
|
+
enc : bytes
|
|
159
|
+
Serialized encoded data containing:
|
|
160
|
+
- Standardized data statistics (mean, std)
|
|
161
|
+
- Original data shape and dtype
|
|
162
|
+
- Projected data
|
|
163
|
+
- Compression parameters
|
|
164
|
+
"""
|
|
165
|
+
data = numcodecs.compat.ensure_ndarray(buf)
|
|
166
|
+
|
|
167
|
+
validations = [
|
|
168
|
+
not np.issubdtype(data.dtype, np.floating),
|
|
169
|
+
data.ndim != 2,
|
|
170
|
+
]
|
|
171
|
+
|
|
172
|
+
if any(validations):
|
|
173
|
+
raise ValueError(
|
|
174
|
+
f"RPCodec requires 2D floating-point data, got {data.dtype} and {data.ndim}D data"
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
np.nan_to_num(data, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
|
|
178
|
+
|
|
179
|
+
data_mean = np.mean(data)
|
|
180
|
+
data_std = np.std(data)
|
|
181
|
+
if data_std == 0:
|
|
182
|
+
data_std = 1
|
|
183
|
+
|
|
184
|
+
standardized_data = (data - data_mean) / data_std
|
|
185
|
+
|
|
186
|
+
original_shape = data.shape
|
|
187
|
+
original_dtype = data.dtype
|
|
188
|
+
|
|
189
|
+
k: int
|
|
190
|
+
if self._mae is not None:
|
|
191
|
+
k = self._estimate_k_for_target_mae(standardized_data)
|
|
192
|
+
elif self._cr is not None:
|
|
193
|
+
assert self._cr is not None
|
|
194
|
+
k = int(ceil(data.shape[1] / self._cr))
|
|
195
|
+
else:
|
|
196
|
+
assert self._k is not None
|
|
197
|
+
k = self._k
|
|
198
|
+
|
|
199
|
+
if self._debug:
|
|
200
|
+
LOG.debug(f"encode with k={k}")
|
|
201
|
+
|
|
202
|
+
if k > _BLOCK_THRESHOLD:
|
|
203
|
+
block_size = _BLOCK_SIZE
|
|
204
|
+
projected = self._project_blocks(
|
|
205
|
+
standardized_data, data.shape[1], k, original_dtype, block_size
|
|
206
|
+
)
|
|
207
|
+
else:
|
|
208
|
+
R = self._gen_R(data.shape[1], k, original_dtype, self._seed)
|
|
209
|
+
projected = np.matmul(standardized_data, R)
|
|
210
|
+
|
|
211
|
+
bio = BytesIO()
|
|
212
|
+
|
|
213
|
+
bio.write(leb128.u.encode(len(original_shape)))
|
|
214
|
+
for dim in original_shape:
|
|
215
|
+
bio.write(leb128.u.encode(dim))
|
|
216
|
+
|
|
217
|
+
dtype_str = original_dtype.str.encode("ascii")
|
|
218
|
+
bio.write(leb128.u.encode(len(dtype_str)))
|
|
219
|
+
bio.write(dtype_str)
|
|
220
|
+
|
|
221
|
+
bio.write(leb128.u.encode(k))
|
|
222
|
+
bio.write(leb128.u.encode(self._seed))
|
|
223
|
+
|
|
224
|
+
mean_bytes = np.array(data_mean, dtype=original_dtype).tobytes()
|
|
225
|
+
bio.write(leb128.u.encode(len(mean_bytes)))
|
|
226
|
+
bio.write(mean_bytes)
|
|
227
|
+
|
|
228
|
+
std_bytes = np.array(data_std, dtype=original_dtype).tobytes()
|
|
229
|
+
bio.write(leb128.u.encode(len(std_bytes)))
|
|
230
|
+
bio.write(std_bytes)
|
|
231
|
+
|
|
232
|
+
projected_byteorder = projected.dtype.byteorder
|
|
233
|
+
|
|
234
|
+
projected_byteorder = (
|
|
235
|
+
projected_byteorder
|
|
236
|
+
if projected_byteorder in ("<", ">")
|
|
237
|
+
else ("<" if (byteorder == "little") else ">")
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
if projected_byteorder != "<":
|
|
241
|
+
projected = projected.byteswap()
|
|
242
|
+
|
|
243
|
+
proj_bytes = projected.tobytes()
|
|
244
|
+
bio.write(leb128.u.encode(len(proj_bytes)))
|
|
245
|
+
bio.write(proj_bytes)
|
|
246
|
+
|
|
247
|
+
return bio.getvalue()
|
|
248
|
+
|
|
249
|
+
def decode(self, buf: Buffer, out: None | Buffer = None) -> Buffer:
|
|
250
|
+
"""
|
|
251
|
+
Decode random projection encoded data.
|
|
252
|
+
|
|
253
|
+
During decode, the standardized data is reconstructed and denormalized.
|
|
254
|
+
|
|
255
|
+
Parameters
|
|
256
|
+
----------
|
|
257
|
+
buf : Buffer
|
|
258
|
+
Encoded data from RPCodec.
|
|
259
|
+
out : Buffer, optional
|
|
260
|
+
Writeable buffer to store decoded data.
|
|
261
|
+
|
|
262
|
+
Returns
|
|
263
|
+
-------
|
|
264
|
+
dec : Buffer
|
|
265
|
+
Reconstructed data with original shape and dtype.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
data = numcodecs.compat.ensure_bytes(buf)
|
|
269
|
+
|
|
270
|
+
bio = BytesIO(data)
|
|
271
|
+
|
|
272
|
+
ndim, _ = leb128.u.decode_reader(bio)
|
|
273
|
+
original_shape = tuple(leb128.u.decode_reader(bio)[0] for _ in range(ndim))
|
|
274
|
+
|
|
275
|
+
dtype_len, _ = leb128.u.decode_reader(bio)
|
|
276
|
+
dtype_str = bio.read(dtype_len).decode("ascii")
|
|
277
|
+
original_dtype = np.dtype(dtype_str)
|
|
278
|
+
|
|
279
|
+
k, _ = leb128.u.decode_reader(bio)
|
|
280
|
+
seed, _ = leb128.u.decode_reader(bio)
|
|
281
|
+
|
|
282
|
+
mean_len, _ = leb128.u.decode_reader(bio)
|
|
283
|
+
mean_bytes = bio.read(mean_len)
|
|
284
|
+
data_mean = np.frombuffer(mean_bytes, dtype=original_dtype)
|
|
285
|
+
|
|
286
|
+
std_len, _ = leb128.u.decode_reader(bio)
|
|
287
|
+
std_bytes = bio.read(std_len)
|
|
288
|
+
data_std = np.frombuffer(std_bytes, dtype=original_dtype)
|
|
289
|
+
|
|
290
|
+
proj_len, _ = leb128.u.decode_reader(bio)
|
|
291
|
+
proj_bytes = bio.read(proj_len)
|
|
292
|
+
|
|
293
|
+
projected = np.frombuffer(
|
|
294
|
+
proj_bytes, dtype=original_dtype.newbyteorder("<")
|
|
295
|
+
).reshape((original_shape[0], k))
|
|
296
|
+
|
|
297
|
+
projected_byteorder = projected.dtype.byteorder
|
|
298
|
+
|
|
299
|
+
projected_byteorder = (
|
|
300
|
+
projected_byteorder
|
|
301
|
+
if projected_byteorder in ("<", ">")
|
|
302
|
+
else ("<" if (byteorder == "little") else ">")
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
if byteorder == "big":
|
|
306
|
+
projected = projected.byteswap()
|
|
307
|
+
|
|
308
|
+
if k > _BLOCK_THRESHOLD:
|
|
309
|
+
block_size = _BLOCK_SIZE
|
|
310
|
+
reconstructed = self._reconstruct_blocks(
|
|
311
|
+
projected, original_shape[1], k, original_dtype, block_size, seed
|
|
312
|
+
)
|
|
313
|
+
else:
|
|
314
|
+
R = self._gen_R(original_shape[1], k, original_dtype, seed)
|
|
315
|
+
reconstructed = np.matmul(projected, R.T)
|
|
316
|
+
|
|
317
|
+
reconstructed = reconstructed * data_std + data_mean
|
|
318
|
+
reconstructed = reconstructed.reshape(original_shape)
|
|
319
|
+
return numcodecs.compat.ndarray_copy(reconstructed, out) # type: ignore
|
|
320
|
+
|
|
321
|
+
def get_config(self) -> dict:
|
|
322
|
+
"""
|
|
323
|
+
Get codec configuration.
|
|
324
|
+
|
|
325
|
+
Returns:
|
|
326
|
+
dict: Codec configuration.
|
|
327
|
+
"""
|
|
328
|
+
config: dict[str, str | int | float] = dict(id=type(self).codec_id)
|
|
329
|
+
|
|
330
|
+
if self._mae is not None:
|
|
331
|
+
config["mae"] = self._mae
|
|
332
|
+
if self._cr is not None:
|
|
333
|
+
config["cr"] = self._cr
|
|
334
|
+
if self._k is not None:
|
|
335
|
+
config["k"] = self._k
|
|
336
|
+
|
|
337
|
+
config["method"] = self._method.name
|
|
338
|
+
config["seed"] = self._seed
|
|
339
|
+
|
|
340
|
+
return config
|
|
341
|
+
|
|
342
|
+
def _estimate_k_for_target_mae(
|
|
343
|
+
self,
|
|
344
|
+
data: np.ndarray,
|
|
345
|
+
) -> int:
|
|
346
|
+
"""
|
|
347
|
+
Estimate the number of dimensions 'k' for the projected space based on the standardized
|
|
348
|
+
input data and targeted MAE.
|
|
349
|
+
|
|
350
|
+
This method assumes standardized input data prior to calling via encode method.
|
|
351
|
+
|
|
352
|
+
Parameters
|
|
353
|
+
----------
|
|
354
|
+
data : np.ndarray
|
|
355
|
+
Standardized input data (mean=0, std=1).
|
|
356
|
+
|
|
357
|
+
Returns
|
|
358
|
+
-------
|
|
359
|
+
int
|
|
360
|
+
Estimated k (number of projected dimensions)
|
|
361
|
+
"""
|
|
362
|
+
|
|
363
|
+
D = data.shape[1]
|
|
364
|
+
|
|
365
|
+
assert self._mae is not None
|
|
366
|
+
target_mae = self._mae
|
|
367
|
+
# normalized_mae = self._mae / data_std if data_std > 0 else self._mae
|
|
368
|
+
|
|
369
|
+
match self._method:
|
|
370
|
+
case RPMethod.gaussian:
|
|
371
|
+
ratio = 1 - target_mae
|
|
372
|
+
case RPMethod.dct:
|
|
373
|
+
ratio = 1 - np.sqrt(target_mae * 4)
|
|
374
|
+
case _:
|
|
375
|
+
assert_never(self._method)
|
|
376
|
+
|
|
377
|
+
estimated_k = int(D * ratio)
|
|
378
|
+
K = max(1, min(estimated_k, D))
|
|
379
|
+
|
|
380
|
+
return K
|
|
381
|
+
|
|
382
|
+
def _project_blocks(
|
|
383
|
+
self, data: np.ndarray, D: int, K: int, dtype: np.dtype, block_size: int
|
|
384
|
+
) -> np.ndarray:
|
|
385
|
+
"""
|
|
386
|
+
Project input data to a lower-dimensional subspace using block-wise matrix generation.
|
|
387
|
+
Processes projection matrix R in blocks of shape (D, block_size) instead of generating the full DxK matrix to reduce memory usage when K is large.
|
|
388
|
+
|
|
389
|
+
Note that due to how blocks are processed and projection matrix is generated, the output is not the same as if the full matrix was used (see _gen_R_block notes).
|
|
390
|
+
|
|
391
|
+
Parameters
|
|
392
|
+
----------
|
|
393
|
+
data : np.ndarray
|
|
394
|
+
Input data array with shape (N, D), where N is the number of samples
|
|
395
|
+
and D is the number of input features.
|
|
396
|
+
D : int
|
|
397
|
+
Number of input features (columns in data).
|
|
398
|
+
K : int
|
|
399
|
+
Number of dimensions in the projected space.
|
|
400
|
+
dtype : np.dtype
|
|
401
|
+
Data type for the projection matrix and output. Should match the
|
|
402
|
+
original data dtype for consistency.
|
|
403
|
+
block_size : int
|
|
404
|
+
Number of features to process in each block. Determines the
|
|
405
|
+
size of each R_block as (D, block_size).
|
|
406
|
+
|
|
407
|
+
Returns
|
|
408
|
+
-------
|
|
409
|
+
np.ndarray
|
|
410
|
+
Projected data with shape (N, K)
|
|
411
|
+
"""
|
|
412
|
+
|
|
413
|
+
rng = MultithreadedRNG(seed=self._seed)
|
|
414
|
+
|
|
415
|
+
out = np.empty((data.shape[0], K), dtype=dtype)
|
|
416
|
+
R_block = None
|
|
417
|
+
out_block = None
|
|
418
|
+
|
|
419
|
+
if self._debug:
|
|
420
|
+
progress = tqdm.tqdm(total=K)
|
|
421
|
+
|
|
422
|
+
for k_start in range(0, K, block_size):
|
|
423
|
+
k_end = min(k_start + block_size, K)
|
|
424
|
+
actual_block_size = k_end - k_start
|
|
425
|
+
|
|
426
|
+
if R_block is None or R_block.shape != (D, actual_block_size):
|
|
427
|
+
R_block = np.empty((D, actual_block_size), dtype=dtype)
|
|
428
|
+
|
|
429
|
+
if out_block is None or out_block.shape != (
|
|
430
|
+
data.shape[0],
|
|
431
|
+
actual_block_size,
|
|
432
|
+
):
|
|
433
|
+
out_block = np.empty((data.shape[0], actual_block_size), dtype=dtype)
|
|
434
|
+
|
|
435
|
+
block_timing = [0.0]
|
|
436
|
+
with self._debug_timing(block_timing):
|
|
437
|
+
self._gen_R_block(K, k_start, rng, out=R_block)
|
|
438
|
+
|
|
439
|
+
matmul_timing = [0.0]
|
|
440
|
+
with self._debug_timing(matmul_timing):
|
|
441
|
+
np.matmul(data, R_block, out=out_block)
|
|
442
|
+
out[:, k_start:k_end] = out_block
|
|
443
|
+
|
|
444
|
+
if self._debug:
|
|
445
|
+
progress.set_postfix_str(
|
|
446
|
+
f"encode N={data.shape[0]} D={D} Kb={actual_block_size} Rgen={np.round(block_timing[0], 2)}s matmul={np.round(matmul_timing[0], 2)}s"
|
|
447
|
+
)
|
|
448
|
+
progress.update(actual_block_size)
|
|
449
|
+
|
|
450
|
+
return out
|
|
451
|
+
|
|
452
|
+
def _reconstruct_blocks(
|
|
453
|
+
self,
|
|
454
|
+
projected: np.ndarray,
|
|
455
|
+
D: int,
|
|
456
|
+
K: int,
|
|
457
|
+
dtype: np.dtype,
|
|
458
|
+
block_size: int,
|
|
459
|
+
seed: int,
|
|
460
|
+
) -> np.ndarray:
|
|
461
|
+
"""
|
|
462
|
+
Reconstruct data using block-wise matrix generation.
|
|
463
|
+
|
|
464
|
+
Performs the inverse operation of _project_blocks by computing projected @ R.T in blocks to reduce memory usage. Accumulate each processed block and return the full reconstructed matrix of shape (N, D).
|
|
465
|
+
|
|
466
|
+
Parameters
|
|
467
|
+
----------
|
|
468
|
+
projected : np.ndarray
|
|
469
|
+
Projected data array with shape (N, K), where N is the number of samples
|
|
470
|
+
and K is the number of projected features.
|
|
471
|
+
D : int
|
|
472
|
+
Number of input features (columns in data).
|
|
473
|
+
K : int
|
|
474
|
+
Number of dimensions in the projected space.
|
|
475
|
+
dtype : np.dtype
|
|
476
|
+
Data type for the reconstructed matrix. Should match the
|
|
477
|
+
original data dtype for consistency.
|
|
478
|
+
block_size : int
|
|
479
|
+
Number of features to process in each block.
|
|
480
|
+
|
|
481
|
+
Returns
|
|
482
|
+
-------
|
|
483
|
+
np.ndarray
|
|
484
|
+
Reconstructed data with shape (N, D)
|
|
485
|
+
"""
|
|
486
|
+
|
|
487
|
+
rng = MultithreadedRNG(seed=seed)
|
|
488
|
+
|
|
489
|
+
out = np.zeros((projected.shape[0], D), dtype=dtype)
|
|
490
|
+
R_block = None
|
|
491
|
+
rec_block = np.empty((projected.shape[0], D), dtype=dtype)
|
|
492
|
+
|
|
493
|
+
if self._debug:
|
|
494
|
+
progress = tqdm.tqdm(total=K)
|
|
495
|
+
|
|
496
|
+
for k_start in range(0, K, block_size):
|
|
497
|
+
k_end = min(k_start + block_size, K)
|
|
498
|
+
actual_block_size = k_end - k_start
|
|
499
|
+
|
|
500
|
+
if R_block is None or R_block.shape != (D, actual_block_size):
|
|
501
|
+
R_block = np.empty((D, actual_block_size), dtype=dtype)
|
|
502
|
+
|
|
503
|
+
block_timing = [0.0]
|
|
504
|
+
with self._debug_timing(block_timing):
|
|
505
|
+
self._gen_R_block(K, k_start, rng, out=R_block)
|
|
506
|
+
|
|
507
|
+
matmul_timing = [0.0]
|
|
508
|
+
with self._debug_timing(matmul_timing):
|
|
509
|
+
projected_block = projected[:, k_start:k_end]
|
|
510
|
+
np.matmul(projected_block, R_block.T, out=rec_block)
|
|
511
|
+
|
|
512
|
+
acc_timing = [0.0]
|
|
513
|
+
with self._debug_timing(acc_timing):
|
|
514
|
+
out += rec_block
|
|
515
|
+
|
|
516
|
+
if self._debug:
|
|
517
|
+
progress.set_postfix_str(
|
|
518
|
+
f"decode N={out.shape[0]} D={D} Kb={actual_block_size} Rgen={np.round(block_timing[0], 2)}s matmul={np.round(matmul_timing[0], 2)}s acc={np.round(acc_timing[0], 2)}s"
|
|
519
|
+
)
|
|
520
|
+
progress.update(actual_block_size)
|
|
521
|
+
|
|
522
|
+
return out
|
|
523
|
+
|
|
524
|
+
def _gen_R(
|
|
525
|
+
self, D: int, K: int, dtype: np.dtype, seed: int | None = None
|
|
526
|
+
) -> np.ndarray:
|
|
527
|
+
"""
|
|
528
|
+
Generate a projection matrix using specified method.
|
|
529
|
+
|
|
530
|
+
DCT method:
|
|
531
|
+
Generates a DxK projection matrix R using Type II Discrete Cosine Transform (DCT) basis.
|
|
532
|
+
|
|
533
|
+
Gaussian method:
|
|
534
|
+
Creates a random DxK matrix R with entries drawn from N(0, 1/√K) distribution,
|
|
535
|
+
which preserves expected distances according to Johnson-Lindenstrauss lemma.
|
|
536
|
+
|
|
537
|
+
Parameters
|
|
538
|
+
----------
|
|
539
|
+
D : int
|
|
540
|
+
Input dimensionality (number of features).
|
|
541
|
+
K : int
|
|
542
|
+
Output dimensionality (number of projected features).
|
|
543
|
+
seed : int, optional
|
|
544
|
+
Random seed of reproducible matrix generation.
|
|
545
|
+
|
|
546
|
+
Returns
|
|
547
|
+
-------
|
|
548
|
+
np.ndarray
|
|
549
|
+
Projection matrix of shape (D, K)
|
|
550
|
+
"""
|
|
551
|
+
|
|
552
|
+
match self._method:
|
|
553
|
+
case RPMethod.dct:
|
|
554
|
+
i = np.arange(D, dtype=dtype).reshape(-1, 1)
|
|
555
|
+
m = np.arange(K, dtype=dtype).reshape(1, -1)
|
|
556
|
+
alpha_m = np.where(m == 0, np.sqrt(1 / D), np.sqrt(2 / D))
|
|
557
|
+
R = alpha_m * np.cos((np.pi * (2 * i + 1) * m) / (2 * D))
|
|
558
|
+
case RPMethod.gaussian:
|
|
559
|
+
scale = np.sqrt(1 / K)
|
|
560
|
+
rng = MultithreadedRNG(seed=seed)
|
|
561
|
+
rng.fill_arr(shape=(D, K))
|
|
562
|
+
R = rng.values * scale
|
|
563
|
+
case _:
|
|
564
|
+
assert_never(self._method)
|
|
565
|
+
|
|
566
|
+
return R.astype(dtype)
|
|
567
|
+
|
|
568
|
+
def _gen_R_block(
|
|
569
|
+
self,
|
|
570
|
+
K: int,
|
|
571
|
+
k_start: int,
|
|
572
|
+
rng: MultithreadedRNG,
|
|
573
|
+
out: np.ndarray,
|
|
574
|
+
) -> None:
|
|
575
|
+
"""
|
|
576
|
+
Generate a block of projection matrix R using a specified method.
|
|
577
|
+
|
|
578
|
+
Parameters
|
|
579
|
+
----------
|
|
580
|
+
K : int
|
|
581
|
+
Number of projected features.
|
|
582
|
+
k_start : int
|
|
583
|
+
Starting index for the projected space.
|
|
584
|
+
rng : MultithreadedRNG
|
|
585
|
+
Random number generator based on https://numpy.org/doc/stable/reference/random/multithreading.html.
|
|
586
|
+
out : np.ndarray
|
|
587
|
+
Block of matrix R with shape (D, block_size) that will be filled
|
|
588
|
+
by this method.
|
|
589
|
+
|
|
590
|
+
Notes
|
|
591
|
+
-----
|
|
592
|
+
- Generating Gaussian R matrix block by block does not produce the same numbers as the Gen_R method.
|
|
593
|
+
This is because the random numbers are generated in chunks based on the block size,
|
|
594
|
+
so the sequence of random numbers used for each block is different than if the full matrix was generated at once.
|
|
595
|
+
"""
|
|
596
|
+
|
|
597
|
+
D, block_size = out.shape
|
|
598
|
+
dtype = out.dtype
|
|
599
|
+
|
|
600
|
+
match self._method:
|
|
601
|
+
case RPMethod.dct:
|
|
602
|
+
i = np.arange(D, dtype=dtype).reshape(-1, 1)
|
|
603
|
+
m = np.arange(k_start, k_start + block_size, dtype=dtype).reshape(1, -1)
|
|
604
|
+
alpha_m = np.where(m == 0, np.sqrt(1 / D), np.sqrt(2 / D))
|
|
605
|
+
out[:] = 2 * i + 1
|
|
606
|
+
out[:] *= m * np.pi
|
|
607
|
+
out[:] /= 2 * D
|
|
608
|
+
np.cos(out, out=out)
|
|
609
|
+
out *= alpha_m
|
|
610
|
+
case RPMethod.gaussian:
|
|
611
|
+
scale = np.sqrt(1 / K)
|
|
612
|
+
if hasattr(rng, "fill_arr"):
|
|
613
|
+
rng.fill_arr(shape=(D, block_size))
|
|
614
|
+
np.multiply(rng.values, scale, out=out)
|
|
615
|
+
case _:
|
|
616
|
+
assert_never(self._method)
|
|
617
|
+
|
|
618
|
+
@contextmanager
|
|
619
|
+
def _debug_timing(self, out: list[float]):
|
|
620
|
+
if self._debug:
|
|
621
|
+
start = time.perf_counter()
|
|
622
|
+
yield
|
|
623
|
+
end = time.perf_counter()
|
|
624
|
+
out[0] = end - start
|
|
625
|
+
else:
|
|
626
|
+
yield
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
numcodecs.registry.register_codec(RPCodec)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import concurrent.futures
|
|
2
|
+
import multiprocessing
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from numpy.random import SeedSequence, default_rng
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MultithreadedRNG:
|
|
9
|
+
"""
|
|
10
|
+
Multithreaded random number generator using numpy's default_rng
|
|
11
|
+
Based on https://numpy.org/doc/stable/reference/random/multithreading.html.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, seed, threads=None):
|
|
15
|
+
"""
|
|
16
|
+
Initialize the multithreaded RNG.
|
|
17
|
+
|
|
18
|
+
Parameters
|
|
19
|
+
----------
|
|
20
|
+
seed : int
|
|
21
|
+
The seed for the random number generator.
|
|
22
|
+
threads : int, optional
|
|
23
|
+
The number of threads to use. If None, uses the number of CPU cores.
|
|
24
|
+
"""
|
|
25
|
+
if threads is None:
|
|
26
|
+
threads = multiprocessing.cpu_count()
|
|
27
|
+
self.threads = threads
|
|
28
|
+
|
|
29
|
+
self.seed_seq = SeedSequence(seed)
|
|
30
|
+
self.shape = None
|
|
31
|
+
self.values = None
|
|
32
|
+
self.step = None
|
|
33
|
+
|
|
34
|
+
self.executor = concurrent.futures.ThreadPoolExecutor(self.threads)
|
|
35
|
+
|
|
36
|
+
def fill_arr(self, shape: tuple[int, int]) -> np.ndarray:
|
|
37
|
+
"""
|
|
38
|
+
Fill an array of given shape with random numbers in parallel using threads.
|
|
39
|
+
|
|
40
|
+
The number of RNG chunks is determined by the shape,
|
|
41
|
+
so results are reproducible regardless of the number of threads used.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
shape : tuple[int]
|
|
46
|
+
The shape of the array to fill.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
np.ndarray
|
|
51
|
+
The filled array with random floating-point numbers.
|
|
52
|
+
"""
|
|
53
|
+
if isinstance(shape, int):
|
|
54
|
+
shape = (shape,)
|
|
55
|
+
self.shape = tuple(shape)
|
|
56
|
+
self.values = np.empty(self.shape)
|
|
57
|
+
n_rows = self.values.shape[0]
|
|
58
|
+
|
|
59
|
+
rows_per_chunk = shape[1]
|
|
60
|
+
n_chunks = max(1, int(np.ceil(n_rows / rows_per_chunk)))
|
|
61
|
+
chunk_step = int(np.ceil(n_rows / n_chunks))
|
|
62
|
+
|
|
63
|
+
child_seeds = self.seed_seq.spawn(n_chunks)
|
|
64
|
+
|
|
65
|
+
chunks = []
|
|
66
|
+
for i in range(n_chunks):
|
|
67
|
+
first = i * chunk_step
|
|
68
|
+
last = min((i + 1) * chunk_step, n_rows)
|
|
69
|
+
if first >= last:
|
|
70
|
+
break
|
|
71
|
+
chunks.append((i, first, last))
|
|
72
|
+
|
|
73
|
+
def _fill_chunk(chunk_idx, out, first, last):
|
|
74
|
+
rng = default_rng(child_seeds[chunk_idx])
|
|
75
|
+
view = out[first:last]
|
|
76
|
+
view[...] = rng.standard_normal(view.shape)
|
|
77
|
+
|
|
78
|
+
futures = [
|
|
79
|
+
self.executor.submit(_fill_chunk, idx, self.values, first, last)
|
|
80
|
+
for idx, first, last in chunks
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
concurrent.futures.wait(futures)
|
|
84
|
+
|
|
85
|
+
return self.values
|
|
86
|
+
|
|
87
|
+
def __del__(self):
|
|
88
|
+
self.executor.shutdown(False)
|
|
File without changes
|