Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

FP2c: fingerprint folded into what it copied, as L1's duplicate check asks. The ledger says its rows' labels, counts and projects once for training, inheritance, pairs and the bootstrap; one half-float codec serves the column cache and a fingerprint's words and evidence; a verb's files and a list's lines are read once; raea check's defects and its sound rules share their level in dB and their moments as issues; Encoders::pins is a map; the bootstrap names its own rows and each sense's defects once

shinyobjectz28fd448ea23b
diff --git a/apps/check/src/defects.rs b/apps/check/src/defects.rs
index b6e99543..d3ffdb77 100644
--- a/apps/check/src/defects.rs
+++ b/apps/check/src/defects.rs
@@ -58,7 +58,7 @@ pub(crate) const SILENT: f64 = -80.0;
pub(crate) const HAD_LEVEL: f64 = -45.0;
pub(crate) fn dropouts(x: &[f32]) -> Vec<(f64, String)> {
- let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| 20.0 * ((f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64).sqrt() + 1e-9).log10()).collect();
+ let rms: Vec<f64> = x.as_chunks::<HOP>().0.iter().map(|f| crate::sound::db(f)).collect();
let step = HOP as f64 / SR as f64;
let mut out = Vec::new();
let mut i = 1;
@@ -132,16 +132,21 @@ pub(crate) fn flash_frame_rule(video: &str, issues: &mut Vec<Issue>, passed: &mu
if found.is_empty() {
passed.push("flash-frame: no stray black or white frame".into());
}
- issues.extend(found.into_iter().map(|(at, says)| Issue { rule: "flash-frame", p: 1, at: Some(at), says }));
+ issues.extend(moments("flash-frame", 1, found));
Ok(())
}
+/// Each moment a rule found, as an issue of that priority
+pub(crate) fn moments(rule: &'static str, p: u8, found: Vec<(f64, String)>) -> impl Iterator<Item = Issue> {
+ found.into_iter().map(move |(at, says)| Issue { rule, p, at: Some(at), says })
+}
+
/// The sound's defects on the decoded mix (sound.rs decodes it once)
pub(crate) fn sound_defects(x: &[f32], issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
for (rule, found, ok) in [("clipping", clipped(x), "clipping: no flat-topped runs"), ("dropout", dropouts(x), "dropout: the sound never drops to silence and back")] {
if found.is_empty() {
passed.push(ok.into());
}
- issues.extend(found.into_iter().map(|(at, says)| Issue { rule, p: 1, at: Some(at), says }));
+ issues.extend(moments(rule, 1, found));
}
}
diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rs
index c062bd5f..e4ed1454 100644
--- a/apps/check/src/sound.rs
+++ b/apps/check/src/sound.rs
@@ -27,6 +27,12 @@ pub(crate) fn pct(v: &[f64], q: f64) -> f64 {
/// a bed that stops under a voice shows in the band the voice doesn't fill (a projector's clatter in the highs). A band's
/// level is its share of the step's mean square (Parseval, undoing the Hann window's power), so a tone reads the same in
/// its band as in the mix
+/// A stretch of sound's level in dB (its RMS)
+pub(crate) fn db(f: &[f32]) -> f64 {
+ let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / f.len().max(1) as f64;
+ 20.0 * (ms.sqrt() + 1e-9).log10()
+}
+
pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
use std::f64::consts::PI;
let n = x.len() / HOP;
@@ -44,8 +50,7 @@ pub(crate) fn levels(x: &[f32]) -> (Vec<f64>, [Vec<f64>; 3]) {
let scale = 2.0 / (HOP * HOP) as f64 / (hann.iter().map(|h| h * h).sum::<f64>() / HOP as f64);
let (mut rms, mut bands) = (Vec::with_capacity(n), [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]);
for f in x.chunks_exact(HOP) {
- let ms = f.iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / HOP as f64;
- rms.push(20.0 * (ms.sqrt() + 1e-9).log10());
+ rms.push(db(f));
let w: Vec<f64> = f.iter().zip(&hann).map(|(&v, h)| v as f64 * h).collect();
let mut e = [0.0; 3];
for (b, tw) in &bins {
@@ -164,7 +169,7 @@ pub(crate) fn sound(video: &str, words: Option<&[Word]>, issues: &mut Vec<Issue>
let x: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
let (rms, bands) = levels(&x);
sound_defects(&x, issues, passed);
- let found = |list: Vec<(f64, String)>, p: u8| list.into_iter().map(move |(at, says)| Issue { rule: "sound", p, at: Some(at), says });
+ let found = |list: Vec<(f64, String)>, p: u8| crate::defects::moments("sound", p, list);
let stops = dead_stops(&rms, &bands);
if stops.is_empty() {
passed.push("sound: no steady sound stops dead".into());
diff --git a/apps/fingerprint/src/approve.rs b/apps/fingerprint/src/approve.rs
index 97b7c8ee..27103ffa 100644
--- a/apps/fingerprint/src/approve.rs
+++ b/apps/fingerprint/src/approve.rs
@@ -5,13 +5,13 @@
//! name a defect. Notes aren't read into labels here; that is FP5a.
use crate::bootstrap::WIN;
-use crate::{flag, words};
+use crate::flag;
use anyhow::{Result, anyhow};
use raea_sys_columns::Encoders;
use raea_sys_fingerprint::evidence::{Row, features};
use raea_sys_fingerprint::folder::Folder;
use raea_sys_fingerprint::taxonomy::Fingerprint;
-use std::path::{Path, PathBuf};
+use std::path::Path;
/// The seconds a note was pinned at on `file`, from every post in its project's feed that shows a file of that name
pub(crate) fn noted(file: &Path) -> Vec<f64> {
@@ -36,7 +36,7 @@ pub(crate) fn windows(dur: f64, notes: &[f64]) -> Vec<(f64, f64)> {
}
pub(crate) fn approve(enc: &mut Encoders, dir: &Folder, fp: &Fingerprint, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<(String, usize)> {
- let files: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| if Path::new(f).is_absolute() { PathBuf::from(f) } else { cwd.join(f) }).collect();
+ let files = crate::named(args, cwd)?;
if files.is_empty() {
return Err(anyhow!("which approved work? raea fingerprint approve FILE..."));
}
diff --git a/apps/fingerprint/src/bootstrap.rs b/apps/fingerprint/src/bootstrap.rs
index 5e789e31..3303c7ba 100644
--- a/apps/fingerprint/src/bootstrap.rs
+++ b/apps/fingerprint/src/bootstrap.rs
@@ -9,7 +9,7 @@
//! modality and on the one FP0b used; and each word head's AUC and catch rate with no labels (FP0g).
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
-use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile};
+use raea_sys_fingerprint::head::{Logistic, Scaler, auc, quantile, share_over};
use raea_sys_fingerprint::taxonomy::Fingerprint;
use raea_sys_fingerprint::train::{C, folds};
use raea_sys_fingerprint::words::Words;
@@ -53,6 +53,26 @@ pub struct Made {
pub skipped: Vec<String>,
}
+/// The rows a bootstrap makes, which the next bootstrap replaces
+fn made_here(r: &Row) -> bool {
+ matches!(r.source.as_str(), "damage" | "cheat")
+}
+
+/// A plain damage row on `axis` ("*" for the clean windows)
+fn damage_on(r: &Row, axis: &str) -> bool {
+ r.source == "damage" && r.axis == axis
+}
+
+/// The plain damage rows on `axis`
+fn damage_rows(l: &Ledger, axis: &str) -> Vec<usize> {
+ (0..l.rows.len()).filter(|&i| damage_on(&l.rows[i], axis)).collect()
+}
+
+/// Each defect of a sense as (kind, axis, source): the plain ones, then their disguises
+fn damages(sense: &[&'static str]) -> Vec<(&'static str, &'static str, &'static str)> {
+ sense.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| sense.contains(&c.1)).map(|c| (c.0, c.1, "cheat"))).collect()
+}
+
/// Below this a window is near silence: a gap or clipping changes nothing, and a row saying it does teaches noise
const QUIET_DB: f32 = -45.0;
@@ -98,7 +118,7 @@ fn picture_of(enc: &mut Encoders, clean: &[Rgb], sig: &[f32], look: &[f32], d: &
/// The bootstrap's rows for `files` into the ledger, replacing any it made before. `say` hears each source's progress.
pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mut Ledger, say: &mut dyn FnMut(String)) -> Result<Made> {
- l.retain(|r| !matches!(r.source.as_str(), "damage" | "cheat"));
+ l.retain(|r| !made_here(r));
let mut made = Made::default();
let mut noise = Noise::new(0);
for (n, file) in files.iter().enumerate() {
@@ -140,15 +160,13 @@ pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mu
l.push(r, &features(c, 0.0, WIN));
};
push(l, &clean, "*", "clean", "damage");
- let picture = PICTURE.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| PICTURE.contains(&c.1)).map(|c| (c.0, c.1, "cheat")));
- for (kind, axis, source) in picture {
+ for (kind, axis, source) in damages(&PICTURE) {
let (sig, look) = picture_of(enc, fr, &clean.sig, &clean.look, &damage::picture(fr, kind))?;
push(l, &Columns { sig, look, ..clean.clone() }, axis, kind, source);
}
let quiet = loudness(&w16) < QUIET_DB;
made.quiet += quiet as usize;
- let sound = SOUND.iter().map(|k| (*k, *k, "damage")).chain(CHEATS.iter().filter(|c| SOUND.contains(&c.1)).map(|c| (c.0, c.1, "cheat")));
- for (kind, axis, source) in sound.filter(|s| !quiet || s.1 == "noise") {
+ for (kind, axis, source) in damages(&SOUND).into_iter().filter(|s| !quiet || s.1 == "noise") {
let (d16, d48) = (damage::sound(&w16, kind, 16_000, &mut noise), damage::sound(&w48, kind, 48_000, &mut noise));
let (clap, yam) = enc.sound(&d16, &d48)?;
push(l, &Columns { clap, yam, level: media::levels(&d16, 16_000), ..clean.clone() }, axis, kind, source);
@@ -157,7 +175,7 @@ pub fn rows(enc: &mut Encoders, who: &str, files: &[PathBuf], per: usize, l: &mu
}
say(format!("source {}/{} {}: {} windows so far", n + 1, files.len(), file.display(), made.windows));
}
- made.rows = l.rows.iter().filter(|r| matches!(r.source.as_str(), "damage" | "cheat")).count();
+ made.rows = l.rows.iter().filter(|r| made_here(r)).count();
Ok(made)
}
@@ -184,9 +202,8 @@ pub fn curve(l: &Ledger, axis: &str, m: Modality, rng: &mut fastrand::Rng) -> Cu
let s = slice(m);
let row = |i: usize| &l.features(i)[s.clone()];
let plain = |i: &usize| l.rows[*i].source == "damage";
- let clean: Vec<usize> = (0..l.rows.len()).filter(|i| plain(i) && l.rows[*i].axis == "*").collect();
- let bad: Vec<usize> = (0..l.rows.len()).filter(|i| plain(i) && l.rows[*i].axis == axis).collect();
- let projects: BTreeSet<String> = clean.iter().map(|&i| l.rows[i].project.clone()).collect();
+ let (clean, bad) = (damage_rows(l, "*"), damage_rows(l, axis));
+ let projects = l.projects(&clean);
let mut k_auc = BTreeMap::new();
for k in KS {
let mut aucs = Vec::new();
@@ -246,13 +263,16 @@ pub struct WordScore {
/// Each word head on the bootstrap's windows (FP0g)
pub fn word_scores(l: &Ledger, words: &Words) -> Vec<WordScore> {
let z = |i: usize, axis: &str| words.z(axis, l.features(i));
- let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { (0..l.rows.len()).filter(|&i| pick(&l.rows[i])).filter_map(|i| z(i, axis)).collect() };
+ let of = |axis: &str, pick: &dyn Fn(&Row) -> bool| -> Vec<f32> { l.rows.iter().enumerate().filter(|(_, r)| pick(r)).filter_map(|(i, _)| z(i, axis)).collect() };
let mut out = Vec::new();
- for axis in PICTURE.iter().chain(&SOUND).filter(|a| words.axes.iter().any(|w| w.0 == **a)) {
- let clean = of(axis, &|r| r.source == "damage" && r.axis == "*");
- let bad = of(axis, &|r| r.source == "damage" && r.axis == *axis);
+ for axis in PICTURE.iter().chain(&SOUND) {
+ if !words.axes.iter().any(|w| w.0 == *axis) {
+ continue;
+ }
+ let clean = of(axis, &|r| damage_on(r, "*"));
+ let bad = of(axis, &|r| damage_on(r, axis));
let thr = quantile(&clean, 0.9);
- let share = |v: &[f32]| v.iter().filter(|x| **x > thr).count() as f64 / v.len().max(1) as f64;
+ let share = |v: &[f32]| share_over(v, thr);
let cheats = CHEATS.iter().filter(|c| c.1 == *axis).map(|c| (c.0.to_string(), share(&of(axis, &|r| r.source == "cheat" && r.kind.as_deref() == Some(c.0))))).collect();
out.push(WordScore { axis: axis.to_string(), auc: auc(&bad, &clean), caught: share(&bad), cheats });
}
diff --git a/apps/fingerprint/src/lib.rs b/apps/fingerprint/src/lib.rs
index 08006795..5c419ae2 100644
--- a/apps/fingerprint/src/lib.rs
+++ b/apps/fingerprint/src/lib.rs
@@ -64,6 +64,25 @@ pub(crate) fn has(args: &[String], name: &str) -> bool {
args.iter().any(|a| a == name)
}
+/// A path as given, against the folder the verb ran in (an absolute one stays itself)
+pub(crate) fn at(cwd: &Path, p: &str) -> std::path::PathBuf {
+ cwd.join(p)
+}
+
+/// The files a verb names, against the folder it ran in
+pub(crate) fn named(args: &[String], cwd: &Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
+ Ok(words(args).map_err(anyhow::Error::msg)?.iter().map(|f| at(cwd, f)).collect())
+}
+
+/// The files a list names, one a line against the list's own folder; blank lines and # lines are skipped
+pub(crate) fn listed(cwd: &Path, list: &str) -> anyhow::Result<Vec<std::path::PathBuf>> {
+ use anyhow::Context;
+ let list = at(cwd, list);
+ let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
+ let base = list.parent().unwrap_or(cwd);
+ Ok(text.lines().map(str::trim).filter(|l| !(l.is_empty() || l.starts_with('#'))).map(|l| at(base, l)).collect())
+}
+
/// The words that aren't flags or their values; an unknown flag is an error
pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
let mut out = Vec::new();
@@ -83,9 +102,12 @@ pub(crate) fn words(args: &[String]) -> Result<Vec<&str>, String> {
/// `raea fingerprint VERB ...`, printed; its exit code (1: the verb failed, 2: the command was wrong)
pub fn cli(args: &[String], eval: Eval) -> i32 {
- let Some(verb) = args.first().map(String::as_str).filter(|v| !matches!(*v, "--help" | "-h" | "help")) else {
- println!("{USAGE}");
- return 0;
+ let verb = match args.first().map(String::as_str) {
+ None | Some("--help" | "-h" | "help") => {
+ println!("{USAGE}");
+ return 0;
+ }
+ Some(v) => v,
};
if let Err(e) = words(&args[1..]) {
eprintln!("raea fingerprint: {e}\n{USAGE}");
diff --git a/apps/fingerprint/src/notes.rs b/apps/fingerprint/src/notes.rs
index e3bda8d0..80930e59 100644
--- a/apps/fingerprint/src/notes.rs
+++ b/apps/fingerprint/src/notes.rs
@@ -87,7 +87,8 @@ pub fn answer(text: &str) -> Option<Vec<Value>> {
/// Fold an answer into the notes: a kind it doesn't know or an axis not in the fingerprint is dropped
pub fn fold(notes: &mut [Reading], fp: &Fingerprint, ans: &[Value], by: &str) {
for a in ans {
- let Some(n) = notes.iter_mut().find(|n| a["id"].as_str() == Some(n.note.as_str())) else { continue };
+ let Some(id) = a["id"].as_str() else { continue };
+ let Some(n) = notes.iter_mut().find(|n| n.note == id) else { continue };
let kind = a["kind"].as_str().unwrap_or("");
if !matches!(kind, "defect" | "direction" | "praise" | "both") {
continue;
@@ -189,7 +190,7 @@ pub(crate) fn readings_here(args: &[String]) -> i32 {
let dir = crate::pick::chosen(args, None).0;
let mut r = readings_of(&dir);
if let Some(n) = flag(args, "--ask").and_then(|n| n.parse::<usize>().ok()) {
- let todo: Vec<usize> = (0..r.len()).filter(|&i| r[i].kind_ok.is_none()).take(n).collect();
+ let todo: Vec<usize> = r.iter().enumerate().filter(|(_, x)| x.kind_ok.is_none()).map(|(i, _)| i).take(n).collect();
let mut cmd = std::process::Command::new(std::env::current_exe().unwrap_or_else(|_| "raea".into()));
cmd.args(["show", "--title", "Check how raea read your notes", "--inbox", INBOX]);
for &i in &todo {
diff --git a/apps/fingerprint/src/pairing.rs b/apps/fingerprint/src/pairing.rs
index bb6fdd1a..7707e878 100644
--- a/apps/fingerprint/src/pairing.rs
+++ b/apps/fingerprint/src/pairing.rs
@@ -5,25 +5,22 @@
//! distance 0.01 or more) and wasn't noted again within 1 s there.
use crate::approve::noted;
-use crate::{flag, words};
+use crate::flag;
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::Encoders;
use raea_sys_columns::window::Modality;
use raea_sys_fingerprint::evidence::{Ledger, Row, features, slice};
use raea_sys_fingerprint::pairs::difference;
-use std::path::{Path, PathBuf};
+use std::path::Path;
fn row(media: &str, a: f64, b: f64, axis: &str, weight: f32, who: &str, project: String, words: Option<String>) -> Row {
Row { media: media.into(), a, b, axis: axis.into(), bad: true, weight, who: who.into(), source: "pair".into(), project, kind: None, region: None, words, at: 0, pin: None }
}
-fn files(args: &[String], cwd: &Path) -> Result<Vec<PathBuf>> {
- Ok(words(args).map_err(|e| anyhow!(e))?.iter().map(|f| if Path::new(f).is_absolute() { PathBuf::from(f) } else { cwd.join(f) }).collect())
-}
/// `pair`: one row, the worse window's features minus the better one's
pub(crate) fn pair(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
- let f = files(args, cwd)?;
+ let f = crate::named(args, cwd)?;
let [worse, better] = f.as_slice() else { bail!("raea fingerprint pair WORSE BETTER --axis A [--at T] [--then T2]") };
let axis = flag(args, "--axis").ok_or_else(|| anyhow!("--axis A: the axis the better one is better on"))?;
let span: f64 = flag(args, "--span").map_or(Ok(2.0), str::parse).context("--span takes seconds")?;
@@ -53,7 +50,7 @@ pub(crate) fn weak(before: &[f32], after: &[f32], t: f64, next_notes: &[f64]) ->
/// `versions`: weak pairs along a chain of versions
pub(crate) fn versions(enc: &mut Encoders, l: &mut Ledger, who: &str, args: &[String], cwd: &Path, project: impl Fn(&Path) -> String) -> Result<String> {
- let f = files(args, cwd)?;
+ let f = crate::named(args, cwd)?;
if f.len() < 2 {
bail!("raea fingerprint versions V1 V2... takes the versions in order");
}
diff --git a/apps/fingerprint/src/pick.rs b/apps/fingerprint/src/pick.rs
index cf2c3585..5fa7c6a4 100644
--- a/apps/fingerprint/src/pick.rs
+++ b/apps/fingerprint/src/pick.rs
@@ -21,7 +21,7 @@ pub(crate) fn chosen(args: &[String], file: Option<&Path>) -> (Folder, Option<Ch
fn here(cwd: &Path, args: &[String], at: usize) -> PathBuf {
let w = words(args).unwrap_or_default();
- w.get(at).map_or_else(|| cwd.to_path_buf(), |p| if Path::new(p).is_absolute() { PathBuf::from(p) } else { cwd.join(p) })
+ w.get(at).map_or_else(|| cwd.to_path_buf(), |p| cwd.join(p))
}
pub(crate) fn which_here(args: &[String], cwd: &Path) -> i32 {
@@ -63,7 +63,8 @@ pub(crate) fn use_here(args: &[String], cwd: &Path) -> i32 {
eprintln!("raea fingerprint use: no fingerprint {name} at the {level} or above it");
return 1;
}
- if let Err(e) = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and_then(|()| std::fs::write(&file, &name)) {
+ let wrote = std::fs::create_dir_all(file.parent().unwrap_or(cwd)).and(std::fs::write(&file, &name));
+ if let Err(e) = wrote {
eprintln!("raea fingerprint use: {}: {e}", file.display());
return 1;
}
diff --git a/apps/fingerprint/src/profiles.rs b/apps/fingerprint/src/profiles.rs
index 7d372983..2d5c3579 100644
--- a/apps/fingerprint/src/profiles.rs
+++ b/apps/fingerprint/src/profiles.rs
@@ -2,7 +2,7 @@
//! FP6e): a profile's measures taken from work the person admires, kept in the fingerprint's profiles/NAME.json, and a
//! piece critiqued against it, measure by measure, with where and which way to move.
-use crate::{flag, words};
+use crate::{flag, listed, named};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, media};
use raea_sys_fingerprint::folder::Folder;
@@ -14,10 +14,6 @@ const BINS: usize = 12;
/// The windows the critique says "where" with, seconds
const WIN: f64 = 4.0;
-fn at(cwd: &Path, p: &str) -> PathBuf {
- if Path::new(p).is_absolute() { PathBuf::from(p) } else { cwd.join(p) }
-}
-
/// A piece's measures, whole and in windows
pub(crate) fn measured(enc: &mut Encoders, file: &Path) -> Result<(Measures, Vec<((f64, f64), Measures)>)> {
let c = enc.columns(file)?;
@@ -39,7 +35,7 @@ fn path(dir: &Folder, name: &str) -> PathBuf {
pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path) -> Result<String> {
let name = flag(args, "--as").ok_or_else(|| anyhow!("name it: raea fingerprint profile REFS... --as NAME"))?;
- let refs: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| at(cwd, f)).collect();
+ let refs = named(args, cwd)?;
if refs.len() < 2 {
bail!("a profile needs two references or more (three for its leave-one-out check)");
}
@@ -49,9 +45,8 @@ pub(crate) fn make(enc: &mut Encoders, dir: &Folder, args: &[String], cwd: &Path
}
let mut other = Vec::new();
if let Some(list) = flag(args, "--against") {
- let list = at(cwd, list);
- for l in std::fs::read_to_string(&list).with_context(|| list.display().to_string())?.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
- other.push(measured(enc, &at(list.parent().unwrap_or(cwd), l))?.0);
+ for f in listed(cwd, list)? {
+ other.push(measured(enc, &f)?.0);
}
}
let p = profile(name, r, &other);
diff --git a/apps/fingerprint/src/reembed.rs b/apps/fingerprint/src/reembed.rs
index 075ec8ed..e871be83 100644
--- a/apps/fingerprint/src/reembed.rs
+++ b/apps/fingerprint/src/reembed.rs
@@ -27,7 +27,7 @@ fn files(places: &[PathBuf]) -> Vec<PathBuf> {
let p = e.path();
if p.is_dir() && depth > 0 {
walk(&p, depth - 1, out);
- } else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| MEDIA.contains(&x.to_ascii_lowercase().as_str())) {
+ } else if MEDIA.iter().any(|m| p.extension().is_some_and(|x| x.eq_ignore_ascii_case(m))) {
out.push(p);
}
}
diff --git a/apps/fingerprint/src/verbs.rs b/apps/fingerprint/src/verbs.rs
index 1b87497a..e7a20ccc 100644
--- a/apps/fingerprint/src/verbs.rs
+++ b/apps/fingerprint/src/verbs.rs
@@ -1,6 +1,6 @@
//! The verbs, run with the encoders loaded: new, bootstrap, teach and score; and report, which needs no encoders.
-use crate::{Eval, flag, has, words};
+use crate::{Eval, at, flag, has, listed, named, words};
use anyhow::{Context, Result, anyhow, bail};
use raea_sys_columns::{Encoders, FPS, media};
use raea_sys_fingerprint::evidence::{Ledger, Row, features};
@@ -8,21 +8,15 @@ use raea_sys_fingerprint::folder::{Folder, root};
use raea_sys_fingerprint::inherit;
use raea_sys_fingerprint_use::score::{Scored, clock, score, summary, timeline};
use raea_sys_fingerprint_use::sheet::{Tick, sheet};
-use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base};
+use raea_sys_fingerprint::taxonomy::{Applies, Fingerprint, base, words_of};
use raea_sys_fingerprint::words::Words;
use crate::bootstrap;
use raea_sys_fingerprint::{report_text, retrain};
use serde_json::json;
-use std::collections::BTreeMap;
-use std::path::{Path, PathBuf};
+use std::path::Path;
/// The fingerprint a verb is about: --fp, else the one `new` made first, else "me"
-fn at(cwd: &Path, p: &str) -> PathBuf {
- let p = Path::new(p);
- if p.is_absolute() { p.to_path_buf() } else { cwd.join(p) }
-}
-
/// A verb's answer and exit code
pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> (String, i32) {
let rest = &args[1..];
@@ -44,10 +38,6 @@ pub(crate) fn run(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, s
ran.unwrap_or_else(|e| (format!("raea fingerprint {}: {e:#}", args[0]), 1))
}
-fn pins(enc: &Encoders) -> BTreeMap<String, String> {
- enc.pins().into_iter().collect()
-}
-
/// A new fingerprint as `new` makes it: raea's base axes, or the axes of the one it --extends, with --who and --about,
/// and the kinds of piece and project tags it judges (--kinds, --tags, each comma-separated)
pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>) -> Fingerprint {
@@ -58,8 +48,7 @@ pub(crate) fn shaped(short: &str, args: &[String], parent: Option<Fingerprint>)
}
fp.who = flag(args, "--who").map(str::to_string).or_else(|| std::env::var("USER").ok());
fp.about = flag(args, "--about").map(str::trim).filter(|a| !a.is_empty()).map(str::to_string);
- let list = |f: &str| -> Vec<String> { flag(args, f).map(|v| v.split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()).collect()).unwrap_or_default() };
- let (kinds, tags) = (list("--kinds"), list("--tags"));
+ let (kinds, tags) = (flag(args, "--kinds").map(words_of).unwrap_or_default(), flag(args, "--tags").map(words_of).unwrap_or_default());
if !kinds.is_empty() || !tags.is_empty() {
fp.applies = Some(Applies { kinds, tags });
}
@@ -76,7 +65,7 @@ fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
};
let from = parent.as_ref().map(|p| format!("{}'s axes", p.name)).unwrap_or_else(|| "raea's base taxonomy".into());
let mut fp = shaped(&short, args, parent);
- fp.encoders = pins(enc);
+ fp.encoders = enc.pins();
dir.create(&fp)?;
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
@@ -102,7 +91,7 @@ fn new(enc: &mut Encoders, args: &[String]) -> Result<(String, i32)> {
fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) -> Result<(Folder, Fingerprint, Words)> {
let dir = crate::pick::chosen(args, file).0;
let mut raw = dir.read(Some(eval))?;
- let here = pins(enc);
+ let here = enc.pins();
if raw.encoders.is_empty() {
raw.encoders = here;
dir.rewrite(&raw)?;
@@ -136,11 +125,9 @@ fn open(enc: &mut Encoders, args: &[String], eval: Eval, file: Option<&Path>) ->
fn boot(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval, say: &mut dyn FnMut(String)) -> Result<(String, i32)> {
let (dir, fp, w) = open(enc, args, eval, None)?;
- let mut files: Vec<PathBuf> = words(args).map_err(|e| anyhow!(e))?.iter().map(|f| at(cwd, f)).collect();
+ let mut files = named(args, cwd)?;
if let Some(list) = flag(args, "--from") {
- let list = at(cwd, list);
- let text = std::fs::read_to_string(&list).with_context(|| list.display().to_string())?;
- files.extend(text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(|l| at(list.parent().unwrap_or(cwd), l)));
+ files.extend(listed(cwd, list)?);
}
if files.is_empty() {
bail!("give it real finished work: raea fingerprint bootstrap FILE... or --from LIST (no placeholder footage)");
@@ -184,7 +171,7 @@ fn approved(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Resu
fn reembedded(enc: &mut Encoders, args: &[String], cwd: &Path, eval: Eval) -> Result<(String, i32)> {
let dir = crate::pick::chosen(args, None).0;
let raw = dir.read(Some(eval))?;
- let (fp, out) = crate::reembed::reembed(enc, &dir, raw, pins(enc), args, cwd)?;
+ let (fp, out) = crate::reembed::reembed(enc, &dir, raw, enc.pins(), args, cwd)?;
let fp = inherit::axes(&fp, &inherit::parents(&fp, Some(eval)));
let w = Words::build(enc, &fp)?;
dir.write_words(&w)?;
diff --git a/systems/columns/src/cache.rs b/systems/columns/src/cache.rs
index 5a342f66..d75b2dbb 100644
--- a/systems/columns/src/cache.rs
+++ b/systems/columns/src/cache.rs
@@ -26,15 +26,27 @@ fn path(media: &str) -> PathBuf {
root().join("columns").join(format!("{media}-{STEP}.cols"))
}
+/// Numbers as little-endian half floats, as the column cache and a fingerprint's files keep them
+pub fn f16s(v: &[f32]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(2 * v.len());
+ for x in v {
+ out.extend(f16::from_f32(*x).to_le_bytes());
+ }
+ out
+}
+
+/// Little-endian half floats read back
+pub fn f32s(b: &[u8]) -> Vec<f32> {
+ b.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect()
+}
+
pub fn save(c: &Columns) -> Result<()> {
let cols = [&c.sig, &c.look, &c.clap, &c.yam, &c.level];
let head = Head { media: c.media.clone(), dur: c.dur, step: STEP, lens: cols.iter().map(|v| v.len()).collect() };
let mut b = serde_json::to_vec(&head)?;
b.push(b'\n');
for v in cols {
- for x in v.iter() {
- b.extend(f16::from_f32(*x).to_le_bytes());
- }
+ b.extend(f16s(v));
}
let p = path(&c.media);
std::fs::create_dir_all(p.parent().unwrap())?;
@@ -56,7 +68,7 @@ pub fn load(media: &str) -> Option<Columns> {
for &n in &head.lens {
let end = at + 2 * n;
let raw = b.get(at..end)?;
- cols.push(raw.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect());
+ cols.push(f32s(raw));
at = end;
}
let mut it = cols.into_iter();
diff --git a/systems/columns/src/damage.rs b/systems/columns/src/damage.rs
index 3bd76da0..bffd180c 100644
--- a/systems/columns/src/damage.rs
+++ b/systems/columns/src/damage.rs
@@ -57,14 +57,24 @@ fn zoomed(f: &Rgb, i: usize) -> Rgb {
}
/// A window's frames with a picture defect (or cheat) put in
+/// A frame with every channel scaled by `k`
+fn darker(f: &Rgb, k: f32) -> Rgb {
+ f.iter().map(|&x| (x as f32 * k) as u8).collect()
+}
+
+/// Sound driven `gain` times louder into a hard ceiling at `ceil`
+fn clipped(w: &mut [f32], gain: f32, ceil: f32) {
+ w.iter_mut().for_each(|x| *x = (*x * gain).clamp(-ceil, ceil));
+}
+
pub fn picture(frames: &[Rgb], kind: &str) -> Vec<Rgb> {
match kind {
"blur" => frames.iter().map(|f| soft(f).into_raw()).collect(),
"sharpblur" => frames.iter().map(sharpened).collect(),
"glow" => frames.iter().map(|f| glow(f, 0.7)).collect(),
"glow_half" => frames.iter().map(|f| glow(f, 0.35)).collect(),
- "dark" => frames.iter().map(|f| f.iter().map(|&x| (x as f32 * 0.3) as u8).collect()).collect(),
- "dark_half" => frames.iter().map(|f| f.iter().map(|&x| (x as f32 * 0.65) as u8).collect()).collect(),
+ "dark" => frames.iter().map(|f| darker(f, 0.3)).collect(),
+ "dark_half" => frames.iter().map(|f| darker(f, 0.65)).collect(),
"freeze" => frames.iter().map(|_| frames[0].clone()).collect(),
"freeze_zoom" => (0..frames.len()).map(|i| zoomed(&frames[0], i)).collect(),
"flash" | "flash_white" => {
@@ -106,8 +116,8 @@ pub fn sound(w: &[f32], kind: &str, rate: u32, noise: &mut Noise) -> Vec<f32> {
let b = (a + (gap * rate as f64) as usize).min(w.len());
w[a..b].iter_mut().for_each(|x| *x = 0.0);
}
- "clip" => w.iter_mut().for_each(|x| *x = (*x * 10.0).clamp(-0.3, 0.3)),
- "clip_soft" => w.iter_mut().for_each(|x| *x = (*x * 3.0).clamp(-0.6, 0.6)),
+ "clip" => clipped(&mut w, 10.0, 0.3),
+ "clip_soft" => clipped(&mut w, 3.0, 0.6),
_ => {}
}
w
diff --git a/systems/columns/src/lib.rs b/systems/columns/src/lib.rs
index a69b4197..df5dad77 100644
--- a/systems/columns/src/lib.rs
+++ b/systems/columns/src/lib.rs
@@ -81,8 +81,8 @@ impl Encoders {
}
/// Each encoder's id and its file's sha256: a fingerprint's heads are pinned to these
- pub fn pins(&self) -> Vec<(String, String)> {
- self.files.pins()
+ pub fn pins(&self) -> std::collections::BTreeMap<String, String> {
+ self.files.pins().into_iter().collect()
}
/// A file's columns, from the cache when it has them
@@ -160,7 +160,7 @@ impl Encoders {
}
/// `$var`, else `rel` under the home folder
-pub(crate) fn under(var: &str, rel: &str) -> PathBuf {
+pub fn under(var: &str, rel: &str) -> PathBuf {
match std::env::var_os(var) {
Some(p) => p.into(),
None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(rel),
diff --git a/systems/fingerprint-use/src/profile.rs b/systems/fingerprint-use/src/profile.rs
index 4dbceb0f..f46cbeff 100644
--- a/systems/fingerprint-use/src/profile.rs
+++ b/systems/fingerprint-use/src/profile.rs
@@ -23,8 +23,9 @@ pub const NAMES: [(&str, &str); 9] = [
("sharpness", "sharpness"),
];
+/// The average; nothing averages to 0
fn mean(v: &[f32]) -> f32 {
- if v.is_empty() { 0.0 } else { v.iter().sum::<f32>() / v.len() as f32 }
+ v.iter().sum::<f32>() / v.len().max(1) as f32
}
fn pct(v: &[f32], q: f32) -> f32 {
diff --git a/systems/fingerprint-use/src/score.rs b/systems/fingerprint-use/src/score.rs
index fbe3996b..75f76b41 100644
--- a/systems/fingerprint-use/src/score.rs
+++ b/systems/fingerprint-use/src/score.rs
@@ -110,6 +110,7 @@ pub fn score(fp: &Fingerprint, words: Option<&Words>, trained: Option<&Trained>,
loop {
let b = (a + WIN).min(c.dur.max(0.25));
let row = features(c, a, b);
+ let nearest = |m: Modality| words.and_then(|w| w.nearest(&row, m));
let head = |name: &str| trained.and_then(|t| t.heads.iter().find(|h| h.axis == name));
let axes: Vec<AxisScore> = fp.axes.iter().filter_map(|ax| one(head(&ax.name), words, &ax.name, ax.modality, &row)).collect();
let (l0, l1) = ((a * 10.0) as usize, ((b * 10.0) as usize).max((a * 10.0) as usize + 1));
@@ -120,8 +121,8 @@ pub fn score(fp: &Fingerprint, words: Option<&Words>, trained: Option<&Trained>,
a,
b,
axes,
- seen: words.and_then(|w| w.nearest(&row, Modality::Picture)),
- heard: words.and_then(|w| w.nearest(&row, Modality::Sound)),
+ seen: nearest(Modality::Picture),
+ heard: nearest(Modality::Sound),
level,
overall,
});
diff --git a/systems/fingerprint-use/src/sheet.rs b/systems/fingerprint-use/src/sheet.rs
index 13402271..38913fc0 100644
--- a/systems/fingerprint-use/src/sheet.rs
+++ b/systems/fingerprint-use/src/sheet.rs
@@ -78,7 +78,7 @@ pub struct Tick {
/// The sheet for a scored piece: `frames` are THUMBS frames spread over it (224 x 224 RGB), `pcm16` its sound
pub fn sheet(s: &Scored, frames: &[Frame], pcm16: &[f32], ticks: &[Tick], modality: &dyn Fn(&str) -> Option<Modality>, out: &std::path::Path) -> Result<()> {
- let axes: Vec<&str> = s.windows.first().map(|w| w.axes.iter().map(|a| a.axis.as_str()).collect()).unwrap_or_default();
+ let axes: Vec<&str> = s.windows.first().into_iter().flat_map(|w| w.axes.iter().map(|a| a.axis.as_str())).collect();
let span = W - LEFT - 10;
let thumb = span / THUMBS;
let h = 30 + thumb + 20 + axes.len() as u32 * LANE + 10 + 40 + 10 + SPEC + 10 + 16 + ticks.len().min(12) as u32 * 10 + 20;
diff --git a/systems/fingerprint-use/src/which.rs b/systems/fingerprint-use/src/which.rs
index 86cee46e..8da77e79 100644
--- a/systems/fingerprint-use/src/which.rs
+++ b/systems/fingerprint-use/src/which.rs
@@ -7,7 +7,7 @@
//! or a sound); its tags are the project's `tags`.
use raea_sys_fingerprint::folder::{Folder, root};
-use raea_sys_fingerprint::taxonomy::Fingerprint;
+use raea_sys_fingerprint::taxonomy::{Fingerprint, words_of};
use serde::Serialize;
use std::path::{Path, PathBuf};
@@ -40,11 +40,17 @@ fn up(from: &Path, marker: &str) -> Option<PathBuf> {
from.ancestors().find(|d| d.join(".raea").join(marker).is_file()).map(Path::to_path_buf)
}
+/// A folder and the fingerprint read from it, when it reads
+fn opened(f: Folder) -> Option<(Folder, Fingerprint)> {
+ let fp = f.read(None).ok()?;
+ Some((f, fp))
+}
+
pub fn piece(path: &Path) -> Piece {
let start = if path.is_dir() { path } else { path.parent().unwrap_or(path) };
let project = up(start, "project");
let workspace = up(start, "workspace");
- let text = project.as_ref().and_then(|p| std::fs::read_to_string(p.join(".raea/project")).ok()).unwrap_or_default();
+ let text = project.as_ref().map(|p| p.join(".raea/project")).and_then(|f| std::fs::read_to_string(f).ok()).unwrap_or_default();
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
let by_file = match ext.as_str() {
"png" | "jpg" | "jpeg" | "webp" => Some("still"),
@@ -52,7 +58,7 @@ pub fn piece(path: &Path) -> Piece {
_ => None,
};
let kind = key(&text, "kind").or_else(|| by_file.map(str::to_string));
- let tags = key(&text, "tags").map(|t| t.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default();
+ let tags = key(&text, "tags").map(|t| words_of(&t)).unwrap_or_default();
Piece { kind, tags, project, workspace }
}
@@ -64,7 +70,7 @@ pub fn at_level(dir: &Path) -> Vec<(Folder, Fingerprint)> {
.flatten()
.map(|e| Folder { dir: e.path() })
.filter(Folder::exists)
- .filter_map(|f| f.read(None).ok().map(|fp| (f, fp)))
+ .filter_map(opened)
.collect();
out.sort_by(|a, b| a.1.name.cmp(&b.1.name));
out
@@ -95,7 +101,7 @@ pub fn levels(p: &Piece) -> Vec<(&'static str, PathBuf)> {
/// A level's `default`, found at that level or above
fn named(name: &str, levels: &[(&'static str, PathBuf)], from: usize) -> Option<(Folder, Fingerprint)> {
- levels[from..].iter().map(|(_, d)| Folder { dir: d.join(name) }).find(Folder::exists).and_then(|f| f.read(None).ok().map(|fp| (f, fp)))
+ levels[from..].iter().map(|(_, d)| Folder { dir: d.join(name) }).find(Folder::exists).and_then(opened)
}
fn choice((f, fp): (Folder, Fingerprint), level: &str, why: String) -> Choice {
diff --git a/systems/fingerprint/Cargo.toml b/systems/fingerprint/Cargo.toml
index 278b0f2b..351c717c 100644
--- a/systems/fingerprint/Cargo.toml
+++ b/systems/fingerprint/Cargo.toml
@@ -10,7 +10,6 @@ description = "Fingerprint (docs/fingerprint.feature FP2-FP4): a taxonomy of axe
# the columns every head reads, the encoders that make them, and the damage the bootstrap puts in
raea-sys-columns = { path = "../columns" }
# evidence rows and word vectors are kept as fp16
-half = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1"
diff --git a/systems/fingerprint/src/evidence.rs b/systems/fingerprint/src/evidence.rs
index f855abe4..f2dd7d41 100644
--- a/systems/fingerprint/src/evidence.rs
+++ b/systems/fingerprint/src/evidence.rs
@@ -4,10 +4,10 @@
//! (FP8); heads are always retrained from them.
use anyhow::Result;
-use half::f16;
+use raea_sys_columns::cache::{f16s, f32s};
use raea_sys_columns::window::Modality;
use serde::{Deserialize, Serialize};
-use std::io::Write;
+use std::collections::BTreeSet;
use std::path::Path;
/// Every modality's features, in Modality::ALL's order
@@ -97,7 +97,7 @@ impl Ledger {
}
let rows = std::fs::read_to_string(j)?.lines().filter(|l| !l.trim().is_empty()).map(serde_json::from_str).collect::<Result<Vec<Row>, _>>()?;
let raw = std::fs::read(f).unwrap_or_default();
- let feats = raw.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect();
+ let feats = f32s(&raw);
Ok(Ledger { rows, feats })
}
@@ -109,10 +109,7 @@ impl Ledger {
j.push(b'\n');
}
std::fs::write(dir.join("evidence.jsonl"), j)?;
- let mut f = std::io::BufWriter::new(std::fs::File::create(dir.join("evidence.f16"))?);
- for x in &self.feats {
- f.write_all(&f16::from_f32(*x).to_le_bytes())?;
- }
+ std::fs::write(dir.join("evidence.f16"), f16s(&self.feats))?;
Ok(())
}
@@ -134,6 +131,22 @@ impl Ledger {
}).collect()
}
+ /// The rows' labels and weights, as a fit takes them
+ pub fn labels(&self, rows: &[usize]) -> (Vec<bool>, Vec<f32>) {
+ rows.iter().map(|&i| (self.rows[i].bad, self.rows[i].weight)).unzip()
+ }
+
+ /// How many of the rows say the defect is there, and how many say it isn't
+ pub fn counts(&self, rows: &[usize]) -> (usize, usize) {
+ let bad = rows.iter().filter(|&&i| self.rows[i].bad).count();
+ (bad, rows.len() - bad)
+ }
+
+ /// The projects the rows come from
+ pub fn projects(&self, rows: &[usize]) -> BTreeSet<String> {
+ rows.iter().map(|&i| self.rows[i].project.clone()).collect()
+ }
+
/// A row's features replaced, as re-embedding does
pub fn set_features(&mut self, i: usize, f: &[f32]) {
let w = width();
diff --git a/systems/fingerprint/src/folder.rs b/systems/fingerprint/src/folder.rs
index 5e25eb9f..4263621c 100644
--- a/systems/fingerprint/src/folder.rs
+++ b/systems/fingerprint/src/folder.rs
@@ -14,7 +14,7 @@ use crate::taxonomy::{Fingerprint, to_ts};
use crate::train::Trained;
use crate::words::Words;
use anyhow::{Context, Result, anyhow, bail};
-use half::f16;
+use raea_sys_columns::cache::{f16s, f32s};
use raea_sys_columns::window::Modality;
use raea_sys_columns::{CLAP, SIG};
use serde::{Deserialize, Serialize};
@@ -26,10 +26,7 @@ pub type Eval = fn(&Path) -> Result<String, String>;
/// Where a person's fingerprints live: $RAEA_FINGERPRINTS, else ~/.raea/fingerprints
pub fn root() -> PathBuf {
- match std::env::var_os("RAEA_FINGERPRINTS") {
- Some(p) => p.into(),
- None => Path::new(&std::env::var_os("HOME").unwrap_or_default()).join(".raea/fingerprints"),
- }
+ raea_sys_columns::under("RAEA_FINGERPRINTS", ".raea/fingerprints")
}
pub struct Folder {
@@ -50,14 +47,6 @@ struct WordsHead {
picture_words: Vec<String>,
}
-fn f16s(v: &[f32]) -> Vec<u8> {
- v.iter().flat_map(|x| f16::from_f32(*x).to_le_bytes()).collect()
-}
-
-fn f32s_of_f16(b: &[u8]) -> Vec<f32> {
- b.as_chunks::<2>().0.iter().map(|p| f16::from_le_bytes(*p).to_f32()).collect()
-}
-
impl Folder {
/// A person's fingerprint by name, or a folder given as a path
pub fn named(name: &str) -> Folder {
@@ -66,11 +55,14 @@ impl Folder {
}
pub fn exists(&self) -> bool {
- self.dir.join("fingerprint.ts").is_file()
+ std::fs::metadata(self.ts()).is_ok_and(|m| m.is_file())
}
+ /// Its fingerprint.ts, the axes a person edits
pub fn ts(&self) -> PathBuf {
- self.dir.join("fingerprint.ts")
+ let mut p = self.dir.clone();
+ p.push("fingerprint.ts");
+ p
}
/// A new fingerprint's folder: its fingerprint.ts; refused when one is there already
@@ -109,7 +101,7 @@ impl Folder {
pub fn words(&self) -> Option<Words> {
let head: WordsHead = serde_json::from_slice(&std::fs::read(self.dir.join("words.json")).ok()?).ok()?;
- let v = f32s_of_f16(&std::fs::read(self.dir.join("words.f16")).ok()?);
+ let v = f32s(&std::fs::read(self.dir.join("words.f16")).ok()?);
let mut at = 0;
let mut take = |n: usize| -> Option<Vec<f32>> {
let r = v.get(at..at + n)?.to_vec();
diff --git a/systems/fingerprint/src/head.rs b/systems/fingerprint/src/head.rs
index 2fde4498..190ce64b 100644
--- a/systems/fingerprint/src/head.rs
+++ b/systems/fingerprint/src/head.rs
@@ -178,6 +178,11 @@ pub fn auc(pos: &[f32], neg: &[f32]) -> f64 {
}
/// The score above which `q` of the clean scores fall (the threshold that flags 1 - q of clean work)
+/// The share of `v` above `thr`; none of nothing
+pub fn share_over(v: &[f32], thr: f32) -> f64 {
+ v.iter().filter(|x| **x > thr).count() as f64 / v.len().max(1) as f64
+}
+
pub fn quantile(v: &[f32], q: f64) -> f32 {
let mut s = v.to_vec();
s.sort_by(f32::total_cmp);
diff --git a/systems/fingerprint/src/inherit.rs b/systems/fingerprint/src/inherit.rs
index 28efb0db..30eb0106 100644
--- a/systems/fingerprint/src/inherit.rs
+++ b/systems/fingerprint/src/inherit.rs
@@ -44,9 +44,12 @@ fn differs(a: &Axis, b: &Axis) -> bool {
pub fn overrides(fp: &Fingerprint, parents: &[(Folder, Fingerprint)]) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for a in &fp.axes {
- if let Some(b) = parents.iter().find_map(|(_, p)| p.axis(&a.name)) {
- if differs(a, b) {
- out.insert(a.name.clone());
+ for (_, p) in parents {
+ if let Some(b) = p.axis(&a.name) {
+ if differs(a, b) {
+ out.insert(a.name.clone());
+ }
+ break;
}
}
}
@@ -104,11 +107,11 @@ pub fn measure(fp: &Fingerprint, l: &Ledger, own: usize) -> Vec<Measured> {
for a in &fp.axes {
let rows = l.for_axis(&a.name);
let mine: Vec<usize> = rows.iter().copied().filter(|&i| i < own).collect();
- let bad = mine.iter().filter(|&&i| l.rows[i].bad).count();
- if bad < 2 || mine.len() - bad < 2 || own == l.rows.len() {
+ let (bad, clean) = l.counts(&mine);
+ if bad < 2 || clean < 2 || own == l.rows.len() {
continue;
}
- let projects: BTreeSet<String> = mine.iter().map(|&i| l.rows[i].project.clone()).collect();
+ let projects = l.projects(&mine);
if projects.len() < 2 {
continue;
}
@@ -118,13 +121,12 @@ pub fn measure(fp: &Fingerprint, l: &Ledger, own: usize) -> Vec<Measured> {
for fold in folds(&projects) {
let held = |i: usize| i < own && fold.contains(&l.rows[i].project);
let train: Vec<usize> = rows.iter().copied().filter(|&i| !held(i) && pick(i)).collect();
- let (tb, tn) = (train.iter().filter(|&&i| l.rows[i].bad).count(), train.iter().filter(|&&i| !l.rows[i].bad).count());
+ let (tb, tn) = l.counts(&train);
if tb == 0 || tn == 0 {
continue;
}
let x: Vec<&[f32]> = train.iter().map(|&i| l.modality(i, m)).collect();
- let y: Vec<bool> = train.iter().map(|&i| l.rows[i].bad).collect();
- let w: Vec<f32> = train.iter().map(|&i| l.rows[i].weight).collect();
+ let (y, w) = l.labels(&train);
let f = Logistic::fit(Scaler::fit(&x), &x, &y, Some(&w), C, true);
for &i in mine.iter().filter(|&&i| held(i)) {
let s = f.score(l.modality(i, m));
diff --git a/systems/fingerprint/src/lib.rs b/systems/fingerprint/src/lib.rs
index 8749788e..93cdaec4 100644
--- a/systems/fingerprint/src/lib.rs
+++ b/systems/fingerprint/src/lib.rs
@@ -49,7 +49,7 @@ pub fn retrain(dir: &Folder, fp: &Fingerprint, w: &Words, l: &Ledger, bootstrap:
let (all, own) = inherit::pooled(l, &parents, &over);
let t = train::train(fp, &all, w);
dir.write_trained(&t, &fp.encoders)?;
- let kept = bootstrap.or_else(|| dir.report().and_then(|r| r.get("bootstrap").cloned()));
+ let kept = bootstrap.or_else(|| Some(dir.report()?.get("bootstrap")?.clone()));
let mut r = report(fp, &t, &all, kept);
if !parents.is_empty() {
r["inherits"] = json!({
diff --git a/systems/fingerprint/src/pairs.rs b/systems/fingerprint/src/pairs.rs
index 4bc58ac8..c08f03e0 100644
--- a/systems/fingerprint/src/pairs.rs
+++ b/systems/fingerprint/src/pairs.rs
@@ -8,7 +8,6 @@ use crate::evidence::Ledger;
use crate::head::{Logistic, Scaler};
use crate::train::{C, folds};
use raea_sys_columns::window::Modality;
-use std::collections::BTreeSet;
/// The pair rows for an axis
pub fn rows(l: &Ledger, axis: &str) -> Vec<usize> {
@@ -23,13 +22,13 @@ pub fn fit(l: &Ledger, rows: &[usize], m: Modality) -> Logistic {
let mut sc = Scaler::fit(&x);
sc.mean.iter_mut().for_each(|v| *v = 0.0);
let y: Vec<bool> = (0..x.len()).map(|i| i < d.len()).collect();
- let w: Vec<f32> = rows.iter().chain(rows).map(|&i| l.rows[i].weight).collect();
+ let w = l.labels(rows).1.repeat(2);
Logistic::fit(sc, &x, &y, Some(&w), C, false)
}
/// Share of held-out pairs (by project) the fit orders right
pub fn held_out(l: &Ledger, rows: &[usize], m: Modality) -> Option<f64> {
- let projects: BTreeSet<String> = rows.iter().map(|&i| l.rows[i].project.clone()).collect();
+ let projects = l.projects(&rows);
if projects.len() < 2 {
return None;
}
diff --git a/systems/fingerprint/src/taxonomy.rs b/systems/fingerprint/src/taxonomy.rs
index 9b51ea3b..605b7bff 100644
--- a/systems/fingerprint/src/taxonomy.rs
+++ b/systems/fingerprint/src/taxonomy.rs
@@ -69,6 +69,17 @@ pub struct Applies {
pub tags: Vec<String>,
}
+/// A comma-separated list of kinds or tags, each trimmed and lowercased, the empty ones dropped
+pub fn words_of(s: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ for w in s.split(',').map(str::trim) {
+ if !w.is_empty() {
+ out.push(w.to_ascii_lowercase());
+ }
+ }
+ out
+}
+
impl Fingerprint {
pub fn axis(&self, name: &str) -> Option<&Axis> {
let i = self.axes.iter().position(|a| a.name == name)?;
diff --git a/systems/fingerprint/src/train.rs b/systems/fingerprint/src/train.rs
index 95edbba9..27cdd045 100644
--- a/systems/fingerprint/src/train.rs
+++ b/systems/fingerprint/src/train.rs
@@ -66,25 +66,11 @@ fn scaler(l: &Ledger, rows: &[usize], m: Modality) -> Scaler {
Scaler::fit(&x)
}
-/// The rows' labels and weights
-fn labels(l: &Ledger, rows: &[usize]) -> (Vec<bool>, Vec<f32>) {
- let (mut y, mut w) = (Vec::with_capacity(rows.len()), Vec::with_capacity(rows.len()));
- for &i in rows {
- y.push(l.rows[i].bad);
- w.push(l.rows[i].weight);
- }
- (y, w)
-}
-/// How many of the rows say the defect is there, and how many say it isn't
-fn counts(l: &Ledger, rows: &[usize]) -> (usize, usize) {
- let bad = rows.iter().filter(|&&i| l.rows[i].bad).count();
- (bad, rows.len() - bad)
-}
fn fit(l: &Ledger, rows: &[usize], m: Modality, sc: Scaler) -> Logistic {
let x: Vec<&[f32]> = rows.iter().map(|&i| l.modality(i, m)).collect();
- let (y, w) = labels(l, rows);
+ let (y, w) = l.labels(rows);
Logistic::fit(sc, &x, &y, Some(&w), C, true)
}
@@ -114,8 +100,8 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHead
for &i in &rows {
h.labels.entry(l.rows[i].source.clone()).or_default()[usize::from(!l.rows[i].bad)] += 1;
}
- let (pos, neg) = counts(l, &rows);
- let projects: BTreeSet<String> = rows.iter().map(|&i| l.rows[i].project.clone()).collect();
+ let (pos, neg) = l.counts(&rows);
+ let projects = l.projects(&rows);
h.projects = projects.len();
let plain: Vec<usize> = (0..l.rows.len()).filter(|&i| !matches!(l.rows[i].source.as_str(), "cheat" | "pair")).collect();
let worded = words.axes.iter().any(|a| a.0 == name);
@@ -150,7 +136,7 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHead
for fold in folds(&projects) {
let held = |i: usize| fold.contains(&l.rows[i].project);
let (test, train): (Vec<usize>, Vec<usize>) = rows.iter().copied().partition(|&i| held(i));
- if matches!(counts(l, &train), (0, _) | (_, 0)) {
+ if matches!(l.counts(&train), (0, _) | (_, 0)) {
continue;
}
let base: Vec<usize> = plain.iter().copied().filter(|&i| !held(i)).collect();
@@ -178,8 +164,8 @@ pub fn axis(fp: &Fingerprint, l: &Ledger, words: &Words, name: &str) -> AxisHead
let mut why = Vec::new();
// another eye's readings (clef's, Kimi's: source "eye:NAME") train the head but never count as the person's (FP6d)
let theirs: Vec<usize> = rows.iter().copied().filter(|&i| !l.rows[i].source.starts_with("eye:")).collect();
- let (pos, neg) = counts(l, &theirs);
- let own_projects = theirs.iter().map(|&i| l.rows[i].project.as_str()).collect::<BTreeSet<_>>().len();
+ let (pos, neg) = l.counts(&theirs);
+ let own_projects = l.projects(&theirs).len();
if pos < GATE_LABELS || neg < GATE_LABELS {
why.push(format!("{pos} defect and {neg} clean labels of yours (needs {GATE_LABELS} of each)"));
}
@@ -206,11 +192,11 @@ pub fn train(fp: &Fingerprint, l: &Ledger, words: &Words) -> Trained {
let heads: Vec<AxisHead> = fp.axes.iter().map(|a| axis(fp, l, words, &a.name)).collect();
// the weighting: overall labels the person gave (axis "*", their own sources), read through every head
let overall: Vec<usize> = (0..l.rows.len()).filter(|&i| l.rows[i].axis == "*" && matches!(l.rows[i].source.as_str(), "teach" | "note" | "approval" | "postmortem")).collect();
- let (p, n) = counts(l, &overall);
+ let (p, n) = l.counts(&overall);
let weighting = (p >= 8 && n >= 8).then(|| {
let x: Vec<Vec<f32>> = overall.iter().map(|&i| scores(&heads, l.features(i))).collect();
let xr: Vec<&[f32]> = x.iter().map(|v| v.as_slice()).collect();
- Logistic::fit(Scaler::fit(&xr), &xr, &labels(l, &overall).0, None, C, true)
+ Logistic::fit(Scaler::fit(&xr), &xr, &l.labels(&overall).0, None, C, true)
});
Trained { heads, weighting }
}