oceanstream 0.0.8.dev0__py3-none-any.whl → 0.0.12.dev0__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.
oceanstream/__init__.py CHANGED
@@ -1,3 +1,5 @@
1
- from .core import compute_sv, combine, convert, process_raw_file
1
+ from .core import initialize, compute_sv, combine, convert, process_raw_file
2
2
 
3
- __all__ = ["compute_sv", "combine", "convert", "process_raw_file"]
3
+ __all__ = [
4
+ "compute_sv", "combine", "convert", "process_raw_file", "initialize"
5
+ ]
oceanstream/cli/main.py CHANGED
@@ -1,5 +1,3 @@
1
- import traceback
2
-
3
1
  import typer
4
2
  import asyncio
5
3
  import os
@@ -11,7 +9,7 @@ from pathlib import Path
11
9
  from rich import print
12
10
  from rich.traceback import install, Traceback
13
11
  from oceanstream.settings import load_config
14
- from dask.distributed import LocalCluster, Client
12
+ from dask.distributed import LocalCluster, Client, Variable
15
13
  from rich.console import Console
16
14
 
17
15
 
@@ -113,16 +111,21 @@ def convert(
113
111
  filePath = Path(source)
114
112
  configData = initialize(settings, filePath, log_level=log_level)
115
113
 
116
- if filePath.is_file():
117
- from oceanstream.process import convert_raw_file
118
- convert_raw_file(filePath, configData)
119
- print(f"[blue]✅ Converted raw file {source} to Zarr and wrote output to: {configData['output_folder']} [/blue]")
120
- elif filePath.is_dir():
121
- from oceanstream.process import convert_raw_files
122
- convert_raw_files(configData, workers_count=workers_count)
123
- else:
124
- print(f"[red]❌ The provided path '{source}' is not a valid file/folder.[/red]")
125
- sys.exit(1)
114
+ try:
115
+ if filePath.is_file():
116
+ from oceanstream.process import convert_raw_file
117
+ convert_raw_file(filePath, configData)
118
+ print(f"[blue]✅ Converted raw file {source} to Zarr and wrote output to: {configData['output_folder']} [/blue]")
119
+ elif filePath.is_dir():
120
+ from oceanstream.process import convert_raw_files
121
+ convert_raw_files(configData, workers_count=workers_count)
122
+ else:
123
+ print(f"[red]❌ The provided path '{source}' is not a valid file/folder.[/red]")
124
+ except KeyboardInterrupt:
125
+ logging.info("KeyboardInterrupt received, terminating processes...")
126
+ except Exception as e:
127
+ logging.exception("Error processing folder %s", configData['raw_path'])
128
+ print(Traceback())
126
129
 
127
130
 
128
131
  @app.command()
@@ -171,7 +174,7 @@ def combine(
171
174
  logging.info("KeyboardInterrupt received, terminating processes...")
172
175
  except Exception as e:
173
176
  logging.exception("Error processing folder %s", configData['raw_path'])
174
- traceback.print_exc()
177
+ print(Traceback())
175
178
  finally:
176
179
  status.stop()
177
180
  client.close()
@@ -190,6 +193,7 @@ def compute_sv(
190
193
  sonar_model: str = typer.Option(DEFAULT_SONAR_MODEL, help="Sonar model used to collect the data",
191
194
  show_choices=["AZFP", "EK60", "ES70", "EK80", "ES80", "EA640", "AD2CP"]),
192
195
  plot_echogram: bool = typer.Option(False, help="Plot the echogram after processing"),
196
+ use_dask: bool = typer.Option(False, help="Start a Local Dask cluster for parallel processing (always enabled for multiple files)"),
193
197
  depth_offset: float = typer.Option(0.0, help="Depth offset for the echogram plot"),
194
198
  waveform_mode: str = typer.Option("CW", help="Waveform mode, can be either CW or BB",
195
199
  show_choices=["CW", "BB"]),
@@ -208,11 +212,14 @@ def compute_sv(
208
212
  file_path = Path(source)
209
213
  config_data = initialize(settings_dict, file_path, log_level=log_level)
210
214
 
215
+ client = None
211
216
  console = Console()
217
+ single_file = file_path.is_dir() and source.endswith(".zarr")
212
218
  with console.status("Processing...", spinner="dots") as status:
213
219
  status.start()
214
- cluster = LocalCluster(n_workers=workers_count, threads_per_worker=1)
215
- client = Client(cluster)
220
+ if use_dask or not single_file:
221
+ cluster = LocalCluster(n_workers=workers_count, threads_per_worker=1)
222
+ client = Client(cluster)
216
223
 
217
224
  try:
218
225
  if file_path.is_dir() and source.endswith(".zarr"):
@@ -230,13 +237,14 @@ def compute_sv(
230
237
  f"[blue] Processing zarr files in {file_path}...[/blue] – navigate to "
231
238
  f"http://localhost:8787/status for progress")
232
239
  from oceanstream.process import process_zarr_files
233
-
240
+ processed_count_var = Variable('processed_count', client)
234
241
  process_zarr_files(config_data,
235
242
  workers_count=workers_count,
236
243
  status=status,
237
244
  chunks=config_data.get('base_chunk_sizes'),
238
245
  plot_echogram=plot_echogram,
239
246
  waveform_mode=waveform_mode,
247
+ processed_count_var=processed_count_var,
240
248
  depth_offset=depth_offset)
241
249
  else:
242
250
  print(f"[red]❌ The provided path '{source}' is not a valid Zarr root.[/red]")
@@ -245,10 +253,11 @@ def compute_sv(
245
253
  logging.info("KeyboardInterrupt received, terminating processes...")
246
254
  except Exception as e:
247
255
  logging.exception("Error while processing %s", config_data['raw_path'])
248
- traceback.print_exc()
256
+ print(Traceback())
249
257
  finally:
250
- client.close()
251
- cluster.close()
258
+ if use_dask:
259
+ client.close()
260
+ cluster.close()
252
261
  status.stop()
253
262
 
254
263
 
@@ -1,2 +1 @@
1
- typer
2
- rich
1
+ typer
oceanstream/core.py CHANGED
@@ -5,6 +5,7 @@ import sys
5
5
 
6
6
  from pathlib import Path
7
7
  from oceanstream.settings import load_config
8
+ from oceanstream.process import convert_raw_file, convert_raw_files, compute_single_file
8
9
 
9
10
  DEFAULT_OUTPUT_FOLDER = "output"
10
11
  DEFAULT_SONAR_MODEL = "EK60"
@@ -12,10 +13,20 @@ DEFAULT_SONAR_MODEL = "EK60"
12
13
  logging.basicConfig(level="ERROR", format='%(asctime)s - %(levelname)s - %(message)s')
13
14
 
14
15
 
15
- def initialize(settings, file_path, log_level=None):
16
+ def initialize(settings, file_path=None, log_level=None, chunks=None):
16
17
  logging.debug(f"Initializing with settings: {settings}, file path: {file_path}, log level: {log_level}")
18
+ if "config" not in settings:
19
+ settings["config"] = ""
20
+
17
21
  config_data = load_config(settings["config"])
18
- config_data["raw_path"] = file_path
22
+
23
+ if chunks:
24
+ config_data['chunks'] = chunks
25
+ else:
26
+ config_data['chunks'] = config_data.get('base_chunk_sizes', None)
27
+
28
+ if file_path is not None:
29
+ config_data["raw_path"] = file_path
19
30
 
20
31
  if log_level is not None:
21
32
  logging.basicConfig(level=log_level, format='%(asctime)s - %(levelname)s - %(message)s', force=True)
@@ -24,9 +35,21 @@ def initialize(settings, file_path, log_level=None):
24
35
  if 'sonar_model' in settings and settings["sonar_model"] is not None:
25
36
  config_data["sonar_model"] = settings["sonar_model"]
26
37
 
27
- if settings["output_folder"] is not None:
38
+ if settings.get('plot_echogram', None) is not None:
39
+ config_data["plot_echogram"] = settings["plot_echogram"]
40
+
41
+ if settings.get('waveform_mode', None) is not None:
42
+ config_data["waveform_mode"] = settings["waveform_mode"]
43
+
44
+ if settings.get('depth_offset', None) is not None:
45
+ config_data["depth_offset"] = settings["depth_offset"]
46
+
47
+ if settings.get("output_folder", None) is not None:
28
48
  config_data["output_folder"] = settings["output_folder"]
29
49
 
50
+ if settings.get('cloud_storage', None) is not None:
51
+ config_data['cloud_storage'] = settings['cloud_storage']
52
+
30
53
  return config_data
31
54
 
32
55
 
@@ -57,27 +80,29 @@ def process_raw_file(source, output=None, sonar_model=None, plot_echogram=False,
57
80
  sys.exit(1)
58
81
 
59
82
 
60
- def convert(source, output=None, workers_count=None, config=None, log_level="WARNING", chunks=None):
83
+ def convert(source, output=None, base_path=None, workers_count=None, config=None, log_level="WARNING", chunks=None):
61
84
  logging.debug("Starting convert function")
62
85
  settings = {
63
- "config": config,
64
86
  "output_folder": output or DEFAULT_OUTPUT_FOLDER
65
87
  }
66
88
 
89
+ if config is not None:
90
+ settings.update(config)
91
+
67
92
  file_path = Path(source)
68
93
  config_data = initialize(settings, file_path, log_level=log_level)
69
94
 
70
95
  if chunks:
71
96
  config_data['chunks'] = chunks
97
+ else:
98
+ config_data['chunks'] = config_data.get('base_chunk_sizes', None)
72
99
 
73
100
  if file_path.is_file():
74
101
  logging.debug(f"Converting raw file: {file_path}")
75
- from oceanstream.process import convert_raw_file
76
- convert_raw_file(file_path, config_data)
102
+ convert_raw_file(file_path, config_data, base_path=base_path)
77
103
  logging.info(f"Converted raw file {source} to Zarr and wrote output to: {config_data['output_folder']}")
78
104
  elif file_path.is_dir():
79
105
  logging.debug(f"Converting raw files in directory: {file_path}")
80
- from oceanstream.process import convert_raw_files
81
106
  convert_raw_files(config_data, workers_count=workers_count)
82
107
  else:
83
108
  logging.error(f"The provided path '{source}' is not a valid file/folder.")
@@ -103,8 +128,7 @@ def combine(source, output=None, config=None, log_level="WARNING", chunks=None):
103
128
 
104
129
  file_name = f"{Path(dir_path).stem}-combined.zarr"
105
130
  zarr_output_file = os.path.join(config_data['output_folder'], file_name)
106
- logging.info(
107
- f"Combining Zarr files to {zarr_output_file}; navigate to http://localhost:8787/status for progress")
131
+ logging.info(f"Combining Zarr files to {zarr_output_file}")
108
132
 
109
133
  combine_zarr_files(dir_path, zarr_output_file=zarr_output_file, chunks=chunks)
110
134
  logging.info("Zarr files have been combined successfully.")
@@ -113,30 +137,34 @@ def combine(source, output=None, config=None, log_level="WARNING", chunks=None):
113
137
 
114
138
 
115
139
  def compute_sv(source, output=None, workers_count=None, sonar_model=DEFAULT_SONAR_MODEL, plot_echogram=False,
116
- depth_offset=0.0, waveform_mode="CW", config=None, log_level="WARNING", chunks=None):
117
- logging.debug("Starting compute_sv function")
140
+ depth_offset=0.0, waveform_mode="CW", log_level="WARNING", chunks=None, config=None,
141
+ processed_count_var=None):
118
142
  settings_dict = {
119
- "config": config,
120
143
  "sonar_model": sonar_model,
121
144
  "output_folder": output or DEFAULT_OUTPUT_FOLDER
122
145
  }
146
+
147
+ if config is not None:
148
+ settings_dict.update(config)
149
+
123
150
  file_path = Path(source)
124
151
  config_data = initialize(settings_dict, file_path, log_level=log_level)
125
152
 
126
153
  if chunks:
127
154
  config_data['chunks'] = chunks
155
+ else:
156
+ config_data['chunks'] = config_data.get('base_chunk_sizes', None)
128
157
 
129
158
  if file_path.is_dir() and source.endswith(".zarr"):
130
159
  logging.debug(f"Computing Sv for Zarr root file: {file_path}")
131
- from oceanstream.process import compute_single_file
132
-
133
160
  compute_single_file(config_data, chunks=chunks, plot_echogram=plot_echogram, waveform_mode=waveform_mode,
134
161
  depth_offset=depth_offset)
135
162
  elif file_path.is_dir():
136
163
  logging.debug(f"Processing Zarr files in directory: {file_path}")
137
164
  from oceanstream.process import process_zarr_files
138
165
 
139
- process_zarr_files(config_data, workers_count=workers_count, chunks=chunks, plot_echogram=plot_echogram,
166
+ process_zarr_files(config_data, workers_count=workers_count, chunks=chunks,
167
+ processed_count_var=processed_count_var, plot_echogram=plot_echogram,
140
168
  waveform_mode=waveform_mode, depth_offset=depth_offset)
141
169
  else:
142
170
  logging.error(f"The provided path '{source}' is not a valid Zarr root.")
@@ -1 +0,0 @@
1
- pydantic
@@ -96,8 +96,6 @@ def add_depth(Sv: Dataset, depth_offset: float = 0, tilt: float = 0, downward: b
96
96
  first_channel = Sv["channel"].values[0]
97
97
  first_ping_time = Sv["ping_time"].values[0]
98
98
 
99
- original_echo_range = Sv["echo_range"].sel(channel=first_channel, ping_time=first_ping_time).values
100
-
101
99
  # Slice the echo_range to get the desired range of values
102
100
  selected_echo_range = Sv["echo_range"].sel(channel=first_channel, ping_time=first_ping_time)
103
101
  selected_echo_range = selected_echo_range.values.tolist()
@@ -1,7 +1,10 @@
1
1
  import asyncio
2
2
  import os
3
+ import tempfile
3
4
  import xarray as xr
4
5
  import numpy as np
6
+ import logging
7
+
5
8
  from matplotlib.colors import LinearSegmentedColormap, Colormap
6
9
  import matplotlib.pyplot as plt
7
10
  import matplotlib.dates as mdates
@@ -287,18 +290,13 @@ def plot_individual_channel_image_only(ds_Sv, channel, output_path, file_base_na
287
290
  plt.close()
288
291
 
289
292
 
290
- def plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_name,
291
- cmap='viridis',
292
- regions2d=None,
293
- region_ids=None, region_class=None):
293
+ def plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_name, echogram_path=None,
294
+ config_data=None, cmap='ocean_r'):
294
295
  """Plot and save echogram for a single channel with optional regions and enhancements."""
295
296
  full_channel_name = ds_Sv.channel.values[channel]
296
297
  channel_name = "_".join(full_channel_name.split()[:3])
297
298
 
298
299
  plt.figure(figsize=(30, 18))
299
- echogram_output_path = os.path.join(output_path, f"{file_base_name}_{channel_name}.png")
300
-
301
- # Apply the same preprocessing steps from _plot_echogram
302
300
  ds = ds_Sv
303
301
 
304
302
  filtered_ds = ds['Sv']
@@ -332,7 +330,7 @@ def plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_na
332
330
  yincrease=False,
333
331
  vmin=-80,
334
332
  vmax=-50,
335
- cmap='ocean_r',
333
+ cmap=cmap,
336
334
  cbar_kwargs={'label': 'Volume backscattering strength (Sv re 1 m-1)'}
337
335
  )
338
336
 
@@ -340,8 +338,20 @@ def plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_na
340
338
  plt.xlabel('Ping time', fontsize=14)
341
339
  plt.ylabel('Depth', fontsize=14)
342
340
  plt.title(f'Echogram for Channel {channel_name}', fontsize=16, fontweight='bold')
343
- plt.savefig(echogram_output_path, dpi=300, bbox_inches='tight')
344
- plt.close()
341
+
342
+ echogram_file_name = f"{file_base_name}_{channel_name}.png"
343
+
344
+ if config_data and 'cloud_storage' in config_data:
345
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
346
+ plt.savefig(temp_file.name, dpi=300, bbox_inches='tight')
347
+ plt.close()
348
+ echogram_output_path = os.path.join(echogram_path, echogram_file_name)
349
+ upload_to_cloud_storage(temp_file.name, echogram_output_path, config_data['cloud_storage'])
350
+ os.remove(temp_file.name)
351
+ else:
352
+ echogram_output_path = os.path.join(output_path, echogram_file_name)
353
+ plt.savefig(echogram_output_path, dpi=300, bbox_inches='tight')
354
+ plt.close()
345
355
 
346
356
 
347
357
  def plot_sv_data_parallel(ds_Sv, file_base_name=None, output_path=None, cmap=None, client=None):
@@ -360,15 +370,15 @@ def plot_sv_data_parallel(ds_Sv, file_base_name=None, output_path=None, cmap=Non
360
370
  wait(futures)
361
371
 
362
372
 
363
- def plot_sv_data(ds_Sv, file_base_name=None, output_path=None, cmap=None, regions2d=None, region_ids=None,
364
- region_class=None):
373
+ def plot_sv_data(ds_Sv, file_base_name=None, output_path=None, echogram_path=None, config_data=None, cmap=None):
365
374
  """Plot the echogram data and the regions."""
366
375
  if not plt.isinteractive():
367
376
  plt.switch_backend('Agg')
368
377
 
369
378
  for channel in range(ds_Sv.dims['channel']):
370
- plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_name, cmap, regions2d, region_ids,
371
- region_class)
379
+ plot_individual_channel_simplified(ds_Sv, channel, output_path, file_base_name, echogram_path=echogram_path,
380
+ config_data=config_data,
381
+ cmap='ocean_r')
372
382
  # plot_individual_channel_image_only(ds_Sv, channel, output_path, file_base_name, cmap)
373
383
  # plot_individual_channel_shaders(ds_Sv=ds_Sv, channel=channel, output_path=output_path,
374
384
  # file_base_name=file_base_name, cmap='ocean_r')
@@ -540,3 +550,24 @@ def _plot_region_ids(colors, ds_Sv, idx, labels_added, region_ids, regions2d):
540
550
  labels_added.add(label)
541
551
  idx += 1
542
552
  return idx
553
+
554
+
555
+ def upload_to_cloud_storage(local_path, remote_path, cloud_storage_config):
556
+ storage_type = cloud_storage_config['storage_type']
557
+ container_name = cloud_storage_config['container_name']
558
+ storage_options = cloud_storage_config['storage_options']
559
+
560
+ if storage_type == 'azure':
561
+ upload_to_azure_blob(local_path, remote_path, container_name, storage_options)
562
+ else:
563
+ raise ValueError(f"Unsupported storage type: {storage_type}")
564
+
565
+
566
+ def upload_to_azure_blob(local_path, remote_path, container_name, storage_options):
567
+ from azure.storage.blob import BlobServiceClient
568
+ blob_service_client = BlobServiceClient.from_connection_string(storage_options['connection_string'])
569
+ blob_client = blob_service_client.get_blob_client(container=container_name, blob=remote_path)
570
+
571
+ with open(local_path, "rb") as data:
572
+ blob_client.upload_blob(data, overwrite=True)
573
+ logging.info(f"Uploaded {local_path} to Azure Blob Storage as {remote_path}")
@@ -0,0 +1,9 @@
1
+ from .s3 import process_survey_data_with_progress, list_raw_files_from_bucket, convert_survey_data_from_bucket, \
2
+ download_file_from_bucket
3
+
4
+ __all__ = [
5
+ "process_survey_data_with_progress",
6
+ "list_raw_files_from_bucket",
7
+ "convert_survey_data_from_bucket",
8
+ "download_file_from_bucket"
9
+ ]
@@ -0,0 +1,93 @@
1
+ import os
2
+ import tempfile
3
+ import botocore
4
+ import boto3
5
+ from asyncio import CancelledError
6
+ from rich import print
7
+ from rich.traceback import install, Traceback
8
+ from tqdm.auto import tqdm
9
+ from dask import delayed
10
+ from botocore.config import Config
11
+
12
+
13
+ install(show_locals=False, width=120)
14
+
15
+
16
+ def process_survey_data_with_progress(files_by_day, bucket_name, client, config_data, process_func):
17
+ try:
18
+ total_files = sum(len(files) for files in files_by_day.values())
19
+ progress_bar = tqdm(total=total_files, desc="Processing Files", unit="file", ncols=100)
20
+
21
+ def update_progress(*args):
22
+ progress_bar.update()
23
+
24
+ temp_dir = tempfile.mkdtemp()
25
+ futures, temp_dir = convert_survey_data_from_bucket(files_by_day, temp_dir, bucket_name, client, config_data,
26
+ process_func)
27
+
28
+ for future in futures:
29
+ future.add_done_callback(update_progress)
30
+
31
+ client.gather(futures) # Ensure all tasks complete
32
+
33
+ progress_bar.close()
34
+ os.rmdir(temp_dir)
35
+ except KeyboardInterrupt:
36
+ print("Closing down.")
37
+ except CancelledError:
38
+ print("Closing down.")
39
+ except Exception as e:
40
+ print(f"[bold red]An error occurred:[/bold red] {e}")
41
+ print(f"{Traceback()}\n")
42
+
43
+
44
+ def convert_survey_data_from_bucket(files_by_day, temp_dir, bucket_name, dask_client, config_data, process_func):
45
+ """Process survey data from S3."""
46
+ tasks = []
47
+
48
+ for day, files in files_by_day.items():
49
+ for file in files:
50
+ task = delayed(_process_raw_file)(file, day, temp_dir, bucket_name, config_data, process_func)
51
+ tasks.append(task)
52
+
53
+ # Execute all tasks in parallel
54
+ futures = dask_client.compute(tasks)
55
+
56
+ return futures, temp_dir
57
+
58
+
59
+ def list_raw_files_from_bucket(bucket_name, prefix):
60
+ """List files in the S3 bucket along with their metadata."""
61
+ s3_client = boto3.client('s3', config=Config(signature_version=botocore.UNSIGNED))
62
+ response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
63
+
64
+ files = [
65
+ {
66
+ 'Key': item['Key'],
67
+ 'Size': item['Size'],
68
+ 'LastModified': item['LastModified']
69
+ }
70
+ for item in response.get('Contents', []) if item['Key'].endswith('.raw')
71
+ ]
72
+
73
+ return files
74
+
75
+
76
+ def download_file_from_bucket(bucket_name, s3_key, local_dir):
77
+ """Download a file from S3."""
78
+ s3_client = boto3.client('s3', config=Config(signature_version=botocore.UNSIGNED))
79
+ local_path = os.path.join(local_dir, os.path.basename(s3_key))
80
+ s3_client.download_file(bucket_name, s3_key, local_path)
81
+
82
+ return local_path
83
+
84
+
85
+ def _process_raw_file(file, day, temp_dir, bucket_name, config_data, process_func):
86
+ """Process a single file."""
87
+ day_dir = os.path.join(temp_dir, day)
88
+ os.makedirs(day_dir, exist_ok=True)
89
+ local_path = download_file_from_bucket(bucket_name, file['Key'], day_dir)
90
+
91
+ process_func(local_path, config=config_data, base_path=temp_dir)
92
+ os.remove(local_path)
93
+
@@ -0,0 +1,8 @@
1
+ from .blob_storage import list_zarr_files
2
+ from .azure_processor import process_survey_data_with_progress, process_survey_data
3
+
4
+ __all__ = [
5
+ "list_zarr_files",
6
+ "process_survey_data",
7
+ "process_survey_data_with_progress"
8
+ ]
@@ -0,0 +1,66 @@
1
+ import re
2
+
3
+ from asyncio import CancelledError
4
+ from rich import print
5
+ from rich.traceback import install, Traceback
6
+ from tqdm.auto import tqdm
7
+ from dask import delayed
8
+ from .blob_storage import open_zarr_store
9
+
10
+ install(show_locals=False, width=120)
11
+
12
+
13
+ def process_survey_data_with_progress(files_by_day, azfs, container_name, client, config_data, process_func):
14
+ try:
15
+ total_files = sum(len(files) for files in files_by_day.values())
16
+ progress_bar = tqdm(total=total_files, desc="Processing Files", unit="file", ncols=100)
17
+
18
+ def update_progress(*args):
19
+ progress_bar.update()
20
+
21
+ futures = process_survey_data(files_by_day, azfs, container_name, client, config_data, process_func)
22
+
23
+ for future in futures:
24
+ future.add_done_callback(update_progress)
25
+
26
+ client.gather(futures) # Ensure all tasks complete
27
+
28
+ progress_bar.close()
29
+ except KeyboardInterrupt:
30
+ print("Closing down.")
31
+ except CancelledError:
32
+ print("Closing down.")
33
+ except Exception as e:
34
+ print(f"[bold red]An error occurred:[/bold red] {e}")
35
+ print(f"{Traceback()}\n")
36
+
37
+
38
+ def process_survey_data(files_by_day, azfs, container_name, dask_client, config_data, process_func):
39
+ """Process survey data from S3."""
40
+
41
+ tasks = []
42
+
43
+ for day, files in files_by_day.items():
44
+ for file in files:
45
+ task = delayed(_process_zarr_file)(file['Key'], azfs, container_name, config_data, process_func)
46
+ tasks.append(task)
47
+
48
+ # Execute all tasks in parallel
49
+ futures = dask_client.compute(tasks)
50
+
51
+ return futures
52
+
53
+
54
+ def _process_zarr_file(file, azfs, container_name, config_data, process_func=None):
55
+ """Process a single Zarr file."""
56
+ base_path = file.replace('.zarr', '')
57
+ pattern = rf"^{re.escape(container_name)}/"
58
+ base_path = re.sub(pattern, '', base_path)
59
+
60
+ echodata = open_zarr_store(azfs, file, chunks=config_data['chunks'])
61
+
62
+ process_func(echodata, config_data, base_path=base_path,
63
+ chunks=config_data.get('chunks'),
64
+ plot_echogram=config_data.get('plot_echogram', False),
65
+ waveform_mode=config_data.get('waveform_mode', "CW"),
66
+ depth_offset=config_data.get('depth_offset', 0.0))
@@ -0,0 +1,54 @@
1
+ import echopype as ep
2
+
3
+
4
+ def list_zarr_files(azfs, path):
5
+ """List all Zarr files in the Azure Blob Storage container along with their metadata."""
6
+ zarr_files = []
7
+ for blob in azfs.ls(path, detail=True):
8
+ if blob['type'] == 'directory' and not blob['name'].endswith('.zarr'):
9
+ subdir_files = list_zarr_files(azfs, blob['name'])
10
+ zarr_files.extend(subdir_files)
11
+ elif blob['name'].endswith('.zarr'):
12
+ zarr_files.append({
13
+ 'Key': blob['name'],
14
+ 'Size': blob['size'] if blob['size'] else 0,
15
+ 'LastModified': blob['last_modified'] if 'last_modified' in blob else 0
16
+ })
17
+
18
+ return zarr_files
19
+
20
+
21
+ def open_zarr_store(azfs, store_name, chunks=None):
22
+ """Open a Zarr store from Azure Blob Storage."""
23
+ mapper = azfs.get_mapper(store_name)
24
+
25
+ return ep.open_converted(mapper, chunks=chunks)
26
+
27
+
28
+ def _list_zarr_files_extended(azfs, path):
29
+ """List all Zarr files in the Azure Blob Storage container along with their metadata."""
30
+ zarr_files = []
31
+ for blob in azfs.ls(path, detail=True):
32
+ if blob['type'] == 'directory' and not blob['name'].endswith('.zarr'):
33
+ subdir_files = list_zarr_files(azfs, blob['name'])
34
+ zarr_files.extend(subdir_files)
35
+ else:
36
+ # Calculate the total size and most recent modification date for the .zarr folder
37
+ total_size = 0
38
+ last_modified = None
39
+ for sub_blob in azfs.ls(blob['name'], detail=True):
40
+ if sub_blob['type'] == 'file':
41
+ total_size += sub_blob['size']
42
+ if last_modified is None or sub_blob['last_modified'] > last_modified:
43
+ last_modified = sub_blob['last_modified']
44
+
45
+ zarr_files.append({
46
+ 'Key': blob['name'],
47
+ 'Size': total_size,
48
+ 'LastModified': last_modified
49
+ })
50
+
51
+ return zarr_files
52
+
53
+
54
+
@@ -5,7 +5,6 @@ import time
5
5
  from datetime import datetime
6
6
  from rich import print
7
7
  from pathlib import Path
8
- import psutil
9
8
  from oceanstream.echodata import check_reversed_time, fix_time_reversions
10
9
 
11
10
 
@@ -21,7 +20,7 @@ def read_zarr_files(input_folder):
21
20
  logging.error("Input folder does not exist: %s", input_folder)
22
21
  return
23
22
 
24
- zarr_files = list(input_path.glob("*.zarr"))
23
+ zarr_files = list(input_path.rglob("*.zarr"))
25
24
  if not zarr_files:
26
25
  logging.error("No .zarr files found in directory: %s", input_folder)
27
26
  return
@@ -47,7 +46,7 @@ def fix_time(ed):
47
46
  return ed
48
47
 
49
48
 
50
- def combine_zarr_files(input_folder, zarr_output_file=None, chunks=None, log_level=logging.DEBUG):
49
+ def combine_zarr_files(input_folder, zarr_output_file=None, chunks=None):
51
50
  start_time = time.time()
52
51
 
53
52
  logging.debug("Starting to combine Zarr files from folder: %s", input_folder)
@@ -87,4 +86,4 @@ def from_filename(file_name):
87
86
  creation_time = datetime.strptime(date_str + time_str, '%Y%m%d%H%M%S')
88
87
  return creation_time
89
88
 
90
- return None
89
+ return None
@@ -12,9 +12,9 @@ from rich.traceback import install, Traceback
12
12
  from rich.progress import Progress, TimeElapsedColumn, BarColumn, TextColumn
13
13
 
14
14
  from oceanstream.plot import plot_sv_data_with_progress, plot_sv_data
15
- from oceanstream.echodata import get_campaign_metadata
16
- from .process import compute_sv, process_file_with_progress, read_file_with_progress
15
+ from oceanstream.echodata import get_campaign_metadata, read_file
17
16
 
17
+ from .process import compute_sv, process_file_with_progress, read_file_with_progress
18
18
 
19
19
  install(show_locals=True, width=120)
20
20
 
@@ -23,13 +23,14 @@ def get_chunk_sizes(var_dims, chunk_sizes):
23
23
  return {dim: chunk_sizes[dim] for dim in var_dims if dim in chunk_sizes}
24
24
 
25
25
 
26
- def compute_Sv_to_zarr(echodata, config_data, chunks=None, plot_echogram=False, **kwargs):
26
+ def compute_Sv_to_zarr(echodata, config_data, base_path=None, chunks=None, plot_echogram=False, **kwargs):
27
27
  """
28
28
  Compute Sv from echodata and save to zarr file.
29
29
 
30
30
  Args:
31
31
  echodata:
32
32
  config_data:
33
+ base_path:
33
34
  chunks:
34
35
  plot_echogram:
35
36
  **kwargs:
@@ -37,17 +38,35 @@ def compute_Sv_to_zarr(echodata, config_data, chunks=None, plot_echogram=False,
37
38
  Returns:
38
39
  str: Path to the zarr file.
39
40
  """
40
- file_path = config_data["raw_path"]
41
41
  waveform_mode = kwargs.get("waveform_mode", "CW")
42
42
  encode_mode = waveform_mode == "CW" and "power" or "complex"
43
43
  Sv = compute_sv(echodata, encode_mode=encode_mode, **kwargs)
44
44
 
45
- parent_folder = os.path.join(Path(config_data["output_folder"]), file_path.stem)
46
- if not os.path.exists(parent_folder):
47
- os.makedirs(parent_folder)
48
-
49
- output_path = os.path.join(parent_folder, f"{file_path.stem}_Sv.zarr")
50
-
45
+ if config_data.get('raw_path') is not None:
46
+ file_path = config_data["raw_path"]
47
+ file_base_name = file_path.stem
48
+ if base_path:
49
+ relative_path = file_path.relative_to(base_path)
50
+
51
+ if relative_path.parent != ".":
52
+ zarr_path = Path(relative_path.parent) / file_base_name
53
+ else:
54
+ zarr_path = relative_path.stem
55
+ else:
56
+ zarr_path = file_base_name
57
+
58
+ output_path = Path(config_data["output_folder"]) / zarr_path
59
+ output_path.mkdir(parents=True, exist_ok=True)
60
+
61
+ zarr_file_name = f"{file_base_name}_Sv.zarr"
62
+ else:
63
+ zarr_path = base_path
64
+ zarr_file_name = f"{zarr_path}_Sv.zarr"
65
+ output_path = None
66
+ file_base_name = None
67
+ file_path = None
68
+
69
+ echogram_path = zarr_path
51
70
  if chunks is not None:
52
71
  for var in Sv.data_vars:
53
72
  var_chunk_sizes = get_chunk_sizes(Sv[var].dims, chunks)
@@ -56,14 +75,15 @@ def compute_Sv_to_zarr(echodata, config_data, chunks=None, plot_echogram=False,
56
75
  if 'chunks' in Sv[var].encoding:
57
76
  del Sv[var].encoding['chunks']
58
77
 
59
- print("Removing background noise...")
60
78
  ds_processed = Sv
79
+
61
80
  # ds_processed = apply_background_noise_removal(Sv, config=config_data)
62
- ds_processed.to_zarr(output_path)
81
+ write_zarr_file(zarr_path, zarr_file_name, ds_processed, config_data, output_path)
63
82
 
64
83
  if plot_echogram:
65
84
  try:
66
- plot_sv_data(ds_processed, file_base_name=file_path.stem, output_path=parent_folder)
85
+ plot_sv_data(ds_processed, file_base_name=file_base_name, output_path=output_path,
86
+ echogram_path=echogram_path, config_data=config_data)
67
87
  except Exception as e:
68
88
  logging.exception(f"Error plotting echogram for {file_path}:")
69
89
  raise e
@@ -71,13 +91,22 @@ def compute_Sv_to_zarr(echodata, config_data, chunks=None, plot_echogram=False,
71
91
  return output_path
72
92
 
73
93
 
94
+ def write_zarr_file(zarr_path, zarr_file_name, ds_processed, config_data=None, output_path=None):
95
+ if 'cloud_storage' in config_data:
96
+ store = get_chunk_store(config_data['cloud_storage'], Path(zarr_path) / zarr_file_name)
97
+ else:
98
+ store = os.path.join(output_path, zarr_file_name)
99
+
100
+ ds_processed.to_zarr(store, mode='w')
101
+
102
+
74
103
  async def process_raw_file_with_progress(config_data, plot_echogram, waveform_mode="CW", depth_offset=0):
75
104
  try:
76
105
  with Progress(
77
- TextColumn("[progress.description]{task.description}"),
78
- BarColumn(),
79
- TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
80
- TimeElapsedColumn()
106
+ TextColumn("[progress.description]{task.description}"),
107
+ BarColumn(),
108
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
109
+ TimeElapsedColumn()
81
110
  ) as progress:
82
111
  print(f"[green] Processing file: {config_data['raw_path']}[/green]")
83
112
  read_task = progress.add_task("[cyan]Reading raw file data...", total=100)
@@ -117,14 +146,29 @@ async def process_raw_file_with_progress(config_data, plot_echogram, waveform_mo
117
146
  logging.exception(f"Error processing file {config_data['raw_path']}: {e}")
118
147
 
119
148
 
120
- def convert_raw_file(file_path, config_data, progress_queue=None):
149
+ def convert_raw_file(file_path, config_data, base_path=None, progress_queue=None):
121
150
  logging.debug("Starting processing of file: %s", file_path)
122
- from oceanstream.echodata import read_file
123
151
 
124
152
  try:
125
- file_config_data = {**config_data, 'raw_path': Path(file_path)}
153
+ file_path_obj = Path(file_path)
154
+ file_config_data = {**config_data, 'raw_path': file_path_obj}
155
+
156
+ if base_path:
157
+ relative_path = file_path_obj.relative_to(base_path)
158
+ relative_path = relative_path.parent
159
+ else:
160
+ relative_path = file_path_obj.name
161
+
126
162
  echodata, encode_mode = read_file(file_config_data, use_swap=True, skip_integrity_check=True)
127
- echodata.to_zarr(save_path=config_data["output_folder"], overwrite=True, parallel=False)
163
+
164
+ if 'cloud_storage' in config_data:
165
+ file_name = file_path_obj.stem + ".zarr"
166
+ store = get_chunk_store(config_data['cloud_storage'], Path(relative_path) / file_name)
167
+ echodata.to_zarr(save_path=store, overwrite=True, parallel=False)
168
+ else:
169
+ output_path = Path(config_data["output_folder"]) / relative_path
170
+ output_path.mkdir(parents=True, exist_ok=True)
171
+ echodata.to_zarr(save_path=output_path, overwrite=True, parallel=False)
128
172
 
129
173
  if progress_queue:
130
174
  progress_queue.put(file_path)
@@ -149,3 +193,14 @@ def compute_single_file(config_data, **kwargs):
149
193
  end_time = time.time()
150
194
  total_time = end_time - start_time
151
195
  print(f"Total time taken: {total_time:.2f} seconds")
196
+
197
+
198
+ def get_chunk_store(storage_config, path):
199
+ if storage_config['storage_type'] == 'azure':
200
+ from adlfs import AzureBlobFileSystem
201
+ azfs = AzureBlobFileSystem(**storage_config['storage_options'])
202
+
203
+ return azfs.get_mapper(f"{storage_config['container_name']}/{path}")
204
+
205
+ else:
206
+ raise ValueError(f"Unsupported storage type: {storage_config['storage_type']}")
@@ -7,6 +7,7 @@ import sys
7
7
  import traceback
8
8
  import warnings
9
9
 
10
+ from dask import delayed, compute
10
11
  from pathlib import Path
11
12
  from datetime import datetime
12
13
  from rich import print
@@ -21,8 +22,10 @@ from .process import compute_sv
21
22
  from .processed_data_io import write_processed
22
23
  from .file_processor import convert_raw_file, compute_single_file
23
24
 
24
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
25
+ # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
25
26
  warnings.filterwarnings("ignore", module="echopype")
27
+ warnings.filterwarnings("ignore", category=UserWarning)
28
+ warnings.filterwarnings("ignore", category=FutureWarning)
26
29
  pool = None
27
30
 
28
31
 
@@ -123,6 +126,15 @@ def signal_handler(sig, frame):
123
126
  sys.exit(0)
124
127
 
125
128
 
129
+ def find_raw_files(base_dir):
130
+ raw_files = []
131
+ for root, dirs, files in os.walk(base_dir):
132
+ for file in files:
133
+ if file.endswith('.raw'):
134
+ raw_files.append(os.path.join(root, file))
135
+ return raw_files
136
+
137
+
126
138
  def convert_raw_files(config_data, workers_count=os.cpu_count()):
127
139
  global pool
128
140
 
@@ -132,8 +144,7 @@ def convert_raw_files(config_data, workers_count=os.cpu_count()):
132
144
  configure_logging(log_level)
133
145
 
134
146
  print(f"Starting to convert folder: {dir_path} to Zarr using {workers_count} parallel processes...")
135
- raw_files = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if
136
- os.path.isfile(os.path.join(dir_path, f)) and f.endswith('.raw')]
147
+ raw_files = find_raw_files(dir_path)
137
148
  file_info = []
138
149
 
139
150
  if not raw_files:
@@ -166,7 +177,8 @@ def convert_raw_files(config_data, workers_count=os.cpu_count()):
166
177
  pool = Pool(processes=workers_count)
167
178
 
168
179
  # Partial function with config_data, progress_queue and other arguments
169
- process_func = partial(convert_raw_file, config_data=config_data, progress_queue=progress_queue)
180
+ process_func = partial(convert_raw_file, config_data=config_data, progress_queue=progress_queue,
181
+ base_path=dir_path)
170
182
 
171
183
  # Run the progress updater in a separate process
172
184
  progress_updater = Process(target=update_progress, args=(progress_queue, len(sorted_files), log_level))
@@ -192,14 +204,25 @@ def convert_raw_files(config_data, workers_count=os.cpu_count()):
192
204
  logging.exception("Error processing folder %s: %s", config_data['raw_path'], e)
193
205
 
194
206
 
195
- def process_single_zarr_file(file_path, config_data, chunks=None, plot_echogram=False, waveform_mode="CW",
196
- depth_offset=0):
207
+ def process_single_zarr_file(file_path, config_data, base_path=None, chunks=None, plot_echogram=False, waveform_mode="CW",
208
+ depth_offset=0, total_files=1, processed_count_var=None):
197
209
  file_config_data = {**config_data, 'raw_path': Path(file_path)}
198
- compute_single_file(file_config_data, chunks=chunks, plot_echogram=plot_echogram,
210
+
211
+ processed_count = None
212
+
213
+ if processed_count_var:
214
+ processed_count = processed_count_var.get() + 1
215
+ processed_count_var.set(processed_count)
216
+
217
+ compute_single_file(file_config_data, base_path=base_path, chunks=chunks, plot_echogram=plot_echogram,
199
218
  waveform_mode=waveform_mode, depth_offset=depth_offset)
200
219
 
220
+ if processed_count:
221
+ print(f"Processed file: {file_path}. {processed_count}/{total_files}")
222
+
201
223
 
202
- def process_zarr_files(config_data, workers_count=os.cpu_count(), status=None, chunks=None, plot_echogram=False,
224
+ def process_zarr_files(config_data, workers_count=os.cpu_count(), status=None, chunks=None, processed_count_var=None,
225
+ plot_echogram=False,
203
226
  waveform_mode="CW", depth_offset=0):
204
227
  dir_path = config_data['raw_path']
205
228
  zarr_files = read_zarr_files(dir_path)
@@ -208,24 +231,26 @@ def process_zarr_files(config_data, workers_count=os.cpu_count(), status=None, c
208
231
  logging.error("No valid .zarr files with creation time found in directory: %s", dir_path)
209
232
  return
210
233
 
211
- logging.info(f"Found {len(zarr_files)} Zarr files in directory: {dir_path}")
212
-
213
- # def wrapped_process_single_zarr_file(file_path):
214
- # print(f"Computing Sv for {file_path}...\n")
215
- # return process_single_zarr_file(file_path, config_data,
216
- # chunks=chunks, plot_echogram=plot_echogram, waveform_mode=waveform_mode,
217
- # depth_offset=depth_offset)
218
- #
219
- # # Use Dask bag to parallelize the processing
220
- # bag = db.from_sequence(zarr_files, npartitions=workers_count)
221
- # bag = bag.map(wrapped_process_single_zarr_file)
222
- #
223
- # # Compute the results
224
- # results = bag.compute()
234
+ if status:
235
+ status.update(f"Found {len(zarr_files)} Zarr files in directory: {dir_path}\n")
236
+
237
+ tasks = []
238
+ total_files = len(zarr_files)
239
+
240
+ if processed_count_var:
241
+ processed_count_var.set(0)
242
+
225
243
  for file_path in zarr_files:
226
- status.update(f"Computing Sv for {file_path}...\n")
227
- process_single_zarr_file(file_path, config_data, chunks=chunks, plot_echogram=plot_echogram,
228
- waveform_mode=waveform_mode, depth_offset=depth_offset)
244
+ if status:
245
+ status.update(f"Computing Sv for {file_path}...\n")
246
+ task = delayed(process_single_zarr_file)(file_path, config_data, chunks=chunks, base_path=dir_path,
247
+ plot_echogram=plot_echogram,
248
+ waveform_mode=waveform_mode, depth_offset=depth_offset,
249
+ total_files=total_files, processed_count_var=processed_count_var)
250
+ tasks.append(task)
251
+
252
+ # Execute all tasks in parallel
253
+ compute(*tasks)
229
254
 
230
255
  logging.info("✅ All files have been processed")
231
256
 
@@ -243,4 +268,5 @@ def from_filename(file_name):
243
268
  return None
244
269
 
245
270
 
271
+
246
272
  signal.signal(signal.SIGINT, signal_handler)
@@ -0,0 +1,159 @@
1
+ from pathlib import Path
2
+ from rich.console import Console
3
+ from rich.table import Table
4
+ from rich import box
5
+ import pandas as pd
6
+ from IPython.display import display, HTML
7
+ import re
8
+ from datetime import datetime, timedelta
9
+
10
+
11
+ split_by_day_pattern = r'D(\d{8})-T(\d{6})'
12
+
13
+
14
+ def extract_timestamp_from_filename(file_name):
15
+ """Extract creation time from the file name if it follows a specific pattern."""
16
+ pattern = r'(\d{4}[A-Z])?-D(\d{8})-T(\d{6})'
17
+ match = re.search(pattern, file_name)
18
+ if match:
19
+ date_str = match.group(2)
20
+ time_str = match.group(3)
21
+ creation_time = datetime.strptime(date_str + time_str, '%Y%m%d%H%M%S')
22
+ return creation_time
23
+
24
+ return None
25
+
26
+
27
+ def extract_timestamp_str(filename):
28
+ """Extract timestamp from the filename."""
29
+ match = re.search(r'D(\d{8})-T(\d{6})', filename)
30
+ if match:
31
+ date_str, time_str = match.groups()
32
+ return f"{date_str}T{time_str}"
33
+ return None
34
+
35
+
36
+ def parse_filename(filename):
37
+ """Parse the date and time from the filename."""
38
+ match = re.search(r'D(\d{8})-T(\d{6})', filename)
39
+ if match:
40
+ date_str, time_str = match.groups()
41
+ return datetime.strptime(f"{date_str} {time_str}", "%Y%m%d %H%M%S")
42
+ return None
43
+
44
+
45
+ def sort_raw_files(raw_files):
46
+ return sorted(raw_files, key=lambda x: extract_timestamp_str(Path(x).stem))
47
+
48
+
49
+ def group_files_by_day(files, extract_filename_from_object=lambda x: x['Key']):
50
+ """Group files by day based on the parsed date from the filename."""
51
+ files_by_day = {}
52
+ for file in files:
53
+ date_str, _ = re.search(split_by_day_pattern, extract_filename_from_object(file)).groups()
54
+ day = date_str
55
+ if day not in files_by_day:
56
+ files_by_day[day] = []
57
+ files_by_day[day].append(file)
58
+
59
+ for day in files_by_day:
60
+ files_by_day[day] = sorted(files_by_day[day], key=lambda x: parse_filename(x['Key']))
61
+
62
+ return files_by_day
63
+
64
+
65
+ def _print_survey_summary(files_by_day):
66
+ """Print summary of files by day."""
67
+ print("Summary of files by day:")
68
+ for day, files in files_by_day.items():
69
+ print(f"Day: {day}, Number of files: {len(files)}")
70
+ print(f"Total number of days: {len(files_by_day)}")
71
+
72
+
73
+ def print_survey_summary(files_by_day, show_in_terminal=True, show_in_notebook=False, show_file_size=False):
74
+ """Print summary of files by day in terminal and Jupyter notebook."""
75
+ # Calculate statistics
76
+ statistics = calculate_survey_statistics(files_by_day)
77
+
78
+ if show_in_terminal:
79
+ # Create a summary using rich for terminal display
80
+ console = Console()
81
+ table = Table(title="Survey Summary", box=box.ROUNDED, show_header=True, header_style="bold magenta")
82
+
83
+ # Add columns to the table
84
+ table.add_column("Day", justify="center")
85
+ table.add_column("Number of Files", justify="center")
86
+ table.add_column("Total Recorded Time (HH:MM:SS)", justify="center")
87
+ if show_file_size:
88
+ table.add_column("Average File Size (MB)", justify="center")
89
+
90
+ # Add rows to the table
91
+ for day, stats in statistics.items():
92
+ row = [
93
+ datetime.strptime(day, "%Y%m%d").strftime("%b %d, %Y"),
94
+ str(stats["Number of Files"]),
95
+ stats["Total Recorded Time"]
96
+ ]
97
+ if show_file_size:
98
+ row.append(str(stats["Average File Size (MB)"]))
99
+ table.add_row(*row)
100
+
101
+ # Display the table in the terminal
102
+ console.print(table)
103
+
104
+ if show_in_notebook:
105
+ # Create a summary using pandas for Jupyter notebook display
106
+ df = pd.DataFrame.from_dict(statistics, orient='index')
107
+ df.index = pd.to_datetime(df.index, format='%Y%m%d').strftime('%b %d, %Y')
108
+
109
+ if not show_file_size:
110
+ df = df.drop(columns=["Average File Size (MB)"])
111
+
112
+ display(HTML("<h2>Survey Summary</h2>"))
113
+ display(df.style.set_table_styles(
114
+ [{
115
+ 'selector': 'thead th',
116
+ 'props': [('background-color', 'magenta'), ('color', 'white'), ('font-weight', 'bold')]
117
+ }, {
118
+ 'selector': 'tbody td',
119
+ 'props': [('border', '1px solid black')]
120
+ }, {
121
+ 'selector': 'table',
122
+ 'props': [('border-collapse', 'collapse'), ('width', '100%')]
123
+ }]
124
+ ).set_properties(**{'text-align': 'center'}))
125
+
126
+
127
+ def calculate_survey_statistics(files_by_day):
128
+ """Calculate the total recorded time and average file size per day."""
129
+ statistics = {}
130
+ for day, files in files_by_day.items():
131
+ total_time = timedelta()
132
+ previous_time = None
133
+ total_size = sum(file['Size'] for file in files)
134
+ avg_size = total_size / len(files) if files else 0
135
+
136
+ for file in files:
137
+ current_time = parse_filename(file['Key'])
138
+ if previous_time:
139
+ time_diff = current_time - previous_time
140
+ if time_diff > timedelta(minutes=10): # More than 10 minutes indicates a stop
141
+ total_time += timedelta(minutes=10)
142
+ else:
143
+ total_time += time_diff
144
+ previous_time = current_time
145
+
146
+ statistics[day] = {
147
+ "Number of Files": len(files),
148
+ "Total Recorded Time": format_duration(total_time),
149
+ "Average File Size (MB)": round(avg_size / (1024 * 1024), 2)
150
+ }
151
+ return statistics
152
+
153
+
154
+ def format_duration(duration):
155
+ """Format a timedelta duration as HH:MM:SS."""
156
+ total_seconds = int(duration.total_seconds())
157
+ hours, remainder = divmod(total_seconds, 3600)
158
+ minutes, seconds = divmod(remainder, 60)
159
+ return f"{hours:02}:{minutes:02}:{seconds:02}"
@@ -111,8 +111,8 @@
111
111
  },
112
112
  "profile": false,
113
113
  "base_chunk_sizes": {
114
- "ping_time": 50,
115
- "range_sample": 50
114
+ "ping_time": 100,
115
+ "range_sample": 100
116
116
  },
117
117
  "sonar_model": null,
118
118
  "output_folder": "output",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: oceanstream
3
- Version: 0.0.8.dev0
3
+ Version: 0.0.12.dev0
4
4
  Summary: OceanStream: process raw sonar data at scale
5
5
  Home-page: https://oceanstream.io
6
6
  Author: Pineview Labs
@@ -9,27 +9,27 @@ Maintainer: Andrei Rusu
9
9
  Maintainer-email: hello@pineview.io
10
10
  License: MIT
11
11
  Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
12
13
  Classifier: Programming Language :: Python :: 3.11
13
14
  Classifier: License :: OSI Approved :: MIT License
14
15
  Classifier: Operating System :: OS Independent
15
- Requires-Python: >=3.11
16
+ Requires-Python: >=3.10
16
17
  Description-Content-Type: text/markdown
17
18
  License-File: LICENSE
18
19
  Requires-Dist: dask[array,distributed] ==2024.5.2
19
20
  Requires-Dist: xarray
20
21
  Requires-Dist: numpy
22
+ Requires-Dist: pydantic
23
+ Requires-Dist: rich
24
+ Requires-Dist: tqdm
21
25
  Provides-Extra: cli
22
26
  Requires-Dist: typer ; extra == 'cli'
23
- Requires-Dist: rich ; extra == 'cli'
24
27
  Provides-Extra: complete
25
28
  Requires-Dist: typer ; extra == 'complete'
26
- Requires-Dist: rich ; extra == 'complete'
27
- Requires-Dist: pydantic ; extra == 'complete'
28
29
  Requires-Dist: matplotlib ; extra == 'complete'
29
30
  Requires-Dist: cmocean ; extra == 'complete'
30
31
  Provides-Extra: denoise
31
32
  Provides-Extra: echodata
32
- Requires-Dist: pydantic ; extra == 'echodata'
33
33
  Provides-Extra: exports
34
34
  Provides-Extra: plot
35
35
  Requires-Dist: matplotlib ; extra == 'plot'
@@ -1,9 +1,9 @@
1
- oceanstream/__init__.py,sha256=sFoir3TVQ0vEEaVV3H9xVHDI16sz-3T-Ldf4dKhbi0Y,132
2
- oceanstream/core.py,sha256=__4u1UsLutOYUB0kILapErEOam4N5aMiI4C17lvUJp4,5537
1
+ oceanstream/__init__.py,sha256=iaizEL-rGMSKdbGtsvdzfPsoaX5luJlzRRkg7zrQI9Y,165
2
+ oceanstream/core.py,sha256=kJ9Yuga3-GXrtXwc3JLVPe4kpTGCGQFsKQf6is2ikiU,6473
3
3
  oceanstream/utils.py,sha256=meViPVwoDEmKA5zM5v226JyKjUMkOaj5ENGCpfipdv4,3127
4
4
  oceanstream/cli/__init__.py,sha256=3cNr7Lft68oxlCiyflezy6dzuw4HEd5mvMZkSzNujWE,51
5
- oceanstream/cli/main.py,sha256=T4JFFs7ngWNgEDsYlDb_u0XXfk_rmA22Tf31ewvufUU,11450
6
- oceanstream/cli/requirements.txt,sha256=Ui83FHUAHe6Ir7De-fN5CXnsTdZn5o3gVYKtblpcWME,10
5
+ oceanstream/cli/main.py,sha256=c8CVIKKFpDn7a55-QyvD8GvexZT5HcponvwV6jO8E9I,12157
6
+ oceanstream/cli/requirements.txt,sha256=GctO0dkeETliruimS7jJEf92lGUoAihDUV-IbeJmVSY,5
7
7
  oceanstream/denoise/__init__.py,sha256=K8j5OCDJlGmjqQPuQidO77J289Z17hSsslIitUJnGpo,133
8
8
  oceanstream/denoise/apply_masks.py,sha256=zWqYW0qANbPOPG5m6UDGbvN2dqUikzLZB_5G-ZVyY_g,1425
9
9
  oceanstream/denoise/applying_masks_handler.py,sha256=VP2R_vBiQmcnUaCxLUh7Txv3bbh9bT1aK6okLRMNklU,5880
@@ -16,9 +16,9 @@ oceanstream/echodata/__init__.py,sha256=WGIEXQxemdP5s26ldlzqixVfFPyxn90Z1Tt0V7yP
16
16
  oceanstream/echodata/ensure_time_continuity.py,sha256=QL3xvwCsGSi04iACeIOYYxFUrp-vdBcv8wdjbBc8YYo,2506
17
17
  oceanstream/echodata/mvbs_computation.py,sha256=7ILXIPMQ7Mf-jNx9SDWqjNbI_9Qbs8lzE_TTXo2RW70,3150
18
18
  oceanstream/echodata/raw_handler.py,sha256=tgXqvRBebphzSR3qkjNaWwMcYPozcwuIHd-__1v9rqU,19311
19
- oceanstream/echodata/requirements.txt,sha256=cmo_5n0F_YY5td5nPZBfdjBENkmGg_pE5ShWXYbXxTM,9
19
+ oceanstream/echodata/requirements.txt,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
20
  oceanstream/echodata/sv_computation.py,sha256=OvmgnLV1akx2pqnANNnQzX5olpY0smo3EeoD19hn4lM,3603
21
- oceanstream/echodata/sv_dataset_extension.py,sha256=Hmu0vZDIql11FOc_sx_QVoRq_J7HyPzMPiuRgjrzL0I,4382
21
+ oceanstream/echodata/sv_dataset_extension.py,sha256=JpAnL4CODRCQU4ZTGPAjFDDJlTobTfBKkcYYhJCiJe4,4277
22
22
  oceanstream/echodata/sv_interpolation.py,sha256=nvhtBKlIVT_77aDl7BrU0PC6ZYwhhQpVErXCyPrdoBM,11405
23
23
  oceanstream/echodata/target_strength_computation.py,sha256=vIlSOf3dvvfmwlsv4xw-E1FVjDBDkWz3P3Vv1bYyagM,3272
24
24
  oceanstream/exports/__init__.py,sha256=5BrGFSzGKatg_0TtBFzSAGDd5TdleKYCiJxIpsVNalg,103
@@ -33,21 +33,27 @@ oceanstream/exports/shoals/shoal_detection_handler.py,sha256=aqUanU2lyF6lDu3meCt
33
33
  oceanstream/exports/shoals/shoal_process.py,sha256=yTDU4qeZ7DraEsoXEvOVDaqANh2hWax7WwX0Ok-x2Kg,6892
34
34
  oceanstream/exports/shoals/shoals_handler.py,sha256=UB48tQz0IPGEM9K4XYV5X6x7awdubYB_ExULXSgyMu0,1039
35
35
  oceanstream/plot/__init__.py,sha256=HFu67GwAxdm0nOS2IUbGgeF8gZ4MKvP0vH6eJDGu1PU,136
36
- oceanstream/plot/echogram.py,sha256=REeWWiXbpsWkWArDQd7FUr1ISS42b0sUTHd-NWxFENM,22016
36
+ oceanstream/plot/echogram.py,sha256=1UBt3L8P8NxK-YqqQOEwXIE0dPxBTjRNYnCZ2OFpdeo,23430
37
37
  oceanstream/plot/requirements.txt,sha256=CKWyfMfq42Innw74FAz4RvWV2zBcG0qOnN6DN6Whk8c,19
38
38
  oceanstream/process/__init__.py,sha256=3JgO18BS5z3w2Mh7Y3IcmTCytqqEJZiSlZBnJrUZ8ZE,753
39
- oceanstream/process/combine_zarr.py,sha256=F_ZA5twGIHd6z7dv_wHsfaCsIZbAtSEY4kYBx1WzoP4,2791
40
- oceanstream/process/file_processor.py,sha256=8GVHLOqOSvu9TIRFR47G3wsf75wxd2AIZ8YbZ6Vjp1g,6186
41
- oceanstream/process/folder_processor.py,sha256=QAujhDR393T2mstG5BaBsr2EzUAiwMGe0Rh7urT7SDI,9824
39
+ oceanstream/process/combine_zarr.py,sha256=B11r56xBUBXwFcDmyDHI1qVXWp8ZnSGWQrMdyG50cec,2754
40
+ oceanstream/process/file_processor.py,sha256=6URtJYYI7BUpOf38ilhom3O6S5yiRx2HmVbpdIyv1m4,8237
41
+ oceanstream/process/folder_processor.py,sha256=m8IoLseD98fAwpw6vUkMIhecN0t2Qm1M0W0UUOUCHWU,10403
42
42
  oceanstream/process/process.py,sha256=jK5a5AVQJnODEcDSZi_oYuOpljBl3vewxEsyK_OLSgY,2263
43
43
  oceanstream/process/processed_data_io.py,sha256=aDKhh0-9kwgccjRIUS4D4GHkkRAyUyWgMSq1L13U4w4,4663
44
44
  oceanstream/process/requirements.txt,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
45
+ oceanstream/process/utils.py,sha256=IThB7A__YUXeCjbYx1wI-RitWJrU7vysWZj2bndz0Ts,5734
46
+ oceanstream/process/aws/__init__.py,sha256=Hr0eB1aSkrMoRSQQsZ2lUB6aJCvA1anObhDt4Q3_qCE,305
47
+ oceanstream/process/aws/s3.py,sha256=-Am0IhTw5mLaaGqBIji8fzBOcKlVuSJmUp0RUOPCT1g,3055
48
+ oceanstream/process/azure/__init__.py,sha256=HDkLwTa9pdqeIMCwfNNj-_-DRQOFWst6tL0bQvOMzbM,230
49
+ oceanstream/process/azure/azure_processor.py,sha256=KbZIIJ10Q_7Ym-GqaC03B0d-wRbg8Rkh-WYUDw1lG_Y,2265
50
+ oceanstream/process/azure/blob_storage.py,sha256=tiUM_T2ZTbPcrNEFzEDZAVpbfsNyJLLkaW07RDsMd6c,1970
45
51
  oceanstream/settings/__init__.py,sha256=Uh8oeGPgpLuLpEAv0ygUBOQAuQj0wG4f1Tj2zIqoIy4,32
46
52
  oceanstream/settings/config.py,sha256=koIVrrbvPVz7TFPNKutPoxcXtbVrH5EFDVgESPyhE80,479
47
- oceanstream/settings/defaults.config.json,sha256=U4WLeOl4Nx1etFvyTr2-shwta8rikweD8PphtRVW-yw,1984
48
- oceanstream-0.0.8.dev0.dist-info/LICENSE,sha256=-5V4voa5xg_L9IVdMD881urt9gjA-k4rWk9Wew3uyf0,1078
49
- oceanstream-0.0.8.dev0.dist-info/METADATA,sha256=vp0O0g1c8Euf5IA16xeUseVWuKqVNUAyibwqPtdUHm0,5087
50
- oceanstream-0.0.8.dev0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
51
- oceanstream-0.0.8.dev0.dist-info/entry_points.txt,sha256=7NApSbVm7X53EC54ryz6q3zvyAF7aVAEL8IGLfJeOAU,58
52
- oceanstream-0.0.8.dev0.dist-info/top_level.txt,sha256=rdOKWkpJy5DPBPPhjwxtclDVTea-S38kiQeIqoFcINs,12
53
- oceanstream-0.0.8.dev0.dist-info/RECORD,,
53
+ oceanstream/settings/defaults.config.json,sha256=wXAlYUb8QSOGldkR45nvmaMGwftZWQvm_f7xKZVSEaw,1986
54
+ oceanstream-0.0.12.dev0.dist-info/LICENSE,sha256=-5V4voa5xg_L9IVdMD881urt9gjA-k4rWk9Wew3uyf0,1078
55
+ oceanstream-0.0.12.dev0.dist-info/METADATA,sha256=BlGASaoRJbOmxL9ksadsajHJKQrWJ4WBG1eOtu-bUGk,5032
56
+ oceanstream-0.0.12.dev0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
57
+ oceanstream-0.0.12.dev0.dist-info/entry_points.txt,sha256=7NApSbVm7X53EC54ryz6q3zvyAF7aVAEL8IGLfJeOAU,58
58
+ oceanstream-0.0.12.dev0.dist-info/top_level.txt,sha256=rdOKWkpJy5DPBPPhjwxtclDVTea-S38kiQeIqoFcINs,12
59
+ oceanstream-0.0.12.dev0.dist-info/RECORD,,