Files
sorsfonalak/services/worker/src/analysis/compact.rs
T

385 lines
15 KiB
Rust
Raw Normal View History

//! Compact text views of charts for the language model.
//!
//! Only astrological positions go in: no names, birth date, time, place or
//! coordinates. Plain text is shorter than the JSON and easier for models.
use std::fmt::Write;
use serde_json::Value;
/// Points listed one per line; asteroids go on a shorter line.
const MAIN_POINTS: [&str; 14] = [
"sun",
"moon",
"mercury",
"venus",
"mars",
"jupiter",
"saturn",
"uranus",
"neptune",
"pluto",
"chiron",
"north_node",
"south_node",
"lilith",
];
const ASTEROIDS: [&str; 4] = ["ceres", "pallas", "juno", "vesta"];
const ANGLES: [&str; 4] = ["ascendant", "midheaven", "descendant", "imum_coeli"];
const MAX_SYNASTRY_ASPECTS: usize = 45;
fn point_name(id: &str) -> String {
match id {
"north_node" => "North Node".into(),
"south_node" => "South Node".into(),
"lilith" => "Lilith (Black Moon)".into(),
"midheaven" => "Midheaven (MC)".into(),
"imum_coeli" => "Imum Coeli (IC)".into(),
"ascendant" => "Ascendant".into(),
"descendant" => "Descendant".into(),
other => capitalize(other),
}
}
fn capitalize(s: &str) -> String {
let mut chars = s.chars();
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
}
fn words(s: &str) -> String {
s.replace('_', " ")
}
/// "Cancer 0°24'" from a position object (sign + degree_in_sign).
fn position(p: &Value) -> String {
let degree = p["degree_in_sign"].as_f64().unwrap_or(0.0);
// Rounded to the second first, as in the `degree_in_sign_dms` field; never 30°.
let secs = ((degree * 3600.0).round() as i64).clamp(0, 30 * 3600 - 1);
let (d, m) = (secs / 3600, secs % 3600 / 60);
format!("{} {d}°{m:02}'", capitalize(p["sign"].as_str().unwrap_or("?")))
}
fn time_known(chart: &Value) -> bool {
chart["time"]["time_known"].as_bool().unwrap_or(false)
}
fn is_main(id: &str) -> bool {
MAIN_POINTS.contains(&id) || ANGLES.contains(&id)
}
fn points(chart: &Value) -> impl Iterator<Item = &Value> {
chart["points"].as_array().into_iter().flatten()
}
fn names(list: &Value) -> String {
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
}
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) {
let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p));
if houses && let Some(h) = p["house"].as_i64() {
let _ = write!(line, ", house {h}");
}
if p["retrograde"].as_bool() == Some(true) {
line.push_str(", retrograde");
}
for dignity in p["dignities"].as_array().into_iter().flatten().filter_map(Value::as_str) {
let _ = write!(line, ", {}", words(dignity));
}
if p["out_of_bounds"].as_bool() == Some(true) {
line.push_str(", out of bounds");
}
let _ = writeln!(out, "{line}");
}
let minor: Vec<String> = points(chart)
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
.map(|p| {
let house = if houses {
p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default()
} else {
String::new()
};
format!("{} {}{house}", point_name(p["id"].as_str().unwrap_or("?")), position(p))
})
.collect();
if !minor.is_empty() {
let _ = writeln!(out, "{prefix}- Asteroids: {}", minor.join("; "));
}
}
fn angle_lines(out: &mut String, chart: &Value, prefix: &str) {
let angles = &chart["angles"];
for (id, label) in [("ascendant", "Ascendant"), ("midheaven", "Midheaven (MC)")] {
if angles[id].is_object() {
let _ = writeln!(out, "{prefix}- {label}: {}", position(&angles[id]));
}
}
}
const BIRTH_TIME_UNKNOWN: &str = "Birth time: UNKNOWN. The chart is cast for noon, so there are no houses, \
no Ascendant and no Midheaven, and the Moon may be up to about 7° off (its sign is uncertain near a sign boundary).";
/// A natal chart (the horoscope-api `/v1/natal` result).
pub fn natal(chart: &Value) -> String {
let mut out = String::new();
let settings = &chart["settings"];
let known = time_known(chart);
let _ = writeln!(
out,
"NATAL CHART ({} zodiac, {} houses)",
settings["zodiac"].as_str().unwrap_or("tropical"),
capitalize(&words(
chart["houses"]["system"].as_str().or(settings["house_system"].as_str()).unwrap_or("placidus")
))
);
let _ = writeln!(out, "{}", if known { "Birth time: known." } else { BIRTH_TIME_UNKNOWN });
let summary = &chart["summary"];
if let Some(sect) = summary["sect"].as_str() {
let _ = writeln!(out, "Sect: {sect} chart.");
}
let phase = &chart["moon_phase"];
if let Some(name) = phase["phase"].as_str() {
let illumination = phase["illumination"].as_f64().map(|i| format!(" ({:.0}% illuminated)", i * 100.0));
let _ = writeln!(out, "Moon phase: {}{}.", words(name), illumination.unwrap_or_default());
}
if known {
out.push_str("\nAngles:\n");
angle_lines(&mut out, chart, "");
let ruler = &summary["chart_ruler"];
for kind in ["traditional", "modern"] {
let r = &ruler[kind];
if let Some(planet) = r["planet"].as_str() {
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
continue;
}
let _ = writeln!(
out,
"- Chart ruler ({kind}): {} in {}, house {}",
point_name(planet),
capitalize(r["sign"].as_str().unwrap_or("?")),
r["house"]
);
}
}
}
out.push_str("\nPlanets and points:\n");
point_lines(&mut out, chart, "", known);
if known && let Some(cusps) = chart["houses"]["cusps"].as_array() {
let list: Vec<String> = cusps.iter().map(|c| format!("{} {}", c["house"], position(c))).collect();
let _ = writeln!(out, "\nHouse cusps: {}", list.join(" | "));
}
aspect_lines(&mut out, &chart["aspects"], "\nAspects (tightest first; orb in degrees):", usize::MAX);
out.push_str("\nBalance (main planets):\n");
for (title, key) in [("Elements", "elements"), ("Modalities", "modalities")] {
if let Some(groups) = summary[key].as_object() {
let list: Vec<String> = groups
.iter()
.map(|(name, g)| {
let members = names(&g["points"]);
if members.is_empty() { format!("{name} 0") } else { format!("{name} {} ({members})", g["count"]) }
})
.collect();
let _ = writeln!(out, "- {title}: {}", list.join("; "));
}
}
if known && let Some(h) = summary["hemispheres"].as_object() {
let list: Vec<String> = h.iter().map(|(name, g)| format!("{} {}", words(name), g["count"])).collect();
let _ = writeln!(out, "- Hemispheres: {}", list.join(", "));
}
let retro = names(&summary["retrograde"]);
if !retro.is_empty() {
let _ = writeln!(out, "- Retrograde: {retro}");
}
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
let fortune = Value::Object(fortune.clone());
let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]);
}
out
}
/// A synastry: both natal charts plus the synastry result (inter-aspects,
/// house overlays, composite) as stored by the backend.
pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String {
let mut out = String::from("SYNASTRY: two natal charts compared (Person 1 and Person 2), tropical zodiac.\n");
for (label, chart) in [("Person 1", chart1), ("Person 2", chart2)] {
let _ = writeln!(out, "\n{label}:");
if time_known(chart) {
let _ = writeln!(out, " Birth time: known.");
angle_lines(&mut out, chart, " ");
} else {
let _ = writeln!(out, " {BIRTH_TIME_UNKNOWN}");
}
point_lines(&mut out, chart, " ", time_known(chart));
}
let mut aspects: Vec<&Value> = result["aspects"]
.as_array()
.into_iter()
.flatten()
.filter(|a| is_main(a["person1"].as_str().unwrap_or("")) && is_main(a["person2"].as_str().unwrap_or("")))
.collect();
aspects.sort_by(|a, b| a["orb"].as_f64().unwrap_or(99.0).total_cmp(&b["orb"].as_f64().unwrap_or(99.0)));
if !aspects.is_empty() {
let _ = writeln!(
out,
"\nInter-chart aspects (Person 1's point first; tightest {} of {}):",
aspects.len().min(MAX_SYNASTRY_ASPECTS),
aspects.len()
);
for a in aspects.iter().take(MAX_SYNASTRY_ASPECTS) {
let _ = writeln!(
out,
"- {} {} {} (orb {:.1}°, {})",
point_name(a["person1"].as_str().unwrap_or("?")),
words(a["aspect"].as_str().unwrap_or("?")),
point_name(a["person2"].as_str().unwrap_or("?")),
a["orb"].as_f64().unwrap_or(0.0),
a["nature"].as_str().unwrap_or("neutral")
);
}
}
if let Some(by_nature) = result["summary"]["by_nature"].as_object() {
let list: Vec<String> = by_nature.iter().map(|(k, v)| format!("{k} {v}")).collect();
let _ = writeln!(out, "All aspects by nature: {}", list.join(", "));
}
let overlays = &result["house_overlays"];
for (key, label) in [
("person1_in_person2", "Person 1's planets in Person 2's houses"),
("person2_in_person1", "Person 2's planets in Person 1's houses"),
] {
let list: Vec<String> = overlays[key]
.as_array()
.into_iter()
.flatten()
.filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or("")))
.filter_map(|o| Some(format!("{} {}", point_name(o["point"].as_str()?), o["house"].as_i64()?)))
.collect();
if !list.is_empty() {
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
}
}
let composite = &result["composite"];
if composite["points"].is_array() {
let both_known = time_known(chart1) && time_known(chart2);
let _ = writeln!(out, "\nComposite chart ({} method):", composite["method"].as_str().unwrap_or("midpoint"));
if both_known {
angle_lines(&mut out, composite, "");
}
point_lines(&mut out, composite, "", both_known);
aspect_lines(&mut out, &composite["aspects"], "Composite aspects (tightest first):", 12);
}
out
}
/// Aspects between main points and angles, tightest first.
fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize) {
let mut list: Vec<&Value> = aspects
.as_array()
.into_iter()
.flatten()
.filter(|a| is_main(a["point1"].as_str().unwrap_or("")) && is_main(a["point2"].as_str().unwrap_or("")))
.collect();
if list.is_empty() {
return;
}
list.sort_by(|a, b| a["orb"].as_f64().unwrap_or(99.0).total_cmp(&b["orb"].as_f64().unwrap_or(99.0)));
let _ = writeln!(out, "{heading}");
for a in list.into_iter().take(limit) {
let motion = match a["applying"].as_bool() {
Some(true) => ", applying",
Some(false) => ", separating",
None => "",
};
let _ = writeln!(
out,
"- {} {} {} (orb {:.1}°{motion})",
point_name(a["point1"].as_str().unwrap_or("?")),
words(a["aspect"].as_str().unwrap_or("?")),
point_name(a["point2"].as_str().unwrap_or("?")),
a["orb"].as_f64().unwrap_or(0.0)
);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(name: &str) -> Value {
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
/// Birth data that must never reach the model.
fn assert_private(text: &str) {
for secret in ["1990", "1988", "14:30", "08:10", "Szeged", "Pécs", "Hungary", "HU", "46.", "20.1", "Budapest"]
{
assert!(!text.contains(secret), "'{secret}' leaked into:\n{text}");
}
}
#[test]
fn natal_with_birth_time() {
let text = natal(&fixture("natal-1990-03-15.json"));
assert_private(&text);
for expected in [
"Birth time: known.",
"- Ascendant: Leo 19°23'",
"- Chart ruler (traditional): Sun in Pisces, house 8",
"- Sun: Pisces 24°42', house 8",
"- Pluto: Scorpio 17°36', house 4, retrograde, domicile",
"- Asteroids: Ceres Gemini 25°43' (house 11);",
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
"- Moon trine Chiron (orb 0.1°, applying)",
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
"- Part of Fortune: Aries 5°10', house 8",
] {
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
}
// Tightest aspect first.
assert!(text.find("Moon trine Chiron").unwrap() < text.find("Moon square Ascendant").unwrap());
}
#[test]
fn natal_without_birth_time_has_no_houses() {
let text = natal(&fixture("natal-1988-11-02-notime.json"));
assert_private(&text);
assert!(text.contains("Birth time: UNKNOWN"));
for absent in
["house ", "House cusps", "Ascendant:", "Midheaven (MC):", "Chart ruler", "Hemispheres", "Fortune"]
{
assert!(!text.contains(absent), "'{absent}' in:\n{text}");
}
assert!(text.contains("- Venus: Libra 4°12', domicile"));
}
#[test]
fn synastry_view() {
// The full horoscope-api response, with both persons' birth data in it.
let response = fixture("synastry-response.json");
let text = synastry(&response["person1"], &response["person2"], &response);
assert_private(&text);
for expected in [
"Person 1:\n Birth time: known.",
" - Sun: Pisces 24°42', house 8",
"Inter-chart aspects (Person 1's point first; tightest 45 of",
"(orb 0.0°, harmonious)",
"All aspects by nature: ",
"Person 1's planets in Person 2's houses: Sun 4, Moon 12",
"Composite chart (midpoint method):\n- Ascendant: Libra 8°39'",
"Composite aspects (tightest first):\n- Saturn conjunction Neptune (orb 0.1°)",
] {
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
}
}
}