wluma 4.4.0

Automatic brightness adjustment based on screen contents and ALS
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
use crate::predictor::data::{Data, Entry};
use itertools::Itertools;
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;

const INITIAL_TIMEOUT_SECS: u64 = 5;
const PENDING_COOLDOWN_RESET: u8 = 15;
const NEXT_ALS_COOLDOWN_RESET: u8 = 15;

pub struct Controller {
    prediction_tx: Sender<u64>,
    user_rx: Receiver<u64>,
    als_rx: Receiver<String>,
    pending_cooldown: u8,
    pending: Option<Entry>,
    data: Data,
    stateful: bool,
    initial_brightness: Option<u64>,
    last_als: Option<String>,
    next_als: Option<String>,
    next_als_cooldown: u8,
    output_name: String,
}

impl Controller {
    pub fn new(
        prediction_tx: Sender<u64>,
        user_rx: Receiver<u64>,
        als_rx: Receiver<String>,
        stateful: bool,
        output_name: &str,
    ) -> Self {
        let data = if stateful {
            Data::load(output_name)
        } else {
            Data::new(output_name)
        };

        Self {
            prediction_tx,
            user_rx,
            als_rx,
            pending_cooldown: 0,
            pending: None,
            data,
            stateful,
            initial_brightness: None,
            last_als: None,
            next_als: None,
            next_als_cooldown: 0,
            output_name: output_name.to_string(),
        }
    }

    pub fn adjust(&mut self, luma: u8) {
        if self.last_als.is_none() {
            // ALS controller is expected to send the initial value on this channel asap
            self.last_als = self
                .als_rx
                .recv_timeout(Duration::from_secs(INITIAL_TIMEOUT_SECS))
                .map_or_else(
                    |_| panic!("Did not receive initial ALS value in time"),
                    Some,
                );

            // Brightness controller is expected to send the initial value on this channel asap
            let initial_brightness = self
                .user_rx
                .recv_timeout(Duration::from_secs(INITIAL_TIMEOUT_SECS))
                .map_or_else(
                    |_| panic!("Did not receive initial brightness value in time"),
                    Some,
                );

            // If there are no learned entries yet, we will use this as the first data point,
            // assuming that user is happy with the current brightness settings
            if self.data.entries.is_empty() {
                self.initial_brightness = initial_brightness;
            };
        }

        match self.als_rx.try_iter().last() {
            new_als @ Some(_) if self.next_als != new_als => {
                self.next_als = new_als;
                self.next_als_cooldown = NEXT_ALS_COOLDOWN_RESET;
            }
            _ if self.next_als_cooldown > 1 => {
                self.next_als_cooldown -= 1;
            }
            _ if self.next_als_cooldown == 1 => {
                self.next_als_cooldown = 0;
                self.last_als = self.next_als.take();
            }
            _ => {}
        }

        let lux = &self.last_als.clone().expect("ALS value must be known");
        self.process(lux, luma);
    }

    fn process(&mut self, lux: &str, luma: u8) {
        let initial_brightness = self.initial_brightness.take();
        let user_changed_brightness = self.user_rx.try_iter().last().or(initial_brightness);

        if let Some(brightness) = user_changed_brightness {
            self.pending = match &self.pending {
                // First time we notice user adjusting brightness, freeze lux and luma...
                None => Some(Entry::new(lux, luma, brightness)),
                // ... but as user keeps changing brightness,
                // allow some time for them to reach the desired brightness level for the pending lux and luma
                Some(Entry { lux, luma, .. }) => Some(Entry::new(lux, *luma, brightness)),
            };
            // Every time user changed brightness, reset the cooldown period
            self.pending_cooldown = PENDING_COOLDOWN_RESET;
        } else if self.pending_cooldown > 0 {
            self.pending_cooldown -= 1;
        } else if self.pending.is_some() {
            self.learn();
        } else {
            self.predict(lux, luma);
        }
    }

    fn learn(&mut self) {
        let pending = self.pending.take().expect("No pending entry to learn");
        log::debug!("[{}] Learning {:?}", self.output_name, pending);

        self.data.entries.retain(|entry| {
            let different_env = entry.lux != pending.lux;

            let same_env_darker_screen = entry.lux == pending.lux
                && entry.luma < pending.luma
                && entry.brightness >= pending.brightness;

            let same_env_brighter_screen = entry.lux == pending.lux
                && entry.luma > pending.luma
                && entry.brightness <= pending.brightness;

            different_env || same_env_darker_screen || same_env_brighter_screen
        });

        self.data.entries.push(pending);

        self.data
            .entries
            .sort_unstable_by(|x, y| x.lux.cmp(&y.lux).then(x.luma.cmp(&y.luma)));

        if self.stateful {
            self.data.save().expect("Unable to save data");
        }
    }

    fn predict(&mut self, lux: &str, luma: u8) {
        let entries = self
            .data
            .entries
            .iter()
            .filter(|e| e.lux == lux)
            .collect_vec();

        if entries.is_empty() {
            return;
        }

        let points = entries
            .iter()
            .map(|entry| {
                let distance = (luma as f64 - entry.luma as f64).abs();
                (entry.brightness as f64, distance)
            })
            .collect_vec();

        let points = points
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let other_distances: f64 = points[0..i]
                    .iter()
                    .chain(&points[i + 1..])
                    .map(|p| p.1)
                    .product();
                (p.0, p.1, other_distances)
            })
            .collect_vec();

        let distance_denominator: f64 = points
            .iter()
            .map(|p| p.1)
            .combinations(points.len() - 1)
            .map(|c| c.iter().product::<f64>())
            .sum();

        let prediction = points
            .iter()
            .map(|p| p.0 * p.2 / distance_denominator)
            .sum::<f64>() as u64;

        log::trace!("Prediction: {} (lux: {}, luma: {})", prediction, lux, luma);
        self.prediction_tx
            .send(prediction)
            .expect("Unable to send predicted brightness value, channel is dead");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::iproduct;
    use std::collections::HashSet;
    use std::error::Error;
    use std::sync::mpsc;

    const ALS_DARK: &str = "dark";
    const ALS_DIM: &str = "dim";
    const ALS_BRIGHT: &str = "bright";

    fn setup() -> Result<(Controller, Sender<u64>, Receiver<u64>), Box<dyn Error>> {
        let (als_tx, als_rx) = mpsc::channel();
        let (user_tx, user_rx) = mpsc::channel();
        let (prediction_tx, prediction_rx) = mpsc::channel();
        als_tx.send(ALS_BRIGHT.to_string())?;
        user_tx.send(0)?;
        let controller = Controller::new(prediction_tx, user_rx, als_rx, false, "Dell 1");
        Ok((controller, user_tx, prediction_rx))
    }

    #[test]
    fn test_process_first_user_change() -> Result<(), Box<dyn Error>> {
        let (mut controller, user_tx, _) = setup()?;

        // User changes brightness to value 33 for a given lux and luma
        user_tx.send(33)?;
        controller.process(ALS_DIM, 66);

        assert_eq!(Some(Entry::new(ALS_DIM, 66, 33)), controller.pending);
        assert_eq!(PENDING_COOLDOWN_RESET, controller.pending_cooldown);

        Ok(())
    }

    #[test]
    fn test_process_several_continuous_user_changes() -> Result<(), Box<dyn Error>> {
        let (mut controller, user_tx, _) = setup()?;

        // User initiates brightness change for a given lux and luma to value 33...
        user_tx.send(33)?;
        controller.process(ALS_DIM, 66);
        // then quickly continues increasing it to 34 (while lux and luma might already be different)...
        user_tx.send(34)?;
        controller.process(ALS_BRIGHT, 36);
        // and even faster to 36 (which is the indended brightness value they wish to learn for the initial lux and luma)
        user_tx.send(35)?;
        user_tx.send(36)?;
        controller.process(ALS_DARK, 16);

        assert_eq!(Some(Entry::new(ALS_DIM, 66, 36)), controller.pending);
        assert_eq!(PENDING_COOLDOWN_RESET, controller.pending_cooldown);

        Ok(())
    }

    #[test]
    fn test_process_learns_user_change_after_cooldown() -> Result<(), Box<dyn Error>> {
        let (mut controller, user_tx, _) = setup()?;

        // User changes brightness to a desired value
        user_tx.send(33)?;
        controller.process(ALS_DIM, 66);
        user_tx.send(33)?;
        controller.process(ALS_BRIGHT, 36);
        user_tx.send(35)?;
        controller.process(ALS_DARK, 16);

        for i in 1..=PENDING_COOLDOWN_RESET {
            // User doesn't change brightness anymore, so even if lux or luma change, we are in cooldown period
            controller.process(ALS_BRIGHT, i);
            assert_eq!(PENDING_COOLDOWN_RESET - i, controller.pending_cooldown);
            assert_eq!(Some(Entry::new(ALS_DIM, 66, 35)), controller.pending);
        }

        // One final process will trigger the learning
        controller.process(ALS_DARK, 17);

        assert_eq!(None, controller.pending);
        assert_eq!(0, controller.pending_cooldown);
        assert_eq!(vec![Entry::new(ALS_DIM, 66, 35)], controller.data.entries);

        Ok(())
    }

    // If user configured brightness value in certain conditions (amount of light around, screen contents),
    // how changes in environment or screen contents can affect the desired brightness level:
    //
    // |                 | darker env      | same env         | brighter env     |
    // | darker screen   | any             | same or brighter | same or brighter |
    // | same screen     | same or dimmer  | only same        | same or brighter |
    // | brighter screen | same or dimmer  | same or dimmer   | any              |
    //
    // *UPDATE*: experimenting with not changing other envs

    #[test]
    fn test_learn_data_cleanup() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, _) = setup()?;

        let pending = Entry::new(ALS_DIM, 20, 30);

        let all_als = vec![ALS_DARK, ALS_DIM, ALS_BRIGHT];
        let all_combinations: HashSet<_> = iproduct!(-1i32..=1, -1i32..=1, -1i32..=1)
            .map(|(i, j, k)| {
                Entry::new(
                    all_als[(1 + i) as usize].clone(),
                    (20 + j) as u8,
                    (30 + k) as u64,
                )
            })
            .collect();

        let to_be_deleted: HashSet<_> = vec![
            // same env darker screen
            Entry::new(ALS_DIM, 19, 29),
            // same env same screen
            Entry::new(ALS_DIM, 20, 29),
            Entry::new(ALS_DIM, 20, 31),
            // same env brighter screen
            Entry::new(ALS_DIM, 21, 31),
        ]
        .into_iter()
        .collect();

        controller.data.entries = all_combinations.iter().cloned().collect_vec();
        controller.pending = Some(pending);

        controller.learn();

        let to_remain: HashSet<_> = all_combinations.difference(&to_be_deleted).collect();
        let remained = controller.data.entries.iter().collect();

        assert_eq!(
            Vec::<&&Entry>::new(),
            to_remain.difference(&remained).collect_vec(),
            "unexpected entries were removed"
        );

        assert_eq!(
            Vec::<&&Entry>::new(),
            remained.difference(&to_remain).collect_vec(),
            "some entries were not removed"
        );

        assert_eq!(
            to_remain.len(),
            controller.data.entries.len(),
            "duplicate entries remained"
        );

        Ok(())
    }

    #[test]
    fn test_predict_no_data_points() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![];

        // predict() should not be called with no data, but just in case confirm we don't panic
        controller.predict(ALS_DIM, 20);

        assert_eq!(true, prediction_rx.try_recv().is_err());

        Ok(())
    }

    #[test]
    fn test_predict_no_data_points_for_current_als_profile() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![
            Entry::new(ALS_DARK, 50, 100),
            Entry::new(ALS_BRIGHT, 60, 100),
        ];

        // predict() should not be called with no data, but just in case confirm we don't panic
        controller.predict(ALS_DIM, 20);

        assert_eq!(true, prediction_rx.try_recv().is_err());

        Ok(())
    }

    #[test]
    fn test_predict_one_data_point() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![Entry::new(ALS_DIM, 10, 15)];

        controller.predict(ALS_DIM, 20);

        assert_eq!(15, prediction_rx.try_recv()?);
        Ok(())
    }

    #[test]
    fn test_predict_known_conditions() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![Entry::new(ALS_DIM, 10, 15), Entry::new(ALS_DIM, 20, 30)];

        controller.predict(ALS_DIM, 20);

        assert_eq!(30, prediction_rx.try_recv()?);
        Ok(())
    }

    #[test]
    fn test_predict_approximate() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![
            Entry::new(ALS_DIM, 10, 15),
            Entry::new(ALS_DIM, 20, 30),
            Entry::new(ALS_DIM, 100, 100),
        ];

        // Approximated using weighted distance to all known points:
        // dist1 = sqrt((x1 - x2)^2 + (y1 - y2)^2)
        // weight1 = (1/dist1) / (1/dist1 + 1/dist2 + 1/dist3)
        // prediction = weight1*brightness1 + weight2*brightness2 + weight3*brightness
        controller.predict(ALS_DIM, 50);

        assert_eq!(43, prediction_rx.try_recv()?);
        Ok(())
    }

    #[test]
    fn test_predict_only_uses_data_for_current_als_profile() -> Result<(), Box<dyn Error>> {
        let (mut controller, _, prediction_rx) = setup()?;
        controller.data.entries = vec![
            Entry::new(ALS_DIM, 10, 15),
            Entry::new(ALS_DIM, 20, 30),
            Entry::new(ALS_DIM, 100, 100),
            Entry::new(ALS_DARK, 50, 100),
            Entry::new(ALS_BRIGHT, 51, 100),
        ];

        controller.predict(ALS_DIM, 50);

        assert_eq!(43, prediction_rx.try_recv()?);
        Ok(())
    }
}