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
use super::*;
use crate::{
config::*,
ps::{ApsMode, ApsSettings, AvPowerSpectra, CPSSettings},
*,
};
use anyhow::{Result, bail};
use crossbeam::channel::{Receiver, Sender};
use ndarray::ArcArray2;
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
/// Status of the Cross Power Spectra computation thread
#[derive(Debug, Clone)]
pub enum CPSComputeStatus {
/// Waiting for data to be available
Waiting,
/// Computing / updating Cross Power Spectra
Computing,
/// Done computing Cross Power Spectra
Done(Option<Array3<Cflt>>),
}
/// Internal message for interacting with the Cross Power Spectra computation thread
enum CPSMessage {
/// New time data to process
NewTimeData(ArcArray2<Flt>),
/// Stop waiting for new time data blocks for computing Cross Power Spectra.
/// This breaks the waiting loop for messages on the channel, finishes and
/// returns the result.
StopHere,
}
/// Handle to the computation thread for computing Cross Power Spectra.
#[derive(Debug)]
pub struct CPSThread {
settings: CPSSettings,
tx: Sender<CPSMessage>,
consumer: triple_buffer::Output<CPSComputeStatus>,
killFlag: Arc<AtomicBool>,
}
impl CPSThread {
/// Create a new Cross Power Spectra computation thread
///
/// # Arguments
///
/// * `fs` - The sample rate of the input data
/// * `settings` - The settings for the Cross Power Spectra computation
/// * `queue_size` - The size of the queue for the computation thread. If
/// None, the queue will be unbounded.
pub fn new(fs: StrictlyPositive, settings: CPSSettings, queue_size: Option<usize>) -> Self {
let (tx, rx) = if let Some(size) = queue_size {
crossbeam::channel::bounded(size)
} else {
crossbeam::channel::unbounded()
};
let (mut producer, consumer) = triple_buffer::triple_buffer(&CPSComputeStatus::Waiting);
// Flag to communicate to the thread that we are not interested in the
// results anymore
let killFlag = Arc::new(AtomicBool::new(false));
// Copies for storing in struct, and for passing to thread.
let killflag2 = killFlag.clone();
let settings2 = settings;
let apssettings = ApsSettings {
mode: ApsMode::AllAveraging {},
overlap: settings.overlap,
windowType: settings.window,
freqWeightingType: FreqWeighting::Z,
nfft: settings.nfft,
fs,
};
spawn(
move || {
let mut aps = AvPowerSpectra::new(apssettings);
producer.write(CPSComputeStatus::Waiting);
'msgloop: while let Ok(msg) = rx.recv() {
if killFlag.load(Ordering::Relaxed) {
// The main thread is not interested in the result
// (anymore). We stop the computation perform early
// return
producer.write(CPSComputeStatus::Done(None));
return;
}
match msg {
CPSMessage::NewTimeData(block) => {
producer.write(CPSComputeStatus::Computing);
aps.compute_last(&block);
}
CPSMessage::StopHere => {
break 'msgloop;
}
}
}
producer.write(CPSComputeStatus::Done(
aps.get_result().map(|r| r.into_inner()),
));
},
ThreadPriority::Low,
);
Self {
consumer,
tx,
settings: settings2,
killFlag: killflag2,
}
}
/// Get the settings used for the computation.
pub fn getSettings(&self) -> &CPSSettings {
&self.settings
}
/// Stop waiting for new data, perform computation until the last block is
/// processed.
pub fn stopHere(&self) {
self.tx.send(CPSMessage::StopHere).unwrap();
}
/// Push new time series data to the computation thread.
pub fn push(&self, data: ArcArray2<Flt>) {
self.tx.send(CPSMessage::NewTimeData(data)).unwrap();
}
/// Get the status of the computation thread.
pub fn get_status(&mut self) -> &CPSComputeStatus {
self.consumer.read()
}
/// Wait till all blocks in queue are processed, then the thread stops and
/// the result is returned.
pub fn join(&mut self) -> (CPSSettings, Option<Array3<Cflt>>) {
self.stopHere();
while !matches!(self.get_status(), CPSComputeStatus::Done(_)) {
std::thread::sleep(std::time::Duration::from_millis(10));
}
let res = {
let CPSComputeStatus::Done(res) = &self.get_status() else {
panic!("BUG: Unexpected thread status!");
};
res.clone()
};
(self.settings, res)
}
}
impl Drop for CPSThread {
fn drop(&mut self) {
// Set kill flag to stop the thread
self.killFlag.store(true, Ordering::Relaxed);
// Send one last message to wake up the thread. If already stopped, this
// will be ignored, but we get a senderror back because the receiver is
// already dropped.
let _ = self.tx.send(CPSMessage::StopHere);
// Wait for thread to finish
while !matches!(self.get_status(), CPSComputeStatus::Done(_)) {
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}