pymodaq_utils 0.0.2__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,35 @@
1
+ import importlib.util
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import warnings
7
+
8
+ try:
9
+ # with open(str(Path(__file__).parent.joinpath('resources/VERSION')), 'r') as fvers:
10
+ # __version__ = fvers.read().strip()
11
+
12
+ from pymodaq_utils.logger import set_logger
13
+ from pymodaq_utils.utils import get_version, PackageNotFoundError
14
+ try:
15
+ __version__ = get_version('pymodaq_utils')
16
+ except PackageNotFoundError:
17
+ __version__ = '0.0.0dev'
18
+ try:
19
+ LOGGER = set_logger('pymodaq', add_handler=True, base_logger=True)
20
+ except Exception:
21
+ print("Couldn't create the local folder to store logs , presets...")
22
+
23
+ LOGGER.info('')
24
+ LOGGER.info('')
25
+
26
+ from pymodaq_utils.config import Config
27
+
28
+ CONFIG = Config() # to ckeck for config file existence, otherwise create one
29
+
30
+
31
+ except Exception as e:
32
+ try:
33
+ LOGGER.exception(str(e))
34
+ except Exception as e:
35
+ print(str(e))
@@ -0,0 +1,48 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created the 21/11/2022
4
+
5
+ @author: Sebastien Weber
6
+
7
+ Introduce some nice ABCMeta class allowing that a particular attribute has been declared when instantiating
8
+ See https://stackoverflow.com/a/50381071/8090831
9
+ """
10
+
11
+ from abc import ABCMeta as NativeABCMeta
12
+ from abc import abstractmethod
13
+ from typing import cast, Any, Callable, TypeVar
14
+
15
+
16
+ R = TypeVar('R')
17
+
18
+
19
+ class DummyAttribute:
20
+ pass
21
+
22
+
23
+ def abstract_attribute(obj: Callable[[Any], R] = None) -> R:
24
+ _obj = cast(Any, obj)
25
+ if obj is None:
26
+ _obj = DummyAttribute()
27
+ _obj.__is_abstract_attribute__ = True
28
+ return cast(R, _obj)
29
+
30
+
31
+ class ABCMeta(NativeABCMeta):
32
+
33
+ def __call__(cls, *args, **kwargs):
34
+ instance = NativeABCMeta.__call__(cls, *args, **kwargs)
35
+ abstract_attributes = {
36
+ name
37
+ for name in dir(instance)
38
+ if getattr(getattr(instance, name), '__is_abstract_attribute__', False)
39
+ }
40
+ if abstract_attributes:
41
+ raise NotImplementedError(
42
+ "Can't instantiate abstract class {} with"
43
+ " abstract attributes: {}".format(
44
+ cls.__name__,
45
+ ', '.join(abstract_attributes)
46
+ )
47
+ )
48
+ return instance
@@ -0,0 +1,386 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Mon March 03 2021
4
+ author: Sebastien Weber
5
+ """
6
+ import numpy as np
7
+
8
+
9
+ def random_step(start, stop, step):
10
+ tmp = start
11
+ out = np.array([tmp])
12
+ sign = stop - start
13
+ if step == 0:
14
+ raise ValueError('step must be strictly positive or negative')
15
+ if step > 0 and sign > 0:
16
+ while tmp <= stop:
17
+ tmp = tmp + (np.random.random() + 0.5) * step
18
+ out = np.append(out, tmp)
19
+ elif step < 0 and sign < 0:
20
+ while tmp >= stop:
21
+ tmp = tmp + (np.random.random() + 0.5) * step
22
+ out = np.append(out, tmp)
23
+ else:
24
+ raise ValueError(f'the step value {step} is not of the same sign as stop - start : {sign}')
25
+ return out[0:-1]
26
+
27
+
28
+ def linspace_this_vect(x, y=None, Npts=None):
29
+ """
30
+ Given a vector x, it returns a vector xlin where xlin is a
31
+ linearised version of x on the same interval and with the same size.
32
+ if args is provided it is a y vector and the function returns both xlin
33
+ and ylin where ylin is a linear interpolation of y on this new xlin axis
34
+
35
+ Parameters
36
+ ----------
37
+ x : (ndarray)
38
+ y : (ndarray) optional
39
+ Npts: (int) size of the linear vector (optional)
40
+
41
+ Returns
42
+ -------
43
+ xlin : vector
44
+ (ylin : vector) optional if args is provided
45
+
46
+ """
47
+ if not Npts:
48
+ Npts = np.size(x)
49
+ xlin = np.linspace(np.min(x), np.max(x), Npts)
50
+ if y is not None:
51
+ ylin = np.interp(xlin, x, y)
52
+ return xlin, ylin
53
+ else:
54
+ return xlin
55
+
56
+
57
+ def find_index(x, threshold):
58
+ """
59
+ find_index finds the index ix such that x(ix) is the closest from threshold
60
+
61
+ Parameters
62
+ ----------
63
+ x : vector
64
+ threshold : list of scalar
65
+
66
+ Returns
67
+ -------
68
+ out : list of 2-tuple containing ix,x[ix]
69
+ out=[(ix0,xval0),(ix1,xval1),...]
70
+ """
71
+
72
+ if np.isscalar(threshold):
73
+ threshold = [threshold]
74
+ out = []
75
+ for value in threshold:
76
+ ix = int(np.argmin(np.abs(x - value)))
77
+ out.append((ix, x[ix]))
78
+ return out
79
+
80
+
81
+ def find_rising_edges(x, threshold):
82
+ """find_rising_edges finds the index ix such that x(ix) is the closest from threshold and values are increasing
83
+
84
+ Parameters
85
+ ----------
86
+ x : vector
87
+ threshold : list of scalar
88
+
89
+ Returns
90
+ -------
91
+ out : list of 2-tuple containing ix,x[ix]
92
+ out=[(ix0,xval0),(ix1,xval1),...]
93
+
94
+ """
95
+ x_shifted = np.concatenate((x[1:], np.array((np.NaN,))))
96
+ if np.isscalar(threshold):
97
+ threshold = [threshold]
98
+ out = []
99
+ for value in threshold:
100
+ dat = np.bitwise_and(x < value, x_shifted > value)
101
+ ix = [ind for ind, flag in enumerate(dat) if flag]
102
+ out.append((ix, x[ix]))
103
+ return out
104
+
105
+
106
+ def crop_vector_to_axis(x, V, xlim):
107
+ """crops a vector V with given x axis vector to a given xlim tuple
108
+
109
+ Parameters
110
+ ----------
111
+ x : vector
112
+ V : vector
113
+ xlim: tuple containing (xmin,xmax)
114
+
115
+ Returns
116
+ -------
117
+ x_c : vector
118
+ V_c : vector
119
+ """
120
+ x1 = find_index(x, xlim[0])[0][0]
121
+ x2 = find_index(x, xlim[1])[0][0]
122
+ if x2 > x1:
123
+ ixx = np.linspace(x1, x2, x2 - x1 + 1, dtype=int);
124
+ else:
125
+ ixx = np.linspace(x2, x1, x1 - x2 + 1, dtype=int);
126
+
127
+ x_c = x[ixx]
128
+ V_c = V[ixx]
129
+ return x_c, V_c
130
+
131
+ def rescale(x, window=[0.0, 1.0]):
132
+ """ Rescales a numpy array to the range specified by ``window``.
133
+
134
+ Default is [0, 1].
135
+ """
136
+ maxx = np.max(x)
137
+ minx = np.min(x)
138
+ return (x - minx) / (maxx - minx) * (window[1] - window[0]) + window[0]
139
+
140
+
141
+ def marginals(data, normalize=False, axes=None):
142
+ """ Calculates the marginals of the data array.
143
+
144
+ axes specifies the axes of the marginals, e.g., the axes on which the
145
+ sum is projected.
146
+
147
+ If axis is None a list of all marginals is returned.
148
+ """
149
+ if axes is None:
150
+ axes = range(data.ndim)
151
+ axes = list(axes)
152
+ full_axes = list(range(data.ndim))
153
+ m = []
154
+ for i in axes:
155
+ # for the marginal sum over all axes except the specified one
156
+ margin_axes = tuple(j for j in full_axes if j != i)
157
+ m.append(np.sum(data, axis=margin_axes))
158
+ if normalize:
159
+ m = [rescale(mx) for mx in m]
160
+ return tuple(m) if len(m) != 1 else m[0]
161
+
162
+
163
+ def find(x, condition, n=1):
164
+ """ Return the index of the nth element that fulfills the condition.
165
+ """
166
+ search_n = 1
167
+ for i in range(len(x)):
168
+ if condition(x[i]):
169
+ if search_n == n:
170
+ return i
171
+ search_n += 1
172
+ return -1
173
+
174
+
175
+ def arglimit(y, threshold=1e-3, padding=0.0, normalize=True):
176
+ """ Returns the first and last index where `y >= threshold * max(abs(y))`.
177
+ """
178
+ t = np.abs(y)
179
+ if normalize:
180
+ t = t / np.max(t)
181
+
182
+ idx1 = find(t, lambda x: x >= threshold)
183
+ if idx1 == -1:
184
+ idx1 = 0
185
+ idx2 = find(t[::-1], lambda x: x >= threshold)
186
+ if idx2 == -1:
187
+ idx2 = t.shape[0] - 1
188
+ else:
189
+ idx2 = t.shape[0] - 1 - idx2
190
+
191
+ return (idx1, idx2)
192
+
193
+
194
+ def limit(x, y=None, threshold=1e-3, padding=0.25, extend=True):
195
+ """ Returns the maximum x-range where the y-values are sufficiently large.
196
+
197
+ Parameters
198
+ ----------
199
+ x : array_like
200
+ The x values of the graph.
201
+ y : array_like, optional
202
+ The y values of the graph. If `None` the maximum range of `x` is
203
+ used. That is only useful if `padding > 0`.
204
+ threshold : float
205
+ The threshold relative to the maximum of `y` of values that should be
206
+ included in the bracket.
207
+ padding : float
208
+ The relative padding on each side in fractions of the bracket size.
209
+ extend : bool, optional
210
+ Signals if the returned range can be larger than the values in ``x``.
211
+ Default is `True`.
212
+
213
+ Returns
214
+ -------
215
+ xl, xr : float
216
+ Lowest and biggest value of the range.
217
+
218
+ """
219
+ if y is None:
220
+ x1, x2 = np.min(x), np.max(x)
221
+ if not extend:
222
+ return (x1, x2)
223
+ else:
224
+ idx1, idx2 = arglimit(y, threshold=threshold)
225
+ x1, x2 = sorted([x[idx1], x[idx2]])
226
+
227
+ # calculate the padding
228
+ if padding != 0.0:
229
+ pad = (x2 - x1) * padding
230
+ x1 -= pad
231
+ x2 += pad
232
+
233
+ if not extend:
234
+ x1 = max(x1, np.min(x))
235
+ x2 = min(x2, np.max(x))
236
+
237
+ return (x1, x2)
238
+
239
+
240
+ def crop_array_to_axis(x, y, M, cropbox):
241
+ """crops an array M with given cropbox as a tuple (xmin,xmax,ymin,ymax).
242
+
243
+ Parameters
244
+ ----------
245
+ x : vector
246
+ y : vector
247
+ M : 2D array
248
+ cropbox: 4 elements tuple containing (xmin,xmax,ymin,ymax)
249
+
250
+ Returns
251
+ -------
252
+ x_c : croped x vector
253
+ y_c : croped y vector
254
+ M_c : croped 2D M array
255
+
256
+ """
257
+ x1 = find_index(x, cropbox[0])[0][0]
258
+ x2 = find_index(x, cropbox[1])[0][0]
259
+ if x2 > x1:
260
+ ixx = np.linspace(x1, x2, x2 - x1 + 1, dtype=int)
261
+ else:
262
+ ixx = np.linspace(x2, x1, x1 - x2 + 1, dtype=int)
263
+
264
+ y1 = find_index(y, cropbox[2])[0][0]
265
+ y2 = find_index(y, cropbox[3])[0][0]
266
+ if y2 > y1:
267
+ iyy = np.linspace(y1, y2, y2 - y1 + 1, dtype=int)
268
+ else:
269
+ iyy = np.linspace(y2, y1, y1 - y2 + 1, dtype=int)
270
+
271
+ x_c = x[ixx]
272
+ y_c = y[iyy]
273
+
274
+ M_c = M[iyy[0]:iyy[-1] + 1, ixx[0]:ixx[-1] + 1]
275
+ return x_c, y_c, M_c
276
+
277
+
278
+ def interp1D(x, M, xlin, axis=1):
279
+ """
280
+ same as numpy interp function but works on 2D array
281
+ you have to specify the axis over which to do the interpolation
282
+ kwargs refers to the numpy interp kwargs
283
+ returns both xlin and the new 2D array Minterp
284
+ """
285
+ if axis == 0:
286
+ Minterp = np.zeros((np.size(xlin), np.size(M, axis=1)))
287
+ indexes = np.arange(0, np.size(M, axis=1))
288
+ for ind in indexes:
289
+ # print(ind)
290
+ Minterp[:, ind] = np.interp(xlin, x, M[:, ind])
291
+ else:
292
+ Minterp = np.zeros((np.size(M, axis=0), np.size(xlin)))
293
+ indexes = np.arange(0, np.size(M, axis=0))
294
+ for ind in indexes:
295
+ Minterp[ind, :] = np.interp(xlin, x, M[ind, :])
296
+ return Minterp
297
+
298
+
299
+ def linspace_this_image(x, M, axis=1, Npts=None):
300
+ """
301
+ Given a vector x and a 2D array M, it returns an array vector xlin where xlin is a
302
+ linearised version of x on the same interval and with the same size. it returns as well
303
+ a 2D array Minterp interpolated on the new xlin vector along the specified axis.
304
+
305
+ Parameters
306
+ ----------
307
+ x : (vector)
308
+ M : (2D array)
309
+ axis : (int)
310
+ Npts: (int) size of the linear vector (optional)
311
+
312
+ Returns
313
+ -------
314
+ xlin : vector
315
+ Minterp : 2D array
316
+ """
317
+ xlin = linspace_this_vect(x, Npts=Npts)
318
+ Minterp = interp1D(x, M, xlin, axis=axis)
319
+
320
+ return xlin, Minterp
321
+
322
+
323
+ def max_ind(x, axis=None):
324
+ """returns the max value in a vector or array and its index (in a tuple)
325
+
326
+ Parameters
327
+ ----------
328
+ x : vector
329
+
330
+ axis : optional dimension aginst which to normalise
331
+
332
+ Returns
333
+ -------
334
+ ind_max : index of the maximum value
335
+
336
+ max_val : maximum value
337
+ """
338
+ ind_max = np.argmax(x, axis=axis)
339
+ max_val = np.max(x, axis=axis)
340
+ return ind_max, max_val
341
+
342
+
343
+ def min_ind(x, axis=None):
344
+ """returns the min value in a vector or array and its index (in flattened array)
345
+
346
+ Parameters
347
+ ----------
348
+ x : vector
349
+ axis : optional dimension to check the function
350
+
351
+ Returns
352
+ -------
353
+ ind_min : index of the minimum value
354
+ min_val : minimum value
355
+ """
356
+ ind_min = np.argmin(x, axis=axis)
357
+ min_val = np.min(x, axis=axis)
358
+ return ind_min, min_val
359
+
360
+
361
+ if __name__ == '__main__': # pragma: no cover
362
+ from pymodaq.utils import daq_utils as utils
363
+ import matplotlib.pyplot as plt
364
+
365
+ x = random_step(00, 100, 5)
366
+ y = random_step(00, 100, 5)
367
+ g2 = utils.gauss2D(x, 35, 15, y, 55, 20, 1)
368
+ (xlin, g2_interp) = linspace_this_image(x, g2, axis=1, Npts=100)
369
+ (ylin, g2_interp_both) = linspace_this_image(y, g2_interp, axis=0, Npts=100)
370
+ plt.figure('gauss2D')
371
+ plt.subplot(221)
372
+ plt.pcolormesh(x, y, g2)
373
+ plt.subplot(222)
374
+ plt.pcolormesh(xlin, y, g2_interp)
375
+ plt.subplot(223)
376
+ plt.pcolormesh(xlin, ylin, g2_interp_both)
377
+
378
+ plt.show()
379
+
380
+ x_c, y_c, M_c = crop_array_to_axis(x, y, g2, [20, 60, 40, 80])
381
+ plt.figure('cropped')
382
+ plt.subplot(121)
383
+ plt.pcolormesh(x, y, g2)
384
+ plt.subplot(122)
385
+ plt.pcolormesh(x_c, y_c, M_c)
386
+ plt.show()