fosanalysis
A framework to evaluate distributed fiber optic sensor data
Loading...
Searching...
No Matches
misc.py
Go to the documentation of this file.
2r"""
3Contains miscellaneous standalone functions.
4\author Bertram Richter
5\date 2023
6"""
7
8import datetime
9import numpy as np
10
11def find_closest_value_in_sorted_array(arr: np.array, v: np.array) -> tuple:
12 r"""
13 Returns index and value in `arr`, that is closest to the given `v`.
14 In case of equal distance of `v` to both neighbors, the smaller one is chosen.
15 \param arr Arraylike (1D) of values in ascending order.
16 \param v The target value(s), to which the distance should be minimized.
17 `v` can be a `float` or an arraylike.
18 \return `(<index>, <entry>)`
19 \retval index Index positions of the returned value(s). Same dimensions as `v`.
20 \retval entry `np.array` of the value(s) of `arr` closest to the value(s) of `v`. Same dimensions as `v`.
21 """
22 arr = np.array(arr)
23 i = np.searchsorted(arr, v)
24
25 # restrict i to actually available indices if v is larger than any element of arr
26 i = np.minimum(i, arr.shape[0]-1)
27 # get the item left to the position and prevent an an underflow (-1 flips to the last element)
28 i_left = np.maximum(i-1, 0)
29 # v between some array entries
30 dist_l = np.abs(v - arr[i_left])
31 dist_r = np.abs(v - arr[i])
32 i = np.where(dist_l >= dist_r, i, i-1)
33 if np.size(i) == 1:
34 i = i.item()
35 return i, arr[i]
36
37def last_finite_index(arr: np.array, axis: int = -1) -> np.array:
38 r"""
39 Returns an array with the indices of the most recent finite entry
40 when traversing the `arr` along the specified axis.
41 The returned array has the same shape as `arr`.
42
43 Example:
44
45 ```.py
46 >>> arr = np.array([1.,2.,"nan", "inf", 5], dtype=float)
47 array([1., 2., nan, inf, 5.])
48 >>> last_finite_index(arr)
49 array([0, 1, 1, 1, 4])
50 ```
51
52 The first element is assumed to be a finite value.
53 All indices before the first finite entry will be `0`.
54
55 ```.py
56 >>> arr = np.array(["nan","nan", "inf", 5], dtype=float)
57 array([nan, nan, inf, 5.])
58 >>> last_finite_index(arr)
59 array([0, 0, 0, 3])
60 ```
61
62 \param arr Array like.
63 \param axis Axis along which to apply the indexing.
64 Defaults to the last axis.
65 """
66 arr = np.array(arr)
67 is_finite = np.isfinite(arr)
68 finite_indices = np.argwhere(is_finite)
69 last_finite_array = np.zeros_like(arr, dtype=int)
70 last_finite_array[is_finite] = finite_indices[:,axis]
71 last_finite_array = np.maximum.accumulate(last_finite_array, axis=axis)
72 return last_finite_array
73
74def nan_diff_1d(arr: np.array) -> np.array:
75 r"""
76 Calculate the difference to the previous finite entry.
77 This is similar to `np.diff()`, but skipping `NaN` or `inf` entries.
78
79 Example:
80
81 ```.py
82 >>> arr = np.array([1.,2.,"nan", "inf", 5], dtype=float)
83 array([1., 2., nan, inf, 5.])
84 >>> nan_diff_1d(arr)
85 array([1., nan, -inf, 3.])
86 ```
87
88 \param arr Array like, needs to be 1D.
89 """
90 arr = np.array(arr)
91 last_finite_array = last_finite_index(arr)
92 arr_to_diff = arr[last_finite_array]
93 diff_array = arr[1:] - arr_to_diff[:-1]
94 return diff_array
95
96def nan_diff(arr: np.array, axis: int = -1) -> np.array:
97 r"""
98 Calculate the difference to the previous finite entry.
99 This is similar to `np.diff()`, but skipping `NaN` or `inf` entries.
100 This function is a wrapper around \ref nan_diff_1d().
101
102 Example:
103
104 ```.py
105 >>> arr = np.array([1.,2.,"nan", "inf", 5], dtype=float)
106 array([1., 2., nan, inf, 5.])
107 >>> nan_diff(arr)
108 array([1., nan, -inf, 3.])
109 ```
110
111 \param arr Array like.
112 \param axis Axis along which to calculate the incremental difference.
113 Defaults to the last axis.
114 """
115 return np.apply_along_axis(nan_diff_1d, axis=axis, arr=arr)
116
118 array: np.array,
119 index: int,
120 to_left: bool,
121 recurse: int = 0,
122 ) -> tuple:
123 r"""
124 Find the next finite neighbor of the entry `array[index]`.
125 An entry `<entry>` is finite, if `np.isfinite(<entry>) == True`.
126 \param array Array, on which the search is carried out.
127 \param index Position in the `array`, where the search is started.
128 \param to_left `True`, if a neighbor to the left of the starting index should be found, `False` for a neighbor to the right.
129 \param recurse Number of recursions, that are done. Examples:
130 - `0`: direct neighbors of the starting index
131 - `1`: neighbors of the neighbors
132 - `2`: neighbors of the neighbors' neighbors
133 - and so on.
134 \return Tuple like `(<index>, <entry>)`.
135 If no finite value could be found before reaching the end of `array` `(None, None)` is returned.
136 """
137 i = index
138 result = None
139 result_index = None
140 while True:
141 i = i - 1 if to_left else i + 1
142 if (0 <= i <= len(array) - 1):
143 if np.isfinite(array[i]):
144 result = array[i]
145 result_index = i
146 break
147 else:
148 break
149 if result_index is not None and recurse > 0:
150 result_index, result = next_finite_neighbor(array=array, index=result_index, to_left=to_left, recurse=recurse-1)
151 return result_index, result
152
153def np_to_python(data):
154 r"""
155 Convert the given data to a Python built-in type.
156 This function should be used, when type-checking.
157 Iterables are recursively converted into `list` and instances of
158 `np.scalar` are converted into standard data types using the method
159 [`np.item()`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html).
160 """
161 try:
162 return [np_to_python(i) for i in data]
163 except TypeError:
164 return data.item() if isinstance(data, np.generic) else data
165
166def datetime_to_timestamp(datetime_array: np.array) -> np.array:
167 r"""
168 Converts an array of datetime entries to an array of Unix timestamps.
169 \param datetime_array Array of datetime objects.
170 \return Returns an array of Unix timestamps.
171 """
172 return np.vectorize(datetime.datetime.timestamp)(datetime_array)
173
174def timestamp_to_datetime(timestamp_array: np.array) -> np.array:
175 r"""
176 Converts an array of Unix timestamps to an array of datetime entries.
177 \param timestamp_array Array of `float`s, representing Unix timestamps.
178 \return Returns an array of `datetime.datetime` objects.
179 """
180 return np.vectorize(datetime.datetime.fromtimestamp)(timestamp_array)
np.array nan_diff(np.array arr, int axis=-1)
Calculate the difference to the previous finite entry.
Definition misc.py:96
tuple next_finite_neighbor(np.array array, int index, bool to_left, int recurse=0)
Find the next finite neighbor of the entry array[index].
Definition misc.py:122
np.array datetime_to_timestamp(np.array datetime_array)
Converts an array of datetime entries to an array of Unix timestamps.
Definition misc.py:166
tuple find_closest_value_in_sorted_array(np.array arr, np.array v)
Returns index and value in arr, that is closest to the given v.
Definition misc.py:11
np.array nan_diff_1d(np.array arr)
Calculate the difference to the previous finite entry.
Definition misc.py:74
np.array timestamp_to_datetime(np.array timestamp_array)
Converts an array of Unix timestamps to an array of datetime entries.
Definition misc.py:174
np_to_python(data)
Convert the given data to a Python built-in type.
Definition misc.py:153
np.array last_finite_index(np.array arr, int axis=-1)
Returns an array with the indices of the most recent finite entry when traversing the arr along the s...
Definition misc.py:37