legend-pydataobj 1.11.6__py3-none-any.whl → 1.12.0a1__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.
lgdo/lh5/core.py CHANGED
@@ -4,6 +4,7 @@ import bisect
4
4
  import inspect
5
5
  import sys
6
6
  from collections.abc import Mapping, Sequence
7
+ from contextlib import suppress
7
8
  from typing import Any
8
9
 
9
10
  import h5py
@@ -92,8 +93,7 @@ def read(
92
93
  will be set to ``True``, while the rest will default to ``False``.
93
94
  obj_buf
94
95
  Read directly into memory provided in `obj_buf`. Note: the buffer
95
- will be expanded to accommodate the data requested. To maintain the
96
- buffer length, send in ``n_rows = len(obj_buf)``.
96
+ will be resized to accommodate the data retrieved.
97
97
  obj_buf_start
98
98
  Start location in ``obj_buf`` for read. For concatenating data to
99
99
  array-like objects.
@@ -106,12 +106,8 @@ def read(
106
106
 
107
107
  Returns
108
108
  -------
109
- (object, n_rows_read)
110
- `object` is the read-out object `n_rows_read` is the number of rows
111
- successfully read out. Essential for arrays when the amount of data
112
- is smaller than the object buffer. For scalars and structs
113
- `n_rows_read` will be``1``. For tables it is redundant with
114
- ``table.loc``. If `obj_buf` is ``None``, only `object` is returned.
109
+ object
110
+ the read-out object
115
111
  """
116
112
  if isinstance(lh5_file, h5py.File):
117
113
  lh5_obj = lh5_file[name]
@@ -119,12 +115,12 @@ def read(
119
115
  lh5_file = h5py.File(lh5_file, mode="r", locking=locking)
120
116
  lh5_obj = lh5_file[name]
121
117
  else:
122
- lh5_files = list(lh5_file)
123
-
124
- n_rows_read = 0
125
- obj_buf_is_new = False
118
+ if obj_buf is not None:
119
+ obj_buf.resize(obj_buf_start)
120
+ else:
121
+ obj_buf_start = 0
126
122
 
127
- for i, h5f in enumerate(lh5_files):
123
+ for i, h5f in enumerate(lh5_file):
128
124
  if (
129
125
  isinstance(idx, (list, tuple))
130
126
  and len(idx) > 0
@@ -146,33 +142,26 @@ def read(
146
142
  idx = np.array(idx[0])[n_rows_to_read_i:] - n_rows_i
147
143
  else:
148
144
  idx_i = None
149
- n_rows_i = n_rows - n_rows_read
150
145
 
151
- obj_ret = read(
146
+ obj_buf_start_i = len(obj_buf) if obj_buf else 0
147
+ n_rows_i = n_rows - (obj_buf_start_i - obj_buf_start)
148
+
149
+ obj_buf = read(
152
150
  name,
153
151
  h5f,
154
- start_row,
152
+ start_row if i == 0 else 0,
155
153
  n_rows_i,
156
154
  idx_i,
157
155
  use_h5idx,
158
156
  field_mask,
159
157
  obj_buf,
160
- obj_buf_start,
158
+ obj_buf_start_i,
161
159
  decompress,
162
160
  )
163
- if isinstance(obj_ret, tuple):
164
- obj_buf, n_rows_read_i = obj_ret
165
- obj_buf_is_new = True
166
- else:
167
- obj_buf = obj_ret
168
- n_rows_read_i = len(obj_buf)
169
161
 
170
- n_rows_read += n_rows_read_i
171
- if n_rows_read >= n_rows or obj_buf is None:
172
- return obj_buf, n_rows_read
173
- start_row = 0
174
- obj_buf_start += n_rows_read_i
175
- return obj_buf if obj_buf_is_new else (obj_buf, n_rows_read)
162
+ if obj_buf is None or (len(obj_buf) - obj_buf_start) >= n_rows:
163
+ return obj_buf
164
+ return obj_buf
176
165
 
177
166
  if isinstance(idx, (list, tuple)) and len(idx) > 0 and not np.isscalar(idx[0]):
178
167
  idx = idx[0]
@@ -192,8 +181,10 @@ def read(
192
181
  obj_buf_start=obj_buf_start,
193
182
  decompress=decompress,
194
183
  )
184
+ with suppress(AttributeError):
185
+ obj.resize(obj_buf_start + n_rows_read)
195
186
 
196
- return obj if obj_buf is None else (obj, n_rows_read)
187
+ return obj
197
188
 
198
189
 
199
190
  def write(
lgdo/lh5/iterator.py CHANGED
@@ -24,7 +24,8 @@ class LH5Iterator(typing.Iterator):
24
24
 
25
25
  This can be used as an iterator:
26
26
 
27
- >>> for lh5_obj, i_entry, n_rows in LH5Iterator(...):
27
+
28
+ >>> for lh5_obj in LH5Iterator(...):
28
29
  >>> # do the thing!
29
30
 
30
31
  This is intended for if you are reading a large quantity of data. This
@@ -42,6 +43,8 @@ class LH5Iterator(typing.Iterator):
42
43
  In addition to accessing requested data via ``lh5_obj``, several
43
44
  properties exist to tell you where that data came from:
44
45
 
46
+ - lh5_it.current_i_entry: get the index within the entry list of the
47
+ first entry that is currently read
45
48
  - lh5_it.current_local_entries: get the entry numbers relative to the
46
49
  file the data came from
47
50
  - lh5_it.current_global_entries: get the entry number relative to the
@@ -49,9 +52,9 @@ class LH5Iterator(typing.Iterator):
49
52
  - lh5_it.current_files: get the file name corresponding to each entry
50
53
  - lh5_it.current_groups: get the group name corresponding to each entry
51
54
 
52
- This class can also be used either for random access:
55
+ This class can also be used for random access:
53
56
 
54
- >>> lh5_obj, n_rows = lh5_it.read(i_entry)
57
+ >>> lh5_obj = lh5_it.read(i_entry)
55
58
 
56
59
  to read the block of entries starting at i_entry. In case of multiple files
57
60
  or the use of an event selection, i_entry refers to a global event index
@@ -65,6 +68,8 @@ class LH5Iterator(typing.Iterator):
65
68
  base_path: str = "",
66
69
  entry_list: list[int] | list[list[int]] | None = None,
67
70
  entry_mask: list[bool] | list[list[bool]] | None = None,
71
+ i_start: int = 0,
72
+ n_entries: int | None = None,
68
73
  field_mask: dict[str, bool] | list[str] | tuple[str] | None = None,
69
74
  buffer_len: int = "100*MB",
70
75
  file_cache: int = 10,
@@ -89,6 +94,10 @@ class LH5Iterator(typing.Iterator):
89
94
  entry_mask
90
95
  mask of entries to read. If a list of arrays is provided, expect
91
96
  one for each file. Ignore if a selection list is provided.
97
+ i_start
98
+ index of first entry to start at when iterating
99
+ n_entries
100
+ number of entries to read before terminating iteration
92
101
  field_mask
93
102
  mask of which fields to read. See :meth:`LH5Store.read` for
94
103
  more details.
@@ -183,7 +192,8 @@ class LH5Iterator(typing.Iterator):
183
192
  msg = f"can't open any files from {lh5_files}"
184
193
  raise RuntimeError(msg)
185
194
 
186
- self.n_rows = 0
195
+ self.i_start = i_start
196
+ self.n_entries = n_entries
187
197
  self.current_i_entry = 0
188
198
  self.next_i_entry = 0
189
199
 
@@ -317,14 +327,21 @@ class LH5Iterator(typing.Iterator):
317
327
  )
318
328
  return self.global_entry_list
319
329
 
320
- def read(self, i_entry: int) -> tuple[LGDO, int]:
321
- """Read the nextlocal chunk of events, starting at i_entry. Return the
322
- LH5 buffer and number of rows read."""
323
- self.n_rows = 0
324
- i_file = np.searchsorted(self.entry_map, i_entry, "right")
330
+ def read(self, i_entry: int, n_entries: int | None = None) -> LGDO:
331
+ "Read the nextlocal chunk of events, starting at entry."
332
+ self.lh5_buffer.resize(0)
333
+
334
+ if n_entries is None:
335
+ n_entries = self.buffer_len
336
+ elif n_entries == 0:
337
+ return self.lh5_buffer
338
+ elif n_entries > self.buffer_len:
339
+ msg = "n_entries cannot be larger than buffer_len"
340
+ raise ValueError(msg)
325
341
 
326
342
  # if file hasn't been opened yet, search through files
327
343
  # sequentially until we find the right one
344
+ i_file = np.searchsorted(self.entry_map, i_entry, "right")
328
345
  if i_file < len(self.lh5_files) and self.entry_map[i_file] == np.iinfo("q").max:
329
346
  while i_file < len(self.lh5_files) and i_entry >= self._get_file_cumentries(
330
347
  i_file
@@ -332,10 +349,10 @@ class LH5Iterator(typing.Iterator):
332
349
  i_file += 1
333
350
 
334
351
  if i_file == len(self.lh5_files):
335
- return (self.lh5_buffer, self.n_rows)
352
+ return self.lh5_buffer
336
353
  local_i_entry = i_entry - self._get_file_cumentries(i_file - 1)
337
354
 
338
- while self.n_rows < self.buffer_len and i_file < len(self.file_map):
355
+ while len(self.lh5_buffer) < n_entries and i_file < len(self.file_map):
339
356
  # Loop through files
340
357
  local_idx = self.get_file_entrylist(i_file)
341
358
  if local_idx is not None and len(local_idx) == 0:
@@ -344,18 +361,17 @@ class LH5Iterator(typing.Iterator):
344
361
  continue
345
362
 
346
363
  i_local = local_i_entry if local_idx is None else local_idx[local_i_entry]
347
- self.lh5_buffer, n_rows = self.lh5_st.read(
364
+ self.lh5_buffer = self.lh5_st.read(
348
365
  self.groups[i_file],
349
366
  self.lh5_files[i_file],
350
367
  start_row=i_local,
351
- n_rows=self.buffer_len - self.n_rows,
368
+ n_rows=n_entries - len(self.lh5_buffer),
352
369
  idx=local_idx,
353
370
  field_mask=self.field_mask,
354
371
  obj_buf=self.lh5_buffer,
355
- obj_buf_start=self.n_rows,
372
+ obj_buf_start=len(self.lh5_buffer),
356
373
  )
357
374
 
358
- self.n_rows += n_rows
359
375
  i_file += 1
360
376
  local_i_entry = 0
361
377
 
@@ -364,7 +380,7 @@ class LH5Iterator(typing.Iterator):
364
380
  if self.friend is not None:
365
381
  self.friend.read(i_entry)
366
382
 
367
- return (self.lh5_buffer, self.n_rows)
383
+ return self.lh5_buffer
368
384
 
369
385
  def reset_field_mask(self, mask):
370
386
  """Replaces the field mask of this iterator and any friends with mask"""
@@ -375,7 +391,7 @@ class LH5Iterator(typing.Iterator):
375
391
  @property
376
392
  def current_local_entries(self) -> NDArray[int]:
377
393
  """Return list of local file entries in buffer"""
378
- cur_entries = np.zeros(self.n_rows, dtype="int32")
394
+ cur_entries = np.zeros(len(self.lh5_buffer), dtype="int32")
379
395
  i_file = np.searchsorted(self.entry_map, self.current_i_entry, "right")
380
396
  file_start = self._get_file_cumentries(i_file - 1)
381
397
  i_local = self.current_i_entry - file_start
@@ -402,7 +418,7 @@ class LH5Iterator(typing.Iterator):
402
418
  @property
403
419
  def current_global_entries(self) -> NDArray[int]:
404
420
  """Return list of local file entries in buffer"""
405
- cur_entries = np.zeros(self.n_rows, dtype="int32")
421
+ cur_entries = np.zeros(len(self.lh5_buffer), dtype="int32")
406
422
  i_file = np.searchsorted(self.entry_map, self.current_i_entry, "right")
407
423
  file_start = self._get_file_cumentries(i_file - 1)
408
424
  i_local = self.current_i_entry - file_start
@@ -433,7 +449,7 @@ class LH5Iterator(typing.Iterator):
433
449
  @property
434
450
  def current_files(self) -> NDArray[str]:
435
451
  """Return list of file names for entries in buffer"""
436
- cur_files = np.zeros(self.n_rows, dtype=object)
452
+ cur_files = np.zeros(len(self.lh5_buffer), dtype=object)
437
453
  i_file = np.searchsorted(self.entry_map, self.current_i_entry, "right")
438
454
  file_start = self._get_file_cumentries(i_file - 1)
439
455
  i_local = self.current_i_entry - file_start
@@ -455,7 +471,7 @@ class LH5Iterator(typing.Iterator):
455
471
  @property
456
472
  def current_groups(self) -> NDArray[str]:
457
473
  """Return list of group names for entries in buffer"""
458
- cur_groups = np.zeros(self.n_rows, dtype=object)
474
+ cur_groups = np.zeros(len(self.lh5_buffer), dtype=object)
459
475
  i_file = np.searchsorted(self.entry_map, self.current_i_entry, "right")
460
476
  file_start = self._get_file_cumentries(i_file - 1)
461
477
  i_local = self.current_i_entry - file_start
@@ -485,14 +501,19 @@ class LH5Iterator(typing.Iterator):
485
501
  def __iter__(self) -> typing.Iterator:
486
502
  """Loop through entries in blocks of size buffer_len."""
487
503
  self.current_i_entry = 0
488
- self.next_i_entry = 0
504
+ self.next_i_entry = self.i_start
489
505
  return self
490
506
 
491
507
  def __next__(self) -> tuple[LGDO, int, int]:
492
- """Read next buffer_len entries and return lh5_table, iterator entry
493
- and n_rows read."""
494
- buf, n_rows = self.read(self.next_i_entry)
495
- self.next_i_entry = self.current_i_entry + n_rows
496
- if n_rows == 0:
508
+ """Read next buffer_len entries and return lh5_table and iterator entry."""
509
+ n_entries = self.n_entries
510
+ if n_entries is not None:
511
+ n_entries = min(
512
+ self.buffer_len, n_entries + self.i_start - self.next_i_entry
513
+ )
514
+
515
+ buf = self.read(self.next_i_entry, n_entries)
516
+ if len(buf) == 0:
497
517
  raise StopIteration
498
- return (buf, self.current_i_entry, n_rows)
518
+ self.next_i_entry = self.current_i_entry + len(buf)
519
+ return buf
lgdo/lh5/store.py CHANGED
@@ -5,7 +5,6 @@ HDF5 files.
5
5
 
6
6
  from __future__ import annotations
7
7
 
8
- import bisect
9
8
  import logging
10
9
  import os
11
10
  import sys
@@ -15,11 +14,11 @@ from inspect import signature
15
14
  from typing import Any
16
15
 
17
16
  import h5py
18
- import numpy as np
19
17
  from numpy.typing import ArrayLike
20
18
 
21
19
  from .. import types
22
20
  from . import _serializers, utils
21
+ from .core import read
23
22
 
24
23
  log = logging.getLogger(__name__)
25
24
 
@@ -155,7 +154,7 @@ class LH5Store:
155
154
  """Returns an LH5 object appropriate for use as a pre-allocated buffer
156
155
  in a read loop. Sets size to `size` if object has a size.
157
156
  """
158
- obj, n_rows = self.read(name, lh5_file, n_rows=0, field_mask=field_mask)
157
+ obj = self.read(name, lh5_file, n_rows=0, field_mask=field_mask)
159
158
  if hasattr(obj, "resize") and size is not None:
160
159
  obj.resize(new_size=size)
161
160
  return obj
@@ -182,72 +181,20 @@ class LH5Store:
182
181
  """
183
182
  # grab files from store
184
183
  if isinstance(lh5_file, (str, h5py.File)):
185
- lh5_obj = self.gimme_file(lh5_file, "r", **file_kwargs)[name]
184
+ h5f = self.gimme_file(lh5_file, "r", **file_kwargs)
186
185
  else:
187
- lh5_files = list(lh5_file)
188
- n_rows_read = 0
189
-
190
- for i, h5f in enumerate(lh5_files):
191
- if (
192
- isinstance(idx, (list, tuple))
193
- and len(idx) > 0
194
- and not np.isscalar(idx[0])
195
- ):
196
- # a list of lists: must be one per file
197
- idx_i = idx[i]
198
- elif idx is not None:
199
- # make idx a proper tuple if it's not one already
200
- if not (isinstance(idx, tuple) and len(idx) == 1):
201
- idx = (idx,)
202
- # idx is a long continuous array
203
- n_rows_i = utils.read_n_rows(name, h5f)
204
- # find the length of the subset of idx that contains indices
205
- # that are less than n_rows_i
206
- n_rows_to_read_i = bisect.bisect_left(idx[0], n_rows_i)
207
- # now split idx into idx_i and the remainder
208
- idx_i = np.array(idx[0])[:n_rows_to_read_i]
209
- idx = np.array(idx[0])[n_rows_to_read_i:] - n_rows_i
210
- else:
211
- idx_i = None
212
- n_rows_i = n_rows - n_rows_read
213
-
214
- obj_buf, n_rows_read_i = self.read(
215
- name,
216
- h5f,
217
- start_row,
218
- n_rows_i,
219
- idx_i,
220
- use_h5idx,
221
- field_mask,
222
- obj_buf,
223
- obj_buf_start,
224
- decompress,
225
- )
226
-
227
- n_rows_read += n_rows_read_i
228
- if n_rows_read >= n_rows or obj_buf is None:
229
- return obj_buf, n_rows_read
230
- start_row = 0
231
- obj_buf_start += n_rows_read_i
232
- return obj_buf, n_rows_read
233
-
234
- if isinstance(idx, (list, tuple)) and len(idx) > 0 and not np.isscalar(idx[0]):
235
- idx = idx[0]
236
- if isinstance(idx, np.ndarray) and idx.dtype == np.dtype("?"):
237
- idx = np.where(idx)[0]
238
-
239
- return _serializers._h5_read_lgdo(
240
- lh5_obj.id,
241
- lh5_obj.file.filename,
242
- lh5_obj.name,
243
- start_row=start_row,
244
- n_rows=n_rows,
245
- idx=idx,
246
- use_h5idx=use_h5idx,
247
- field_mask=field_mask,
248
- obj_buf=obj_buf,
249
- obj_buf_start=obj_buf_start,
250
- decompress=decompress,
186
+ h5f = [self.gimme_file(f, "r", **file_kwargs) for f in lh5_file]
187
+ return read(
188
+ name,
189
+ h5f,
190
+ start_row,
191
+ n_rows,
192
+ idx,
193
+ use_h5idx,
194
+ field_mask,
195
+ obj_buf,
196
+ obj_buf_start,
197
+ decompress,
251
198
  )
252
199
 
253
200
  def write(
lgdo/types/array.py CHANGED
@@ -17,12 +17,12 @@ import pint_pandas # noqa: F401
17
17
 
18
18
  from .. import utils
19
19
  from ..units import default_units_registry as u
20
- from .lgdo import LGDO
20
+ from .lgdo import LGDOCollection
21
21
 
22
22
  log = logging.getLogger(__name__)
23
23
 
24
24
 
25
- class Array(LGDO):
25
+ class Array(LGDOCollection):
26
26
  r"""Holds an :class:`numpy.ndarray` and attributes.
27
27
 
28
28
  :class:`Array` (and the other various array types) holds an `nda` instead
@@ -78,11 +78,7 @@ class Array(LGDO):
78
78
  elif isinstance(nda, Array):
79
79
  nda = nda.nda
80
80
 
81
- elif not isinstance(nda, np.ndarray):
82
- nda = np.array(nda)
83
-
84
81
  self.nda = nda
85
- self.dtype = self.nda.dtype
86
82
 
87
83
  super().__init__(attrs)
88
84
 
@@ -96,18 +92,83 @@ class Array(LGDO):
96
92
  return dt + "<" + nd + ">{" + et + "}"
97
93
 
98
94
  def __len__(self) -> int:
99
- return len(self.nda)
95
+ return self._size
96
+
97
+ @property
98
+ def nda(self):
99
+ return self._nda[: self._size, ...] if self._nda.shape != () else self._nda
100
+
101
+ @nda.setter
102
+ def nda(self, value):
103
+ self._nda = value if isinstance(value, np.ndarray) else np.array(value)
104
+ self._size = len(self._nda) if self._nda.shape != () else 0
105
+
106
+ @property
107
+ def dtype(self):
108
+ return self._nda.dtype
109
+
110
+ @property
111
+ def shape(self):
112
+ return (len(self),) + self._nda.shape[1:]
113
+
114
+ def reserve_capacity(self, capacity: int) -> None:
115
+ "Set size (number of rows) of internal memory buffer"
116
+ if capacity < len(self):
117
+ msg = "Cannot reduce capacity below Array length"
118
+ raise ValueError(msg)
119
+ self._nda.resize((capacity,) + self._nda.shape[1:], refcheck=False)
120
+
121
+ def get_capacity(self) -> int:
122
+ "Get capacity (i.e. max size before memory must be re-allocated)"
123
+ return len(self._nda)
124
+
125
+ def trim_capacity(self) -> None:
126
+ "Set capacity to be minimum needed to support Array size"
127
+ self.reserve_capacity(np.prod(self.shape))
128
+
129
+ def resize(self, new_size: int, trim=False) -> None:
130
+ """Set size of Array in rows. Only change capacity if it must be
131
+ increased to accommodate new rows; in this case double capacity.
132
+ If trim is True, capacity will be set to match size."""
133
+
134
+ self._size = new_size
135
+
136
+ if trim and new_size != self.get_capacity:
137
+ self.reserve_capacity(new_size)
100
138
 
101
- def resize(self, new_size: int) -> None:
102
- new_shape = (new_size,) + self.nda.shape[1:]
103
- return self.nda.resize(new_shape, refcheck=True)
139
+ # If capacity is not big enough, set to next power of 2 big enough
140
+ if new_size > self.get_capacity():
141
+ self.reserve_capacity(int(2 ** (np.ceil(np.log2(new_size)))))
104
142
 
105
143
  def append(self, value: np.ndarray) -> None:
106
- self.resize(len(self) + 1)
107
- self.nda[-1] = value
144
+ "Append value to end of array (with copy)"
145
+ self.insert(len(self), value)
108
146
 
109
147
  def insert(self, i: int, value: int | float) -> None:
110
- self.nda = np.insert(self.nda, i, value)
148
+ "Insert value into row i (with copy)"
149
+ if i > len(self):
150
+ msg = f"index {i} is out of bounds for array with size {len(self)}"
151
+ raise IndexError(msg)
152
+
153
+ value = np.array(value)
154
+ if value.shape == self.shape[1:]:
155
+ self.resize(len(self) + 1)
156
+ self[i + 1 :] = self[i:-1]
157
+ self[i] = value
158
+ elif value.shape[1:] == self.shape[1:]:
159
+ self.resize(len(self) + len(value))
160
+ self[i + len(value) :] = self[i : -len(value)]
161
+ self[i : i + len(value)] = value
162
+ else:
163
+ msg = f"Could not insert value with shape {value.shape} into Array with shape {self.shape}"
164
+ raise ValueError(msg)
165
+
166
+ def replace(self, i: int, value: int | float) -> None:
167
+ "Replace value at row i"
168
+ if i >= len(self):
169
+ msg = f"index {i} is out of bounds for array with size {len(self)}"
170
+ raise IndexError(msg)
171
+ self[i] = value
111
172
 
112
173
  def __getitem__(self, key):
113
174
  return self.nda[key]
lgdo/types/encoded.py CHANGED
@@ -11,12 +11,12 @@ from numpy.typing import NDArray
11
11
 
12
12
  from .. import utils
13
13
  from .array import Array
14
- from .lgdo import LGDO
14
+ from .lgdo import LGDOCollection
15
15
  from .scalar import Scalar
16
16
  from .vectorofvectors import VectorOfVectors
17
17
 
18
18
 
19
- class VectorOfEncodedVectors(LGDO):
19
+ class VectorOfEncodedVectors(LGDOCollection):
20
20
  """An array of variable-length encoded arrays.
21
21
 
22
22
  Used to represent an encoded :class:`.VectorOfVectors`. In addition to an
@@ -92,6 +92,17 @@ class VectorOfEncodedVectors(LGDO):
92
92
 
93
93
  return False
94
94
 
95
+ def reserve_capacity(self, *capacity: int) -> None:
96
+ self.encoded_data.reserve_capacity(*capacity)
97
+ self.decoded_size.reserve_capacity(capacity[0])
98
+
99
+ def get_capacity(self) -> tuple:
100
+ return (self.decoded_size.get_capacity, *self.encoded_data.get_capacity())
101
+
102
+ def trim_capacity(self) -> None:
103
+ self.encoded_data.trim_capacity()
104
+ self.decoded_size.trim_capacity()
105
+
95
106
  def resize(self, new_size: int) -> None:
96
107
  """Resize vector along the first axis.
97
108
 
@@ -102,21 +113,6 @@ class VectorOfEncodedVectors(LGDO):
102
113
  self.encoded_data.resize(new_size)
103
114
  self.decoded_size.resize(new_size)
104
115
 
105
- def append(self, value: tuple[NDArray, int]) -> None:
106
- """Append a 1D encoded vector at the end.
107
-
108
- Parameters
109
- ----------
110
- value
111
- a tuple holding the encoded array and its decoded size.
112
-
113
- See Also
114
- --------
115
- .VectorOfVectors.append
116
- """
117
- self.encoded_data.append(value[0])
118
- self.decoded_size.append(value[1])
119
-
120
116
  def insert(self, i: int, value: tuple[NDArray, int]) -> None:
121
117
  """Insert an encoded vector at index `i`.
122
118
 
@@ -282,7 +278,7 @@ class VectorOfEncodedVectors(LGDO):
282
278
  raise ValueError(msg)
283
279
 
284
280
 
285
- class ArrayOfEncodedEqualSizedArrays(LGDO):
281
+ class ArrayOfEncodedEqualSizedArrays(LGDOCollection):
286
282
  """An array of encoded arrays with equal decoded size.
287
283
 
288
284
  Used to represent an encoded :class:`.ArrayOfEqualSizedArrays`. In addition
@@ -349,14 +345,23 @@ class ArrayOfEncodedEqualSizedArrays(LGDO):
349
345
 
350
346
  return False
351
347
 
352
- def resize(self, new_size: int) -> None:
348
+ def reserve_capacity(self, *capacity: int) -> None:
349
+ self.encoded_data.reserve_capacity(capacity)
350
+
351
+ def get_capacity(self) -> tuple:
352
+ return self.encoded_data.get_capacity()
353
+
354
+ def trim_capacity(self) -> None:
355
+ self.encoded_data.trim_capacity()
356
+
357
+ def resize(self, new_size: int, trim: bool = False) -> None:
353
358
  """Resize array along the first axis.
354
359
 
355
360
  See Also
356
361
  --------
357
362
  .VectorOfVectors.resize
358
363
  """
359
- self.encoded_data.resize(new_size)
364
+ self.encoded_data.resize(new_size, trim)
360
365
 
361
366
  def append(self, value: NDArray) -> None:
362
367
  """Append a 1D encoded array at the end.
lgdo/types/histogram.py CHANGED
@@ -424,7 +424,7 @@ class Histogram(Struct):
424
424
  dict.__setitem__(self, name, obj)
425
425
  else:
426
426
  msg = "histogram fields cannot be mutated "
427
- raise TypeError(msg)
427
+ raise AttributeError(msg)
428
428
 
429
429
  def __getattr__(self, name: str) -> None:
430
430
  # do not allow for new attributes on this
lgdo/types/lgdo.py CHANGED
@@ -92,3 +92,53 @@ class LGDO(ABC):
92
92
 
93
93
  def __repr__(self) -> str:
94
94
  return self.__class__.__name__ + f"(attrs={self.attrs!r})"
95
+
96
+
97
+ class LGDOCollection(LGDO):
98
+ """Abstract base class representing a LEGEND Collection Object (LGDO).
99
+ This defines the interface for classes used as table columns.
100
+ """
101
+
102
+ @abstractmethod
103
+ def __init__(self, attrs: dict[str, Any] | None = None) -> None:
104
+ super().__init__(attrs)
105
+
106
+ @abstractmethod
107
+ def __len__(self) -> int:
108
+ """Provides ``__len__`` for this array-like class."""
109
+
110
+ @abstractmethod
111
+ def reserve_capacity(self, capacity: int) -> None:
112
+ """Reserve capacity (in rows) for later use. Internal memory buffers
113
+ will have enough entries to store this many rows.
114
+ """
115
+
116
+ @abstractmethod
117
+ def get_capacity(self) -> int:
118
+ "get reserved capacity of internal memory buffers in rows"
119
+
120
+ @abstractmethod
121
+ def trim_capacity(self) -> None:
122
+ """set capacity to only what is required to store current contents
123
+ of LGDOCollection
124
+ """
125
+
126
+ @abstractmethod
127
+ def resize(self, new_size: int, trim: bool = False) -> None:
128
+ """Return this LGDO's datatype attribute string."""
129
+
130
+ def append(self, val) -> None:
131
+ "append val to end of LGDOCollection"
132
+ self.insert(len(self), val)
133
+
134
+ @abstractmethod
135
+ def insert(self, i: int, val) -> None:
136
+ "insert val into LGDOCollection at position i"
137
+
138
+ @abstractmethod
139
+ def replace(self, i: int, val) -> None:
140
+ "replace item at position i with val in LGDOCollection"
141
+
142
+ def clear(self, trim: bool = False) -> None:
143
+ "set size of LGDOCollection to zero"
144
+ self.resize(0, trim=trim)