Skip to main content

weirdnet_plugin/
columns.rs

1//! Computed columns to a result view (and writes): what generated code spaces (math,
2//! Polars, Python) end with, and handy in Rust ones.
3use crate::{Frame, Host, Json, Result, View};
4
5/// How to show computed columns.
6#[derive(Debug, Clone, Default)]
7pub struct Output {
8    pub title: String,
9    /// `chart` (default), `table` or `value` (the last value of each column, per group).
10    pub view: String,
11    /// The x axis: a field or computed column; empty: `timestamp` if the input has it, else `row`.
12    pub x: String,
13    /// Columns to show, in order; empty: all computed ones.
14    pub show: Vec<String>,
15    /// (field, column): write a computed column into a field of the input records.
16    pub updates: Vec<(String, String)>,
17}
18
19/// Most tiles a grouped chart gets.
20pub const MAX_GROUP_TILES: usize = 12;
21
22fn key_text(k: &[(String, Json)]) -> String {
23    k.iter().map(|(_, v)| v.text()).collect::<Vec<_>>().join(" ")
24}
25
26fn num(v: f64) -> Json {
27    if v.is_finite() {
28        Json::Num(v)
29    } else {
30        Json::Null
31    }
32}
33
34/// Write the updates, then build the view. `cols` are full columns, row for row with `frame`.
35pub fn finish(host: &Host, frame: &Frame, out: &Output, cols: Vec<(String, Vec<f64>)>) -> Result<View> {
36    let col = |name: &str| -> Result<Vec<f64>> {
37        match cols.iter().find(|(n, _)| n == name) {
38            Some((_, v)) => Ok(v.clone()),
39            None => frame.f64(name),
40        }
41    };
42    if !out.updates.is_empty() {
43        let mut vals = vec![];
44        for (field, c) in &out.updates {
45            vals.push((field.clone(), col(c)?));
46        }
47        let ups: Vec<(String, Json)> =
48            frame.ids.iter().enumerate().map(|(i, id)| (id.clone(), vals.iter().fold(Json::obj(), |o, (f, v)| o.with(f, num(v[i]))))).collect();
49        if !ups.is_empty() {
50            let n = host.update_each(&frame.model, ups)?;
51            host.log(format!("updated {n} {} records", frame.model));
52        }
53    }
54    let show: Vec<String> = if out.show.is_empty() { cols.iter().map(|(n, _)| n.clone()).collect() } else { out.show.clone() };
55    let mut shown = vec![];
56    for s in &show {
57        shown.push((s.clone(), col(s)?));
58    }
59    let x = if !out.x.is_empty() {
60        out.x.clone()
61    } else if frame.has("timestamp") {
62        "timestamp".into()
63    } else {
64        "row".into()
65    };
66    let time = x == "_created_at" || x == "_updated_at" || frame.fields.iter().any(|f| f.name == x && f.ty == "timestamp");
67    let xs = col(&x)?;
68    let groups = frame.groups();
69    let gfields: Vec<String> = groups.first().map(|g| g.key.iter().map(|(k, _)| k.clone()).collect()).unwrap_or_default();
70    let title = if out.title.is_empty() { show.join(", ") } else { out.title.clone() };
71    match out.view.as_str() {
72        "table" => {
73            let mut head: Vec<&str> = gfields.iter().map(String::as_str).collect();
74            head.push(&x);
75            head.extend(show.iter().map(String::as_str));
76            let mut v = View::table(&title, &head);
77            for g in &groups {
78                for i in g.start..g.start + g.len {
79                    let mut r: Vec<Json> = g.key.iter().map(|(_, k)| k.clone()).collect();
80                    r.push(num(xs[i]));
81                    r.extend(shown.iter().map(|(_, c)| num(c[i])));
82                    v = v.row(r);
83                }
84            }
85            Ok(v)
86        }
87        "value" | "values" => {
88            let mut head: Vec<&str> = gfields.iter().map(String::as_str).collect();
89            head.extend(show.iter().map(String::as_str));
90            let mut v = View::table(&title, &head);
91            for g in &groups {
92                let mut r: Vec<Json> = g.key.iter().map(|(_, k)| k.clone()).collect();
93                for (_, c) in &shown {
94                    let last = c[g.start..g.start + g.len].iter().rev().find(|x| x.is_finite()).copied().unwrap_or(f64::NAN);
95                    r.push(num(last));
96                }
97                v = v.row(r);
98            }
99            Ok(v)
100        }
101        _ => {
102            let chart = |t: &str, a: usize, n: usize| {
103                shown.iter().fold(View::chart(t).x(&x, xs[a..a + n].to_vec(), time), |v, (name, c)| v.line(name, c[a..a + n].to_vec()))
104            };
105            if groups.len() <= 1 {
106                return Ok(chart(&title, 0, frame.len()));
107            }
108            if groups.len() > MAX_GROUP_TILES {
109                host.log(format!("{} groups: charting the first {MAX_GROUP_TILES}", groups.len()));
110            }
111            let tiles = groups.iter().take(MAX_GROUP_TILES).map(|g| chart(&key_text(&g.key), g.start, g.len)).collect();
112            Ok(View::tiles(&title, true, tiles))
113        }
114    }
115}