pqopen-lib 0.2.0__tar.gz

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,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 DaqOpen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.4
2
+ Name: pqopen-lib
3
+ Version: 0.2.0
4
+ Summary: A power quality processing library for calculating parameters from waveform data
5
+ Project-URL: Homepage, https://github.com/DaqOpen/pqopen-lib
6
+ Project-URL: Issues, https://github.com/DaqOpen/pqopen-lib/issues
7
+ Author-email: Michael Oberhofer <info@pqopen.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.11
13
+ Requires-Dist: daqopen-lib
14
+ Requires-Dist: numpy
15
+ Requires-Dist: scipy
16
+ Description-Content-Type: text/markdown
17
+
18
+ # pqopen-lib
19
+
20
+ `pqopen-lib` is a Python library designed for advanced power system and power quality analysis. It provides tools for creating and analyzing power systems, detecting events, managing data storage, and more. Built with modularity and flexibility in mind, it supports single-phase to multi-phase systems and complies with IEC standards for power quality analysis.
21
+
22
+
23
+
24
+ ## Features
25
+
26
+ - **Power System Modeling**: Create single-phase or multi-phase power systems with detailed phase configuration.
27
+ - **Power Quality Analysis**: Perform harmonic, fluctuation, and power quality calculations in compliance with standards like IEC 61000-4-7 and IEC 61000-4-30.
28
+ - **Event Detection**: Detect and classify events such as overvoltage, undervoltage, and other anomalies in real-time.
29
+ - **Data Storage and Export**: Manage time-series and aggregated data with support for various storage backends like CSV, and MQTT
30
+ - **Zero-Crossing Detection**: Enable accurate cycle-by-cycle processing for fundamental frequency synchronization.
31
+ - **High Performance**: Efficiently handle high-resolution waveform data and sampling rates.
32
+
33
+
34
+
35
+ ## Installation
36
+
37
+ Ensure you have Python 3.11 or later installed. To install `pqopen-lib` along with its dependencies:
38
+
39
+ ```bash
40
+ pip install pqopen-lib
41
+ ```
42
+
43
+
44
+
45
+ ## Documentation
46
+
47
+ Detailed [documentation](https://docs.daqopen.com/reference/pqopen/) is available for each module and function. Key modules include:
48
+
49
+ - **`powersystem`**: Define and manage power systems and phases.
50
+ - **`powerquality`**: Perform power quality and harmonic analyses.
51
+ - **`eventdetector`**: Detect and analyze power events.
52
+ - **`storagecontroller`**: Manage and export time-series and aggregated data.
53
+ - **`zcd`**: Handle zero-crossing detection for waveform synchronization.
54
+
55
+
56
+
57
+ ## Use Cases
58
+
59
+ - **Education**: Learn to understand how power and power quality analysis works
60
+ - **Power Quality Monitoring**: Ensure compliance with power quality standards.
61
+ - **Industrial Power Systems**: Monitor and analyze complex, multi-phase systems.
62
+ - **Research and Development**: Use as a reference platform for power quality testing
63
+
64
+
65
+
66
+ ## Getting Started
67
+
68
+ Here’s a quick example to get you started:
69
+
70
+ ### Create a Simple Power System
71
+
72
+ ```python
73
+ import numpy as np
74
+
75
+ from pqopen.powersystem import PowerSystem
76
+ from daqopen.channelbuffer import AcqBuffer
77
+
78
+ samplerate = 10_000 # Hz
79
+ signal_duration = 1.0 # seconds
80
+
81
+ voltage_magnitude = 230.0 # Volt
82
+ current_magnitude = 10.0 # Ampere
83
+
84
+ frequency = 50.0 # Hz
85
+
86
+ # Create time signal
87
+ t = np.linspace(0,int(signal_duration),int(samplerate*signal_duration),endpoint=False)
88
+ # Create voltage signal
89
+ u = voltage_magnitude*np.sqrt(2)*np.sin(2*np.pi*t*frequency)
90
+ # Create current signal
91
+ i = current_magnitude*np.sqrt(2)*np.sin(2*np.pi*t*frequency)
92
+
93
+ # Create Channel/Buffer for input waveform
94
+ ch_t = AcqBuffer()
95
+ ch_u = AcqBuffer()
96
+ ch_i = AcqBuffer()
97
+
98
+ # Create minimal power system
99
+ my_power_system = PowerSystem(zcd_channel=ch_u,
100
+ input_samplerate=samplerate)
101
+
102
+ # Create power phase and append to power system
103
+ my_power_system.add_phase(u_channel=ch_u, i_channel=ch_i)
104
+
105
+ # Add data to channels (we can apply all data at once because the
106
+ # buffer is big enough to hold the test dataset)
107
+ ch_t.put_data(t)
108
+ ch_u.put_data(u)
109
+ ch_i.put_data(i)
110
+
111
+ # Perform calculation
112
+ my_power_system.process()
113
+
114
+ # View the results
115
+ for ch_name, ch_buffer in my_power_system.output_channels.items():
116
+ print(f"{ch_name:<14} {ch_buffer.last_sample_value:.2f} {ch_buffer.unit}")
117
+ ```
118
+
119
+
120
+
121
+ ## Contributing
122
+
123
+ Contributions are welcome! Please open issues for bugs or feature requests and submit pull requests for improvements.
124
+
125
+ 1. Fork the repository.
126
+ 2. Create your feature branch (`git checkout -b feature/my-feature`).
127
+ 3. Commit your changes (`git commit -m 'Add my feature'`).
128
+ 4. Push to the branch (`git push origin feature/my-feature`).
129
+ 5. Open a pull request.
130
+
131
+
132
+
133
+ ## License
134
+
135
+ This project is licensed under the MIT License. See the LICENSE file for details.
136
+
137
+ ------
138
+
139
+ For any questions or support, feel free to reach out via the issues page or contact me michael@daqopen.com
@@ -0,0 +1,122 @@
1
+ # pqopen-lib
2
+
3
+ `pqopen-lib` is a Python library designed for advanced power system and power quality analysis. It provides tools for creating and analyzing power systems, detecting events, managing data storage, and more. Built with modularity and flexibility in mind, it supports single-phase to multi-phase systems and complies with IEC standards for power quality analysis.
4
+
5
+
6
+
7
+ ## Features
8
+
9
+ - **Power System Modeling**: Create single-phase or multi-phase power systems with detailed phase configuration.
10
+ - **Power Quality Analysis**: Perform harmonic, fluctuation, and power quality calculations in compliance with standards like IEC 61000-4-7 and IEC 61000-4-30.
11
+ - **Event Detection**: Detect and classify events such as overvoltage, undervoltage, and other anomalies in real-time.
12
+ - **Data Storage and Export**: Manage time-series and aggregated data with support for various storage backends like CSV, and MQTT
13
+ - **Zero-Crossing Detection**: Enable accurate cycle-by-cycle processing for fundamental frequency synchronization.
14
+ - **High Performance**: Efficiently handle high-resolution waveform data and sampling rates.
15
+
16
+
17
+
18
+ ## Installation
19
+
20
+ Ensure you have Python 3.11 or later installed. To install `pqopen-lib` along with its dependencies:
21
+
22
+ ```bash
23
+ pip install pqopen-lib
24
+ ```
25
+
26
+
27
+
28
+ ## Documentation
29
+
30
+ Detailed [documentation](https://docs.daqopen.com/reference/pqopen/) is available for each module and function. Key modules include:
31
+
32
+ - **`powersystem`**: Define and manage power systems and phases.
33
+ - **`powerquality`**: Perform power quality and harmonic analyses.
34
+ - **`eventdetector`**: Detect and analyze power events.
35
+ - **`storagecontroller`**: Manage and export time-series and aggregated data.
36
+ - **`zcd`**: Handle zero-crossing detection for waveform synchronization.
37
+
38
+
39
+
40
+ ## Use Cases
41
+
42
+ - **Education**: Learn to understand how power and power quality analysis works
43
+ - **Power Quality Monitoring**: Ensure compliance with power quality standards.
44
+ - **Industrial Power Systems**: Monitor and analyze complex, multi-phase systems.
45
+ - **Research and Development**: Use as a reference platform for power quality testing
46
+
47
+
48
+
49
+ ## Getting Started
50
+
51
+ Here’s a quick example to get you started:
52
+
53
+ ### Create a Simple Power System
54
+
55
+ ```python
56
+ import numpy as np
57
+
58
+ from pqopen.powersystem import PowerSystem
59
+ from daqopen.channelbuffer import AcqBuffer
60
+
61
+ samplerate = 10_000 # Hz
62
+ signal_duration = 1.0 # seconds
63
+
64
+ voltage_magnitude = 230.0 # Volt
65
+ current_magnitude = 10.0 # Ampere
66
+
67
+ frequency = 50.0 # Hz
68
+
69
+ # Create time signal
70
+ t = np.linspace(0,int(signal_duration),int(samplerate*signal_duration),endpoint=False)
71
+ # Create voltage signal
72
+ u = voltage_magnitude*np.sqrt(2)*np.sin(2*np.pi*t*frequency)
73
+ # Create current signal
74
+ i = current_magnitude*np.sqrt(2)*np.sin(2*np.pi*t*frequency)
75
+
76
+ # Create Channel/Buffer for input waveform
77
+ ch_t = AcqBuffer()
78
+ ch_u = AcqBuffer()
79
+ ch_i = AcqBuffer()
80
+
81
+ # Create minimal power system
82
+ my_power_system = PowerSystem(zcd_channel=ch_u,
83
+ input_samplerate=samplerate)
84
+
85
+ # Create power phase and append to power system
86
+ my_power_system.add_phase(u_channel=ch_u, i_channel=ch_i)
87
+
88
+ # Add data to channels (we can apply all data at once because the
89
+ # buffer is big enough to hold the test dataset)
90
+ ch_t.put_data(t)
91
+ ch_u.put_data(u)
92
+ ch_i.put_data(i)
93
+
94
+ # Perform calculation
95
+ my_power_system.process()
96
+
97
+ # View the results
98
+ for ch_name, ch_buffer in my_power_system.output_channels.items():
99
+ print(f"{ch_name:<14} {ch_buffer.last_sample_value:.2f} {ch_buffer.unit}")
100
+ ```
101
+
102
+
103
+
104
+ ## Contributing
105
+
106
+ Contributions are welcome! Please open issues for bugs or feature requests and submit pull requests for improvements.
107
+
108
+ 1. Fork the repository.
109
+ 2. Create your feature branch (`git checkout -b feature/my-feature`).
110
+ 3. Commit your changes (`git commit -m 'Add my feature'`).
111
+ 4. Push to the branch (`git push origin feature/my-feature`).
112
+ 5. Open a pull request.
113
+
114
+
115
+
116
+ ## License
117
+
118
+ This project is licensed under the MIT License. See the LICENSE file for details.
119
+
120
+ ------
121
+
122
+ For any questions or support, feel free to reach out via the issues page or contact me michael@daqopen.com
@@ -0,0 +1,11 @@
1
+ # pqopen/__init__.py
2
+
3
+ """ Power and power quality processing library
4
+
5
+ Modules:
6
+ powersystem: Create single to multi-phase power systems
7
+ powerquality: Collection of Classes and functions for power quality analysis
8
+ zcd: Zero cross detector for cycle-by-cycle processing
9
+ helper: Some helper functions and classes
10
+
11
+ """
@@ -0,0 +1,184 @@
1
+ import numpy as np
2
+ from daqopen.channelbuffer import DataChannelBuffer, AcqBuffer
3
+ from persistmq.client import PersistClient
4
+ from pathlib import Path
5
+ from typing import List, Dict
6
+ import logging
7
+ import json
8
+ import uuid
9
+ from dataclasses import dataclass
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ @dataclass
14
+ class Event:
15
+ start_ts: float
16
+ stop_ts: float
17
+ start_sidx: int
18
+ stop_sidx: int
19
+ extrem_value: float
20
+ channel: str
21
+ type: str
22
+ id: uuid.UUID
23
+
24
+
25
+ class EventDetector(object):
26
+ def __init__(self, limit: float, threshold: float, observed_channel: DataChannelBuffer):
27
+ self.limit = limit
28
+ self.threshold = threshold
29
+ self.observed_channel = observed_channel
30
+ self.last_channel_data = None
31
+ self.last_channel_sidx = None
32
+ self._unfinished_event = {}
33
+ self._type = ""
34
+
35
+ def process(self, start_sidx: int, stop_sidx: int):
36
+ ...
37
+
38
+ def _get_channel_data(self, start_sidx, stop_sidx):
39
+ data, sidx = self.observed_channel.read_data_by_acq_sidx(start_sidx, stop_sidx)
40
+ if data.size < 1:
41
+ return None, None
42
+ if self.last_channel_data:
43
+ data = np.r_[self.last_channel_data, data]
44
+ sidx = np.r_[self.last_channel_sidx, sidx]
45
+ self.last_channel_data = data[-1]
46
+ self.last_channel_sidx = sidx[-1]
47
+ return data, sidx
48
+
49
+ class EventDetectorLevelLow(EventDetector):
50
+ def __init__(self, limit: float, threshold: float, observed_channel: DataChannelBuffer):
51
+ super().__init__(limit, threshold, observed_channel)
52
+ self._type = "LEVEL_LOW"
53
+
54
+ def process(self, start_sidx, stop_sidx):
55
+ data, sidx = self._get_channel_data(start_sidx, stop_sidx)
56
+ if data is None:
57
+ return None
58
+ limit_cross = np.diff(np.sign(data - self.limit))
59
+ limit_cross_idx = np.where(limit_cross < 0)[0] + 1 # take next index
60
+ threshold_cross = np.diff(np.sign(data - self.limit - self.threshold))
61
+ threshold_cross_idx = np.where(threshold_cross > 0)[0] + 1 # take next index
62
+ events = []
63
+ if self._unfinished_event:
64
+ events.append(self._unfinished_event)
65
+ limit_cross_idx = np.r_[0, limit_cross_idx]
66
+ evt_stop_idx = 0
67
+ for limit_idx in limit_cross_idx:
68
+ if limit_idx < evt_stop_idx:
69
+ continue
70
+ if limit_idx > 0: # Add new event
71
+ events.append({"start_sidx": int(sidx[limit_idx]), "stop_sidx": None, "extrem_value": np.inf, "id": uuid.uuid4()})
72
+ evt_stop_thr_idx = np.where(threshold_cross_idx > limit_idx)[0]
73
+ if evt_stop_thr_idx.size > 0: # complete event
74
+ logger.debug("Event Completed")
75
+ evt_stop_idx = threshold_cross_idx[evt_stop_thr_idx[0]]
76
+ events[-1]["stop_sidx"] = int(sidx[evt_stop_idx])
77
+ events[-1]["extrem_value"] = min(events[-1]["extrem_value"], data[limit_idx:evt_stop_idx].min())
78
+ else:
79
+ events[-1]["extrem_value"] = min(events[-1]["extrem_value"], data[limit_idx:].min())
80
+ break
81
+
82
+ if events and events[-1]["stop_sidx"] is None:
83
+ self._unfinished_event = events[-1]
84
+ else:
85
+ self._unfinished_event = {}
86
+
87
+ return events
88
+
89
+ class EventDetectorLevelHigh(EventDetector):
90
+ def __init__(self, limit: float, threshold: float, observed_channel: DataChannelBuffer):
91
+ super().__init__(limit, threshold, observed_channel)
92
+ self._type = "LEVEL_HIGH"
93
+
94
+ def process(self, start_sidx, stop_sidx):
95
+ data, sidx = self._get_channel_data(start_sidx, stop_sidx)
96
+ if data is None:
97
+ return None
98
+ limit_cross = np.diff(np.sign(data - self.limit))
99
+ limit_cross_idx = np.where(limit_cross > 0)[0] + 1 # take next index
100
+ threshold_cross = np.diff(np.sign(data - self.limit + self.threshold))
101
+ threshold_cross_idx = np.where(threshold_cross < 0)[0] + 1 # take next index
102
+ events = []
103
+ if self._unfinished_event:
104
+ events.append(self._unfinished_event)
105
+ limit_cross_idx = np.r_[0, limit_cross_idx]
106
+ evt_stop_idx = 0
107
+ for limit_idx in limit_cross_idx:
108
+ if limit_idx < evt_stop_idx:
109
+ continue
110
+ if limit_idx > 0: # Add new event
111
+ events.append({"start_sidx": int(sidx[limit_idx]), "stop_sidx": None, "extrem_value": -np.inf, "id": uuid.uuid4()})
112
+ evt_stop_thr_idx = np.where(threshold_cross_idx > limit_idx)[0]
113
+ if evt_stop_thr_idx.size > 0: # complete event
114
+ logger.debug("Event Completed")
115
+ evt_stop_idx = threshold_cross_idx[evt_stop_thr_idx[0]]
116
+ events[-1]["stop_sidx"] = int(sidx[evt_stop_idx])
117
+ events[-1]["extrem_value"] = max(events[-1]["extrem_value"], data[limit_idx:evt_stop_idx].max())
118
+ else:
119
+ events[-1]["extrem_value"] = max(events[-1]["extrem_value"], data[limit_idx:].max())
120
+ break
121
+
122
+ if events and events[-1]["stop_sidx"] is None:
123
+ self._unfinished_event = events[-1]
124
+ else:
125
+ self._unfinished_event = {}
126
+
127
+ return events
128
+
129
+
130
+ class EventController(object):
131
+ PROCESSING_DELAY_SECONDS = 0.1
132
+
133
+ def __init__(self, time_channel: AcqBuffer, sample_rate: float):
134
+ self._time_channel = time_channel
135
+ self._sample_rate = sample_rate
136
+ self._event_detectors: List[EventDetector] = []
137
+ self._last_processed_sidx = 0
138
+ self._unfinished_events: Dict[uuid.UUID: Event] = {}
139
+
140
+ def add_event_detector(self, event_detector: EventDetector):
141
+ self._event_detectors.append(event_detector)
142
+
143
+ def process(self) -> List[Event]:
144
+ start_acq_sidx = self._last_processed_sidx
145
+ stop_acq_sidx = self._time_channel.sample_count - int(self.PROCESSING_DELAY_SECONDS*self._sample_rate)
146
+ start_sidx_ts = int(self._time_channel.read_data_by_index(start_acq_sidx, start_acq_sidx+1)[0])
147
+ self._last_processed_sidx = stop_acq_sidx
148
+ if stop_acq_sidx <= 0:
149
+ return []
150
+ all_events = []
151
+ for event_detector in self._event_detectors:
152
+ events = event_detector.process(start_acq_sidx, stop_acq_sidx)
153
+ if events:
154
+ for event in events:
155
+ if event["id"] in self._unfinished_events:
156
+ start_ts = self._unfinished_events[event["id"]].start_ts
157
+ else:
158
+ start_ts = self._time_channel.read_data_by_index(event["start_sidx"], event["start_sidx"]+1)[0]/1e6
159
+ if event["stop_sidx"]:
160
+ stop_ts = self._time_channel.read_data_by_index(event["stop_sidx"], event["stop_sidx"]+1)[0]/1e6
161
+ # Delete finished event from map
162
+ if event["id"] in self._unfinished_events:
163
+ del self._unfinished_events[event["id"]]
164
+ else:
165
+ stop_ts = None
166
+ single_event = Event(start_ts=start_ts,
167
+ stop_ts=stop_ts if stop_ts else None,
168
+ start_sidx=event["start_sidx"],
169
+ stop_sidx=event["stop_sidx"],
170
+ extrem_value=event["extrem_value"],
171
+ channel=event_detector.observed_channel.name,
172
+ type=event_detector._type,
173
+ id=event["id"])
174
+ all_events.append(single_event)
175
+ # Add unfinished event to map
176
+ if single_event.stop_sidx is None:
177
+ self._unfinished_events[single_event.id] = single_event
178
+ return all_events
179
+
180
+
181
+
182
+
183
+
184
+
@@ -0,0 +1,19 @@
1
+ from datetime import datetime
2
+
3
+ def floor_timestamp(timestamp: float | int, interval_seconds: int, ts_resolution: str = "us"):
4
+ """Floor eines Zeitstempels auf ein gegebenes Intervall."""
5
+ if ts_resolution == "s":
6
+ conversion_factor = 1.0
7
+ elif ts_resolution == "ms":
8
+ conversion_factor = 1_000.0
9
+ elif ts_resolution == "us":
10
+ conversion_factor = 1_000_000.0
11
+ else:
12
+ raise NotImplementedError(f"Time interval {ts_resolution} not implemented")
13
+ if isinstance(timestamp, float):
14
+ seconds = timestamp / conversion_factor
15
+ floored_seconds = seconds - (seconds % interval_seconds)
16
+ return floored_seconds * conversion_factor
17
+ else:
18
+ fraction = timestamp % int(conversion_factor*interval_seconds)
19
+ return timestamp - fraction