|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Collection, Iterable, MutableSequence |
| 4 | +from typing import ( |
| 5 | + TYPE_CHECKING, |
| 6 | + Any, |
| 7 | + final, |
| 8 | + overload, |
| 9 | +) |
| 10 | + |
| 11 | +import numpy as np |
| 12 | +import numpy.typing as npt |
| 13 | + |
| 14 | +from nitypes._exceptions import invalid_arg_value, invalid_arg_type |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + # Import from the public package so the docs don't reference private submodules. |
| 18 | + from nitypes.bintime import CVITimeIntervalDType, TimeDelta, TimeValueTuple |
| 19 | +else: |
| 20 | + from nitypes.bintime._dtypes import CVITimeIntervalDType |
| 21 | + from nitypes.bintime._timedelta import TimeDelta |
| 22 | + from nitypes.bintime._time_value_tuple import TimeValueTuple |
| 23 | + |
| 24 | + |
| 25 | +@final |
| 26 | +class TimeDeltaArray(MutableSequence[TimeDelta]): |
| 27 | + """A mutable array of :class:`TimeDelta` values in NI Binary Time Format (NI-BTF). |
| 28 | +
|
| 29 | + Raises: |
| 30 | + TypeError: If any item in value is not a TimeDelta instance. |
| 31 | + """ |
| 32 | + |
| 33 | + __slots__ = ["_array"] |
| 34 | + |
| 35 | + _array: npt.NDArray[np.void] |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + value: Collection[TimeDelta] | None = None, |
| 40 | + ) -> None: |
| 41 | + """Initialize a new TimeDeltaArray.""" |
| 42 | + if value is None: |
| 43 | + value = [] |
| 44 | + if not all(isinstance(item, TimeDelta) for item in value): |
| 45 | + raise invalid_arg_type("value", "iterable of TimeDelta", value) |
| 46 | + self._array = np.fromiter( |
| 47 | + (entry.to_tuple().to_cvi() for entry in value), |
| 48 | + dtype=CVITimeIntervalDType, |
| 49 | + count=len(value), |
| 50 | + ) |
| 51 | + |
| 52 | + @overload |
| 53 | + def __getitem__( # noqa: D105 - missing docstring in magic method |
| 54 | + self, index: int |
| 55 | + ) -> TimeDelta: ... |
| 56 | + |
| 57 | + @overload |
| 58 | + def __getitem__( # noqa: D105 - missing docstring in magic method |
| 59 | + self, index: slice |
| 60 | + ) -> TimeDeltaArray: ... |
| 61 | + |
| 62 | + def __getitem__(self, index: int | slice) -> TimeDelta | TimeDeltaArray: |
| 63 | + """Return self[index]. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + TypeError: If index is an invalid type. |
| 67 | + IndexError: If index is out of range. |
| 68 | + """ |
| 69 | + if isinstance(index, int): |
| 70 | + entry = self._array[index].item() |
| 71 | + as_tuple = TimeValueTuple.from_cvi(*entry) |
| 72 | + return TimeDelta.from_tuple(as_tuple) |
| 73 | + elif isinstance(index, slice): |
| 74 | + sliced_entries = self._array[index] |
| 75 | + new_array = TimeDeltaArray() |
| 76 | + new_array._array = sliced_entries |
| 77 | + return new_array |
| 78 | + else: |
| 79 | + raise invalid_arg_type("index", "int or slice", index) |
| 80 | + |
| 81 | + def __len__(self) -> int: |
| 82 | + """Return len(self).""" |
| 83 | + return len(self._array) |
| 84 | + |
| 85 | + @overload |
| 86 | + def __setitem__( # noqa: D105 - missing docstring in magic method |
| 87 | + self, index: int, value: TimeDelta |
| 88 | + ) -> None: ... |
| 89 | + |
| 90 | + @overload |
| 91 | + def __setitem__( # noqa: D105 - missing docstring in magic method |
| 92 | + self, index: slice, value: Iterable[TimeDelta] |
| 93 | + ) -> None: ... |
| 94 | + |
| 95 | + def __setitem__(self, index: int | slice, value: TimeDelta | Iterable[TimeDelta]) -> None: |
| 96 | + """Set a new value for TimeDelta at the specified location or slice. |
| 97 | +
|
| 98 | + Raises: |
| 99 | + TypeError: If index is an invalid type, or slice value is not iterable. |
| 100 | + ValueError: If slice assignment length doesn't match the selected range. |
| 101 | + IndexError: If index is out of range. |
| 102 | + """ |
| 103 | + if isinstance(index, int): |
| 104 | + if not isinstance(value, TimeDelta): |
| 105 | + raise invalid_arg_type("value", "TimeDelta", value) |
| 106 | + self._array[index] = value.to_tuple().to_cvi() |
| 107 | + elif isinstance(index, slice): |
| 108 | + if not isinstance(value, Iterable): |
| 109 | + raise invalid_arg_type("value", "iterable of TimeDelta", value) |
| 110 | + if not all(isinstance(item, TimeDelta) for item in value): |
| 111 | + raise invalid_arg_type("value", "iterable of TimeDelta", value) |
| 112 | + |
| 113 | + start, stop, step = index.indices(len(self)) |
| 114 | + selected_count = len(range(start, stop, step)) |
| 115 | + values = list(value) |
| 116 | + new_entry_count = len(values) |
| 117 | + if step > 1 and new_entry_count != selected_count: |
| 118 | + raise invalid_arg_value( |
| 119 | + "value", "iterable with the same length as the slice", value |
| 120 | + ) |
| 121 | + |
| 122 | + if new_entry_count < selected_count: |
| 123 | + # Shrink |
| 124 | + replaced = slice(start, start + new_entry_count) |
| 125 | + removed = slice(start + new_entry_count, stop) |
| 126 | + self._array[replaced] = [item.to_tuple().to_cvi() for item in values] |
| 127 | + del self[removed] |
| 128 | + elif new_entry_count > selected_count: |
| 129 | + # Grow |
| 130 | + replaced = slice(start, stop) |
| 131 | + self._array[replaced] = [ |
| 132 | + item.to_tuple().to_cvi() for item in values[:selected_count] |
| 133 | + ] |
| 134 | + self._array = np.insert( |
| 135 | + self._array, |
| 136 | + stop, |
| 137 | + [item.to_tuple().to_cvi() for item in values[selected_count:]], |
| 138 | + ) |
| 139 | + else: |
| 140 | + # Replace, accounting for strides |
| 141 | + self._array[index] = [item.to_tuple().to_cvi() for item in values] |
| 142 | + else: |
| 143 | + raise invalid_arg_type("index", "int or slice", index) |
| 144 | + |
| 145 | + @overload |
| 146 | + def __delitem__(self, index: int) -> None: ... # noqa: D105 - missing docstring in magic method |
| 147 | + |
| 148 | + @overload |
| 149 | + def __delitem__( # noqa: D105 - missing docstring in magic method |
| 150 | + self, index: slice |
| 151 | + ) -> None: ... |
| 152 | + |
| 153 | + def __delitem__(self, index: int | slice) -> None: |
| 154 | + """Delete the value at the specified location or slice. |
| 155 | +
|
| 156 | + Raises: |
| 157 | + TypeError: If index is an invalid type. |
| 158 | + IndexError: If index is out of range. |
| 159 | + """ |
| 160 | + if isinstance(index, (int, slice)): |
| 161 | + self._array = np.delete(self._array, index) |
| 162 | + else: |
| 163 | + raise invalid_arg_type("index", "int or slice", index) |
| 164 | + |
| 165 | + def insert(self, index: int, value: TimeDelta) -> None: |
| 166 | + """Insert the TimeDelta value before the specified index. |
| 167 | +
|
| 168 | + Raises: |
| 169 | + TypeError: If index is not int or value is not TimeDelta. |
| 170 | + """ |
| 171 | + if not isinstance(index, int): |
| 172 | + raise invalid_arg_type("index", "int", index) |
| 173 | + if not isinstance(value, TimeDelta): |
| 174 | + raise invalid_arg_type("value", "TimeDelta", value) |
| 175 | + lower = -len(self._array) |
| 176 | + upper = len(self._array) |
| 177 | + index = min(max(index, lower), upper) |
| 178 | + as_cvi = value.to_tuple().to_cvi() |
| 179 | + self._array = np.insert(self._array, index, as_cvi) |
| 180 | + |
| 181 | + def __eq__(self, other: object) -> bool: |
| 182 | + """Return self == other.""" |
| 183 | + if not isinstance(other, TimeDeltaArray): |
| 184 | + return NotImplemented |
| 185 | + return np.array_equal(self._array, other._array) |
| 186 | + |
| 187 | + def __reduce__(self) -> tuple[Any, ...]: |
| 188 | + """Return object state for pickling.""" |
| 189 | + return (self.__class__, (list(iter(self)),)) |
| 190 | + |
| 191 | + def __repr__(self) -> str: |
| 192 | + """Return repr(self).""" |
| 193 | + ctor_args = list(iter(self)) |
| 194 | + return f"{self.__class__.__module__}.{self.__class__.__name__}({ctor_args})" |
| 195 | + |
| 196 | + def __str__(self) -> str: |
| 197 | + """Return str(self).""" |
| 198 | + values = list(iter(self)) |
| 199 | + return f"[{'; '.join(str(v) for v in values)}]" |
0 commit comments