legend-pydataobj 1.12.0a3__tar.gz → 1.13.0__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.
Files changed (95) hide show
  1. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/PKG-INFO +1 -1
  2. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/PKG-INFO +1 -1
  3. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/SOURCES.txt +1 -0
  4. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/_version.py +2 -2
  5. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/__init__.py +2 -2
  6. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/write/array.py +2 -3
  7. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/write/composite.py +94 -14
  8. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/core.py +14 -6
  9. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/datatype.py +5 -1
  10. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/iterator.py +38 -43
  11. legend_pydataobj-1.13.0/src/lgdo/lh5/settings.py +34 -0
  12. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/utils.py +2 -2
  13. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/struct.py +52 -2
  14. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/table.py +3 -2
  15. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_core.py +46 -0
  16. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_store.py +59 -12
  17. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_utils.py +7 -0
  18. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_write.py +109 -0
  19. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_histogram.py +2 -2
  20. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_struct.py +2 -2
  21. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_waveformtable.py +1 -1
  22. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/LICENSE +0 -0
  23. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/README.md +0 -0
  24. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/pyproject.toml +0 -0
  25. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/setup.cfg +0 -0
  26. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/dependency_links.txt +0 -0
  27. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/entry_points.txt +0 -0
  28. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/not-zip-safe +0 -0
  29. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/requires.txt +0 -0
  30. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/legend_pydataobj.egg-info/top_level.txt +0 -0
  31. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/__init__.py +0 -0
  32. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/cli.py +0 -0
  33. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/__init__.py +0 -0
  34. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/base.py +0 -0
  35. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/generic.py +0 -0
  36. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/radware.py +0 -0
  37. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/utils.py +0 -0
  38. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/compression/varlen.py +0 -0
  39. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lgdo_utils.py +0 -0
  40. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/__init__.py +0 -0
  41. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/__init__.py +0 -0
  42. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/array.py +0 -0
  43. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/composite.py +0 -0
  44. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/encoded.py +0 -0
  45. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/ndarray.py +0 -0
  46. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/scalar.py +0 -0
  47. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/utils.py +0 -0
  48. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/read/vector_of_vectors.py +0 -0
  49. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/write/__init__.py +0 -0
  50. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/write/scalar.py +0 -0
  51. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/_serializers/write/vector_of_vectors.py +0 -0
  52. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/concat.py +0 -0
  53. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/exceptions.py +0 -0
  54. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/store.py +0 -0
  55. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/lh5/tools.py +0 -0
  56. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/logging.py +0 -0
  57. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/__init__.py +0 -0
  58. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/array.py +0 -0
  59. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/arrayofequalsizedarrays.py +0 -0
  60. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/encoded.py +0 -0
  61. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/fixedsizearray.py +0 -0
  62. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/histogram.py +0 -0
  63. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/lgdo.py +0 -0
  64. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/scalar.py +0 -0
  65. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/vectorofvectors.py +0 -0
  66. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/vovutils.py +0 -0
  67. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/types/waveformtable.py +0 -0
  68. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/units.py +0 -0
  69. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/src/lgdo/utils.py +0 -0
  70. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/conftest.py +0 -0
  71. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/sigcompress/LDQTA_r117_20200110T105115Z_cal_geds_raw-0.dat +0 -0
  72. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/sigcompress/special-wf-clipped.dat +0 -0
  73. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/test_compression.py +0 -0
  74. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/test_radware_sigcompress.py +0 -0
  75. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/test_str2wfcodec.py +0 -0
  76. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/compression/test_uleb128_zigzag_diff.py +0 -0
  77. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/conftest.py +0 -0
  78. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/conftest.py +0 -0
  79. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_concat.py +0 -0
  80. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_exceptions.py +0 -0
  81. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_datatype.py +0 -0
  82. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_iterator.py +0 -0
  83. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/lh5/test_lh5_tools.py +0 -0
  84. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/test_cli.py +0 -0
  85. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/test_lgdo_utils.py +0 -0
  86. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_array.py +0 -0
  87. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_arrayofequalsizedarrays.py +0 -0
  88. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_encoded.py +0 -0
  89. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_fixedsizearray.py +0 -0
  90. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_representations.py +0 -0
  91. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_scalar.py +0 -0
  92. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_table.py +0 -0
  93. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_table_eval.py +0 -0
  94. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_vectorofvectors.py +0 -0
  95. {legend_pydataobj-1.12.0a3 → legend_pydataobj-1.13.0}/tests/types/test_vovutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: legend_pydataobj
3
- Version: 1.12.0a3
3
+ Version: 1.13.0
4
4
  Summary: LEGEND Python Data Objects
5
5
  Author: The LEGEND Collaboration
6
6
  Maintainer: The LEGEND Collaboration
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: legend_pydataobj
3
- Version: 1.12.0a3
3
+ Version: 1.13.0
4
4
  Summary: LEGEND Python Data Objects
5
5
  Author: The LEGEND Collaboration
6
6
  Maintainer: The LEGEND Collaboration
@@ -27,6 +27,7 @@ src/lgdo/lh5/core.py
27
27
  src/lgdo/lh5/datatype.py
28
28
  src/lgdo/lh5/exceptions.py
29
29
  src/lgdo/lh5/iterator.py
30
+ src/lgdo/lh5/settings.py
30
31
  src/lgdo/lh5/store.py
31
32
  src/lgdo/lh5/tools.py
32
33
  src/lgdo/lh5/utils.py
@@ -17,5 +17,5 @@ __version__: str
17
17
  __version_tuple__: VERSION_TUPLE
18
18
  version_tuple: VERSION_TUPLE
19
19
 
20
- __version__ = version = '1.12.0a3'
21
- __version_tuple__ = version_tuple = (1, 12, 0, 'a3')
20
+ __version__ = version = '1.13.0'
21
+ __version_tuple__ = version_tuple = (1, 13, 0)
@@ -7,7 +7,6 @@ browsed easily in python like any `HDF5 <https://www.hdfgroup.org>`_ file using
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- from ._serializers.write.array import DEFAULT_HDF5_SETTINGS
11
10
  from .core import read, read_as, write
12
11
  from .iterator import LH5Iterator
13
12
  from .store import LH5Store
@@ -15,14 +14,15 @@ from .tools import ls, show
15
14
  from .utils import read_n_rows
16
15
 
17
16
  __all__ = [
18
- "DEFAULT_HDF5_SETTINGS",
19
17
  "LH5Iterator",
20
18
  "LH5Store",
21
19
  "concat",
20
+ "default_hdf5_settings",
22
21
  "ls",
23
22
  "read",
24
23
  "read_as",
25
24
  "read_n_rows",
25
+ "reset_default_hdf5_settings",
26
26
  "show",
27
27
  "write",
28
28
  ]
@@ -6,12 +6,11 @@ import h5py
6
6
  import numpy as np
7
7
 
8
8
  from .... import types
9
+ from ... import settings
9
10
  from ...exceptions import LH5EncodeError
10
11
 
11
12
  log = logging.getLogger(__name__)
12
13
 
13
- DEFAULT_HDF5_SETTINGS: dict[str, ...] = {"shuffle": True, "compression": "gzip"}
14
-
15
14
 
16
15
  def _h5_write_array(
17
16
  obj,
@@ -49,7 +48,7 @@ def _h5_write_array(
49
48
  del group[name]
50
49
 
51
50
  # set default compression options
52
- for k, v in DEFAULT_HDF5_SETTINGS.items():
51
+ for k, v in settings.DEFAULT_HDF5_SETTINGS.items():
53
52
  h5py_kwargs.setdefault(k, v)
54
53
 
55
54
  # compress using the 'compression' LGDO attribute, if available
@@ -64,6 +64,59 @@ def _h5_write_lgdo(
64
64
 
65
65
  group = utils.get_h5_group(group, lh5_file)
66
66
 
67
+ # name already in file
68
+ if name in group or (
69
+ ("datatype" in group.attrs or group == "/")
70
+ and (len(name) <= 2 or "/" not in name[1:-1])
71
+ ):
72
+ pass
73
+ # group is in file but not struct or need to create nesting
74
+ else:
75
+ # check if name is nested
76
+ # if name is nested, iterate up from parent
77
+ # otherwise we just need to iterate the group
78
+ if len(name) > 2 and "/" in name[1:-1]:
79
+ group = utils.get_h5_group(
80
+ name[:-1].rsplit("/", 1)[0],
81
+ group,
82
+ )
83
+ curr_name = (
84
+ name.rsplit("/", 1)[1]
85
+ if name[-1] != "/"
86
+ else name[:-1].rsplit("/", 1)[1]
87
+ )
88
+ else:
89
+ curr_name = name
90
+ # initialize the object to be written
91
+ obj = types.Struct({curr_name.replace("/", ""): obj})
92
+
93
+ # if base group already has a child we just append
94
+ if len(group) >= 1:
95
+ wo_mode = "ac"
96
+ else:
97
+ # iterate up the group hierarchy until we reach the root or a group with more than one child
98
+ while group.name != "/":
99
+ if len(group) > 1:
100
+ break
101
+ curr_name = group.name
102
+ group = group.parent
103
+ if group.name != "/":
104
+ obj = types.Struct({curr_name[len(group.name) + 1 :]: obj})
105
+ else:
106
+ obj = types.Struct({curr_name[1:]: obj})
107
+ # if the group has more than one child, we need to append else we can overwrite
108
+ wo_mode = "ac" if len(group) > 1 else "o"
109
+
110
+ # set the new name
111
+ if group.name == "/":
112
+ name = "/"
113
+ elif group.parent.name == "/":
114
+ name = group.name[1:]
115
+ else:
116
+ name = group.name[len(group.parent.name) + 1 :]
117
+ # get the new group
118
+ group = utils.get_h5_group(group.parent if group.name != "/" else "/", lh5_file)
119
+
67
120
  if wo_mode == "w" and name in group:
68
121
  msg = f"can't overwrite '{name}' in wo_mode 'write_safe'"
69
122
  raise LH5EncodeError(msg, lh5_file, group, name)
@@ -87,7 +140,7 @@ def _h5_write_lgdo(
87
140
  lh5_file,
88
141
  group=group,
89
142
  start_row=start_row,
90
- n_rows=n_rows,
143
+ n_rows=n_rows, # if isinstance(obj, types.Table | types.Histogram) else None,
91
144
  wo_mode=wo_mode,
92
145
  write_start=write_start,
93
146
  **h5py_kwargs,
@@ -186,19 +239,31 @@ def _h5_write_struct(
186
239
  write_start=0,
187
240
  **h5py_kwargs,
188
241
  ):
242
+ # this works for structs and derived (tables)
189
243
  assert isinstance(obj, types.Struct)
190
244
 
191
245
  # In order to append a column, we need to update the
192
- # `table{old_fields}` value in `group.attrs['datatype"]` to include
193
- # the new fields. One way to do this is to override
194
- # `obj.attrs["datatype"]` to include old and new fields. Then we
195
- # can write the fields to the table as normal.
246
+ # `struct/table{old_fields}` value in `group.attrs['datatype"]` to include
247
+ # the new fields. One way to do this is to override `obj.attrs["datatype"]`
248
+ # to include old and new fields. Then we can write the fields to the
249
+ # struct/table as normal.
196
250
  if wo_mode == "ac":
251
+ if name not in group:
252
+ msg = "Cannot append column to non-existing struct on disk"
253
+ raise LH5EncodeError(msg, lh5_file, group, name)
254
+
197
255
  old_group = utils.get_h5_group(name, group)
256
+ if "datatype" not in old_group.attrs:
257
+ msg = "Cannot append column to an existing non-LGDO object on disk"
258
+ raise LH5EncodeError(msg, lh5_file, group, name)
259
+
198
260
  lgdotype = datatype.datatype(old_group.attrs["datatype"])
199
261
  fields = datatype.get_struct_fields(old_group.attrs["datatype"])
200
- if not issubclass(lgdotype, types.Struct):
201
- msg = f"Trying to append columns to an object of type {lgdotype.__name__}"
262
+ if lgdotype is not type(obj):
263
+ msg = (
264
+ "Trying to append columns to an object of different "
265
+ f"type {lgdotype.__name__}!={type(obj)}"
266
+ )
202
267
  raise LH5EncodeError(msg, lh5_file, group, name)
203
268
 
204
269
  # If the mode is `append_column`, make sure we aren't appending
@@ -211,8 +276,14 @@ def _h5_write_struct(
211
276
  "column(s) to a table with the same field(s)"
212
277
  )
213
278
  raise LH5EncodeError(msg, lh5_file, group, name)
279
+
214
280
  # It doesn't matter what key we access, as all fields in the old table have the same size
215
- if old_group[next(iter(old_group.keys()))].size != obj.size:
281
+ if (
282
+ isinstance(obj, types.Table)
283
+ and old_group.attrs["datatype"][:6]
284
+ != "struct" # structs dont care about size
285
+ and old_group[next(iter(old_group.keys()))].size != obj.size
286
+ ):
216
287
  msg = (
217
288
  f"Table sizes don't match. Trying to append column of size {obj.size} "
218
289
  f"to a table of size {old_group[next(iter(old_group.keys()))].size}."
@@ -222,16 +293,27 @@ def _h5_write_struct(
222
293
  # Now we can append the obj.keys() to the old fields, and then update obj.attrs.
223
294
  fields.extend(list(obj.keys()))
224
295
  obj.attrs.pop("datatype")
225
- obj.attrs["datatype"] = "table" + "{" + ",".join(fields) + "}"
296
+
297
+ obj.attrs["datatype"] = (
298
+ obj.datatype_name() + "{" + ",".join(sorted(fields)) + "}"
299
+ )
300
+
301
+ # propagating wo_mode="ac" to nested LGDOs does not make any sense
302
+ wo_mode = "append"
303
+
304
+ # overwrite attributes of the existing struct
305
+ attrs_overwrite = True
306
+ else:
307
+ attrs_overwrite = wo_mode == "o"
226
308
 
227
309
  group = utils.get_h5_group(
228
310
  name,
229
311
  group,
230
312
  grp_attrs=obj.attrs,
231
- overwrite=(wo_mode in ["o", "ac"]),
313
+ overwrite=attrs_overwrite,
232
314
  )
233
315
  # If the mode is overwrite, then we need to peek into the file's
234
- # table's existing fields. If we are writing a new table to the
316
+ # table's existing fields. If we are writing a new table to the
235
317
  # group that does not contain an old field, we should delete that
236
318
  # old field from the file
237
319
  if wo_mode == "o":
@@ -260,11 +342,9 @@ def _h5_write_struct(
260
342
  else:
261
343
  obj_fld = obj[field]
262
344
 
263
- # Convert keys to string for dataset names
264
- f = str(field)
265
345
  _h5_write_lgdo(
266
346
  obj_fld,
267
- f,
347
+ str(field),
268
348
  lh5_file,
269
349
  group=group,
270
350
  start_row=start_row,
@@ -5,6 +5,7 @@ import inspect
5
5
  import sys
6
6
  from collections.abc import Mapping, Sequence
7
7
  from contextlib import suppress
8
+ from pathlib import Path
8
9
  from typing import Any
9
10
 
10
11
  import h5py
@@ -268,11 +269,13 @@ def write(
268
269
  end of array is the same as ``append``.
269
270
  - ``overwrite_file`` or ``of``: delete file if present prior to
270
271
  writing to it. `write_start` should be 0 (its ignored).
271
- - ``append_column`` or ``ac``: append columns from an
272
- :class:`~.lgdo.table.Table` `obj` only if there is an existing
273
- :class:`~.lgdo.table.Table` in the `lh5_file` with the same
274
- `name` and :class:`~.lgdo.table.Table.size`. If the sizes don't
275
- match, or if there are matching fields, it errors out.
272
+ - ``append_column`` or ``ac``: append fields/columns from an
273
+ :class:`~.lgdo.struct.Struct` `obj` (and derived types such as
274
+ :class:`~.lgdo.table.Table`) only if there is an existing
275
+ :class:`~.lgdo.struct.Struct` in the `lh5_file` with the same `name`.
276
+ If there are matching fields, it errors out. If appending to a
277
+ ``Table`` and the size of the new column is different from the size
278
+ of the existing table, it errors out.
276
279
  write_start
277
280
  row in the output file (if already existing) to start overwriting
278
281
  from.
@@ -288,7 +291,12 @@ def write(
288
291
  datasets. **Note: `compression` Ignored if compression is specified
289
292
  as an `obj` attribute.**
290
293
  """
291
- if wo_mode in ("w", "write", "of", "overwrite_file"):
294
+
295
+ if (
296
+ isinstance(lh5_file, str)
297
+ and not Path(lh5_file).is_file()
298
+ and wo_mode in ("w", "write_safe", "of", "overwrite_file")
299
+ ):
292
300
  h5py_kwargs.update(
293
301
  {
294
302
  "fs_strategy": "page",
@@ -2,6 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import re
4
4
  from collections import OrderedDict
5
+ from itertools import permutations as perm
5
6
 
6
7
  from .. import types as lgdo
7
8
 
@@ -14,7 +15,10 @@ _lgdo_datatype_map: dict[str, lgdo.LGDO] = OrderedDict(
14
15
  lgdo.ArrayOfEncodedEqualSizedArrays,
15
16
  r"^array_of_encoded_equalsized_arrays<1,1>\{.+\}$",
16
17
  ),
17
- (lgdo.Histogram, r"^struct\{binning,weights,isdensity\}$"),
18
+ (
19
+ lgdo.Histogram,
20
+ rf"^struct\{{(?:{'|'.join([','.join(p) for p in perm(['binning', 'weights', 'isdensity'])])})\}}$",
21
+ ),
18
22
  (lgdo.Struct, r"^struct\{.*\}$"),
19
23
  (lgdo.Table, r"^table\{.*\}$"),
20
24
  (lgdo.FixedSizeArray, r"^fixedsize_array<\d+>\{.+\}$"),
@@ -17,48 +17,43 @@ LGDO = typing.Union[Array, Scalar, Struct, VectorOfVectors]
17
17
 
18
18
 
19
19
  class LH5Iterator(typing.Iterator):
20
- """
21
- A class for iterating through one or more LH5 files, one block of entries
22
- at a time. This also accepts an entry list/mask to enable event selection,
23
- and a field mask.
24
-
25
- This can be used as an iterator:
26
-
27
-
28
- >>> for lh5_obj in LH5Iterator(...):
29
- >>> # do the thing!
30
-
31
- This is intended for if you are reading a large quantity of data. This
32
- will ensure that you traverse files efficiently to minimize caching time
33
- and will limit your memory usage (particularly when reading in waveforms!).
34
- The ``lh5_obj`` that is read by this class is reused in order to avoid
35
- reallocation of memory; this means that if you want to hold on to data
36
- between reads, you will have to copy it somewhere!
37
-
38
- When defining an LH5Iterator, you must give it a list of files and the
39
- hdf5 groups containing the data tables you are reading. You may also
40
- provide a field mask, and an entry list or mask, specifying which entries
41
- to read from the files. You may also pair it with a friend iterator, which
42
- contains a parallel group of files which will be simultaneously read.
43
- In addition to accessing requested data via ``lh5_obj``, several
44
- properties exist to tell you where that data came from:
45
-
46
- - lh5_it.current_i_entry: get the index within the entry list of the
47
- first entry that is currently read
48
- - lh5_it.current_local_entries: get the entry numbers relative to the
49
- file the data came from
50
- - lh5_it.current_global_entries: get the entry number relative to the
51
- full dataset
52
- - lh5_it.current_files: get the file name corresponding to each entry
53
- - lh5_it.current_groups: get the group name corresponding to each entry
54
-
55
- This class can also be used for random access:
56
-
57
- >>> lh5_obj = lh5_it.read(i_entry)
58
-
59
- to read the block of entries starting at i_entry. In case of multiple files
60
- or the use of an event selection, i_entry refers to a global event index
61
- across files and does not count events that are excluded by the selection.
20
+ """Iterate over chunks of entries from LH5 files.
21
+
22
+ The iterator reads ``buffer_len`` entries at a time from one or more
23
+ files. The LGDO instance returned at each iteration is reused to avoid
24
+ reallocations, so copy the data if it should be preserved.
25
+
26
+ Examples
27
+ --------
28
+ Iterate through a table one chunk at a time::
29
+
30
+ from lgdo.lh5 import LH5Iterator
31
+
32
+ for table in LH5Iterator("data.lh5", "geds/raw/energy", buffer_len=100):
33
+ process(table)
34
+
35
+ ``LH5Iterator`` can also be used for random access::
36
+
37
+ it = LH5Iterator(files, groups)
38
+ table = it.read(i_entry)
39
+
40
+ In case of multiple files or an entry selection, ``i_entry`` refers to the
41
+ global event index across all files.
42
+
43
+ When instantiating an iterator you must provide a list of files and the
44
+ HDF5 groups to read. Optional parameters allow field masking, event
45
+ selection and pairing the iterator with a "friend" iterator that is read in
46
+ parallel. Several properties are available to obtain the provenance of the
47
+ data currently loaded:
48
+
49
+ - ``current_i_entry`` -- index within the entry list of the first entry in
50
+ the buffer
51
+ - ``current_local_entries`` -- entry numbers relative to the file the data
52
+ came from
53
+ - ``current_global_entries`` -- entry number relative to the full dataset
54
+ - ``current_files`` -- file name corresponding to each entry in the buffer
55
+ - ``current_groups`` -- group name corresponding to each entry in the
56
+ buffer
62
57
  """
63
58
 
64
59
  def __init__(
@@ -505,7 +500,7 @@ class LH5Iterator(typing.Iterator):
505
500
  return self
506
501
 
507
502
  def __next__(self) -> tuple[LGDO, int, int]:
508
- """Read next buffer_len entries and return lh5_table and iterator entry."""
503
+ """Read the next chunk of entries and return the buffer."""
509
504
  n_entries = self.n_entries
510
505
  if n_entries is not None:
511
506
  n_entries = min(
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ def default_hdf5_settings() -> dict[str, Any]:
7
+ """Returns the HDF5 settings for writing data to disk to the pydataobj defaults.
8
+
9
+ Examples
10
+ --------
11
+ >>> from lgdo import lh5
12
+ >>> lh5.DEFAULT_HDF5_SETTINGS["compression"] = "lzf"
13
+ >>> lh5.write(data, "data", "file.lh5") # compressed with LZF
14
+ >>> lh5.DEFAULT_HDF5_SETTINGS = lh5.default_hdf5_settings()
15
+ >>> lh5.write(data, "data", "file.lh5", "of") # compressed with default settings (GZIP)
16
+ """
17
+
18
+ return {
19
+ "shuffle": True,
20
+ "compression": "gzip",
21
+ }
22
+
23
+
24
+ DEFAULT_HDF5_SETTINGS: dict[str, ...] = default_hdf5_settings()
25
+ """Global dictionary storing the default HDF5 settings for writing data to disk.
26
+
27
+ Modify this global variable before writing data to disk with this package.
28
+
29
+ Examples
30
+ --------
31
+ >>> from lgdo import lh5
32
+ >>> lh5.DEFAULT_HDF5_SETTINGS["compression"] = "lzf"
33
+ >>> lh5.write(data, "data", "file.lh5") # compressed with LZF
34
+ """
@@ -111,7 +111,7 @@ def get_h5_group(
111
111
  grp_attrs is not None
112
112
  and len(set(grp_attrs.items()) ^ set(group.attrs.items())) > 0
113
113
  ):
114
- if not overwrite:
114
+ if not overwrite and len(group.attrs) != 0:
115
115
  msg = (
116
116
  f"Provided {grp_attrs=} are different from "
117
117
  f"existing ones {dict(group.attrs)=} but overwrite flag is not set"
@@ -154,7 +154,7 @@ def expand_vars(expr: str, substitute: dict[str, str] | None = None) -> str:
154
154
 
155
155
  # use provided mapping
156
156
  # then expand env variables
157
- return os.path.expandvars(string.Template(expr).safe_substitute(substitute))
157
+ return os.path.expandvars(string.Template(str(expr)).safe_substitute(substitute))
158
158
 
159
159
 
160
160
  def expand_path(
@@ -5,7 +5,9 @@ utilities.
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
+ import copy
8
9
  import logging
10
+ import re
9
11
  from collections.abc import Mapping
10
12
  from typing import Any
11
13
 
@@ -56,7 +58,21 @@ class Struct(LGDO, dict):
56
58
  # assign
57
59
  super().update({k: v})
58
60
 
59
- # call LGDO constructor to setup attributes
61
+ # check the datatype attribute passed by the user and sort the fields
62
+ # to ensure consistent behavior
63
+ if attrs is not None and "datatype" in attrs:
64
+ _attrs = copy.copy(dict(attrs))
65
+
66
+ if not _is_struct_datatype(self.datatype_name(), _attrs["datatype"]):
67
+ msg = (
68
+ f"datatype attribute ({self.attrs['datatype']}) is not "
69
+ f"compatible with class datatype!"
70
+ )
71
+ raise ValueError(msg)
72
+
73
+ _attrs["datatype"] = _sort_datatype_fields(_attrs["datatype"])
74
+ attrs = _attrs
75
+
60
76
  super().__init__(attrs)
61
77
 
62
78
  def datatype_name(self) -> str:
@@ -64,7 +80,10 @@ class Struct(LGDO, dict):
64
80
 
65
81
  def form_datatype(self) -> str:
66
82
  return (
67
- self.datatype_name() + "{" + ",".join([str(k) for k in self.keys()]) + "}"
83
+ self.datatype_name()
84
+ + "{"
85
+ + ",".join(sorted([str(k) for k in self.keys()]))
86
+ + "}"
68
87
  )
69
88
 
70
89
  def update_datatype(self) -> None:
@@ -157,3 +176,34 @@ class Struct(LGDO, dict):
157
176
  "not possible. Call view_as() on the fields instead."
158
177
  )
159
178
  raise NotImplementedError(msg)
179
+
180
+
181
+ def _is_struct_datatype(dt_name, expr):
182
+ return re.search("^" + dt_name + r"\{(.*)\}$", expr) is not None
183
+
184
+
185
+ def _get_struct_fields(expr: str) -> list[str]:
186
+ assert _is_struct_datatype(".*", expr)
187
+
188
+ arr = re.search(r"\{(.*)\}$", expr).group(1).split(",")
189
+ if arr == [""]:
190
+ arr = []
191
+
192
+ return sorted(arr)
193
+
194
+
195
+ def _struct_datatype_equal(dt_name, dt1, dt2):
196
+ if any(not _is_struct_datatype(dt_name, dt) for dt in (dt1, dt2)):
197
+ return False
198
+
199
+ return _get_struct_fields(dt1) == _get_struct_fields(dt2)
200
+
201
+
202
+ def _sort_datatype_fields(expr):
203
+ assert _is_struct_datatype(".*", expr)
204
+
205
+ match = re.search(r"^(.*)\{.*\}$", expr)
206
+ struct_type = match.group(1)
207
+ fields = _get_struct_fields(expr)
208
+
209
+ return struct_type + "{" + ",".join(sorted([str(k) for k in fields])) + "}"
@@ -81,8 +81,9 @@ class Table(Struct, LGDOCollection):
81
81
  col_dict = _ak_to_lgdo_or_col_dict(col_dict)
82
82
 
83
83
  # call Struct constructor
84
- Struct.__init__(self, obj_dict=col_dict)
85
- LGDOCollection.__init__(self, attrs=attrs)
84
+ Struct.__init__(self, obj_dict=col_dict, attrs=attrs)
85
+ # no need to call the LGDOCollection constructor, as we are calling the
86
+ # Struct constructor already
86
87
 
87
88
  # if col_dict is not empty, set size according to it
88
89
  # if size is also supplied, resize all fields to match it
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import numpy as np
4
+ import pytest
4
5
 
5
6
  import lgdo
6
7
  from lgdo import lh5
@@ -28,6 +29,51 @@ def test_write(tmptestdir):
28
29
  assert lh5.ls(f"{tmptestdir}/tmp-pygama-lgdo-types2.lh5")
29
30
 
30
31
 
32
+ def test_write_safe(tmptestdir):
33
+ # write_safe should create new file
34
+ struct = lgdo.Struct()
35
+ struct.add_field("scalar", lgdo.Scalar(value=10, attrs={"sth": 1}))
36
+ lh5.write(
37
+ struct,
38
+ "struct",
39
+ f"{tmptestdir}/tmp-pygama-write_safe.lh5",
40
+ group="/data",
41
+ start_row=1,
42
+ n_rows=3,
43
+ wo_mode="w",
44
+ )
45
+ assert lh5.ls(f"{tmptestdir}/tmp-pygama-write_safe.lh5")
46
+
47
+ # write_safe should add a new group to an existing file
48
+ struct = lgdo.Struct()
49
+ struct.add_field("scalar", lgdo.Scalar(value=10, attrs={"sth": 1}))
50
+ lh5.write(
51
+ struct,
52
+ "struct2",
53
+ f"{tmptestdir}/tmp-pygama-write_safe.lh5",
54
+ group="/data",
55
+ start_row=1,
56
+ n_rows=3,
57
+ wo_mode="w",
58
+ )
59
+ assert lh5.ls(f"{tmptestdir}/tmp-pygama-write_safe.lh5", "data/") == [
60
+ "data/struct",
61
+ "data/struct2",
62
+ ]
63
+
64
+ # write_safe should not allow writing to existing dataset
65
+ with pytest.raises(lh5.exceptions.LH5EncodeError):
66
+ lh5.write(
67
+ struct,
68
+ "struct",
69
+ f"{tmptestdir}/tmp-pygama-write_safe.lh5",
70
+ group="/data",
71
+ start_row=1,
72
+ n_rows=3,
73
+ wo_mode="w",
74
+ )
75
+
76
+
31
77
  def test_read_as(lh5_file):
32
78
  store = lh5.LH5Store()
33
79
  obj1 = store.read("/data/struct/table", lh5_file, start_row=1)
@@ -9,7 +9,6 @@ import pytest
9
9
 
10
10
  import lgdo
11
11
  from lgdo import lh5, types
12
- from lgdo.lh5 import DEFAULT_HDF5_SETTINGS
13
12
 
14
13
 
15
14
  def test_init():
@@ -42,6 +41,54 @@ def test_write_objects(lh5_file):
42
41
  pass
43
42
 
44
43
 
44
+ def test_write_safe(tmptestdir):
45
+ # write_safe should create new file
46
+ lh5_st = lh5.LH5Store()
47
+ struct = lgdo.Struct()
48
+ struct.add_field("scalar", lgdo.Scalar(value=10, attrs={"sth": 1}))
49
+ lh5_st.write(
50
+ struct,
51
+ "struct",
52
+ f"{tmptestdir}/tmp-pygama-write_safe_store.lh5",
53
+ group="/data",
54
+ start_row=1,
55
+ n_rows=3,
56
+ wo_mode="w",
57
+ )
58
+ assert lh5.ls(f"{tmptestdir}/tmp-pygama-write_safe_store.lh5")
59
+
60
+ # write_safe should add a new group to an existing file
61
+ lh5_st = lh5.LH5Store()
62
+ struct = lgdo.Struct()
63
+ struct.add_field("scalar", lgdo.Scalar(value=10, attrs={"sth": 1}))
64
+ lh5_st.write(
65
+ struct,
66
+ "struct2",
67
+ f"{tmptestdir}/tmp-pygama-write_safe_store.lh5",
68
+ group="/data",
69
+ start_row=1,
70
+ n_rows=3,
71
+ wo_mode="w",
72
+ )
73
+ assert lh5.ls(f"{tmptestdir}/tmp-pygama-write_safe_store.lh5", "data/") == [
74
+ "data/struct",
75
+ "data/struct2",
76
+ ]
77
+
78
+ # write_safe should not allow writing to existing dataset
79
+ lh5_st = lh5.LH5Store()
80
+ with pytest.raises(lh5.exceptions.LH5EncodeError):
81
+ lh5_st.write(
82
+ struct,
83
+ "struct",
84
+ f"{tmptestdir}/tmp-pygama-write_safe_store.lh5",
85
+ group="/data",
86
+ start_row=1,
87
+ n_rows=3,
88
+ wo_mode="w",
89
+ )
90
+
91
+
45
92
  def test_read_n_rows(lh5_file):
46
93
  store = lh5.LH5Store()
47
94
  assert store.read_n_rows("/data/struct_full/aoesa", lh5_file) == 5
@@ -96,7 +143,7 @@ def test_read_array(lh5_file):
96
143
  with h5py.File(lh5_file) as h5f:
97
144
  assert (
98
145
  h5f["/data/struct/array"].compression
99
- is DEFAULT_HDF5_SETTINGS["compression"]
146
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
100
147
  )
101
148
 
102
149
  lh5_obj = store.read("/data/struct_full/array2d", lh5_file)
@@ -170,11 +217,11 @@ def test_read_vov(lh5_file):
170
217
  with h5py.File(lh5_file) as h5f:
171
218
  assert (
172
219
  h5f["/data/struct/vov/cumulative_length"].compression
173
- is DEFAULT_HDF5_SETTINGS["compression"]
220
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
174
221
  )
175
222
  assert (
176
223
  h5f["/data/struct/vov/flattened_data"].compression
177
- is DEFAULT_HDF5_SETTINGS["compression"]
224
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
178
225
  )
179
226
 
180
227
  lh5_obj = store.read("/data/struct/vov3d", lh5_file)
@@ -229,11 +276,11 @@ def test_read_voev(lh5_file):
229
276
  assert h5f["/data/struct/voev/encoded_data/flattened_data"].compression is None
230
277
  assert (
231
278
  h5f["/data/struct/voev/encoded_data/cumulative_length"].compression
232
- is DEFAULT_HDF5_SETTINGS["compression"]
279
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
233
280
  )
234
281
  assert (
235
282
  h5f["/data/struct/voev/decoded_size"].compression
236
- is DEFAULT_HDF5_SETTINGS["compression"]
283
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
237
284
  )
238
285
 
239
286
 
@@ -312,7 +359,7 @@ def test_read_hdf5_compressed_data(lh5_file):
312
359
  with h5py.File(lh5_file) as h5f:
313
360
  assert (
314
361
  h5f["/data/struct/table/a"].compression
315
- is DEFAULT_HDF5_SETTINGS["compression"]
362
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
316
363
  )
317
364
  assert h5f["/data/struct/table/b"].compression == "gzip"
318
365
  assert h5f["/data/struct/table/c"].compression == "gzip"
@@ -333,15 +380,15 @@ def test_read_wftable(lh5_file):
333
380
  with h5py.File(lh5_file) as h5f:
334
381
  assert (
335
382
  h5f["/data/struct/wftable/values"].compression
336
- is DEFAULT_HDF5_SETTINGS["compression"]
383
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
337
384
  )
338
385
  assert (
339
386
  h5f["/data/struct/wftable/t0"].compression
340
- is DEFAULT_HDF5_SETTINGS["compression"]
387
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
341
388
  )
342
389
  assert (
343
390
  h5f["/data/struct/wftable/dt"].compression
344
- is DEFAULT_HDF5_SETTINGS["compression"]
391
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
345
392
  )
346
393
 
347
394
 
@@ -387,11 +434,11 @@ def test_read_wftable_encoded(lh5_file):
387
434
  assert h5f["/data/struct/wftable_enc/values/decoded_size"].compression is None
388
435
  assert (
389
436
  h5f["/data/struct/wftable_enc/t0"].compression
390
- is DEFAULT_HDF5_SETTINGS["compression"]
437
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
391
438
  )
392
439
  assert (
393
440
  h5f["/data/struct/wftable_enc/dt"].compression
394
- is DEFAULT_HDF5_SETTINGS["compression"]
441
+ is lh5.settings.DEFAULT_HDF5_SETTINGS["compression"]
395
442
  )
396
443
 
397
444
 
@@ -51,3 +51,10 @@ def test_expand_path(lgnd_test_data):
51
51
 
52
52
  # Check if it finds a list of files correctly
53
53
  assert sorted(utils.expand_path(f"{base_dir}/*.lh5", list=True)) == sorted(files)
54
+
55
+ # check with base_path specified
56
+ base_path = base_dir.parent
57
+ assert (
58
+ utils.expand_path(f"{base_dir.name}/*20230318T012144Z*", base_path=base_path)
59
+ == Path(files[0]).relative_to(base_path).as_posix()
60
+ )
@@ -15,6 +15,30 @@ def test_write_compressed_lgnd_waveform_table(enc_lgnd_file):
15
15
  pass
16
16
 
17
17
 
18
+ def test_write_with_hdf5_compression_global(tmptestdir):
19
+ data = types.Table(
20
+ size=1000,
21
+ col_dict={
22
+ "col1": types.Array(np.arange(0, 100, 0.1)),
23
+ "col2": types.Array(np.random.default_rng().random(1000)),
24
+ },
25
+ )
26
+ outfile = f"{tmptestdir}/write_hdf5_data_global_var.lh5"
27
+
28
+ lh5.settings.DEFAULT_HDF5_SETTINGS["shuffle"] = False
29
+ lh5.settings.DEFAULT_HDF5_SETTINGS["compression"] = "lzf"
30
+
31
+ lh5.write(data, "data", outfile, wo_mode="of")
32
+
33
+ with h5py.File(outfile) as h5f:
34
+ assert h5f["/data/col1"].shuffle is False
35
+ assert h5f["/data/col1"].compression == "lzf"
36
+
37
+ lh5.settings.DEFAULT_HDF5_SETTINGS = lh5.settings.default_hdf5_settings()
38
+ assert lh5.settings.DEFAULT_HDF5_SETTINGS["shuffle"] is True
39
+ assert lh5.settings.DEFAULT_HDF5_SETTINGS["compression"] == "gzip"
40
+
41
+
18
42
  def test_write_with_hdf5_compression(lgnd_file, tmptestdir):
19
43
  store = lh5.LH5Store()
20
44
  wft = store.read("/geds/raw/waveform", lgnd_file)
@@ -452,6 +476,7 @@ def test_write_histogram(caplog, tmptestdir):
452
476
 
453
477
  # Now, check that the data were overwritten
454
478
  h3 = store.read("my_group/my_histogram", f"{tmptestdir}/write_histogram_test.lh5")
479
+ assert isinstance(h3, types.Histogram)
455
480
  assert np.array_equal(h3.weights.nda, np.array([[10, 10], [10, 10]]))
456
481
  assert h3.binning[0].edges[0] == 2
457
482
  assert h3.binning[1].edges[-1] == 7
@@ -518,6 +543,7 @@ def test_write_histogram_variable(caplog, tmptestdir):
518
543
 
519
544
  # Now, check that the data were overwritten
520
545
  h3 = store.read("my_group/my_histogram", f"{tmptestdir}/write_histogram_test.lh5")
546
+ assert isinstance(h3, types.Histogram)
521
547
  assert np.array_equal(h3.weights.nda, np.array([[10, 10], [10, 10]]))
522
548
  assert np.array_equal(h3.binning[0].edges, np.array([2, 3.5, 4]))
523
549
  with pytest.raises(TypeError):
@@ -531,3 +557,86 @@ def test_write_histogram_variable(caplog, tmptestdir):
531
557
  assert h3.attrs["testattr"] == "test"
532
558
  assert h3["weights"].attrs["weightattr"] == "testweight"
533
559
  assert h3.binning[0].attrs["binningattr"] == "testbinning"
560
+
561
+
562
+ def test_write_append_struct(tmptestdir):
563
+ outfile = str(tmptestdir / "test-write-append-struct.lh5")
564
+ st = types.Struct({"arr1": types.Table({"a": types.Array([1, 2, 3])})})
565
+ lh5.write(st, "struct", outfile, wo_mode="of")
566
+ st2 = types.Struct({"arr2": types.Table({"a": types.Array([1, 2, 3])})})
567
+ lh5.write(st2, "struct", outfile, wo_mode="ac")
568
+
569
+ result = lh5.read("struct", outfile)
570
+ assert list(result.keys()) == ["arr1", "arr2"]
571
+ assert len(result.arr1) == len(st.arr1)
572
+ assert len(result.arr2) == len(st2.arr2)
573
+
574
+ # test error when appending existing field
575
+ with pytest.raises(lh5.exceptions.LH5EncodeError):
576
+ lh5.write(
577
+ types.Struct({"arr2": types.Array([4, 5, 6])}),
578
+ "struct",
579
+ outfile,
580
+ wo_mode="ac",
581
+ )
582
+
583
+ # error if appending to object of different type
584
+ with pytest.raises(lh5.exceptions.LH5EncodeError):
585
+ lh5.write(
586
+ types.Struct({"arr2": types.Array([4, 5, 6])}),
587
+ "struct",
588
+ outfile,
589
+ wo_mode="ac",
590
+ )
591
+
592
+ outfile = str(tmptestdir / "test-write-append-struct.lh5")
593
+ lh5.write(
594
+ types.Table({"arr1": types.Array([1, 2, 3])}), "struct", outfile, wo_mode="of"
595
+ )
596
+
597
+ # error if appending to object of different type
598
+ with pytest.raises(lh5.exceptions.LH5EncodeError):
599
+ lh5.write(
600
+ types.Table({"arr2": types.Array([4, 5, 6, 7])}),
601
+ "struct",
602
+ outfile,
603
+ wo_mode="ac",
604
+ )
605
+
606
+ # append to empty struct
607
+ outfile = str(tmptestdir / "test-write-append-struct.lh5")
608
+ lh5.write(types.Struct({}), "struct", outfile, wo_mode="of")
609
+ st2 = types.Struct({"arr2": types.Table({"a": types.Array([1, 2, 3])})})
610
+ lh5.write(st2, "struct", outfile, wo_mode="ac")
611
+
612
+ result = lh5.read("struct", outfile)
613
+ assert list(result.keys()) == ["arr2"]
614
+ assert len(result.arr2) == len(st2.arr2)
615
+
616
+
617
+ def test_write_structs_not_groups(tmptestdir):
618
+ outfile = str(tmptestdir / "test-write-structs-not-groups2.lh5")
619
+
620
+ scalar = types.Scalar("made with legend-pydataobj!")
621
+ array = types.Array([1, 2, 3])
622
+ array2 = types.Array([4, 5, 6])
623
+ lh5.write(scalar, name="message", lh5_file=outfile, wo_mode="overwrite_file")
624
+ lh5.write(array, name="numbers", group="closet", lh5_file=outfile)
625
+ lh5.write(array2, name="numbers2", group="closet", lh5_file=outfile)
626
+ result = lh5.read("/", outfile)
627
+ assert isinstance(result, types.Struct)
628
+ assert result.attrs["datatype"] == "struct{closet,message}"
629
+
630
+ outfile = str(tmptestdir / "test-write-structs-not-groups.lh5")
631
+ tb = types.Table({"a": types.Array([1, 2, 3])})
632
+ lh5.write(tb, "test/table", outfile)
633
+ print(lh5.show(outfile))
634
+ tb2 = types.Table({"a": types.Array([4, 5, 6])})
635
+ lh5.write(tb2, "test/table2", outfile)
636
+ print(lh5.show(outfile))
637
+
638
+ result = lh5.read("test", outfile)
639
+ assert isinstance(result, types.Struct)
640
+ assert result.attrs["datatype"] == "struct{table,table2}"
641
+ assert result.table.a == tb.a
642
+ assert result.table2.a == tb2.a
@@ -98,7 +98,7 @@ def test_init_np():
98
98
  def test_datatype_name():
99
99
  h = Histogram(np.array([1, 1]), (np.array([0, 1, 2]),))
100
100
  assert h.datatype_name() == "struct"
101
- assert h.form_datatype() == "struct{binning,weights,isdensity}"
101
+ assert h.form_datatype() == "struct{binning,isdensity,weights}"
102
102
 
103
103
 
104
104
  def test_axes():
@@ -266,7 +266,7 @@ def test_view_as_np():
266
266
 
267
267
  def test_not_like_table():
268
268
  h = Histogram(np.array([1, 1]), (np.array([0, 1, 2]),))
269
- assert h.form_datatype() == "struct{binning,weights,isdensity}"
269
+ assert h.form_datatype() == "struct{binning,isdensity,weights}"
270
270
  with pytest.raises(AttributeError):
271
271
  x = h.x # noqa: F841
272
272
  with pytest.raises(AttributeError):
@@ -58,10 +58,10 @@ def test_add_field():
58
58
  assert struct["scalar1"].__class__.__name__ == "Scalar"
59
59
 
60
60
  struct.add_field("array1", lgdo.Array(shape=(700, 21), dtype="f", fill_val=2))
61
- assert struct.attrs["datatype"] == "struct{scalar1,array1}"
61
+ assert struct.attrs["datatype"] == "struct{array1,scalar1}"
62
62
 
63
63
  struct["array2"] = lgdo.Array(shape=(700, 21), dtype="f", fill_val=2)
64
- assert struct.attrs["datatype"] == "struct{scalar1,array1,array2}"
64
+ assert struct.attrs["datatype"] == "struct{array1,array2,scalar1}"
65
65
 
66
66
 
67
67
  def test_getattr():
@@ -12,7 +12,7 @@ def test_init():
12
12
  assert (wft.dt.nda == np.full(1024, fill_value=1)).all()
13
13
  assert isinstance(wft.values, lgdo.VectorOfVectors)
14
14
  assert len(wft.values) == 1024
15
- assert wft.attrs == {"datatype": "table{t0,dt,values}"}
15
+ assert wft.attrs == {"datatype": "table{dt,t0,values}"}
16
16
 
17
17
  wft = WaveformTable(dt_units="ns", values_units="adc")
18
18
  assert wft.dt.attrs["units"] == "ns"