lasprs 0.14.3

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};

use super::file_attr_names::*;
use crate::{
    daq::{DaqChannel, DataType, Qty, RecordSettings, StreamMetaData},
    measurement::*,
    siggen::SourceDescriptor,
    tools::{get_current_timestamp, h5::*},
    *,
};
use hdf5_metno::File;
use snafu::prelude::*;
use uuid::{Uuid, timestamp};

type Result<T> = std::result::Result<T, MeasurementError>;

/// A struct containing all measurement metadata. It can be read and written
/// from/to a HDF5 file. Does contain all metadata that is available at the
/// start of a measurement, but does not contain the total number of frames stored.
#[derive(Debug, Clone)]
pub struct MeasurementMetadata {
    /// Measurement UUID
    uuid: Uuid,

    /// Measurement name. Should correspond to measurement file, without
    /// extension.
    name: String,

    /// Sample rate in Hz
    samplerate: StrictlyPositive,

    /// Quantity actually measured by the DAQ device. This might be just number
    /// for an audio device, or Voltage for a calibrated DAQ device.
    physical_input_qty: Qty,

    /// Data type information (HDF5 variant)
    dataType: DataType,

    /// Channel configuration information
    channels: Vec<DaqChannel>,

    /// Measurement comment
    comment: String,

    /// Recording timestamp (seconds since epoch)
    timestamp: f64,

    /// Measurement type
    measurement_type: MeasurementType,

    /// Signal generator source description.
    #[allow(unused)]
    siggen_source_desc: Option<SourceDescriptor>,

    /// LASP version information of stored file (major, minor)
    measurement_version: (u32, u32),

    /// UUIDs of reference measurements
    ref_uuids: Vec<Uuid>,

    /// Whether any input signal was clipped during measurement
    clipped: bool,
}

impl MeasurementMetadata {
    /// Construct new measurement metadata. Initializes UUID and timestamp.
    ///
    /// # Args
    ///
    /// * `name` - Name of the measurement
    /// * `samplerate` - Sampling rate
    /// * `physical_input_qty` - Physical input quantity
    /// * `dataType` - Data type of the measurement
    /// * `channels` - Channels of the measurement
    /// * `comment` - Comment about the measurement
    /// * `timestamp` - Timestamp of the measurement
    /// * `measurement_type` - Type of the measurement
    /// * `siggen_source_desc` - Signal generator source description
    /// * `ref_uuids` - UUIDs of reference measurements
    /// * `clipped` - Whether any input signal was clipped during measurement
    // TODO: Create builder for this
    #[expect(clippy::too_many_arguments)]
    pub fn new(
        name: &str,
        samplerate: StrictlyPositive,
        physical_input_qty: Option<Qty>,
        dataType: DataType,
        channels: Vec<DaqChannel>,
        comment: Option<&str>,
        timestamp: Option<f64>,
        measurement_type: Option<MeasurementType>,
        siggen_source_desc: Option<SourceDescriptor>,
        ref_uuids: Option<Vec<Uuid>>,
        clipped: bool,
    ) -> Self {
        Self {
            uuid: uuid::Uuid::new_v4(),
            name: name.to_string(),
            samplerate,
            physical_input_qty: physical_input_qty.unwrap_or_default(),
            dataType,
            channels,
            comment: comment.map(|c| c.to_string()).unwrap_or_default(),
            timestamp: timestamp.unwrap_or_else(get_current_timestamp),
            measurement_type: measurement_type.unwrap_or_default(),
            siggen_source_desc,
            ref_uuids: ref_uuids.unwrap_or_default(),
            clipped,
            measurement_version: (LASP_VERSION_MAJOR, LASP_VERSION_MINOR),
        }
    }
    /// Construct new measurement metadata. Initializes UUID and timestamp.
    pub fn new_from_recording(
        meta: &StreamMetaData,
        siggen_source_desc: Option<&SourceDescriptor>,
        settings: &RecordSettings,
    ) -> Self {
        // Reference measurements, write UUIDs to HDF5 file
        let timestamp = get_current_timestamp();
        let ref_uuids = settings
            .reference_meas
            .iter()
            .map(|m| *m.read().uuid())
            .collect::<Vec<_>>();
        let uuid = uuid::Uuid::new_v4();
        let name = settings.measurementName();
        let samplerate = meta.samplerate;
        let physical_input_qty = meta.physicalIOQty;
        let dataType = meta.rawDatatype;
        let channels = meta.channelInfo.clone();
        let comment = "".into();
        let measurement_type = settings.measurementType.clone();
        let measurement_version = (LASP_VERSION_MAJOR, LASP_VERSION_MINOR);
        let clipped = false;

        Self {
            uuid,
            name,
            samplerate,
            physical_input_qty,
            dataType,
            channels,
            comment,
            timestamp,
            measurement_type,
            siggen_source_desc: siggen_source_desc.cloned(),
            measurement_version,
            ref_uuids,
            clipped,
        }
    }

    /// Get the name of the measurement.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Set the name of the measurement.
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = name.into();
    }

    /// Write metadata to an HDF5 file. Assumes attributes do not yet exist.
    ///
    /// # Args
    ///
    /// * `file` - The HDF5 file to write to.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to the HDF5 file fails somewhere.
    pub fn writeToH5(&self, file: &hdf5_metno::File) -> Result<()> {
        // Rust-analyzer helps me to not forget to update this function when
        // fields are added
        let MeasurementMetadata {
            uuid,
            name: _, // Ignore this one
            samplerate,
            physical_input_qty,
            dataType,
            channels,
            comment,
            timestamp,
            measurement_type,
            siggen_source_desc,
            measurement_version,
            ref_uuids,
            clipped,
        } = self;
        let ref_uuid_stringlist = ref_uuids
            .iter()
            .map(|uuid| uuid.to_string())
            .collect::<Vec<_>>();
        write_h5_attr_stringlist(file, REF_UUIDS_ATTR, &ref_uuid_stringlist)?;

        // Write an empty comment string
        write_h5_attr_string(file, COMMENT_ATTR, comment)?;

        // Write source descriptor to HDF5 file
        if let Some(source) = siggen_source_desc {
            let source_ser = serde_json::to_string(&source)
                .expect("Unable to serialize signal source attribure");
            write_h5_attr_string(file, SIGGEN_SOURCE_DESCRIPTION_ATTR, &source_ser)?;
        }

        // Samplerate, block size, number of channels
        write_h5_attr_scalar(file, SAMPLERATE_ATTR, **samplerate)?;
        write_h5_attr_scalar(file, NCHANNELS_ATTR, self.nchannels())?;

        // Version
        write_h5_attr_scalar(file, VERSION_MAJOR_ATTR, measurement_version.0)?;
        write_h5_attr_scalar(file, VERSION_MINOR_ATTR, measurement_version.1)?;

        // Timestamp: time since unix epoch when measurement started
        write_h5_attr_scalar(file, MEASUREMENT_TIME_ATTR, *timestamp)?;

        // Write measurement type
        write_h5_attr_string(
            file,
            MEASUREMENT_TYPE_ATTR,
            &serde_json::to_string(measurement_type).expect("Unable to serialize measurement type"),
        )?;

        // Create UUID for measurement
        use hdf5_metno::types::VarLenUnicode;
        write_h5_attr_string(file, UUID_ATTR, &uuid.to_string())?;

        write_h5_attr_scalar(file, PHYSICAL_INPUT_QTY_ATTR, *physical_input_qty as u32)?;

        write_h5_attr_scalar(file, INPUT_SIGNAL_CLIPPED_ATTR, *clipped)?;
        write_h5_attr_scalar(file, INPUT_DATATYPE_ATTR, *dataType as u32)?;
        self.write_channel_metadata_to_H5(file, channels)?;

        Ok(())
    }

    /// Helper function to write channel metadata to an HDF5 file. Only stores
    /// channel names and quantity enum indices.
    ///
    /// # Arguments
    ///
    /// * `file` - The HDF5 file to write to.
    /// * `channels` - The channels to write metadata for.
    fn write_channel_metadata_to_H5(
        &self,
        file: &hdf5_metno::File,
        channels: &[DaqChannel],
    ) -> Result<()> {
        let names = channels
            .iter()
            .map(|ch| ch.name.clone())
            .collect::<Vec<_>>();
        write_h5_attr_stringlist(file, CHANNEL_NAMES_ATTR, &names)?;

        let qtys_ser = channels.iter().map(|ch| ch.qty as u32).collect::<Vec<_>>();
        write_h5_attr_list(file, QTY_ENUM_IDX_ATTR, &qtys_ser)?;

        // Store sensitivity
        let sens: Vec<Flt> = self.sensitivities(None);
        write_h5_attr_list(file, SENSITIVITY_ATTR, &sens)?;

        Ok(())
    }

    /// Return the data type of the audio data
    #[inline]
    pub fn dataType(&self) -> DataType {
        self.dataType
    }

    /// Return the source descriptor of the signal generator, if one exists
    pub fn getSourceDescriptor(&self) -> Option<&SourceDescriptor> {
        self.siggen_source_desc.as_ref()
    }

    /// Load metadata from an HDF5 file
    pub fn fromMeasurement(file: &hdf5_metno::File) -> Result<Self> {
        let filepath: PathBuf = file.filename().into();
        // Obtain the file name without extension
        let name = filepath.file_stem().and_then(|stem| stem.to_str()).ok_or(
            FileNotFoundSnafu {
                filepath: &filepath,
            }
            .build(),
        )?;

        // Read audio dataset to get shape and type information
        let audio_dataset = file
            .dataset(MEASURED_INPUT_DATASET_NAME)
            .map_err(H5Error::from)
            .context(H5FileProblemSnafu {
                operation: "reading audio dataset",
            })?;

        let shape = audio_dataset.shape();

        ensure!(
            shape.len() == 2,
            DataCorruptedSnafu {
                possible_error: format!(
                    "Invalid audio dataset shape: expected 3 dimensions, got {}",
                    shape.len()
                )
            }
        );
        let nchannels_audio = shape[1];

        // Data type of the data
        let datatype_idx = read_h5_attr_scalar(file, INPUT_DATATYPE_ATTR)?;
        let dataType = DataType::from_repr(datatype_idx).ok_or(
            DataCorruptedSnafu {
                possible_error: "Data type not understood",
            }
            .build(),
        )?;

        // Read version information
        let version_major = file
            .attr("LASP_VERSION_MAJOR")
            .and_then(|attr| attr.read_scalar())
            .unwrap_or(0u32);
        let version_minor = file
            .attr("LASP_VERSION_MINOR")
            .and_then(|attr| attr.read_scalar())
            .unwrap_or(1u32);

        // Read UUID
        let uuid_res = read_h5_attr_string(file, UUID_ATTR);
        let uuid;
        match uuid_res {
            Ok(uuid_res) => {
                uuid = Uuid::from_str(&uuid_res).map_err(|_| MeasurementError::DataCorrupted {
                    possible_error: "Cannot parse UUID".into(),
                })?;
            }
            Err(_) => {
                // Generate UUID and store in file. If it failse, we stop here.
                uuid = Uuid::new_v4();
                let uuid_str = uuid.to_string();
                write_h5_attr_string(file, "UUID", &uuid_str)?;
            }
        }
        let clipped: bool = read_h5_attr_scalar(file, INPUT_SIGNAL_CLIPPED_ATTR)?;

        // Read channel names
        let channel_names: Vec<String> = read_h5_attr_stringlist(file, CHANNEL_NAMES_ATTR)
            .or_else(|_| read_h5_attr_stringlist(file, "channel_names"))?;
        let nchannels = channel_names.len();
        ensure!(
            nchannels_audio == nchannels,
            DataCorruptedSnafu {
                possible_error: "Numer of channels in audio data does not correspond with number of channels in metadata"
            }
        );

        let comment: String = read_h5_attr_string(file, COMMENT_ATTR).unwrap_or_default();

        // Read sensitivity (keep as f64)
        let sensitivity: Vec<f64> =
            read_h5_attr_list(file, "sensitivity").unwrap_or_else(|e|{
                eprintln!("Error: could not read sensitivity values from measurement file: {e}! Defaulting to 1.0 for all channels.");
                let unit: Vec<f64> = vec![1.0; nchannels];
                unit});

        // Read quantities
        let quantities: Vec<Qty> = read_h5_attr_list::<u32>(file,QTY_ENUM_IDX_ATTR)
            .map(|arr| arr.into_iter().map(|val| val.into()).collect())
            .unwrap_or_else(|e| {
                eprintln!("Error: could not read quantity data from measurement file: {e}! Setting defaults as Qty::Number");
                vec![Qty::Number; nchannels]
            });

        // Create DaqChannel vector from the component data
        let mut channels = Vec::with_capacity(nchannels);
        for (i, channel_name) in channel_names.into_iter().enumerate() {
            let channel = DaqChannel {
                name: channel_name,
                qty: quantities[i],
                sensitivity: sensitivity[i],
                ..Default::default()
            };

            channels.push(channel);
        }

        let siggen_source_desc_ser = read_h5_attr_string(file, SIGGEN_SOURCE_DESCRIPTION_ATTR);

        let siggen_source_desc = if let Ok(siggen_source_desc_ser) = siggen_source_desc_ser {
            serde_json::from_str(&siggen_source_desc_ser)
                .map_err(JSONError::from)
                .context(ParseMetaSnafu {
                    field: SIGGEN_SOURCE_DESCRIPTION_ATTR,
                })?
        } else {
            // If the attribute is not present, set source description to None
            None
        };

        let ref_uuid_strings = read_h5_attr_stringlist(file, REF_UUIDS_ATTR)?;
        let ref_uuids = {
            let mut ref_uuids = Vec::with_capacity(ref_uuid_strings.len());
            for i in ref_uuid_strings {
                let uuid = Uuid::from_str(&i).map_err(|e| {
                    DataCorruptedSnafu {
                        possible_error: format!("Error parsing reference UUID: {}", e),
                    }
                    .build()
                })?;
                ref_uuids.push(uuid);
            }
            ref_uuids
        };

        // Read timestamp
        let timestamp: f64 = read_h5_attr_scalar(file, MEASUREMENT_TIME_ATTR)?;

        // Read samplerate
        let samplerate: f64 = read_h5_attr_scalar(file, SAMPLERATE_ATTR)?;
        let samplerate: StrictlyPositive =
            samplerate.try_into().context(ParameterOutOfRangeSnafu {
                parameter: "samplerate",
            })?;

        let physical_input_qty = read_h5_attr_scalar(file, PHYSICAL_INPUT_QTY_ATTR)
            .map(|v: u32| Qty::from(v))
            .unwrap_or(Qty::Number);

        // Read measurement type
        let measurement_type_str = read_h5_attr_string(file, MEASUREMENT_TYPE_ATTR)?;
        let measurement_type: MeasurementType = serde_json::from_str(&measurement_type_str)
            .map_err(JSONError::from)
            .context(ParseMetaSnafu {
                field: "measurement_type_ser",
            })?;

        Ok(MeasurementMetadata {
            name: name.into(),
            uuid,
            samplerate,
            physical_input_qty,
            measurement_type,
            comment,
            timestamp,
            dataType,
            siggen_source_desc,
            measurement_version: (version_major, version_minor),
            ref_uuids,
            clipped,
            channels,
        })
    }

    /// Get the measurement UUID
    pub fn uuid(&self) -> &uuid::Uuid {
        &self.uuid
    }

    /// Return a reference to the channel data
    #[inline]
    pub fn channels(&self) -> &[DaqChannel] {
        &self.channels
    }

    /// Get the number of channels
    #[inline]
    pub fn nchannels(&self) -> usize {
        self.channels.len()
    }

    /// Get formatted time string
    ///
    /// Returns a string representing the measurement time in the format
    /// "YYYY-MM-DD HH:MM:SS".
    pub fn time_string(&self) -> String {
        use chrono::{DateTime, Local, TimeZone, Utc};

        // Convert f64 timestamp (seconds since Unix epoch) to chrono DateTime
        let secs = self.timestamp as i64;
        let nanos = ((self.timestamp - secs as f64) * 1_000_000_000.0) as u32;

        // Create UTC datetime first
        let utc_datetime = match Utc.timestamp_opt(secs, nanos) {
            chrono::LocalResult::Single(dt) => dt,
            chrono::LocalResult::Ambiguous(dt, _) => dt, // Take the first option for ambiguous times
            chrono::LocalResult::None => {
                // Fallback for invalid timestamps
                return format!("Invalid timestamp: {}", self.timestamp);
            }
        };

        // Convert to local timezone
        let local_datetime: DateTime<Local> = utc_datetime.with_timezone(&Local);

        // Format as timezone-aware string
        // With timezone
        // local_datetime.format("%Y-%m-%d %H:%M:%S %Z").to_string()
        // Without timezone
        local_datetime.format("%Y-%m-%d %H:%M:%S").to_string()
    }

    /// Get channel configuration
    pub fn channel_config(&self) -> &[DaqChannel] {
        &self.channels
    }

    /// Get the timestamp of the measurement
    pub fn timestamp(&self) -> f64 {
        self.timestamp
    }

    /// Get the sample rate in Hz
    pub fn samplerate(&self) -> StrictlyPositive {
        self.samplerate
    }

    /// Get channel names
    pub fn channel_names(&self) -> Vec<String> {
        self.channels.iter().map(|ch| ch.name.clone()).collect()
    }

    /// Set new channel names for all channels
    ///
    /// # Arguments
    /// * `new_ch_names`: New channel names for all channels
    ///
    pub fn set_channel_names(&mut self, file: &File, new_ch_names: &[String]) -> Result<()> {
        ensure!(
            new_ch_names.len() == self.channels.len(),
            LogicSnafu {
                name: &self.name,
                message: "Number of channel names must match number of channels"
            }
        );
        write_h5_attr_stringlist_overwrite(file, CHANNEL_NAMES_ATTR, new_ch_names)?;
        self.channels
            .iter_mut()
            .zip(new_ch_names)
            .for_each(|(ch, name)| ch.name = name.to_string());
        Ok(())
    }

    /// Get channel sensitivities
    ///
    /// # Args - `channel_subset`: Optional subset of channels to retrieve
    /// sensitivities for. If None, all channels are considered.
    pub fn sensitivities(&self, channel_subset: Option<&[usize]>) -> Vec<f64> {
        if let Some(ch) = channel_subset {
            ch.iter().map(|ch| self.channels[*ch].sensitivity).collect()
        } else {
            self.channels.iter().map(|ch| ch.sensitivity).collect()
        }
    }

    /// Set channel sensitivities
    ///
    /// # Arguments
    /// - `sens`: New sensitivities for each channel
    pub fn set_sensitivities(&mut self, file: &File, sens: &[Flt]) -> Result<()> {
        ensure!(
            sens.len() == self.channels.len(),
            LogicSnafu {
                name: &self.name,
                message: "Number of sensitivity values provided does not match number of channels"
            }
        );
        write_h5_attr_list_overwrite(file, SENSITIVITY_ATTR, sens)?;
        // Finally do the thing that cannot fail
        for (ch, sens) in self.channels.iter_mut().zip(sens) {
            ch.sensitivity = *sens;
        }
        Ok(())
    }

    /// Get channel quantities
    pub fn quantities(&self) -> Vec<Qty> {
        self.channels.iter().map(|ch| ch.qty).collect()
    }

    /// Set channel quantities. Errors if the number of quantities does not
    /// match the number of channels.
    ///
    /// # Arguments
    /// - `qty`: New quantities for each channel
    pub fn set_quantities(&mut self, file: &File, qty: &[Qty]) -> Result<()> {
        ensure!(
            qty.len() == self.channels.len(),
            LogicSnafu {
                name: &self.name,
                message: "Number of quantity values provided does not match number of channels"
            }
        );

        let qty_int = qty.iter().map(|q| *q as u32).collect::<Vec<u32>>();
        write_h5_attr_list_overwrite(file, QTY_ENUM_IDX_ATTR, &qty_int)?;
        // Finally do the thing that cannot fail
        for (ch, qty) in self.channels.iter_mut().zip(qty) {
            ch.qty = *qty;
        }
        Ok(())
    }

    /// Get measurement comment
    pub fn comment(&self) -> &str {
        &self.comment
    }
    /// Set / update measurement comment
    ///
    /// # Args
    /// - `comment`: New comment string
    pub fn set_comment(&mut self, file: &File, comment: &str) -> Result<()> {
        write_h5_attr_string_overwrite(file, COMMENT_ATTR, comment)?;
        self.comment = comment.to_string();

        Ok(())
    }

    /// Whether the input signal was clipped during measurement
    pub fn clipped(&self) -> bool {
        self.clipped
    }

    /// Quantity actually measured by the DAQ device. This might be just number
    /// for an audio device that just sends numbers (`Full Scale`), or Voltage
    /// for a calibrated DAQ device.
    pub fn physicalInputQty(&self) -> Qty {
        self.physical_input_qty
    }

    /// Return tuple of stored measurement file version (major, minor)
    pub fn measurementVersion(&self) -> (u32, u32) {
        self.measurement_version
    }

    /// Return list of reference measurements for this measurements
    pub fn getRefMeasurements(&self) -> Vec<SharedMeasurement> {
        self.ref_uuids
            .iter()
            .filter_map(find_open_measurement_by_uuid)
            .collect()
    }
    /// Return the measurement type
    pub fn measurementType(&self) -> &MeasurementType {
        &self.measurement_type
    }
}

/// These characters are not allowed in new names for a measurement. On the
/// other hand, if these characters are in an already existing file name, that
/// is OK. The last might happen when the file is renamed from outside the
/// application.
const FORBIDDEN_FILENAME_CHARS: &[char] = &['.', '<', '>', ':', ';', '/', '|', '?', '!', '\\'];

/// Extract the measurement name from a file path, if possible.
#[inline]
pub fn measurementName(path: &Path) -> Result<&str> {
    let name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .context(InvalidMeasurementNameSnafu {
            name: path.to_string_lossy(),
            reason: "Measurement name contains illegal characters",
        })?;
    checkValidMeasurementName(name)?;
    Ok(name)
}

/// Check if a measurement name is valid. Cannot be empty, and cannot contain
/// any of the forbidden characters to not conflict with path build-up.
pub fn checkValidMeasurementName(name: &str) -> Result<()> {
    ensure!(
        !name.is_empty(),
        InvalidMeasurementNameSnafu {
            name,
            reason: "Measurement name cannot be empty"
        }
    );
    for ch in FORBIDDEN_FILENAME_CHARS {
        ensure!(
            !name.contains(*ch),
            InvalidMeasurementNameSnafu {
                name: name.to_string(),
                reason: format!("Measurement name contains illegal character '{}'", ch),
            }
        )
    }
    Ok(())
}