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
use std::fs::File;
use std::io::Read;
use std::io::Cursor;
use byteorder::{ BigEndian, ReadBytesExt };
use crate::task::TaskHandle;
#[derive(Debug)]
pub struct SensorLookupTable {
y_values: Vec<f64>,
step_size: u16
}
pub const UPPER_12: u16 = (1 << 12) - 1;
impl SensorLookupTable {
pub fn from_file(task: TaskHandle, file: &mut File) -> Option<Self> {
let mut file_data = Vec::new();
let _len = task.res_error(file.read_to_end(&mut file_data))?;
let mut cursor = Cursor::new(file_data);
let n = task.res_error(cursor.read_u16::<BigEndian>())?;
let mut y_values = Vec::new();
while let Ok(y_val) = cursor.read_f64::<BigEndian>() {
y_values.push(y_val);
}
if y_values.len() != (n as usize) {
task.error(format!("LookupTable expected {} points, found {}", n, y_values.len()));
None
} else {
let step_size = UPPER_12 / ((y_values.len()-1) as u16);
Some(SensorLookupTable { y_values, step_size })
}
}
pub fn lookup(&self, value: u16) -> Option<f64> {
if value > UPPER_12 {
return None;
}
let index = (value / self.step_size) as usize;
let offset = value % self.step_size;
let lower_y: f64 = self.y_values[index];
let upper_y: f64 = self.y_values[index+1];
if offset == 0 {
Some(lower_y)
} else {
let ratio_a = (offset as f64) / (self.step_size as f64);
let ratio_b = 1.0 - ratio_a;
let y_value = (ratio_a * lower_y) + (ratio_b * upper_y);
Some(y_value)
}
}
pub fn inverse_lookup(&self, value: f64) -> Option<u16> {
let mut low_index = 0;
let mut high_index = self.y_values.len() - 1;
let mut low_val = self.y_values[low_index];
let mut high_val = self.y_values[high_index];
if value < low_val || value > high_val {
return None;
}
while high_index-low_index > 1 {
let mid_index = (low_index + high_index) / 2;
let mid_val = self.y_values[mid_index];
if value <= mid_val {
high_index = mid_index;
high_val = mid_val
} else {
low_index = mid_index;
low_val = mid_val;
}
}
let average_val = (low_val + high_val) / 2.0;
if value < average_val {
Some(low_index as u16)
} else {
Some(high_index as u16)
}
}
}
#[cfg(test)]
mod test {
fn perfect_table_point_lookup_is_exact() {
}
fn lookups_are_between_points() {
}
}