2Contains class implementations to read ODiSI sensor data.
3FileReader Base class of file reader implementation.
4TsvReader Supports the reader for .tsv files.
5DatReader Supports the reader for .dat files.
7\author Anett Kielreiter
15from collections
import OrderedDict
16from datetime
import datetime
17from abc
import abstractmethod
18from collections.abc
import Generator
19from pathlib
import Path
21from fosanalysis
import utils
26 Class to hold sensor specific data (name, serial number, ...).
42 segments: OrderedDict,
47 Constructs a sensor info object with information.
48 \param name Name of the sensor.
49 \param serial_number Serial number of the sensor.
50 \param part_number Part number of the sensor.
51 \param channel Channel of the sensor.
52 \param sensor_type Type of the sensor, e.g., temperature or strain.
53 \param length Sensor length in meter.
54 \param y_axis_unit Unit of the sensor values as string.
55 \param x_axis_unit Unit of the x-axis values as string.
56 \param patch_cord Patch cord length as float.
57 \param key_name Name of the sensor key, defined by initialization.
58 \param tare_name Current tare name of the sensor.
59 \param gages Dictionary with all defined gage names and x-position.
60 \param segments Dictionary with all defined segments.
61 \param x_axis X-axis values of the measurement as array, optional.
62 \param tare Tare values of the measurement as array, optional.
97 Overloads the comparison operator for equal.
99 return (self.
name == other.name
and
103 return getattr(self, key,
None)
106 return setattr(self, key, value)
118 It specifies the basic interface for reading a data file.
123 Constructs a FileReader object.
124 Needs to be reimplemented by sub-classes.
131 Abstract method to get meta and base data of the data file.
132 It contains gages/segments, x-axis and tare
133 of all available sensors.
135 raise NotImplementedError()
140 Returns single measurement of the strain data.
142 raise NotImplementedError()
147 File reader class for the `.tsv` measurement files exported by the
148 ODiSI 6100 series interrogators by Luna Inc LunaInnovations2020.
149 See \cite LunaInnovations2020.
150 Both - gage files (`*_gages.tsv`) and full (`*_full.tsv`) - are supported.
152 def __init__(self, filepath: str, *args, **kwargs):
154 Initializes a tsv file reader.
155 \param filepath Path to the .tsv file to read all sensor information.
156 \param *args Additional positional arguments,
157 will be passed to the superconstructor.
158 \param **kwargs Additional keyword arguments,
159 will be passed to the superconstructor.
173 self.
file = open(filepath)
177 Method to get sensor data from file.
178 For TSV only one sensor exists in the file.
179 \return List with all sensor infos.
180 \return Dictionary with measurement specific data.
186 sensor =
SensorInfo(metadata.get(
'Sensor Name',
''),
187 metadata.get(
'Sensor Serial Number',
''),
188 metadata.get(
'Sensor Part Number',
''),
189 int(metadata.get(
'Channel', 0)),
190 metadata.get(
'Sensor Type',
''),
191 float(metadata.get(
'Length (m)', 0.0)),
192 metadata.get(
'Units',
''),
193 metadata.get(
'X-Axis Units',
''),
194 float(metadata.get(
'Patch Cord Length (m)', 0)),
195 metadata.get(
'Key Name',
''),
196 metadata.get(
'Tare Name',
''),
201 sensor_list.append(sensor)
202 return sensor_list, metadata
206 Retrieves the meta data of the sensor file.
207 Reads the header data like sensor name, length, gage_pitch, ...
208 \return Metadata as dictionary.
211 for line
in self.
file:
215 line_list = line.strip().split(self.
itemsep)
216 if len(line_list) >= 1:
218 fieldname = line_list[0][:-1]
219 if len(line_list) > 1:
220 metadata[fieldname] = line_list[1]
222 metadata[fieldname] =
""
227 Get the base data for all measurements.
228 It reads the segments, gages, x-axis and tare of the file.
229 Search for '_gages' and '_full' files.
230 In case of '_gages' file separate gages and segments.
231 In case of only existing '_full' file no gages will returned.
232 \return X-axis gages of current measurement.
233 \return Tare values of measurement.
234 \return All segments with index and length available in the
235 file as OrderedDict, empty if no segments available.
236 \return All gages with its index in the file as OrderedDict,
237 empty if no gages available.
239 gages = OrderedDict()
240 segments = OrderedDict()
249 for line
in gage_file:
250 line_list = line.strip().split(self.
itemsep)
251 if len(line_list) > 3:
252 if line_list[0].lower() ==
'gage/segment name':
256 if line_list[0].lower() ==
'x-axis':
262 return x_axis, tare, segments, gages
265 start_time: datetime =
None,
266 end_time: datetime =
None,
267 *args, **kwargs) -> Generator[datetime, np.array]:
269 Returns only single entry of measurement as generator
270 to request for multiple times for parts or the whole file.
271 \param start_time Read measurements from given timestamp.
272 \param end_time Read measurements till given timestamp.
273 \return Datetime object of current line.
274 \return Strain values of the current line as array.
276 for line
in self.
file:
277 line_list = line.strip().split(self.
itemsep)
278 if len(line_list) > 3
and line_list[1].lower() ==
'measurement':
279 timestamp = datetime.fromisoformat(line_list[0])
280 if (end_time
is not None
281 and end_time < timestamp):
283 if (start_time
is not None
284 and start_time <= timestamp):
285 yield timestamp, np.array(line_list[3:], dtype=float)
286 elif start_time
is None:
287 yield timestamp, np.array(line_list[3:], dtype=float)
290 segments: OrderedDict,
291 gages: OrderedDict) -> tuple[list, list]:
293 Read gage/segment, x-axis and tare line to discover related data.
294 The segments are written into given segments dictionary.
295 The gages are written into given gages dictionary.
296 This information is used later on to split the data.
297 \param segments Dictionary with named segments is written.
298 \param gages Dictionary, with named gages is written.
299 \return Array with gages of x-axis existing in file.
300 \return Array with whole tare of file, empty if not exist.
305 for line
in self.
file:
306 line_list = line.strip().split(self.
itemsep)
307 if len(line_list) > 3:
308 if line_list[0].lower() ==
'gage/segment name':
310 line_list[3:], segments, gages)
311 elif line_list[0].lower() ==
'x-axis':
312 x_axis = list(map(float, line_list[3:]))
313 if '_gage' in Path(self.
filename).name:
316 elif line_list[0].lower() ==
'tare':
317 tare = list(map(float, line_list[3:]))
322 segments: OrderedDict,
325 Read gage and segment line to discover the gages and segments.
326 The gages are written into given gages dictionary.
327 The segments are written into given segments dictionary.
328 This information is used later on to split the data.
329 \param data List of line elements, contain the gage and segment names.
330 \param segments Dictionary with named segments is written.
331 \param gages Dictionary, with named gages is written.
334 for index, value
in enumerate(data):
336 if segment_name
is not None:
337 segments[segment_name][
'length'] = (index
338 - segments[segment_name][
'index'])
339 segment_name = value.split(
"[")[0]
340 segments[segment_name] = {
'index': index}
341 elif segment_name
is None:
342 gages[value] = {
'index': index}
343 if segment_name
is not None:
344 segments[segment_name][
'length'] = (len(data)
345 - segments[segment_name][
'index'])
349 segments: OrderedDict,
352 Private method to determine the index of x-positions
353 for segments and gages based on x_axis of full file.
354 This method will only be called if both files available.
355 This information is used later to split the data.
356 \param data List of line elements, contain the x-axis data.
357 \param segments Dictionary with named segments.
358 \param gages Dictionary, with named gages.
361 x_pos = data[gages[gage][
'index']]
362 gages[gage][
'x_pos'] = x_pos
363 for part
in segments:
364 index = segments[part][
'index']
365 x_pos_start = data[index]
366 x_pos_end = data[index + segments[part][
'length'] - 1]
367 start_gage = next((name
for name, pos
in gages.items()
368 if pos == x_pos_start),
None)
369 end_gage = next((name
for name, pos
in gages.items()
370 if pos == x_pos_end),
None)
371 if start_gage
is not None and end_gage
is not None:
372 segments[part][
'start_gage'] = start_gage
373 segments[part][
'end_gage'] = end_gage
377 Private method to look for both files (_full and _gage) in folder.
378 If filename is 'gages.tsv' file search for 'full.tsv' and vice versa.
379 \return Path to the found .tsv file, otherwise empty string.
384 new_name = ref_path.name[0:-9] +
"full.tsv"
387 new_name = ref_path.name[0:-8] +
"gages.tsv"
390 path_2 = os.path.join(ref_path.parent, new_name)
391 if os.path.exists(path_2):
398 File reader class for the `.dat` measurement files recorded by the
399 ODiSI 6100 series interrogators by Luna Inc LunaInnovations2020.
400 See \cite LunaInnovations2020.
401 The file contains the raw data from measurement,
402 mostly from different channels (1-8 possible).
404 DEFAULT_FILE_VERSION = 9
406 def __init__(self, filepath: str, *args, **kwargs):
408 Initializes a .dat file reader.
409 \param filepath Path to file object to read in sensor data.
410 \param *args Additional positional arguments,
411 will be passed to the superconstructor.
412 \param **kwargs Additional keyword arguments,
413 will be passed to the superconstructor.
435 Method to get sensor data from file.
436 Returns all sensor data available in the .dat file.
437 \return List of available sensors.
438 \return Dictionary with measurement specific data.
444 for line
in self.
file:
447 line_dict = json.loads(line)
448 except json.JSONDecodeError
as ex:
449 print(f
"Error decoding line {lc} in {self.file}! Skipping line.")
452 if 'sensors' in line_dict:
456 elif 'data' in line_dict:
458 elif 'filename' in line_dict:
459 line_dict[
"start time"] = datetime.fromisoformat(line_dict[
"start time"])
460 line_dict[
"end time"] = datetime.fromisoformat(line_dict[
"end time"])
461 line_dict[
'filename'] = os.path.join(os.path.dirname(self.
file.name), line_dict[
'filename'])
464 return sensor_list, metadata
468 Retrieves the meta data of the sensor file with multi channels.
469 Reads the header data like sensor name, length, gage_pitch, ...
470 \param meta_dict Dictionary with meta infos of first line.
471 \return Metadata as dictionary without sensor info.
472 \return List of SensorInfo objects for each channel.
476 for sensor
in meta_dict.get(
'sensors', []):
477 sensor_dict = copy.deepcopy(sensor)
479 sensor_info =
SensorInfo(sensor_dict.get(
'sensor name',
''),
480 sensor_dict.get(
'sensor serial number',
''),
481 sensor_dict.get(
'sensor part number',
''),
482 sensor_dict.get(
'channel', 0),
483 sensor_dict.get(
'sensor type (disp)',
''),
484 sensor_dict.get(
'length (m)', 0.0),
485 sensor_dict.get(
'units',
''),
486 sensor_dict.get(
'x-axis units',
''),
487 sensor_dict.get(
'patch cord (m)', 0.0),
488 sensor_dict.get(
'key name',
''),
489 sensor_dict.get(
'tare name',
''),
492 sensor_list.append(sensor_info)
494 meta_dict.pop(
'sensors')
495 return meta_dict, sensor_list
499 Reads one line of base data file, parse for channel and record type.
500 The method reads the x-axis and tare if available
501 and adds it to the corresponding SensorInfo object of given list.
502 \param line_dict Current line of hdr.dat with x-axis or tare data.
503 \param sensor_list List of SensorInfo objects created by first line.
505 curr_ch = line_dict.get(
'channel',
None)
506 ch_sensor = next((sensor
for sensor
in sensor_list
507 if sensor.channel == curr_ch),
None)
509 if ch_sensor
is None:
511 if line_dict[
'record type'] ==
'x-axis':
512 ch_sensor.x_axis = line_dict[
'data']
513 elif line_dict[
'record type'] ==
'tare':
514 ch_sensor.tare = line_dict[
'data']
518 start_time: datetime =
None,
519 end_time: datetime =
None,
520 *args, **kwargs) -> Generator[datetime, np.array]:
522 Returns only single entry of a measurement file as generator
523 to request for multiple times for parts or the whole file.
524 Checks the given channel first.
525 \param channel Channel of the selected sensor.
526 \param start_time Read measurements from given timestamp.
527 \param end_time Read measurements till given timestamp.
528 \return Datetime object of current line.
529 \return Strain values of the current line as array.
534 if start_time
is not None and start_time > data_file_info[
"end time"]:
537 data_file = data_file_info[
'filename']
538 with open(data_file)
as f:
542 if not f
'"channel":{channel}' in line:
548 line_dict = json.loads(line)
549 except json.JSONDecodeError
as ex:
550 print(f
"Error decoding line {lc} in {data_file}! Skipping line.")
553 if (line_dict.get(
'channel',
None) == channel
554 and line_dict.get(
'record type',
'') ==
'measurement'
555 and 'data' in line_dict):
556 time = datetime.fromisoformat(line_dict[
'timestamp'])
557 if (end_time
is not None and end_time < time):
560 if (start_time
is None or start_time <= time):
565 Reads single .dat file and parses timestamps and data for each channel
566 Returns a dictionary with channel as key.
567 \param dat_file Path of the .dat file to read from.
568 \return data_dict Dictionary with timestamps and data
569 for each channel in file.
573 with open(dat_file)
as f:
577 line_dict = json.loads(line)
578 except json.JSONDecodeError
as ex:
579 print(f
"Error decoding line {lc} in {dat_file}! Skipping line.")
582 channel = line_dict.get(
'channel',
None)
583 if (line_dict.get(
'record type',
'') ==
'measurement'
584 and 'data' in line_dict):
585 timestamp = datetime.fromisoformat(line_dict[
'timestamp'])
587 if not channel
in data_dict:
588 data_dict[channel] = {
'timestamps': [timestamp],
'datas': [data]}
590 data_dict[channel][
'timestamps'].append(timestamp)
591 data_dict[channel][
'datas'].append(data)
597 ) -> tuple[OrderedDict, OrderedDict]:
599 Private method to extract the gages and segments
600 from metadata dictionary.
601 The gages/segments are stored in the first line of the .dat files.
602 \param sensor_dict Dictionary with gages and segments.
603 \return Segments of the sensor as ordered dict.
604 \return Gages of the sensor as ordered dict.
606 gages = OrderedDict()
607 segments = OrderedDict()
609 for gage
in sensor_dict.get(
'gages', []):
610 gages[gage[
'gage name']] = {
'index':gage[
'index'],
611 'x_pos': gage[
'location (mm)']/1000}
613 for segment
in sensor_dict.get(
'segments', []):
614 name = segment[
'segment name']
615 segments[name] = {
'index': segment[
'index'],
616 'length': segment[
'size'],
617 'start_gage': segment[
'start gage'],
618 'end_gage': segment[
'end gage'],}
619 return segments, gages
623 Private method to parse the measurement data
624 dependent on type and file version.
625 File version = 7: Data provided as bytecode, type is string.
626 File version = 9: Data provided as list with a divisor of 10.
628 \param strain_data Strain data provided by raw data file,
629 maybe string or list.
630 \return Array with converted strain values according to file version.
632 if type(strain_data)
is list:
634 return np.asarray(strain_data, dtype=float) * 0.1
636 return np.asarray(strain_data, dtype=float)
638 int_array = np.frombuffer(bytearray.fromhex(strain_data), np.uint8)
640 for index
in range(0, len(int_array), 2):
641 factor = int_array[index]
642 value = int_array[index+1]
644 if factor == 128
and value == 0:
647 neg = 256 * (256-factor)
650 strain = factor * 256 + value
652 strain_list.append(strain)
653 return np.asarray(strain_list, dtype=float)
654 return np.asarray(strain_data)
File reader class for the .dat measurement files recorded by the ODiSI 6100 series interrogators by L...
filename
File object which is already opened.
str itemsep
Stores the item separator, for dat files the "," is used.
np.array _parse_data(self, strain_data)
tuple[list, dict] read_meta_infos(self)
Method to get sensor data from file.
Generator[datetime, np.array] read_next_measurement(self, int channel, datetime start_time=None, datetime end_time=None, *args, **kwargs)
Returns only single entry of a measurement file as generator to request for multiple times for parts ...
file
Create a file pointer to the raw data .hdr file.
_read_base_data(self, dict line_dict, list sensor_list)
Reads one line of base data file, parse for channel and record type.
int file_version
Stores the file version of .dat file.
dict _read_metadata(self, dict meta_dict)
Retrieves the meta data of the sensor file with multi channels.
tuple[OrderedDict, OrderedDict] _extract_segments_gages(self, dict sensor_dict)
Private method to extract the gages and segments from metadata dictionary.
list measurement_files_info
List dicts containing information on the data chunk files.
__init__(self, str filepath, *args, **kwargs)
Initializes a .dat file reader.
read_dat_file(self, dat_file)
Reads single .dat file and parses timestamps and data for each channel Returns a dictionary with chan...
tuple read_next_measurement(self, *args, **kwargs)
Returns single measurement of the strain data.
tuple read_meta_infos(self, *args, **kwargs)
Abstract method to get meta and base data of the data file.
__init__(self, *args, **kwargs)
Constructs a FileReader object.
Class to hold sensor specific data (name, serial number, ...).
y_axis_unit
Unit of the sensor values as string.
x_axis_unit
Unit of the x-axis values as string.
patch_cord
Patch cord length as float.
tare
Tare values of the measurement as array, optional.
__setitem__(self, key, value)
part_number
Part number of the sensor.
x_axis
X-axis values of the measurement as array, optional.
key_name
Name of the sensor key, defined by initialization.
__init__(self, str name, str serial_number, str part_number, int channel, str sensor_type, float length, str y_axis_unit, str x_axis_unit, float patch_cord, str key_name, str tare_name, OrderedDict gages, OrderedDict segments, list x_axis=None, list tare=None)
Constructs a sensor info object with information.
segments
Dictionary with all defined segments.
sensor_type
Type of the sensor, e.g., temperature or strain.
gages
Dictionary with all defined gage names and x-position.
tare_name
Current tare name of the sensor.
serial_number
Serial number of the sensor.
bool __eq__(self, other)
Overloads the comparison operator for equal.
channel
Channel of the sensor.
length
Sensor length in meter.
File reader class for the .tsv measurement files exported by the ODiSI 6100 series interrogators by L...
tuple[list, list, OrderedDict, OrderedDict] _read_base_data(self)
Get the base data for all measurements.
file
Create a file pointer to the TSV file.
dict _read_metadata(self)
Retrieves the meta data of the sensor file.
_set_pos_for_segments_gages(self, list data, OrderedDict segments, OrderedDict gages)
Private method to determine the index of x-positions for segments and gages based on x_axis of full f...
Generator[datetime, np.array] read_next_measurement(self, datetime start_time=None, datetime end_time=None, *args, **kwargs)
Returns only single entry of measurement as generator to request for multiple times for parts or the ...
str other_tsv
Checks if both files (_full and _gage) are available, if not it is an empty string.
tuple[list, list] _read_base_from_file(self, OrderedDict segments, OrderedDict gages)
Read gage/segment, x-axis and tare line to discover related data.
tuple[list, dict] read_meta_infos(self)
Method to get sensor data from file.
str _locate_full_or_gage_file(self)
Private method to look for both files (_full and _gage) in folder.
__init__(self, str filepath, *args, **kwargs)
Initializes a tsv file reader.
_read_gage_segments_info(self, list data, OrderedDict segments, OrderedDict gages)
Read gage and segment line to discover the gages and segments.
str itemsep
Stores the item separator, for tsv files it is "\t".
Abstract base class, which deals with superflous constructor arguments.