simulok 0.1.0__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,476 @@
1
+
2
+ """Utilities for preparing acoustic signals for simulation."""
3
+
4
+ import math
5
+ import numpy as np
6
+ import warnings
7
+ import copy
8
+ import os
9
+ import re
10
+ import shutil
11
+ import tempfile
12
+ from pathlib import Path
13
+ from math import gcd
14
+ from scipy.signal import resample_poly
15
+
16
+ import soundfile as sf
17
+
18
+ from simulok.call import Call
19
+ from simulok.call_catalog import SCHEMA_VERSION, CallCatalog
20
+
21
+
22
+ def resample_audio(audio, source_rate, target_rate):
23
+ """Resample a mono signal using polyphase filtering.
24
+
25
+ Returns a float64 array without modifying the input.
26
+ """
27
+ audio = np.asarray(audio, dtype=np.float64)
28
+
29
+ if audio.ndim != 1 or audio.size == 0:
30
+ raise ValueError("Audio must be a nonempty mono signal")
31
+ if not np.isfinite(audio).all():
32
+ raise ValueError("Audio must contain only finite samples")
33
+
34
+ for name, rate in (
35
+ ("source_rate", source_rate),
36
+ ("target_rate", target_rate),
37
+ ):
38
+ if isinstance(rate, (bool, np.bool_)) or not isinstance(
39
+ rate, (int, np.integer)
40
+ ) or rate <= 0:
41
+ raise ValueError(f"{name} must be a positive integer")
42
+
43
+ if source_rate == target_rate:
44
+ return audio.copy()
45
+
46
+ common_divisor = gcd(int(source_rate), int(target_rate))
47
+ up = int(target_rate) // common_divisor
48
+ down = int(source_rate) // common_divisor
49
+
50
+ return resample_poly(audio, up, down)
51
+
52
+
53
+ def calculate_rms(audio, sample_rate=None, active_intervals=None):
54
+ """Calculate global RMS or RMS over the union of active intervals.
55
+
56
+ Intervals are expressed in seconds relative to the signal start.
57
+ Missing or empty intervals result in global RMS.
58
+ """
59
+ audio = np.asarray(audio, dtype=np.float64)
60
+
61
+ if audio.ndim != 1 or audio.size == 0:
62
+ raise ValueError("Audio must be a nonempty mono signal")
63
+ if not np.isfinite(audio).all():
64
+ raise ValueError("Audio must contain only finite samples")
65
+
66
+ if active_intervals:
67
+ if isinstance(sample_rate, (bool, np.bool_)) or not isinstance(
68
+ sample_rate, (int, np.integer)
69
+ ) or sample_rate <= 0:
70
+ raise ValueError("A positive integer sample_rate is required")
71
+
72
+ duration = audio.size / sample_rate
73
+ mask = np.zeros(audio.size, dtype=bool)
74
+
75
+ for start, end in active_intervals:
76
+ if (
77
+ not math.isfinite(start)
78
+ or not math.isfinite(end)
79
+ or start < 0
80
+ or start >= end
81
+ or end > duration
82
+ ):
83
+ raise ValueError("Invalid active interval")
84
+
85
+ # Select samples whose timestamps lie within [start, end).
86
+ first = math.ceil(start * sample_rate)
87
+ last = math.ceil(end * sample_rate)
88
+ mask[first:last] = True
89
+
90
+ if not mask.any():
91
+ raise ValueError("Active intervals contain no audio samples")
92
+
93
+ audio = audio[mask]
94
+
95
+ return float(np.sqrt(np.mean(np.square(audio))))
96
+
97
+
98
+ def calculate_peak(audio):
99
+ """Calculate the maximum absolute amplitude of a mono signal."""
100
+ audio = np.asarray(audio, dtype=np.float64)
101
+
102
+ if audio.ndim != 1 or audio.size == 0:
103
+ raise ValueError("Audio must be a nonempty mono signal")
104
+ if not np.isfinite(audio).all():
105
+ raise ValueError("Audio must contain only finite samples")
106
+
107
+ return float(np.max(np.abs(audio)))
108
+
109
+
110
+
111
+ def calculate_target_level(
112
+ levels, strategy="fixed", target_level=0.1
113
+ ):
114
+ """Determine the target amplitude from measured signal levels."""
115
+ valid_strategies = {"fixed", "mean", "median", "p95"}
116
+
117
+ if strategy not in valid_strategies:
118
+ raise ValueError(f"Invalid target strategy: {strategy}")
119
+
120
+ if strategy == "fixed":
121
+ if (
122
+ isinstance(target_level, (bool, np.bool_))
123
+ or not isinstance(target_level, (int, float, np.number))
124
+ or not np.isfinite(target_level)
125
+ or target_level <= 0
126
+ ):
127
+ raise ValueError("target_level must be positive and finite")
128
+ return float(target_level)
129
+
130
+ levels = np.asarray(levels, dtype=np.float64)
131
+
132
+ if levels.ndim != 1 or levels.size == 0:
133
+ raise ValueError("Levels must be a nonempty 1D array")
134
+
135
+ if not np.isfinite(levels).all() or np.any(levels <= 0):
136
+ raise ValueError("All levels must be positive and finite")
137
+
138
+ if strategy == "mean":
139
+ return float(np.mean(levels))
140
+ if strategy == "median":
141
+ return float(np.median(levels))
142
+
143
+ return float(np.percentile(levels, 95))
144
+
145
+
146
+ def normalize_audio(audio, original_level, target_level):
147
+ """Scale a mono signal to a target amplitude level.
148
+
149
+ Returns the normalized float64 audio and the applied scale factor.
150
+ No clipping or limiting is performed.
151
+ """
152
+ audio = np.asarray(audio, dtype=np.float64)
153
+
154
+ if audio.ndim != 1 or audio.size == 0:
155
+ raise ValueError("Audio must be a nonempty mono signal")
156
+ if not np.isfinite(audio).all():
157
+ raise ValueError("Audio must contain only finite samples")
158
+
159
+ for name, level in (
160
+ ("original_level", original_level),
161
+ ("target_level", target_level),
162
+ ):
163
+ if (
164
+ isinstance(level, (bool, np.bool_))
165
+ or not isinstance(level, (int, float, np.number))
166
+ or not np.isfinite(level)
167
+ or level <= 0
168
+ ):
169
+ raise ValueError(f"{name} must be positive and finite")
170
+
171
+ factor = float(target_level / original_level)
172
+ normalized = audio * factor
173
+
174
+ if not np.isfinite(factor) or not np.isfinite(normalized).all():
175
+ raise ValueError("Normalization produced non-finite values")
176
+
177
+ return normalized, factor
178
+
179
+
180
+
181
+
182
+ def prepare_catalog(
183
+ catalog,
184
+ output_dir,
185
+ catalog_id,
186
+ sample_rate=192000,
187
+ normalization="active_rms",
188
+ target_strategy="fixed",
189
+ target_level=0.1,
190
+ ):
191
+ """Create a persistent, reusable catalog of prepared mono WAV files.
192
+
193
+ Process one vocalization at a time. Statistical target strategies use
194
+ a measurement pass followed by a processing and persistence pass.
195
+
196
+ The source catalog remains unchanged. Results are published only
197
+ after successful validation and finalization.
198
+ """
199
+ if not isinstance(catalog, CallCatalog):
200
+ raise TypeError("catalog must be a CallCatalog")
201
+
202
+ if catalog.catalog_type != "original":
203
+ raise ValueError("Input catalog must be original")
204
+
205
+ if catalog.status != "finalized" or catalog.schema_version not in (1, SCHEMA_VERSION):
206
+ raise ValueError("Input catalog must be a finalized schema-v1 or schema-v2 catalog")
207
+
208
+ if normalization not in {"active_rms", "global_rms", "peak"}:
209
+ raise ValueError(f"Invalid normalization method: {normalization}")
210
+
211
+ call_ids = catalog.list_calls()
212
+ if not call_ids:
213
+ raise ValueError("Cannot prepare an empty catalog")
214
+
215
+ destination = Path(output_dir).resolve()
216
+
217
+ if destination.exists():
218
+ raise FileExistsError(f"Output catalog already exists: {destination}")
219
+
220
+ if destination.is_relative_to(catalog.catalog_path):
221
+ raise ValueError("Output catalog cannot be inside the source catalog")
222
+
223
+ catalog.validate()
224
+
225
+ def load_and_measure(call):
226
+ """Load, resample, and measure one vocalization."""
227
+ audio, source_rate = call.load_audio()
228
+ audio = resample_audio(audio, source_rate, sample_rate)
229
+
230
+ method = normalization
231
+ if method == "active_rms" and not call.active_intervals:
232
+ method = "global_rms"
233
+
234
+ if method == "active_rms":
235
+ level = calculate_rms(
236
+ audio, sample_rate, call.active_intervals
237
+ )
238
+ elif method == "global_rms":
239
+ level = calculate_rms(audio)
240
+ else:
241
+ level = calculate_peak(audio)
242
+
243
+ if not np.isfinite(level) or level <= 0:
244
+ raise ValueError(
245
+ f"{call.call_id}: measured amplitude must be positive"
246
+ )
247
+
248
+ return audio, source_rate, method, level
249
+
250
+ def safe_name(value):
251
+ """Create a portable filename component from catalog metadata."""
252
+ component = re.sub(
253
+ r"[^A-Za-z0-9_-]+", "_", str(value)
254
+ ).strip("_-")
255
+ return component or "unknown"
256
+
257
+ # Statistical strategies require a preliminary measurement pass.
258
+ if target_strategy == "fixed":
259
+ target = calculate_target_level(
260
+ [], strategy="fixed", target_level=target_level
261
+ )
262
+ else:
263
+ levels = []
264
+ for call_id in call_ids:
265
+ call = catalog.get_call(call_id)
266
+ audio, _, _, level = load_and_measure(call)
267
+ levels.append(level)
268
+ del audio
269
+
270
+ target = calculate_target_level(
271
+ levels,
272
+ strategy=target_strategy,
273
+ target_level=target_level,
274
+ )
275
+
276
+ destination.parent.mkdir(parents=True, exist_ok=True)
277
+
278
+ staging = Path(
279
+ tempfile.mkdtemp(
280
+ prefix=f".{destination.name}.tmp-",
281
+ dir=destination.parent,
282
+ )
283
+ )
284
+
285
+ published = False
286
+
287
+ try:
288
+ source_reference = {
289
+ "catalog_id": catalog.catalog_id,
290
+ "relative_path": Path(
291
+ os.path.relpath(catalog.catalog_path, destination)
292
+ ).as_posix(),
293
+ }
294
+
295
+ preparation_config = {
296
+ "sample_rate": int(sample_rate),
297
+ "normalization": normalization,
298
+ "target_strategy": target_strategy,
299
+ "target_level": float(target),
300
+ }
301
+
302
+ prepared = CallCatalog(
303
+ catalog_id=catalog_id,
304
+ catalog_path=staging,
305
+ catalog_type="prepared",
306
+ source_catalog=source_reference,
307
+ preparation_config=preparation_config,
308
+ )
309
+
310
+ work_dir = staging / ".work"
311
+ work_dir.mkdir()
312
+
313
+ counters = {}
314
+ filenames = set()
315
+ filenames_by_call = {}
316
+
317
+ for call_id in call_ids:
318
+ call = catalog.get_call(call_id)
319
+
320
+ audio, source_rate, method, level = load_and_measure(call)
321
+
322
+ if normalization == "active_rms" and method == "global_rms":
323
+ warnings.warn(
324
+ f"{call_id}: no active intervals; using global RMS",
325
+ RuntimeWarning,
326
+ stacklevel=2,
327
+ )
328
+
329
+ if level < 1e-6:
330
+ warnings.warn(
331
+ f"{call_id}: very low amplitude ({level:.3e})",
332
+ RuntimeWarning,
333
+ stacklevel=2,
334
+ )
335
+
336
+ normalized, factor = normalize_audio(
337
+ audio,
338
+ original_level=level,
339
+ target_level=target,
340
+ )
341
+
342
+ normalized = normalized.astype(np.float32)
343
+
344
+ if not np.isfinite(normalized).all():
345
+ raise ValueError(
346
+ f"{call_id}: float32 conversion produced non-finite values"
347
+ )
348
+
349
+ if calculate_peak(normalized) > 1:
350
+ warnings.warn(
351
+ f"{call_id}: normalized peak exceeds 1",
352
+ RuntimeWarning,
353
+ stacklevel=2,
354
+ )
355
+
356
+ identity_key = (call.species, call.individual_id)
357
+ counters[identity_key] = counters.get(identity_key, 0) + 1
358
+
359
+ filename = (
360
+ f"{safe_name(call.species)}_"
361
+ f"{safe_name(call.individual_id)}_"
362
+ f"call{counters[identity_key]:03d}.wav"
363
+ )
364
+
365
+ if filename.lower() in filenames:
366
+ raise ValueError(
367
+ f"Duplicate prepared filename: {filename}"
368
+ )
369
+
370
+ filenames.add(filename.lower())
371
+ filenames_by_call[call_id] = filename
372
+
373
+ metadata = copy.deepcopy(call.metadata or {})
374
+ metadata["preparation"] = {
375
+ "source_catalog_id": catalog.catalog_id,
376
+ "source_call_id": call_id,
377
+ "source_sample_rate": int(source_rate),
378
+ "sample_rate": int(sample_rate),
379
+ "measurement_method": method,
380
+ "original_level": float(level),
381
+ "target_level": float(target),
382
+ "normalization_factor": float(factor),
383
+ }
384
+
385
+ provenance = copy.deepcopy(call.provenance or {})
386
+
387
+ if "catalog_ingestion" in provenance:
388
+ provenance["source_catalog_ingestion"] = (
389
+ provenance.pop("catalog_ingestion")
390
+ )
391
+
392
+ provenance["preparation_source"] = {
393
+ "catalog_id": catalog.catalog_id,
394
+ "call_id": call_id,
395
+ "audio_filename": call.audio_path.name,
396
+ }
397
+
398
+ temporary_wav = work_dir / "current.wav"
399
+
400
+ try:
401
+ sf.write(
402
+ temporary_wav,
403
+ normalized,
404
+ sample_rate,
405
+ format="WAV",
406
+ subtype="FLOAT",
407
+ )
408
+
409
+ prepared.add_call(
410
+ Call(
411
+ call_id=call.call_id,
412
+ audio_path=temporary_wav,
413
+ species=call.species,
414
+ individual_id=call.individual_id,
415
+ individual_id_origin=call.individual_id_origin,
416
+ source_recording_id=call.source_recording_id,
417
+ active_intervals=call.active_intervals,
418
+ provenance=provenance,
419
+ metadata=metadata,
420
+ ),
421
+ filename=filename,
422
+ )
423
+ finally:
424
+ temporary_wav.unlink(missing_ok=True)
425
+
426
+ stored = prepared.get_call(call_id)
427
+ info = sf.info(stored.audio_path)
428
+
429
+ if (
430
+ info.channels != 1
431
+ or info.samplerate != sample_rate
432
+ or info.subtype != "FLOAT"
433
+ ):
434
+ raise ValueError(
435
+ f"{call_id}: invalid prepared WAV format"
436
+ )
437
+
438
+ del audio, normalized
439
+
440
+ # Preserve existing annotations without creating empty files.
441
+ for annotation_id, annotation_path in catalog._annotations.items():
442
+ annotation_filename = None
443
+
444
+ if annotation_id in filenames_by_call:
445
+ stem = Path(filenames_by_call[annotation_id]).stem
446
+ annotation_filename = f"{stem}{annotation_path.suffix}"
447
+
448
+ prepared.add_annotation(
449
+ annotation_id,
450
+ annotation_path,
451
+ filename=annotation_filename,
452
+ )
453
+
454
+ work_dir.rmdir()
455
+
456
+ prepared.finalize()
457
+
458
+ if destination.exists():
459
+ raise FileExistsError(
460
+ f"Output catalog already exists: {destination}"
461
+ )
462
+
463
+ staging.rename(destination)
464
+ published = True
465
+
466
+ result = CallCatalog.load(destination)
467
+ result.validate()
468
+
469
+ return result
470
+
471
+ except Exception:
472
+ if published:
473
+ shutil.rmtree(destination, ignore_errors=True)
474
+ else:
475
+ shutil.rmtree(staging, ignore_errors=True)
476
+ raise
simulok/call.py ADDED
@@ -0,0 +1,140 @@
1
+ """Representation and validation of selected acoustic vocalizations."""
2
+
3
+ import copy
4
+ import math
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import soundfile as sf
9
+
10
+
11
+ class Call:
12
+ """Represent one selected vocalization stored in a WAV file.
13
+
14
+ A Call created by a researcher requires a nonempty species name. A standalone
15
+ Call can reference multichannel input; CallCatalog imports channel 0 into a
16
+ separate mono WAV. Original audio is never modified.
17
+
18
+ ``individual_id_origin`` is ``provided`` for researcher-supplied identities,
19
+ ``generated`` for catalog-assigned provisional identities, and ``None`` for
20
+ identities that have not yet been resolved.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ call_id,
26
+ audio_path,
27
+ species=None,
28
+ individual_id=None,
29
+ source_recording_id=None,
30
+ active_intervals=None,
31
+ provenance=None,
32
+ metadata=None,
33
+ individual_id_origin=None,
34
+ *,
35
+ _allow_missing_species=False,
36
+ ):
37
+ if not isinstance(call_id, str):
38
+ raise TypeError("call_id must be a string")
39
+ if not call_id.strip():
40
+ raise ValueError("call_id cannot be empty or whitespace")
41
+ if not isinstance(audio_path, (str, Path)):
42
+ raise TypeError("audio_path must be a string or Path object")
43
+ path = Path(audio_path)
44
+ if path.suffix.lower() != ".wav":
45
+ raise ValueError("audio_path must point to a .wav file")
46
+
47
+ if species is None:
48
+ if not _allow_missing_species:
49
+ raise ValueError("species is required")
50
+ elif not isinstance(species, str):
51
+ raise TypeError("species must be a string")
52
+ elif not species.strip():
53
+ raise ValueError("species cannot be empty or whitespace")
54
+
55
+ for name, value in (
56
+ ("individual_id", individual_id),
57
+ ("source_recording_id", source_recording_id),
58
+ ):
59
+ if value is not None:
60
+ if not isinstance(value, str):
61
+ raise TypeError(f"{name} must be a string or None")
62
+ if not value.strip():
63
+ raise ValueError(f"{name} cannot be empty or whitespace")
64
+
65
+ if individual_id_origin is not None and individual_id_origin not in (
66
+ "provided", "generated"
67
+ ):
68
+ raise ValueError("individual_id_origin must be 'provided', 'generated', or None")
69
+ if individual_id is None and individual_id_origin is not None:
70
+ raise ValueError("individual_id_origin requires individual_id")
71
+ if individual_id is not None and individual_id_origin is None:
72
+ individual_id_origin = "provided"
73
+
74
+ if active_intervals is not None:
75
+ if not isinstance(active_intervals, list):
76
+ raise TypeError("active_intervals must be a list of tuples or None")
77
+ for interval in active_intervals:
78
+ if not isinstance(interval, tuple) or len(interval) != 2:
79
+ raise ValueError(
80
+ "Each active interval must be a tuple of (start_time, end_time)"
81
+ )
82
+ if not all(isinstance(t, (int, float)) for t in interval) or any(
83
+ isinstance(t, bool) for t in interval
84
+ ):
85
+ raise TypeError("Start and end times must be numbers")
86
+ start_time, end_time = interval
87
+ if not (math.isfinite(start_time) and math.isfinite(end_time)):
88
+ raise ValueError("Start and end times must be finite numbers")
89
+ if start_time < 0 or start_time >= end_time:
90
+ raise ValueError("Invalid active interval")
91
+
92
+ for name, value in (("provenance", provenance), ("metadata", metadata)):
93
+ if value is not None and not isinstance(value, dict):
94
+ raise TypeError(f"{name} must be a dictionary or None")
95
+
96
+ self.call_id = call_id
97
+ self.audio_path = path
98
+ self.species = species.strip() if species is not None else None
99
+ self.individual_id = individual_id.strip() if individual_id is not None else None
100
+ self.individual_id_origin = individual_id_origin
101
+ self.source_recording_id = source_recording_id
102
+ self.active_intervals = (
103
+ list(active_intervals) if active_intervals is not None else None
104
+ )
105
+ self.provenance = copy.deepcopy(provenance) if provenance is not None else None
106
+ self.metadata = copy.deepcopy(metadata) if metadata is not None else None
107
+
108
+ @property
109
+ def sample_rate(self):
110
+ """Return the WAV sample rate in Hz without loading samples."""
111
+ return sf.info(self.audio_path).samplerate
112
+
113
+ @property
114
+ def duration(self):
115
+ """Return the WAV duration in seconds without loading samples."""
116
+ return sf.info(self.audio_path).duration
117
+
118
+ def _validate_intervals_against_duration(self, duration):
119
+ if self.active_intervals is None:
120
+ return
121
+ for start_time, end_time in self.active_intervals:
122
+ if end_time > duration:
123
+ raise ValueError(
124
+ "Active interval exceeds the WAV duration: "
125
+ f"({start_time}, {end_time}) > {duration} s"
126
+ )
127
+
128
+ def load_audio(self):
129
+ """Read samples; standalone input may be mono or multichannel."""
130
+ audio, sample_rate = sf.read(self.audio_path)
131
+ if audio.size == 0:
132
+ raise ValueError("WAV must contain at least one sample")
133
+ if not np.isfinite(audio).all():
134
+ raise ValueError("WAV samples must be finite")
135
+ self._validate_intervals_against_duration(audio.shape[0] / sample_rate)
136
+ return audio, sample_rate
137
+
138
+ def validate_audio(self):
139
+ """Validate the referenced WAV and its active intervals."""
140
+ self.load_audio()