xarray-bitpacker 0.0.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,3 @@
1
+ from xarray_bitpacker.bitpacker import BitPacker # type: ignore
2
+
3
+ __version__ = "0.0.1"
@@ -0,0 +1,157 @@
1
+ import warnings
2
+ from typing import Hashable, Literal
3
+
4
+ import numpy as np
5
+ import xarray as xr
6
+
7
+
8
+ @xr.register_dataarray_accessor("bitpacker")
9
+ class BitPacker:
10
+ """DataArray extension allowing bitpacking of boolean arrays
11
+
12
+ methods:
13
+ packbits(dim: Hashable, bitorder: Literal["big", "little"] = "big", separator:
14
+ str = " | "): Pack boolean array along given dimension using numpy packbits.
15
+
16
+ unpackbits(dim: Hashable, axis: int = -1): Unpack bit-packed DataArray into a
17
+ binary DataArray.
18
+ """
19
+
20
+ def __init__(self, xarray_obj: xr.DataArray):
21
+ """"""
22
+ self._obj = xarray_obj
23
+
24
+ def packbits(
25
+ self,
26
+ dim: Hashable,
27
+ bitorder: Literal["big", "little"] = "big",
28
+ separator: str = " | ",
29
+ ) -> xr.DataArray:
30
+ """
31
+ Pack boolean array along given dimension using numpy packbits
32
+
33
+ The DataArray this is called on must be a boolean or binary integer array
34
+ containing multiple flags to be packed. The dimension listed in "dim" must index
35
+ across the flags to be packed. If "dim" has a corresponding coordinate of the
36
+ same type, it will be coerced to a string dtype and used as the name for each
37
+ flag. No name (after coercion) should contain the value of "separator" as a
38
+ substring. If no coordinates for "dim" are available, a default of "flag_0",
39
+ "flag_1", etc. will be used.
40
+
41
+ args:
42
+ dim (hashable): Dimension of array over which bit packing should be
43
+ done.
44
+ bitorder ("big" or "little"): The order in which to pack bits; see the docs
45
+ for numpy.packbits for more info. Default is "big".
46
+ separator (string): String used to separate flag names in the bitpacked
47
+ metadata. Default is " | ".
48
+
49
+ returns:
50
+ xarray.DataArray: Unsigned 8-bit integer array with the same shape and
51
+ dimensions as the input array, except for the dimension "dim" which is
52
+ removed. Each integer has the flags for that location bit-packed using
53
+ numpy.bitpack. The "long_name" attribute will have "Bit-packed"
54
+ prepended if present, and will be created as "Bit-packed flags" if not.
55
+ The bitorder used is saved as the attribute "bitorder", and the
56
+ attribute "bit_flags" contains the flag names (extracted from the
57
+ coordinates on dim in array) separated by the separator value.
58
+ """
59
+ try:
60
+ axis = list(self._obj.dims).index(dim)
61
+ except ValueError as e:
62
+ e.add_note(f"dim must be a dimension of array.")
63
+ raise
64
+ if dim in self._obj.coords:
65
+ flags_list = list(self._obj.coords[dim].astype(np.str_).values)
66
+ else:
67
+ warnings.warn(
68
+ f"No coordinates found for dimension {dim}, using default instead"
69
+ )
70
+ flags_list = [f"flag_{i}" for i in range(self._obj.sizes[dim])]
71
+ packed_data = np.packbits(self._obj.values, axis=axis, bitorder=bitorder)
72
+ output_array = xr.DataArray(
73
+ packed_data, dims=self._obj.dims, attrs=self._obj.attrs
74
+ )
75
+ output_array = output_array.squeeze(dim=dim, drop=True)
76
+ try:
77
+ output_array.attrs["long_name"] = (
78
+ "Bit-packed " + self._obj.attrs["long_name"]
79
+ )
80
+ except KeyError:
81
+ if self._obj.name is not None:
82
+ output_array.attrs["long_name"] = "Bit-packed " + str(self._obj.name)
83
+ else:
84
+ output_array.attrs["long_name"] = "Bit-packed flags"
85
+ output_array.attrs["bitorder"] = bitorder
86
+ output_array.attrs["bit_flags"] = separator.join(flags_list)
87
+ output_array.attrs["bit_flag_separator"] = separator
88
+ output_array.attrs["valid_range"] = [0, 255]
89
+ return output_array
90
+
91
+ def unpackbits(
92
+ self,
93
+ dim: Hashable,
94
+ axis: int = -1,
95
+ ) -> xr.DataArray:
96
+ """
97
+ Unpack bit-packed DataArray into a binary DataArray
98
+
99
+ The DataArray this is called on should be a bit-packed array of unsigned 8-bit
100
+ integers in the format output by the "packbits" method of this class. Should
101
+ have a "bitorder" attribute containing the bit ordering for the packing, either
102
+ "big" or "little", a "bit_flags" attribute which contains the flag names
103
+ separated by the substring found in the "big_flag_separator" attribute, and a
104
+ "long_name" attribute starting with "Bit-packed ".
105
+
106
+ args:
107
+ dim (hashable): Dimension to be added to index between the unpacked flags.
108
+ axis (int): Position in the list of dimensions where the new dimension
109
+ should be added. Default is -1 (end of the list).
110
+
111
+ returns:
112
+ xarray.DataArray: Integer binary array of the same shape as the input array,
113
+ but with a new dimension "dim" added at position "axis". For each
114
+ position along this dimension, the binary value represents the unpacked
115
+ status of the corresponding bit. The dimension "dim" has a coordinate
116
+ list of flag names extracted from the attribute "bit_flags" in the input
117
+ array.
118
+ """
119
+ # Insert the new dimension at the appropriate location
120
+ unpacked_dims = list(self._obj.dims)
121
+ if axis >= 0:
122
+ unpacked_dims.insert(axis, dim)
123
+ else: # Insert doesn't handle negative indices the same way as numpy
124
+ unpacked_dims.insert(len(self._obj.dims) + 1 + axis, dim)
125
+
126
+ # Unpack the coordinates using our known separator
127
+ unpacked_coords = self._obj.attrs["bit_flags"].split(
128
+ self._obj.attrs["bit_flag_separator"]
129
+ )
130
+
131
+ # Unpack the data, using the length of our coordinates to not excessively 0-pad
132
+ unsqueezed_data = np.expand_dims(self._obj.values, axis)
133
+ unpacked_data = np.unpackbits(
134
+ unsqueezed_data,
135
+ axis=axis,
136
+ bitorder=self._obj.attrs["bitorder"],
137
+ count=len(unpacked_coords),
138
+ )
139
+
140
+ # Package everything into an array
141
+ unpacked_array = xr.DataArray(
142
+ unpacked_data,
143
+ dims=unpacked_dims,
144
+ coords={dim: unpacked_coords},
145
+ attrs=self._obj.attrs,
146
+ )
147
+
148
+ # Adjust array metadata
149
+ # Remove "Bit-packed " from the beginning of the long name
150
+ unpacked_array.attrs["long_name"] = unpacked_array.attrs["long_name"][11:]
151
+ # Reset valid range
152
+ unpacked_array.attrs["valid_range"] = [0, 1]
153
+ # Remove no longer relevant flags
154
+ del unpacked_array.attrs["bitorder"]
155
+ del unpacked_array.attrs["bit_flags"]
156
+ del unpacked_array.attrs["bit_flag_separator"]
157
+ return unpacked_array
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: xarray_bitpacker
3
+ Version: 0.0.1
4
+ Summary: Xarray extension that leverages xarray's metadata to automate and enhance numpy's bitpacking functionality.
5
+ Author-email: Lander Ver Hoef <Lander.Ver_Hoef@colostate.edu>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/zyjux/xarray_bitpacker
8
+ Project-URL: Issues, https://github.com/zyjux/xarray_bitpacker/issues
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: numpy
13
+ Requires-Dist: xarray
14
+ Dynamic: license-file
15
+
16
+ # Xarray Bitpacker
17
+ An xarray DataArray accessor extension that leverages xarray's metadata to automate and enhance numpy's bitpacking functionality.
18
+
19
+ When saving data that consists of multiple boolean or binary arrays, it can be more efficient to "bit-pack" the data by recording the state of each flag as the state of a particular bit in a standard 8-bit unsigned integer.
20
+ This allows up to 8 boolean fields to be encoded into a single integer field with no loss of information.
21
+ However, while this allows for efficient storage, the bitpacked fields are not as intuitive to use and plot as the separate binary fields, so both bitpacking and unbitpacking routines are needed.
22
+ Numpy provides efficient bitpacking and unbitpacking routines, but these require that the information about what flag each bit represents and how the bitpacking was performed (including whether the bits are ordered from big to little or little to big) must be recorded separately.
23
+ This package makes use of the enhanced metadata structures available in xarray to store all that information alongside the bitpacked array, allowing for easy and automated unbitpacking.
24
+
25
+ We follow the "accessor" extension framework for xarray found [here](https://docs.xarray.dev/en/stable/internals/extending-xarray.html) to patch in these routines as DataArray methods.
26
+
27
+ ## Usage
28
+ When imported, adds the `bitpacker` namespace to `xarray.DataArrays`, which contains `packbits` and `unpackbits`.
29
+ `packbits` takes a set of boolean or binary flag arrays structured as a single, higher-dimensional DataArray with one dimension that indexes across the flags and bitpacks that information as an 8-bit integer array, with metadata describing the packing process and flags.
30
+ `unpackbits` then takes a packed array with metadata and unpacks it back into a higher-dimensional array with coordinates specifying the packed flags.
31
+
32
+ ```
33
+ import xarray as xr
34
+ import numpy as np
35
+
36
+ import xarray_bitpacker
37
+
38
+ da = xr.DataArray(
39
+ np.stack([np.full((5,), False), np.full((5,), True)], axis=0),
40
+ dims=["flags", "x"],
41
+ coords={"flags": ["flag_1", "flag_2"]}
42
+ )
43
+
44
+ packed_array = da.bitpacker.packbits(dim="flags", bitorder="little")
45
+ packed_array
46
+
47
+ >> <xarray.DataArray (x: 5)> Size: 5B
48
+ >> array([2, 2, 2, 2, 2], dtype=uint8)
49
+ >> Dimensions without coordinates: x
50
+ >> Attributes:
51
+ >> long_name: Bit-packed flags
52
+ >> bitorder: little
53
+ >> bit_flags: flag_1 | flag_2
54
+ >> bit_flag_separator: |
55
+ >> valid_range: [0, 255]
56
+
57
+ unpacked_array = packed_array.bitpacker.unpackbits(dim="flags")
58
+ unpacked_array
59
+
60
+ >> <xarray.DataArray (x: 5, flags: 2)> Size: 10B
61
+ >> array([[0, 1],
62
+ >> [0, 1],
63
+ >> [0, 1],
64
+ >> [0, 1],
65
+ >> [0, 1]], dtype=uint8)
66
+ >> Coordinates:
67
+ >> * flags (flags) <U6 48B 'flag_1' 'flag_2'
68
+ >> Dimensions without coordinates: x
69
+ >> Attributes:
70
+ >> long_name: flags
71
+ >> valid_range: [0, 1]
72
+ ```
73
+
74
+ ## AI Statement
75
+
76
+ No generative AI of any kind was used for development, testing, or coding assistance on this project.
77
+
78
+ ## Acknowledgments
79
+
80
+ The development of this package was supported by the Cooperative Institute for Research in the Atmosphere (CIRA) at Colorado State University and was funded by the U.S. Office of Naval Research (ONR) via the OVERCAST contract, Award N0001424C2214.
@@ -0,0 +1,7 @@
1
+ xarray_bitpacker/__init__.py,sha256=EMGRD1Zd0sKI1xrxAAqiCoisJDVNaRMN1Kss_qzv5_Q,88
2
+ xarray_bitpacker/bitpacker.py,sha256=L8ucPCyrLskmJzJLl__AEFN74EJawl4RkbknwufMRac,6889
3
+ xarray_bitpacker-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
4
+ xarray_bitpacker-0.0.1.dist-info/METADATA,sha256=R_So0tHOkdvSn8B2ymBrLsx2bN0oU-BlQnjlieCII2k,3859
5
+ xarray_bitpacker-0.0.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ xarray_bitpacker-0.0.1.dist-info/top_level.txt,sha256=pKGfXraDJOn0AO5TAqPpeEQs-n-pNraeEWYFodJGerI,17
7
+ xarray_bitpacker-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ xarray_bitpacker