pyadps 0.3.3b0__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,556 @@
1
+ import numpy as np
2
+ import scipy as sp
3
+ from pyadps.utils.readrdi import ReadFile
4
+ from .plotgen import PlotEnds
5
+
6
+
7
+ def trim_ends(ds, mask, transducer_depth=None, delta=20, method="Manual"):
8
+ """
9
+ Trim the ends of the data based on the provided method (e.g., manual selection)
10
+ to remove invalid or irrelevant data points during deployment and recovery
11
+ of moorings. This function modifies the mask to reflect the valid data range by marking
12
+ invalid data points as `1` at the ends.
13
+
14
+ Parameters
15
+ ----------
16
+ ds : pyadps.dataset
17
+ The pyadps dataframe is loaded to obtain the data from the variable leader.
18
+ This includes the depth of the transducer and other relevant information
19
+ for trimming the data.
20
+ mask : numpy.ndarray
21
+ A mask array of the same shape as the data, where `1` indicates invalid data
22
+ and `0` indicates valid data. The function modifies the mask based on the trimming
23
+ process.
24
+ method : str, optional
25
+ The method used for trimming the data. Default is "Manual", which allows the user
26
+ to manually select the start and end indices for trimming. Other methods can be
27
+ added if required in the future.
28
+
29
+ Returns
30
+ -------
31
+ numpy.ndarray
32
+ The updated mask array with the ends trimmed. Data points at the beginning and end
33
+ of the array marked as invalid (`1`) based on the trimming results.
34
+
35
+ Notes
36
+ -----
37
+ - The function uses the transducer depth from the `vlobj` to determine the trimming boundaries.
38
+ - When using the "Manual" method, the user is prompted with a plot that allows them to select
39
+ the start and end indices for trimming. These indices are then used to adjust the mask.
40
+ - The mask array is updated in-place to mark the trimmed areas as invalid.
41
+ - The trimming process is based on the variable leader data and the selected method.
42
+
43
+ Example
44
+ -------
45
+ >>> import pyadps
46
+ >>> ds = pyadps.ReadFile("demo.000")
47
+ >>> mask = pyadps.default_mask(ds)
48
+ >>> updated_mask = trim_ends(ds, mask, method="Manual")
49
+ """
50
+
51
+ if isinstance(ds, ReadFile):
52
+ vlobj = ds.variableleader
53
+ transducer_depth = vlobj.vleader["Depth of Transducer"]
54
+ elif isinstance(ds, np.ndarray) and ds.ndim == 1:
55
+ transducer_depth = ds
56
+ else:
57
+ raise ValueError("Input must be a 1-D numpy array or a PyADPS instance")
58
+
59
+ if method == "Manual":
60
+ out = PlotEnds(transducer_depth, delta=delta)
61
+ out.show()
62
+ if out.start_ens > 0:
63
+ mask[:, 0 : out.start_ens] = 1
64
+
65
+ if out.end_ens < 0:
66
+ mask[:, out.end_ens :] = 1
67
+
68
+ return mask
69
+
70
+
71
+ def side_lobe_beam_angle(
72
+ ds,
73
+ mask,
74
+ orientation="default",
75
+ water_column_depth=0,
76
+ extra_cells=2,
77
+ cells=None,
78
+ cell_size=None,
79
+ bin1dist=None,
80
+ beam_angle=None,
81
+ ):
82
+ """
83
+ Mask the data contaminated due to surface/bottom backscatter based on the
84
+ side lobe beam angle. This function can correct the orientation of the beam
85
+ (upward or downward looking) and can account for deletion of additional cells.
86
+ Water column depth is applicable for downward-looking ADCP.
87
+
88
+ Parameters
89
+ ----------
90
+ ds : pyadps.dataset or np.ndarray
91
+ The pyadps dataframe is loaded to obtain the data from the fixed and variable leader.
92
+ This includes the depth of the transducer and other relevant information
93
+ for trimming the data.
94
+
95
+ If numpy.ndarray is loaded, the value should contain the transducer_depth.
96
+ In such cases provide cells, cell_size, and bin 1 distance.
97
+ Orientiation should be either 'up' or 'down' and not 'default'.
98
+
99
+ mask : numpy.ndarray
100
+ A mask array where invalid or false data points are marked. The mask is updated
101
+ based on the calculated side lobe beam angles.
102
+ orientation : str, optional
103
+ The orientation of the beam. It can be 'default', 'up', or 'down'.
104
+ Default orientation, set before deployment, is obtained from the file.
105
+ If 'up' or 'down' is selected, the function will correct the orientation accordingly.
106
+ water_column_depth : int, optional
107
+ The depth of the water column. This value is used to adjust the beam angle
108
+ calculations. Default is 0.
109
+ extra_cells : int, optional
110
+ The number of extra cells to consider when calculating the beam angle. Default is 2.
111
+ cells: int, optional
112
+ Number of cells
113
+ cell_size: int, optional
114
+ Cell size or depth cell length in cm
115
+ beam_angle: int, optional
116
+ Beam angle in degrees
117
+
118
+ Returns
119
+ -------
120
+ numpy.ndarray
121
+ The updated mask array with side lobe beam angle adjustments. The mask will
122
+ reflect valid and invalid data points based on the calculated beam angles.
123
+
124
+ Notes
125
+ -----
126
+ - The function uses the fixedleader and variableleader to retrieve the necessary information
127
+ for the beam angle calculation. The `mask` array is updated based on these calculations.
128
+ - The `orientation` parameter allows for adjustments to account for upward or downward
129
+ looking ADCPs.
130
+ - The `water_column_depth` permits detecting the bottom of the ocean for downward looking
131
+ ADCP.
132
+ - The `extra_cells` parameter adds additional cells in addition to those masked by beam angle
133
+ calculation.
134
+
135
+ Example
136
+ -------
137
+ >>> import pyadps
138
+ >>> ds = pyadps.ReadFile("demo.000")
139
+ >>> mask = pyadps.default_mask(ds)
140
+ >>> updated_mask = side_lobe_beam_angle(ds, mask, orientation='down', water_column_depth=50, extra_cells=3)
141
+
142
+ >>> transducer_depth = ds.variableleader.transducer_depth
143
+ >>> cells = ds.fixedleader.cells
144
+ >>> cell_size = ds.fixedleader.depth_cell_length
145
+ >>> new_mask = side_lobe_beam_angle(transducer_depth, orientation='up', cells=cells, cell_size=cell_size, bin1dist=bindist)
146
+ """
147
+ if isinstance(ds, ReadFile) or ds.__class__.__name__ == "ReadFile":
148
+ flobj = ds.fixedleader
149
+ vlobj = ds.variableleader
150
+ beam_angle = int(flobj.system_configuration()["Beam Angle"])
151
+ cell_size = flobj.field()["Depth Cell Len"]
152
+ bin1dist = flobj.field()["Bin 1 Dist"]
153
+ cells = flobj.field()["Cells"]
154
+ ensembles = flobj.ensembles
155
+ transducer_depth = vlobj.vleader["Depth of Transducer"]
156
+ if orientation.lower() == "default":
157
+ orientation = flobj.system_configuration()["Beam Direction"]
158
+ elif isinstance(ds, np.ndarray) and np.squeeze(ds).ndim == 1:
159
+ transducer_depth = ds
160
+ ensembles = np.size(ds)
161
+ else:
162
+ raise ValueError("Input must be a 1-D numpy array or a PyADPS instance")
163
+
164
+ if orientation.lower() == "up":
165
+ sgn = -1
166
+ water_column_depth = 0
167
+ elif orientation.lower() == "down":
168
+ sgn = 1
169
+ else:
170
+ raise ValueError("Orientation should be either `up` or `down`")
171
+
172
+ beam_angle = np.deg2rad(beam_angle)
173
+ depth = transducer_depth / 10
174
+ valid_depth = (water_column_depth - sgn * depth) * np.cos(
175
+ beam_angle
176
+ ) + sgn * bin1dist / 100
177
+ valid_cells = np.trunc(valid_depth * 100 / cell_size) - extra_cells
178
+
179
+ for i in range(ensembles):
180
+ c = int(valid_cells[i])
181
+ if cells > c:
182
+ mask[c:, i] = 1
183
+
184
+ return mask
185
+
186
+
187
+ def side_lobe_rssi_bump(echo, mask):
188
+ pass
189
+
190
+
191
+ def manual_cut_bins(mask, min_cell, max_cell, min_ensemble, max_ensemble):
192
+ """
193
+ Apply manual bin cutting by selecting a specific range of cells and ensembles.
194
+
195
+ Parameters:
196
+ mask (numpy array): The mask array to modify.
197
+ min_cell (int): The minimum cell index to mask.
198
+ max_cell (int): The maximum cell index to mask.
199
+ min_ensemble (int): The minimum ensemble index to mask.
200
+ max_ensemble (int): The maximum ensemble index to mask.
201
+
202
+ Returns:
203
+ numpy array: The updated mask with selected areas masked.
204
+ """
205
+ # Ensure the indices are within valid range
206
+ min_cell = max(0, min_cell)
207
+ max_cell = min(mask.shape[0], max_cell)
208
+ min_ensemble = max(0, min_ensemble)
209
+ max_ensemble = min(mask.shape[1], max_ensemble)
210
+
211
+ # Apply mask on the selected range
212
+ mask[min_cell:max_cell, min_ensemble:max_ensemble] = 1
213
+
214
+ return mask
215
+
216
+
217
+ def regrid2d(
218
+ ds,
219
+ data,
220
+ fill_value,
221
+ end_cell_option="cell",
222
+ trimends=None,
223
+ method="nearest",
224
+ orientation="default",
225
+ boundary_limit=0,
226
+ cells=None,
227
+ cell_size=None,
228
+ bin1dist=None,
229
+ ):
230
+ """
231
+ Regrids 2D data onto a new grid based on specified parameters.
232
+
233
+ Parameters:
234
+ -----------
235
+ ds : pyadps.dataset or numpy.ndarray
236
+ If pyadps dataframe is loaded, the data from the fixed and variable leader
237
+ is automatically obtained. This includes the depth of the transducer and other relevant information
238
+ for trimming the data.
239
+
240
+ If numpy.ndarray is loaded, the value should contain the transducer_depth.
241
+ In such cases provide cells, cell_size, and bin 1 distance.
242
+ Orientiation should be either 'up' or 'down' and not 'default'.
243
+
244
+
245
+ data : array-like
246
+ The 2D data array to be regridded.
247
+
248
+ fill_value : scalar
249
+ The value used to fill missing or undefined grid points.
250
+
251
+ end_cell_option : str or float, optional, default="cell"
252
+ The depth of the last bin or boundary for the grid.
253
+ Options include:
254
+ - "cell" : Calculates the depth of the default last bin for the grid.
255
+ Truncates to surface for upward ADCP.
256
+ - "surface": The data is gridded till the surface
257
+ - "manual": User-defined depth for the grid.
258
+ Use boundary_limit option to provide the value.
259
+ otherwise, a specific numerical depth value can be provided.
260
+
261
+ trimends : tuple of floats, optional, default=None
262
+ If provided, defines the ensemble range (start, end) for
263
+ calculating the maximum/minimum transducer depth.
264
+ Helps avoiding the deployment or retrieval data.
265
+ E.g. (10, 3000)
266
+
267
+ method : str, optional, default="nearest"
268
+ The interpolation method to use for regridding based
269
+ on scipy.interpolate.interp1d.
270
+ Options include:
271
+ - "nearest" : Nearest neighbor interpolation.
272
+ - "linear" : Linear interpolation.
273
+ - "cubic" : Cubic interpolation.
274
+
275
+ orientation : str, optional, default="up"
276
+ Defines the direction of the regridding for an upward/downward looking ADCP. Options include:
277
+ - "up" : Regrid upwards (for upward-looking ADCP).
278
+ - "down" : Regrid downwards (for downward-looking ADCP).
279
+
280
+ boundary_limit : float, optional, default=0
281
+ The limit for the boundary depth. This restricts the grid regridding to depths beyond the specified limit.
282
+
283
+ cells: int, optional
284
+ Number of cells
285
+
286
+ cell_size: int, optional
287
+ Cell size or depth cell length in cm
288
+
289
+ bin1dist: int, optional
290
+ Distance from the first bin in cm
291
+
292
+
293
+ Returns:
294
+ --------
295
+ z: regridded depth
296
+ regridded_data : array-like
297
+ The regridded 2D data array, based on the specified method,
298
+ orientation, and other parameters.
299
+
300
+ Notes:
301
+ ------
302
+ - If `end_cell_option == boundary`, then `boundary_limit` is used to regrid the data.
303
+ - This function allows for flexible regridding of 2D data to fit a new grid, supporting different interpolation methods.
304
+ - The `boundary_limit` parameter helps restrict regridding to depths above or below a certain threshold.
305
+ """
306
+
307
+ if isinstance(ds, ReadFile) or ds.__class__.__name__ == "ReadFile":
308
+ flobj = ds.fixedleader
309
+ vlobj = ds.variableleader
310
+ # Get values and convert to 'm'
311
+ bin1dist = flobj.field()["Bin 1 Dist"] / 100
312
+ transdepth = vlobj.vleader["Depth of Transducer"] / 10
313
+ cell_size = flobj.field()["Depth Cell Len"] / 100
314
+ cells = flobj.field()["Cells"]
315
+ ensembles = flobj.ensembles
316
+ if orientation.lower() == "default":
317
+ orientation = flobj.system_configuration()["Beam Direction"]
318
+
319
+ elif isinstance(ds, np.ndarray) and np.squeeze(ds).ndim == 1:
320
+ transdepth = ds / 10
321
+ ensembles = np.size(ds)
322
+
323
+ if cells is None:
324
+ raise ValueError("Input must include number of cells.")
325
+
326
+ if cell_size is None:
327
+ raise ValueError("Input must include cell size.")
328
+ else:
329
+ cell_size = cell_size / 100
330
+
331
+ if bin1dist is None:
332
+ raise ValueError("Input must include bin 1 distance.")
333
+ else:
334
+ bin1dist = bin1dist / 100
335
+
336
+ if orientation.lower() != "up" and orientation.lower() != "down":
337
+ raise ValueError("Orientation must be `up` or `down`.")
338
+ else:
339
+ raise ValueError("Input must be a 1-D numpy array or a PyADPS instance")
340
+
341
+ if orientation.lower() == "up":
342
+ sgn = -1
343
+ else:
344
+ sgn = 1
345
+
346
+ # Create a regular grid
347
+
348
+ # Find depth of first cell
349
+ depth = transdepth + sgn * bin1dist
350
+
351
+ # Find the maximum and minimum depth for first cell for upward
352
+ # looking ADCP (minimum and maximum for downward looking)
353
+ if trimends is not None:
354
+ max_depth = abs(np.min(sgn * depth[trimends[0] : trimends[1]]))
355
+ min_depth = abs(np.max(sgn * depth[trimends[0] : trimends[1]]))
356
+ else:
357
+ max_depth = abs(np.min(sgn * depth))
358
+ min_depth = abs(np.max(sgn * depth))
359
+
360
+ # FIRST CELL
361
+ # Convert the first cell depth to the first regular grid depth
362
+ depthfirstcell = max_depth - max_depth % cell_size
363
+
364
+ # LAST CELL
365
+ # Convert the last cell depth to last regular grid depth
366
+ if end_cell_option.lower() == "surface":
367
+ # Added one additional negative cell to accomodate 0 m.
368
+ depthlastcell = sgn * cell_size
369
+ elif end_cell_option.lower() == "cell":
370
+ min_depth_regrid = min_depth - sgn * min_depth % cell_size
371
+ depthlastcell = min_depth_regrid + sgn * (cells + 1) * cell_size
372
+ # Check if this is required. Use 'surface' option
373
+ if depthlastcell < 0:
374
+ depthlastcell = sgn * cell_size
375
+ elif end_cell_option.lower() == "manual":
376
+ if sgn < 0 and boundary_limit > depthfirstcell:
377
+ print(
378
+ "ERROR: For upward looking ADCP, boundary limit should be less than transducer depth"
379
+ )
380
+ return
381
+ if sgn > 0 and boundary_limit < depthfirstcell:
382
+ print(
383
+ "ERROR: For downward looking ADCP, boundary limit should be greater than transducer depth"
384
+ )
385
+ return
386
+ # Set the last grid cell depth
387
+ depthlastcell = boundary_limit
388
+ else:
389
+ print("ERROR: `end_cell_option` not recognized.")
390
+ return
391
+
392
+ # Negative used for upward and positive for downward.
393
+ z = np.arange(sgn * depthfirstcell, sgn * depthlastcell, cell_size)
394
+ regbins = len(z)
395
+
396
+ regridded_data = np.zeros((regbins, ensembles))
397
+
398
+ # Create original depth array
399
+ for i, d in enumerate(depth):
400
+ n = d + sgn * cell_size * cells
401
+ # np.arange may include unexpected elements due to floating-point
402
+ # precision issues at the stopping point. Changed to np.linspace.
403
+ #
404
+ # depth_bins = np.arange(sgn*d, sgn*n, cell_size)
405
+ depth_bins = np.linspace(sgn * d, sgn * n, cells)
406
+ f = sp.interpolate.interp1d(
407
+ depth_bins,
408
+ data[:, i],
409
+ kind=method,
410
+ fill_value=fill_value,
411
+ bounds_error=False,
412
+ )
413
+ gridz = f(z)
414
+
415
+ regridded_data[:, i] = gridz
416
+
417
+ return abs(z), regridded_data
418
+
419
+
420
+ def regrid3d(
421
+ ds,
422
+ data,
423
+ fill_value,
424
+ end_cell_option="cell",
425
+ trimends=None,
426
+ method="nearest",
427
+ orientation="up",
428
+ boundary_limit=0,
429
+ cells=None,
430
+ cell_size=None,
431
+ bin1dist=None,
432
+ beams=None,
433
+ ):
434
+ """
435
+ Regrids 3D data onto a new grid based on specified parameters.
436
+
437
+ Parameters:
438
+ -----------
439
+ ds : pyadps.dataset
440
+ The pyadps dataframe is loaded to obtain the data from the fixed and variable leader.
441
+ This includes the depth of the transducer and other relevant information
442
+ for trimming the data.
443
+
444
+ data : array-like
445
+ The 3D data array to be regridded, with dimensions
446
+ typically representing time, depth, and another axis (e.g., ensembles).
447
+
448
+ fill_value : scalar
449
+ The value used to fill missing or undefined grid points.
450
+
451
+ end_cell_option : str or float, optional, default="cell"
452
+ The depth of the last bin or boundary for the grid.
453
+ Options include:
454
+ - "cell" : Calculates the depth of the default last bin for the grid.
455
+ Truncates to surface for upward ADCP.
456
+ - "surface" : The data is gridded till the surface.
457
+ - "manual" : User-defined depth for the grid.
458
+ Use boundary_limit option to provide the value.
459
+ Otherwise, a specific numerical depth value can be provided.
460
+
461
+ trimends : tuple of integer, optional, default=None
462
+ If provided, defines the ensemble range (start, end) for
463
+ calculating the maximum/minimum transducer depth.
464
+ Helps avoiding the deployment or retrieval data.
465
+ E.g., (10, 3000)
466
+
467
+ method : str, optional, default="nearest"
468
+ The interpolation method to use for regridding based
469
+ on scipy.interpolate.interp1d.
470
+ Options include:
471
+ - "nearest" : Nearest neighbor interpolation.
472
+ - "linear" : Linear interpolation.
473
+ - "cubic" : Cubic interpolation.
474
+
475
+ orientation : str, optional, default="up"
476
+ Defines the direction of the regridding for an upward/downward looking ADCP. Options include:
477
+ - "up" : Regrid upwards (for upward-looking ADCP).
478
+ - "down" : Regrid downwards (for downward-looking ADCP).
479
+
480
+ boundary_limit : float, optional, default=0
481
+ The limit for the boundary depth. This restricts the grid regridding to depths beyond the specified limit.
482
+
483
+ cells: int, optional
484
+ Number of cells
485
+
486
+ cell_size: int, optional
487
+ Cell size or depth cell length in cm
488
+
489
+ bin1dist: int, optional
490
+ Distance from the first bin in cm
491
+
492
+ beams: int, optional
493
+ Number of beams
494
+
495
+
496
+
497
+ Returns:
498
+ --------
499
+ z : array-like
500
+ The regridded depth array.
501
+ regridded_data : array-like
502
+ The regridded 3D data array, based on the specified method,
503
+ orientation, and other parameters.
504
+
505
+ Notes:
506
+ ------
507
+ - If `end_cell_option == boundary`, then `boundary_limit` is used to regrid the data.
508
+ - This function allows for flexible regridding of 3D data to fit a new grid, supporting different interpolation methods.
509
+ - The `boundary_limit` parameter helps restrict regridding to depths above or below a certain threshold.
510
+ - This function is an extension of 2D regridding to handle the time dimension or other additional axes in the data.
511
+ """
512
+
513
+ if isinstance(ds, ReadFile):
514
+ flobj = ds.fixedleader
515
+ beams = flobj.field()["Beams"]
516
+ elif isinstance(ds, np.ndarray) and ds.ndim == 1:
517
+ if beams is None:
518
+ raise ValueError("Input must include number of beams.")
519
+ else:
520
+ raise ValueError("Input must be a 1-D numpy array or a PyADPS instance")
521
+
522
+ z, data_dummy = regrid2d(
523
+ ds,
524
+ data[0, :, :],
525
+ fill_value,
526
+ end_cell_option=end_cell_option,
527
+ trimends=trimends,
528
+ method=method,
529
+ orientation=orientation,
530
+ boundary_limit=boundary_limit,
531
+ cells=cells,
532
+ cell_size=cell_size,
533
+ bin1dist=bin1dist,
534
+ )
535
+
536
+ newshape = np.shape(data_dummy)
537
+ regridded_data = np.zeros((beams, newshape[0], newshape[1]))
538
+ regridded_data[0, :, :] = data_dummy
539
+
540
+ for i in range(beams - 1):
541
+ z, data_dummy = regrid2d(
542
+ ds,
543
+ data[i + 1, :, :],
544
+ fill_value,
545
+ end_cell_option=end_cell_option,
546
+ trimends=trimends,
547
+ method=method,
548
+ orientation=orientation,
549
+ boundary_limit=boundary_limit,
550
+ cells=cells,
551
+ cell_size=cell_size,
552
+ bin1dist=bin1dist,
553
+ )
554
+ regridded_data[i + 1, :, :] = data_dummy
555
+
556
+ return z, regridded_data