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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! The library contains all internal data structures utilized in maintaining
//! records.
#![deny(missing_docs)]
#![feature(test)]
extern crate test;

use serde::{Deserialize, Serialize};

use std::collections::hash_map::Entry;
use std::collections::hash_map::Values;
use std::collections::HashMap;
use std::fs::File;

pub mod communication;
pub mod file;
pub mod parse;
pub mod stats;

/// A UUID identifies a user. In the flask front-end it's stored as a randomly
/// generated cookie and transmitted as a hexadecimal string.
pub type UserIdentifier = u64;
/// Mapping from time (f32) to styles.
pub type TimeStyleRecord = (f32, (HeaderStyle, BodyStyle));

/// A generic Request enum that encapsulates functionality of put and get
/// requests.
#[derive(Debug, PartialEq)]
#[allow(missing_docs)]
pub enum Request {
    PutRequest(PutRequest),
    GetRequest(GetRequest),
    WriteRequest,
}

/// This request may be sent to modify the database and add an entry.
#[derive(Debug, PartialEq)]
pub enum PutRequest {
    /// User-identified time-style record
    UserData(UserIdentifier, TimeStyleRecord),
    /// f32 contrast coefficient paired with text styles.
    ContrastCoefficients((Style, Style), f32),
}

/// This request may be sent to retrieve a record from the database.
#[derive(Debug, Eq, PartialEq)]
pub enum GetRequest {
    /// Get all the data for the given user ID
    UserData(UserIdentifier),
    /// Get an iterator across all of UserData, between identifiers and their
    /// TimeStyleRecords.
    AllUserData,
    /// Get the contrast coefficient for given pairing
    ContrastCoefficients(Style, Style),
    /// All means of contrast coefficients
    ContrastCoefficientsMeans,
    /// Frequency data
    ContrastCoefficientsCounts,
    /// Number of people who have been timed (unique UUIDs)
    NavigabilityPeopleCount,
    /// Request contrast
    Contrast(TextStyle, TextStyle),
    /// Request (contrast, time) pairs
    ContrastTimePairs,
    /// Request PMCC
    PMCC,
}

/// A generic request response.
pub type RequestAns<'a> = Option<GetRequestAns<'a>>;

/// The returned answer of processing a GetRequest: must map 1-to-1 with
/// GetRequest. See GetRequest for information on variants.
#[derive(Debug)]
#[allow(missing_docs)]
pub enum GetRequestAns<'a> {
    UserData(Option<&'a Vec<TimeStyleRecord>>),
    AllUserData(Values<'a, UserIdentifier, Vec<TimeStyleRecord>>),
    ContrastCoefficients(Option<&'a Vec<f32>>),
    ContrastCoefficientsMeans(
        HashMap<(Inlines, Inlines), f32>,
        HashMap<(Align, Align), f32>,
        HashMap<(Font, Font), f32>,
    ),
    ContrastCoefficientsCounts(
        HashMap<(Inlines, Inlines), usize>,
        HashMap<(Align, Align), usize>,
        HashMap<(Font, Font), usize>,
    ),
    NavigabilityPeopleCount(usize),
    Contrast(Option<f32>),
    ContrastTimePairs(Vec<(f32, f32)>),
    PMCC((f32, usize)),
}

/// BodyStyle is just a textstyle, we don't care about things like
/// paragraph delimiters
pub type BodyStyle = TextStyle;

/// Defines styles that text may take. Headers and body text specifically has
/// extra values, which are in practiced randomised for control.
#[derive(Serialize, Deserialize, Clone, Eq, Debug, Hash, PartialEq)]
pub struct TextStyle {
    inlines: Vec<InlineStyle>,
    align: Align,
    font: Font,
}

/// Header specific style, contains a TextStyle
#[derive(Serialize, Deserialize, Clone, Eq, Debug, PartialEq)]
pub struct HeaderStyle {
    style: TextStyle,
    offset_top: i32,
    offset_bot: i32,
}

/// The database structure delegates record handling to one of two tables, being
/// a UserData table and a ContrastCoefficients table.
#[derive(Serialize, Deserialize)]
pub struct Database {
    ud: UserData,
    cc: ContrastCoefficients,
}

impl TextStyle {
    /// Get the euclidiean difference between two text styles
    pub fn sub(a: &Self, b: &Self, db: &ContrastCoefficients) -> Option<f32> {
        Some(
            ((stats::avg(
                &mut db
                    .get_from_inlines(&a.inlines, &b.inlines)?
                    .iter()
                    .copied(),
            ))
            .powf(2.0)
                + (stats::avg(
                    &mut db
                        .get_from_aligns(&a.align, &b.align)?
                        .iter()
                        .copied(),
                ))
                .powf(2.0)
                + (stats::avg(
                    &mut db.get_from_fonts(&a.font, &b.font)?.iter().copied(),
                ))
                .powf(2.0))
            .sqrt(),
        )
    }
}

/// Map from a UUID to TSRs.
pub type UserData = HashMap<UserIdentifier, Vec<TimeStyleRecord>>;

/// The contrast coefficients structure stores the recorded contrast
/// coefficients for structure pairings.
#[derive(Serialize, Deserialize)]
pub struct ContrastCoefficients {
    inlines: HashMap<(Inlines, Inlines), Vec<f32>>,
    aligns: HashMap<(Align, Align), Vec<f32>>,
    fonts: HashMap<(Font, Font), Vec<f32>>,
}

impl ContrastCoefficients {
    /// Return an empty CC table
    pub fn new() -> ContrastCoefficients {
        ContrastCoefficients {
            inlines: HashMap::new(),
            aligns: HashMap::new(),
            fonts: HashMap::new(),
        }
    }

    /// Insert a record of Inlines and a contrast coefficient.
    pub fn insert_inlines(&mut self, a: Inlines, b: Inlines, val: f32) {
        // Entry can't take a borrowed value for reasons that are beyond me,
        // there's an RFC about it somewhere.
        if let Entry::Vacant(_) = self.inlines.entry((a.clone(), b.clone())) {
            self.inlines.insert((a, b), vec![val]);
        } else {
            self.inlines.get_mut(&(a, b)).unwrap().push(val);
        }
    }

    /// Insert a record of Aligns and a contrast coefficient.
    pub fn insert_align(&mut self, a: Align, b: Align, val: f32) {
        if let Entry::Vacant(_) = self.aligns.entry((a.clone(), b.clone())) {
            self.aligns.insert((a, b), vec![val]);
        } else {
            self.aligns.get_mut(&(a, b)).unwrap().push(val);
        }
    }

    /// Insert a record of Fonts and a contrast coefficient.
    pub fn insert_font(&mut self, a: Font, b: Font, val: f32) {
        if let Entry::Vacant(_) = self.fonts.entry((a.clone(), b.clone())) {
            self.fonts.insert((a, b), vec![val]);
        } else {
            self.fonts.get_mut(&(a, b)).unwrap().push(val);
        }
    }

    /// Get the corresponding contrast coefficients for inline styles
    pub fn get_from_inlines(
        &self,
        a: &Inlines,
        b: &Inlines,
    ) -> Option<&Vec<f32>> {
        self.inlines.get(&(a.to_owned(), b.to_owned()))
    }

    /// Get the corresponding contrast coefficients for aligns
    pub fn get_from_aligns(&self, a: &Align, b: &Align) -> Option<&Vec<f32>> {
        self.aligns.get(&(a.clone(), b.clone()))
    }

    /// Get the corresponding contrast coefficients for fonts
    pub fn get_from_fonts(&self, a: &Font, b: &Font) -> Option<&Vec<f32>> {
        self.fonts.get(&(a.clone(), b.clone()))
    }
}

impl Database {
    /// Construct an empty db
    pub fn new() -> Database {
        Database {
            ud: UserData::new(),
            cc: ContrastCoefficients::new(),
        }
    }

    /// Read from a file
    pub fn from(file: File) -> bincode::Result<Self> {
        bincode::deserialize_from(file)
    }

    /// Serialize the structure with bincode
    pub fn serialize(&self) -> bincode::Result<Vec<u8>> {
        bincode::serialize(self)
    }

    /// Process a generic request: if the request is a getrequest, a
    /// Some(GetRequestAns) is returned, otherwise None is returned.
    pub fn process(&mut self, request: Request) -> Option<GetRequestAns> {
        match request {
            Request::PutRequest(pr) => {
                self.put(pr);
                None
            }
            Request::GetRequest(gr) => Some(self.get(gr)),
            Request::WriteRequest => {
                self.write_to_file();
                None
            }
        }
    }

    /// Process and insert a PutRequest
    ///
    /// Panics if a contrast coefficient comparing unequal styles is passed.
    fn put(&mut self, request: PutRequest) {
        match request {
            PutRequest::UserData(user_id, time) => {
                if let Entry::Vacant(entry) = self.ud.entry(user_id) {
                    entry.insert(Vec::new());
                }

                self.ud.get_mut(&user_id).unwrap().push(time);
            }
            PutRequest::ContrastCoefficients((a, b), coefficient) => {
                match (a, b) {
                    (Style::Inlines(a), Style::Inlines(b)) => {
                        self.cc.insert_inlines(a, b, coefficient);
                    }
                    (Style::Align(a), Style::Align(b)) => {
                        self.cc.insert_align(a, b, coefficient);
                    }
                    (Style::Font(a), Style::Font(b)) => {
                        self.cc.insert_font(a, b, coefficient);
                    }
                    _ => {
                        panic!(
                            "Incompatible styles have been passed to the \
                               contrast coefficient table."
                        )
                    }
                };
            }
        };
    }

    /// Process a GetRequest
    fn get(&self, request: GetRequest) -> GetRequestAns {
        match request {
            GetRequest::UserData(id) => {
                GetRequestAns::UserData(self.ud.get(&id))
            }
            GetRequest::AllUserData => {
                GetRequestAns::AllUserData(self.get_time_style_records())
            }
            GetRequest::ContrastCoefficients(a, b) => {
                GetRequestAns::ContrastCoefficients(self.get_cc_vec(&a, &b))
            }
            GetRequest::ContrastCoefficientsMeans => {
                GetRequestAns::ContrastCoefficientsMeans(
                    stats::average_for_pairs::<Inlines>(&self.cc.inlines),
                    stats::average_for_pairs(&self.cc.aligns),
                    stats::average_for_pairs(&self.cc.fonts),
                )
            }
            GetRequest::ContrastCoefficientsCounts => {
                GetRequestAns::ContrastCoefficientsCounts(
                    stats::counts_for_pairs(&self.cc.inlines),
                    stats::counts_for_pairs(&self.cc.aligns),
                    stats::counts_for_pairs(&self.cc.fonts),
                )
            }
            GetRequest::NavigabilityPeopleCount => {
                GetRequestAns::NavigabilityPeopleCount(self.ud.len())
            }
            GetRequest::Contrast(a, b) => {
                GetRequestAns::Contrast(TextStyle::sub(&a, &b, &self.cc))
            }
            GetRequest::ContrastTimePairs => GetRequestAns::ContrastTimePairs(
                self.get_ud_pairs()
            ),
            GetRequest::PMCC => GetRequestAns::PMCC(
                stats::pmcc(self.get_ud_pairs())
            ),
        }
    }

    /// Get (delta stdev's from mean, contrast) pairs.
    fn get_ud_pairs(&self) -> Vec<(f32, f32)> {
          self.ud
              .iter()
              // !----!
              .filter_map(|(_, v)| {
                  let mut times = v.iter().map(|(t, (_, _))| *t);
                  let mean = stats::avg(&mut times.clone());
                  let stdev = stats::stdev(&mut times)?;

                  Some(v.iter().map(move |(t, (h, b))| ((t - mean) / stdev, (h, b))))
              })
              // !----!
              .flatten()
              .map(|(t, (h, b)) | {
                  (t, TextStyle::sub(&h.style, &b, &self.cc))
              }).map(|(t, d)| {
                  (t, d)
              }).filter(|(_, d)| {
                  d.is_some()
              }).map(|(t, d)| (d.unwrap(), t)).collect()
    }

    /// Return an iterator over userdata time style records
    fn get_time_style_records(
        &self,
    ) -> Values<UserIdentifier, Vec<TimeStyleRecord>> {
        self.ud.values()
    }

    /// Get contrast coefficient vector by styles
    fn get_cc_vec(&self, a: &Style, b: &Style) -> Option<&Vec<f32>> {
        match (a, b) {
            (Style::Inlines(a), Style::Inlines(b)) => {
                self.cc.get_from_inlines(a, b)
            }
            (Style::Align(a), Style::Align(b)) => self.cc.get_from_aligns(a, b),
            (Style::Font(a), Style::Font(b)) => self.cc.get_from_fonts(a, b),
            _ => {
                panic!(
                    "Incompatible styles have been requested from the contrast \
                     coefficient table."
                )
            }
        }
    }

    fn write_to_file(&self) {
        let bin_data = bincode::serialize(self).unwrap();
        let bin_file = file::BinFile::from_contents(bin_data).unwrap();
        bin_file.write().expect("Writing to disk failed.");
    }
}

/// A style is the set of all modifications that this study tests.
#[derive(Clone, Eq, Debug, Hash, PartialEq)]
#[allow(missing_docs)]
pub enum Style {
    Inlines(Inlines),
    Align(Align),
    Font(Font),
}

/// Styles that may be applied to text. This is usually used as a vector of
/// styles so that multiple may be applied at once.
#[derive(Serialize, Deserialize, Clone, Eq, Debug, Hash, PartialEq)]
#[allow(missing_docs)]
pub enum InlineStyle {
    Bold,
    Italic,
    Underline,
}

/// Give a formal name to a set of inlines.
pub type Inlines = Vec<InlineStyle>;

/// Text align
#[derive(Serialize, Deserialize, Clone, Eq, Debug, Hash, PartialEq)]
pub enum Align {
    /// Align left
    Left,
    /// Justify, with the Knuth and Plass line breaking algorithm
    Justified,
    /// Center align
    Center,
    /// Right align
    Right,
}

/// Font, variants are self-explanatory
#[derive(Serialize, Deserialize, Clone, Eq, Debug, Hash, PartialEq)]
#[allow(missing_docs)]
pub enum Font {
    Serif,
    SansSerif,
    Mono,
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use rand::Rng;
    use test::Bencher;

    fn s_a() -> Style {
        Style::Font(Font::Serif)
    }

    fn s_b() -> Style {
        Style::Font(Font::SansSerif)
    }

    fn s_c() -> Style {
        Style::Font(Font::Mono)
    }

    fn ts_a() -> TextStyle {
        TextStyle {
            inlines: vec![InlineStyle::Bold, InlineStyle::Italic],
            align: Align::Left,
            font: Font::Mono,
        }
    }

    fn ts_b() -> TextStyle {
        TextStyle {
            inlines: vec![],
            align: Align::Justified,
            font: Font::Serif,
        }
    }

    fn hs_a() -> HeaderStyle {
        HeaderStyle {
            style: ts_a(),
            offset_top: 4,
            offset_bot: 2,
        }
    }

    fn hs_b() -> HeaderStyle {
        HeaderStyle {
            style: ts_b(),
            offset_top: 0,
            offset_bot: 2,
        }
    }

    fn bs_a() -> BodyStyle {
        ts_a()
    }

    #[test]
    fn put_cc() {
        let mut db = Database::new();

        db.put(PutRequest::ContrastCoefficients(
            (s_a().clone(), s_b().clone()),
            0.2,
        ));

        assert_eq!(db.get_cc_vec(&s_a(), &s_b()), Some(&vec![0.2]));

        db.put(PutRequest::ContrastCoefficients((s_a(), s_b()), 0.33));

        assert_eq!(db.get_cc_vec(&s_a(), &s_b()), Some(&vec![0.2, 0.33]));

        db.put(PutRequest::ContrastCoefficients((s_c(), s_b()), 0.41));

        assert_eq!(db.get_cc_vec(&s_a(), &s_b()), Some(&vec![0.2, 0.33]));
    }

    #[test]
    fn put_ud() {
        let mut db = Database::new();

        let tsr_a: TimeStyleRecord = (3.4, (hs_a(), bs_a()));
        let tsr_b: TimeStyleRecord = (3.2, (hs_b(), bs_a()));

        let mut tsrs = db.get_time_style_records();
        assert_eq!(tsrs.next(), None);

        db.put(PutRequest::UserData(1, tsr_a.clone()));

        if let GetRequestAns::AllUserData(mut tsrs) =
            db.get(GetRequest::AllUserData)
        {
            assert_eq!(tsrs.next().unwrap(), &vec![tsr_a.clone()]);
        } else {
            panic!("User data wasn't returned when requested.");
        }

        db.put(PutRequest::UserData(1, tsr_b.clone()));

        if let GetRequestAns::AllUserData(mut tsrs) =
            db.get(GetRequest::AllUserData)
        {
            assert_eq!(
                tsrs.next().unwrap(),
                &vec![tsr_a.clone(), tsr_b.clone()]
            );
        } else {
            panic!("User data wasn't returned when requested.");
        }

        db.put(PutRequest::UserData(0, tsr_b.clone()));

        if let GetRequestAns::UserData(tsrs) = db.get(GetRequest::UserData(1)) {
            let tsrs = tsrs.unwrap();
            let first = &tsrs[0];
            let second = &tsrs[1];
            assert!(first == &tsr_a.clone() || first == &tsr_b.clone());
            assert!(second == &tsr_a.clone() || second == &tsr_b.clone());
        }
    }

    #[bench]
    fn bench_put(b: &mut Bencher) {
        let mut rng = rand::thread_rng();
        let mut db = Database::new();
        let tsr_a: TimeStyleRecord = (3.4, (hs_a(), bs_a()));
        b.iter(|| db.put(PutRequest::UserData(rng.gen(), tsr_a.clone())));
    }
}