lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
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
//! Construction is the only application-function boundary. All consumers retain
//! final coefficients, scientific membership, numeric text and complete mapping recipes.

use super::{
    collect_input, numeric_key, validated_alpha, AlphaDeclaration, AlphaMapping, AlphaMembers,
    AlphaValues,
};
use crate::data::source::{collect_source, copy_source_string, reserve_source, sort_source_by};
use crate::data::RawKey;
use crate::numeric::{mapping::normalized_fraction, set::guide_presentation};
use crate::{CategoryValues, Error, NumericValues, Result};

fn domain(domain: (f64, f64)) -> Result<(f64, f64)> {
    if !domain.0.is_finite() || !domain.1.is_finite() || domain.0 >= domain.1 {
        return Err(Error::Data(
            "alpha domain endpoints must be finite and strictly ascending".into(),
        ));
    }
    Ok((
        f64::from_bits(numeric_key(domain.0)),
        f64::from_bits(numeric_key(domain.1)),
    ))
}

fn numeric_members(source: &NumericValues, positive: bool) -> Result<Vec<u64>> {
    collect_source((0..source.len()).map(|index| {
        let value = source.get(index).flatten().ok_or_else(|| {
            Error::Data(
                format!(
                    "alpha source {:?} is missing at index {index}",
                    source.name()
                )
                .into(),
            )
        })?;
        if !value.is_finite() || (positive && value <= 0.0) {
            return Err(Error::Data(
                format!(
                    "alpha source {:?} at index {index} must be {}finite",
                    source.name(),
                    if positive {
                        "strictly positive and "
                    } else {
                        ""
                    },
                )
                .into(),
            ));
        }
        Ok(numeric_key(value))
    }))
}

fn representatives(domain: (f64, f64)) -> Result<Vec<f64>> {
    let midpoint = f64::midpoint(domain.0, domain.1);
    let mut values = collect_source(
        [
            domain.0,
            f64::midpoint(domain.0, midpoint),
            midpoint,
            f64::midpoint(midpoint, domain.1),
            domain.1,
        ]
        .into_iter()
        .map(|value| Ok(f64::from_bits(numeric_key(value)))),
    )?;
    values.dedup_by(|a, b| a.to_bits() == b.to_bits());
    Ok(values)
}

fn clamped_key(member: u64, domain: (f64, f64)) -> u64 {
    numeric_key(f64::from_bits(member).clamp(domain.0, domain.1))
}

fn evaluations(
    members: &[u64],
    representatives: &[f64],
    domain: (f64, f64),
    mut evaluate: impl FnMut(f64) -> Result<f64>,
) -> Result<Vec<(u64, f64)>> {
    let mut keys = collect_source(
        members
            .iter()
            .map(|&member| Ok(clamped_key(member, domain))),
    )?;
    reserve_source(&mut keys, representatives.len())?;
    keys.extend(representatives.iter().map(|&value| numeric_key(value)));
    sort_source_by(&mut keys, |a, b| {
        f64::from_bits(*a).total_cmp(&f64::from_bits(*b))
    })?;
    keys.dedup();
    collect_source(
        keys.iter()
            .map(|&key| Ok((key, evaluate(f64::from_bits(key))?))),
    )
}

fn evaluated(table: &[(u64, f64)], key: u64) -> f64 {
    let index = table
        .binary_search_by(|(value, _)| f64::from_bits(*value).total_cmp(&f64::from_bits(key)))
        .expect("validated materialized alpha coordinate");
    table[index].1
}

fn interpolate(fraction: f64, range: (f64, f64)) -> Result<f64> {
    let value = if fraction <= 0.0 || range.0.to_bits() == range.1.to_bits() {
        range.0
    } else if fraction >= 1.0 {
        range.1
    } else {
        (1.0 - fraction) * range.0 + fraction * range.1
    };
    validated_alpha(value)
}

fn continuous_coordinates(domain: (f64, f64), logarithmic: bool) -> Result<(f64, f64)> {
    Ok(if logarithmic {
        if domain.0 <= 0.0 {
            return Err(Error::Data(
                "log10 alpha domain must be strictly positive".into(),
            ));
        }
        let coordinates = (
            crate::numeric::log10(domain.0)?,
            crate::numeric::log10(domain.1)?,
        );
        if !coordinates.0.is_finite()
            || !coordinates.1.is_finite()
            || coordinates.0 >= coordinates.1
        {
            return Err(Error::Data(
                "log10 alpha domain coordinates must be finite and distinguishable".into(),
            ));
        }
        coordinates
    } else {
        domain
    })
}

pub(super) fn builtin(
    source: &NumericValues,
    raw_domain: (f64, f64),
    range: (f64, f64),
    logarithmic: bool,
) -> Result<AlphaValues> {
    let domain = domain(raw_domain)?;
    let range = (validated_alpha(range.0)?, validated_alpha(range.1)?);
    let name = copy_source_string(source.raw_name())?;
    let coordinates = continuous_coordinates(domain, logarithmic)?;
    let members = numeric_members(source, logarithmic)?;
    let examples = guide_presentation(&representatives(domain)?, None)?;
    let example_values = collect_source(
        examples
            .members
            .iter()
            .map(crate::numeric::operand::Operand::binary64),
    )?;
    let table = evaluations(&members, &example_values, domain, |value| {
        let fraction = if value <= domain.0 {
            0.0
        } else if value >= domain.1 {
            1.0
        } else {
            let coordinate = if logarithmic {
                crate::numeric::log10(value)?
            } else {
                value
            };
            normalized_fraction(coordinates, coordinate)?
        };
        interpolate(fraction, range)
    })?;
    let rule = if logarithmic {
        AlphaMapping::Log10 {
            domain: [raw_domain.0, raw_domain.1],
            range: [range.0, range.1],
        }
    } else {
        AlphaMapping::Linear {
            domain: [raw_domain.0, raw_domain.1],
            range: [range.0, range.1],
        }
    };
    finish_continuous(
        source,
        name,
        &members,
        domain,
        |_| Ok(rule),
        examples,
        table,
    )
}

pub(super) fn continuous(
    source: &NumericValues,
    raw_domain: (f64, f64),
    mut f: impl FnMut(f64) -> f64,
) -> Result<AlphaValues> {
    let domain = domain(raw_domain)?;
    let name = copy_source_string(source.raw_name())?;
    let members = numeric_members(source, false)?;
    let representatives = representatives(domain)?;
    let examples = guide_presentation(&representatives, None)?;
    let table = evaluations(&members, &representatives, domain, |value| {
        validated_alpha(f(value))
    })?;
    finish_continuous(
        source,
        name,
        &members,
        domain,
        |table| {
            Ok(AlphaMapping::Continuous {
                domain: [raw_domain.0, raw_domain.1],
                evaluated: collect_source(
                    table
                        .into_iter()
                        .map(|(key, alpha)| Ok((f64::from_bits(key), alpha))),
                )?,
            })
        },
        examples,
        table,
    )
}

fn finish_continuous(
    source: &NumericValues,
    name: String,
    members: &[u64],
    domain: (f64, f64),
    rule: impl FnOnce(Vec<(u64, f64)>) -> Result<AlphaMapping>,
    examples: crate::numeric::set::FormattedSet,
    table: Vec<(u64, f64)>,
) -> Result<AlphaValues> {
    let values = collect_source(
        members
            .iter()
            .map(|&member| Ok(evaluated(&table, clamped_key(member, domain)))),
    )?;
    let samples = collect_source(examples.members.iter().map(|value| {
        let value = value.binary64()?;
        Ok((value, evaluated(&table, numeric_key(value))))
    }))?;
    AlphaValues::from_parts(
        name,
        values,
        AlphaMembers::Numeric(source.clone()),
        AlphaDeclaration {
            mapping: rule(table)?,
            examples: samples,
            labels: examples.labels,
        },
    )
}

pub(super) fn categorical(
    source: &CategoryValues,
    mut f: impl FnMut(&str) -> f64,
) -> Result<AlphaValues> {
    let original = source.key_values();
    let values = original
        .get_strings()
        .ok_or_else(|| Error::Data("categorical alpha requires actual string categories".into()))?;
    // Check the complete actual source before invoking application code.
    for (index, value) in values.iter().enumerate() {
        crate::operation::check()?;
        if value.is_none() {
            return Err(Error::Data(
                format!(
                    "alpha source {:?} is missing at index {index}",
                    source.name()
                )
                .into(),
            ));
        }
    }
    let entries = collect_source(values.levels().iter().map(|category| {
        Ok((
            RawKey::String(copy_source_string(category)?),
            validated_alpha(f(category))?,
        ))
    }))?;
    AlphaValues::from_declared_categories(source, entries)
}

fn validate_continuous_entries(domain: (f64, f64), entries: &[(f64, f64)]) -> Result<()> {
    for &(coordinate, alpha) in entries {
        crate::operation::check()?;
        if !coordinate.is_finite() || coordinate < domain.0 || coordinate > domain.1 {
            return Err(Error::Data(
                "alpha evaluated coordinate lies outside its domain".into(),
            ));
        }
        validated_alpha(alpha)?;
    }
    if entries.windows(2).any(|pair| pair[0].0 >= pair[1].0) {
        return Err(Error::Data(
            "alpha evaluated coordinates must be unique and ascending".into(),
        ));
    }
    for coordinate in representatives(domain)? {
        if entries
            .binary_search_by(|(value, _)| {
                f64::from_bits(numeric_key(*value)).total_cmp(&coordinate)
            })
            .is_err()
        {
            return Err(Error::Data(
                format!("alpha mapping has no declared value for {coordinate}").into(),
            ));
        }
    }
    Ok(())
}

fn category_indices(entries: &[(RawKey, f64)]) -> Result<std::collections::HashMap<&str, usize>> {
    let mut indices = std::collections::HashMap::new();
    indices.try_reserve(entries.len()).map_err(|error| {
        Error::Render(format!("alpha category index reservation: {error}").into())
    })?;
    for (index, (key, alpha)) in entries.iter().enumerate() {
        let RawKey::String(key) = key else {
            return Err(Error::Data(
                "categorical alpha mapping requires string keys".into(),
            ));
        };
        validated_alpha(*alpha)?;
        if indices.insert(key.as_str(), index).is_some() {
            return Err(Error::Data("duplicate categorical alpha key".into()));
        }
    }

    Ok(indices)
}

impl AlphaValues {
    // An evaluated table is an actual finite mapping, never an interpolation
    // rule or a serialized application function. New coordinates must belong
    // to the retained declaration (after the original clamping rule).
    pub(crate) fn from_declared_continuous(
        source: &NumericValues,
        raw_domain: (f64, f64),
        entries: &[(f64, f64)],
    ) -> Result<Self> {
        let domain = domain(raw_domain)?;
        let members = numeric_members(source, false)?;
        let name = copy_source_string(source.raw_name())?;
        validate_continuous_entries(domain, entries)?;
        let table =
            collect_source(entries.iter().map(|&(coordinate, alpha)| {
                Ok((numeric_key(coordinate), validated_alpha(alpha)?))
            }))?;
        let representatives = representatives(domain)?;
        for &member in &members {
            crate::operation::check()?;
            let key = clamped_key(member, domain);
            if table
                .binary_search_by(|(value, _)| {
                    f64::from_bits(*value).total_cmp(&f64::from_bits(key))
                })
                .is_err()
            {
                return Err(Error::Data(
                    format!(
                        "alpha mapping has no declared value for {}",
                        f64::from_bits(key)
                    )
                    .into(),
                ));
            }
        }
        let examples = guide_presentation(&representatives, None)?;
        finish_continuous(
            source,
            name,
            &members,
            domain,
            |table| {
                Ok(AlphaMapping::Continuous {
                    domain: [raw_domain.0, raw_domain.1],
                    evaluated: table
                        .into_iter()
                        .map(|(key, alpha)| (f64::from_bits(key), alpha))
                        .collect(),
                })
            },
            examples,
            table,
        )
    }

    pub(crate) fn from_declared_categories(
        source: &CategoryValues,
        mut entries: Vec<(RawKey, f64)>,
    ) -> Result<Self> {
        let name = copy_source_string(source.name())?;
        let original = source.key_values();
        let values = original.get_strings().ok_or_else(|| {
            Error::Data("categorical alpha requires actual string categories".into())
        })?;
        let indices = category_indices(&entries)?;
        let members = collect_source(values.iter().enumerate().map(|(index, key)| {
            let key = key.ok_or_else(|| {
                Error::Data(format!("alpha source {name:?} is missing at index {index}").into())
            })?;
            indices.get(key).copied().ok_or_else(|| {
                Error::Data(format!("alpha mapping has no declared value for {key:?}").into())
            })
        }))?;
        drop(indices);
        for (_, alpha) in &mut entries {
            *alpha = validated_alpha(*alpha)?;
        }
        let values = collect_source(members.iter().map(|&index| Ok(entries[index].1)))?;
        Self::from_parts(
            name,
            values,
            AlphaMembers::Categorical(original, members),
            AlphaDeclaration {
                mapping: AlphaMapping::Categorical(entries),
                examples: Vec::new(),
                labels: Vec::new(),
            },
        )
    }
}

fn validate_thresholds(boundaries: &[f64], alphas: &[f64]) -> Result<()> {
    if boundaries.iter().any(|value| !value.is_finite())
        || boundaries.windows(2).any(|pair| pair[0] >= pair[1])
    {
        return Err(Error::Data(
            "alpha thresholds must be finite and strictly ascending".into(),
        ));
    }
    if boundaries.len().checked_add(1) != Some(alphas.len()) {
        return Err(Error::Data(
            "alpha thresholds require one more coefficient than boundaries".into(),
        ));
    }
    for &alpha in alphas {
        crate::operation::check()?;
        validated_alpha(alpha)?;
    }
    Ok(())
}

pub(super) fn threshold(
    source: &NumericValues,
    boundaries: impl IntoIterator<Item = f64>,
    alphas: impl IntoIterator<Item = f64>,
) -> Result<AlphaValues> {
    let name = copy_source_string(source.raw_name())?;
    let boundaries = collect_input(boundaries)?;
    let alphas = collect_source(alphas.into_iter().map(validated_alpha))?;
    validate_thresholds(&boundaries, &alphas)?;
    let source_members = numeric_members(source, false)?;
    let members = collect_source(
        source_members
            .iter()
            .map(|&key| Ok(boundaries.partition_point(|&bound| f64::from_bits(key) >= bound))),
    )?;
    let values = collect_source(members.iter().map(|&index| Ok(alphas[index])))?;
    let display_boundaries = collect_source(
        boundaries
            .iter()
            .map(|&value| Ok(f64::from_bits(numeric_key(value)))),
    )?;
    let display_boundaries = guide_presentation(&display_boundaries, None)?;
    let mut labels = Vec::new();
    reserve_source(&mut labels, alphas.len())?;
    if display_boundaries.labels.is_empty() {
        labels.push(copy_source_string("all values")?);
    } else {
        labels.push(format!("< {}", display_boundaries.labels[0]));
        for pair in display_boundaries.labels.windows(2) {
            labels.push(format!("[{}, {})", pair[0], pair[1]));
        }
        labels.push(format!(
            ">= {}",
            display_boundaries.labels.last().expect("nonempty bounds")
        ));
    }
    AlphaValues::from_parts(
        name,
        values,
        AlphaMembers::Threshold(source.clone(), members),
        AlphaDeclaration {
            mapping: AlphaMapping::Threshold { boundaries, alphas },
            examples: Vec::new(),
            labels,
        },
    )
}
impl AlphaMapping {
    pub(crate) fn validate_declaration(&self) -> Result<()> {
        match self {
            Self::Undeclared => Ok(()),
            Self::Linear {
                domain: [a, b],
                range,
            }
            | Self::Log10 {
                domain: [a, b],
                range,
            } => {
                let domain = domain((*a, *b))?;
                continuous_coordinates(domain, matches!(self, Self::Log10 { .. }))?;
                validated_alpha(range[0])?;
                validated_alpha(range[1])?;
                Ok(())
            }
            Self::Continuous {
                domain: [a, b],
                evaluated,
            } => validate_continuous_entries(domain((*a, *b))?, evaluated),
            Self::Categorical(entries) => category_indices(entries).map(|_| ()),
            Self::Threshold { boundaries, alphas } => validate_thresholds(boundaries, alphas),
        }
    }
}