Skip to main content

astroceleste_engine/chinese/
bazi.rs

1//! Ba Zi (八字), the Four Pillars of Destiny of a birth, cast from its
2//! [`ChineseCalendar`]. No kernel is needed.
3//!
4//! - The year pillar changes at 立春 and the month pillar at each jie term; both compare
5//!   instants, so they do not depend on the clock the birth was recorded in.
6//! - The day and hour pillars are cast on true solar time at the birthplace (the default)
7//!   or on civil time. The Zi hour (23:00-01:00) belongs to the next day by default; with
8//!   `zi_hour = "split"` the day changes at midnight and the late Zi hour keeps its day,
9//!   its stem still taken from the next day's.
10//! - The luck pillars (大運) run forward from the month pillar for a yang year and a man
11//!   or a yin year and a woman, backward otherwise. They start after the days from the
12//!   birth to the next (forward) or previous (backward) jie term, three days to a year.
13
14use serde::Serialize;
15
16use super::calendar::{day_number, ChineseCalendar, SolarTerm, LICHUN};
17use super::{
18    branch_element, cycle_index, polarity, stem_element, year_cycle_index, ANIMALS, BRANCHES,
19    ELEMENTS, STEMS,
20};
21use crate::error::EngineError;
22use crate::instant::UtcInstant;
23
24const TROPICAL_YEAR: f64 = 365.242_19;
25const MICROS_PER_MINUTE: f64 = 60_000_000.0;
26
27/// The stems hidden in each branch (藏干): main qi first, then middle and residual qi.
28const HIDDEN_STEMS: [&[usize]; 12] = [
29    &[9],       // 子 癸
30    &[5, 9, 7], // 丑 己癸辛
31    &[0, 2, 4], // 寅 甲丙戊
32    &[1],       // 卯 乙
33    &[4, 1, 9], // 辰 戊乙癸
34    &[2, 6, 4], // 巳 丙庚戊
35    &[3, 5],    // 午 丁己
36    &[5, 3, 1], // 未 己丁乙
37    &[6, 8, 4], // 申 庚壬戊
38    &[7],       // 酉 辛
39    &[4, 7, 3], // 戌 戊辛丁
40    &[8, 0],    // 亥 壬甲
41];
42
43/// Share of its branch each hidden stem carries in the element balance, by how many the
44/// branch holds.
45fn hidden_weights(count: usize) -> &'static [f64] {
46    match count {
47        1 => &[1.0],
48        2 => &[0.7, 0.3],
49        _ => &[0.6, 0.3, 0.1],
50    }
51}
52
53/// NaYin (納音) of each pair of the sexagenary cycle, 甲子乙丑 first.
54const NAYIN: [&str; 30] = [
55    "sea_metal",
56    "furnace_fire",
57    "forest_wood",
58    "roadside_earth",
59    "sword_metal",
60    "mountain_fire",
61    "stream_water",
62    "rampart_earth",
63    "wax_metal",
64    "willow_wood",
65    "spring_water",
66    "roof_earth",
67    "thunder_fire",
68    "pine_wood",
69    "river_water",
70    "sand_metal",
71    "foothill_fire",
72    "plain_wood",
73    "wall_earth",
74    "gold_leaf_metal",
75    "lamp_fire",
76    "heavenly_river_water",
77    "highway_earth",
78    "hairpin_metal",
79    "mulberry_wood",
80    "creek_water",
81    "sand_earth",
82    "sky_fire",
83    "pomegranate_wood",
84    "ocean_water",
85];
86
87/// The twelve stages of life (十二長生), from Birth.
88const LIFE_STAGES: [&str; 12] = [
89    "birth",
90    "bath",
91    "cap_and_belt",
92    "coming_of_age",
93    "prosperity",
94    "decline",
95    "sickness",
96    "death",
97    "tomb",
98    "extinction",
99    "conception",
100    "nurture",
101];
102
103/// The branch where each stem is born (長生); yang stems go forward through the
104/// branches, yin stems backward.
105const BIRTH_BRANCH: [usize; 10] = [11, 6, 2, 9, 2, 9, 5, 0, 8, 3];
106
107/// The Ten Gods (十神) by the element relation to the Day Master (same, produced by it,
108/// controlled by it, controlling it, producing it) and same or opposite polarity.
109const TEN_GODS: [[&str; 2]; 5] = [
110    ["friend", "rob_wealth"],
111    ["eating_god", "hurting_officer"],
112    ["indirect_wealth", "direct_wealth"],
113    ["seven_killings", "direct_officer"],
114    ["indirect_resource", "direct_resource"],
115];
116
117/// When the day changes around the Zi hour.
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum ZiHour {
120    /// 23:00: the whole Zi hour belongs to the next day.
121    NextDay,
122    /// Midnight: the late Zi hour (夜子時) keeps its day.
123    Split,
124}
125
126/// How to cast the pillars.
127#[derive(Debug, Clone)]
128pub struct BaziOptions<'a> {
129    /// Cast the day and hour on true solar time at the birthplace (`true`, the default)
130    /// or on civil time.
131    pub solar_time: bool,
132    /// "next_day" (default): the day changes at 23:00; "split": at midnight.
133    pub zi_hour: &'a str,
134    /// "male" or "female": sets the direction of the luck pillars, which are left out
135    /// without it.
136    pub sex: Option<&'a str>,
137    /// How many ten-year luck pillars to list (default 10).
138    pub luck_pillars: u8,
139}
140
141impl Default for BaziOptions<'_> {
142    fn default() -> Self {
143        BaziOptions {
144            solar_time: true,
145            zi_hour: "next_day",
146            sex: None,
147            luck_pillars: 10,
148        }
149    }
150}
151
152/// A stem hidden in a branch.
153#[derive(Debug, Clone, PartialEq, Serialize)]
154pub struct HiddenStem {
155    /// Stem code, e.g. "gui".
156    pub stem: &'static str,
157    /// Its element.
158    pub element: &'static str,
159    /// Its relation to the Day Master.
160    pub ten_god: &'static str,
161    /// Its share of the branch in the element balance.
162    pub weight: f64,
163}
164
165/// A stem and a branch: one of the four pillars, or a luck pillar.
166#[derive(Debug, Clone, PartialEq, Serialize)]
167pub struct Pillar {
168    /// Heavenly Stem code, e.g. "jia".
169    pub stem: &'static str,
170    /// Earthly Branch code, e.g. "zi".
171    pub branch: &'static str,
172    /// Position in the sexagenary cycle, 0 (甲子) to 59 (癸亥).
173    pub cycle: u8,
174    /// Element of the stem.
175    pub element: &'static str,
176    /// "yang" or "yin", of the stem and the branch alike.
177    pub polarity: &'static str,
178    /// Element of the branch.
179    pub branch_element: &'static str,
180    /// Animal of the branch.
181    pub animal: &'static str,
182    /// The stem's relation to the Day Master; `None` for the Day Master itself.
183    pub ten_god: Option<&'static str>,
184    /// The stems hidden in the branch, main qi first.
185    pub hidden_stems: Vec<HiddenStem>,
186    /// NaYin element of the pair, e.g. "sea_metal".
187    pub nayin: &'static str,
188    /// The Day Master's stage of life in this branch.
189    pub life_stage: &'static str,
190}
191
192/// Weight of each element among the eight characters (stems count 1, each branch 1
193/// shared among its hidden stems).
194#[derive(Debug, Clone, PartialEq, Serialize)]
195pub struct ElementBalance {
196    /// 木
197    pub wood: f64,
198    /// 火
199    pub fire: f64,
200    /// 土
201    pub earth: f64,
202    /// 金
203    pub metal: f64,
204    /// 水
205    pub water: f64,
206}
207
208/// A solar term the pillars refer to.
209#[derive(Debug, Clone, PartialEq, Serialize)]
210pub struct TermMoment {
211    /// Pinyin code, e.g. "jingzhe".
212    pub name: String,
213    /// ISO 8601 UTC.
214    pub utc: String,
215}
216
217/// A date of the lunisolar calendar.
218#[derive(Debug, Clone, PartialEq, Serialize)]
219pub struct LunarDate {
220    /// The lunar year: the Gregorian year its New Year falls in.
221    pub year: i32,
222    /// Month number, 1-12.
223    pub month: u8,
224    /// Whether the month is intercalary.
225    pub leap: bool,
226    /// Day of the month, 1-30.
227    pub day: u8,
228    /// Stem of the lunar year.
229    pub year_stem: &'static str,
230    /// Branch of the lunar year.
231    pub year_branch: &'static str,
232    /// Animal of the lunar year: the popular "Chinese zodiac sign", which changes at the
233    /// New Year rather than at 立春.
234    pub animal: &'static str,
235}
236
237/// A ten-year luck pillar.
238#[derive(Debug, Clone, PartialEq, Serialize)]
239pub struct LuckPillar {
240    /// Age at which it starts, years.
241    pub start_age: f64,
242    /// Start, ISO 8601 UTC.
243    pub start: String,
244    /// End (the next one's start), ISO 8601 UTC.
245    pub end: String,
246    /// Its stem and branch.
247    pub pillar: Pillar,
248}
249
250/// The luck pillars (大運).
251#[derive(Debug, Clone, PartialEq, Serialize)]
252pub struct Luck {
253    /// "forward" or "backward" through the sexagenary cycle from the month pillar.
254    pub direction: &'static str,
255    /// Age at which the first one starts, years.
256    pub start_age: f64,
257    /// The pillars in order.
258    pub pillars: Vec<LuckPillar>,
259}
260
261/// The Four Pillars of a birth.
262#[derive(Debug, Clone, PartialEq, Serialize)]
263pub struct Bazi {
264    /// "solar" or "civil": the clock the day and hour pillars were cast on.
265    pub time_basis: &'static str,
266    /// "next_day" or "split".
267    pub zi_hour: &'static str,
268    /// Local civil time of birth, `YYYY-MM-DDTHH:MM:SS`.
269    pub civil_time: String,
270    /// True solar time of birth at the birthplace, `YYYY-MM-DDTHH:MM:SS`.
271    pub solar_time: String,
272    /// Year pillar (changes at 立春).
273    pub year: Pillar,
274    /// Month pillar (changes at each jie term).
275    pub month: Pillar,
276    /// Day pillar; its stem is the Day Master.
277    pub day: Pillar,
278    /// Hour pillar.
279    pub hour: Pillar,
280    /// Stem of the day pillar, the self.
281    pub day_master: &'static str,
282    /// Element of the Day Master.
283    pub day_master_element: &'static str,
284    /// The weight of each element among the eight characters.
285    pub elements: ElementBalance,
286    /// The jie term that opened the birth month.
287    pub month_term: TermMoment,
288    /// The next jie term after the birth.
289    pub next_term: TermMoment,
290    /// The birth date in the lunisolar calendar; `None` when the calendar lacks it.
291    pub lunar_date: Option<LunarDate>,
292    /// The luck pillars; `None` without the native's sex.
293    pub luck: Option<Luck>,
294}
295
296fn invalid(message: &str) -> EngineError {
297    EngineError::InvalidInput(message.to_string())
298}
299
300/// `YYYY-MM-DDTHH:MM:SS` of a wall-clock instant.
301fn wall_clock(instant: UtcInstant) -> String {
302    let (y, m, d, hh, mm, ss, _) = instant.civil();
303    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}")
304}
305
306/// The relation of `stem` to the Day Master `master`.
307fn ten_god(master: usize, stem: usize) -> &'static str {
308    let relation = (stem_element(stem) + 5 - stem_element(master)) % 5;
309    TEN_GODS[relation][usize::from(master % 2 != stem % 2)]
310}
311
312/// The stage of life of `stem` in `branch`.
313fn life_stage(stem: usize, branch: usize) -> &'static str {
314    let birth = BIRTH_BRANCH[stem] as i64;
315    let steps = if stem % 2 == 0 {
316        branch as i64 - birth
317    } else {
318        birth - branch as i64
319    };
320    LIFE_STAGES[steps.rem_euclid(12) as usize]
321}
322
323/// The pillar at `cycle` (0-59), seen from the Day Master `master`.
324fn pillar(cycle: usize, master: usize, is_master: bool) -> Pillar {
325    let (stem, branch) = (cycle % 10, cycle % 12);
326    let hidden = HIDDEN_STEMS[branch];
327    Pillar {
328        stem: STEMS[stem],
329        branch: BRANCHES[branch],
330        cycle: cycle as u8,
331        element: ELEMENTS[stem_element(stem)],
332        polarity: polarity(stem),
333        branch_element: ELEMENTS[branch_element(branch)],
334        animal: ANIMALS[branch],
335        ten_god: (!is_master).then(|| ten_god(master, stem)),
336        hidden_stems: hidden
337            .iter()
338            .zip(hidden_weights(hidden.len()))
339            .map(|(&h, &weight)| HiddenStem {
340                stem: STEMS[h],
341                element: ELEMENTS[stem_element(h)],
342                ten_god: ten_god(master, h),
343                weight,
344            })
345            .collect(),
346        nayin: NAYIN[cycle / 2],
347        life_stage: life_stage(master, branch),
348    }
349}
350
351fn balance(cycles: [usize; 4]) -> ElementBalance {
352    let mut weights = [0.0f64; 5];
353    for cycle in cycles {
354        let (stem, branch) = (cycle % 10, cycle % 12);
355        weights[stem_element(stem)] += 1.0;
356        let hidden = HIDDEN_STEMS[branch];
357        for (&h, &w) in hidden.iter().zip(hidden_weights(hidden.len())) {
358            weights[stem_element(h)] += w;
359        }
360    }
361    let round = |x: f64| (x * 100.0).round() / 100.0;
362    ElementBalance {
363        wood: round(weights[0]),
364        fire: round(weights[1]),
365        earth: round(weights[2]),
366        metal: round(weights[3]),
367        water: round(weights[4]),
368    }
369}
370
371/// A solar term with its parsed moment.
372type Dated<'a> = (UtcInstant, &'a SolarTerm);
373
374/// The last term at or before `birth` matching `pick`, and the first after it.
375fn around<'a>(
376    terms: &'a [Dated<'a>],
377    birth: UtcInstant,
378    pick: impl Fn(&SolarTerm) -> bool,
379) -> (Option<&'a Dated<'a>>, Option<&'a Dated<'a>>) {
380    let before = terms.iter().rev().find(|(t, s)| *t <= birth && pick(s));
381    let after = terms.iter().find(|(t, s)| *t > birth && pick(s));
382    (before, after)
383}
384
385fn term_moment((instant, term): &Dated) -> TermMoment {
386    TermMoment {
387        name: term.name.clone(),
388        utc: instant.isoformat(),
389    }
390}
391
392fn lunar_date(calendar: &ChineseCalendar, day: i64) -> Result<Option<LunarDate>, EngineError> {
393    for month in &calendar.lunar_months {
394        let start = month.start_day()?;
395        if start <= day && day < start + i64::from(month.days) {
396            let cycle = year_cycle_index(month.year);
397            return Ok(Some(LunarDate {
398                year: month.year,
399                month: month.month,
400                leap: month.leap,
401                day: (day - start + 1) as u8,
402                year_stem: STEMS[cycle % 10],
403                year_branch: BRANCHES[cycle % 12],
404                animal: ANIMALS[cycle % 12],
405            }));
406        }
407    }
408    Ok(None)
409}
410
411/// Cast the Four Pillars of a birth at `birth` (UTC), at `longitude` (degrees east) where
412/// civil time was `utc_offset_minutes` ahead of UTC, from its `calendar`
413/// ([`chinese_calendar`](super::calendar::chinese_calendar) of the same moment).
414pub fn bazi(
415    calendar: &ChineseCalendar,
416    birth: UtcInstant,
417    longitude: f64,
418    utc_offset_minutes: f64,
419    options: &BaziOptions,
420) -> Result<Bazi, EngineError> {
421    let zi_hour = match options.zi_hour {
422        "" | "next_day" => ZiHour::NextDay,
423        "split" => ZiHour::Split,
424        _ => return Err(invalid("zi_hour must be \"next_day\" or \"split\"")),
425    };
426    let male = match options.sex {
427        None | Some("") => None,
428        Some("male") => Some(true),
429        Some("female") => Some(false),
430        Some(_) => return Err(invalid("sex must be \"male\" or \"female\"")),
431    };
432
433    let terms = calendar
434        .solar_terms
435        .iter()
436        .map(|t| Ok((t.instant()?, t)))
437        .collect::<Result<Vec<_>, EngineError>>()?;
438    let (lichun, _) = around(&terms, birth, |t| t.longitude == LICHUN);
439    let (month_term, next_term) = around(&terms, birth, |t| t.jie);
440    let (Some(lichun), Some(month_term), Some(next_term)) = (lichun, month_term, next_term) else {
441        return Err(invalid("the calendar does not cover the birth"));
442    };
443
444    // Year and month: by the solar terms.
445    let year_cycle = year_cycle_index(lichun.0.civil().0);
446    let month_offset = usize::from((month_term.1.longitude + 360 - LICHUN) % 360 / 30);
447    let month_stem = ((year_cycle % 10) % 5 * 2 + 2 + month_offset) % 10;
448    let month_cycle = cycle_index(month_stem, (2 + month_offset) % 12);
449
450    // Day and hour: by the local clock.
451    let to_micros = |minutes: f64| (minutes * MICROS_PER_MINUTE).round() as i64;
452    let civil = birth.add_micros(to_micros(utc_offset_minutes));
453    let solar = birth.add_micros(to_micros(longitude * 4.0 + calendar.equation_of_time));
454    let local = if options.solar_time { solar } else { civil };
455    let hour = local.civil().3;
456    let date = day_number(local);
457    let late_zi = hour >= 23;
458    let day = if late_zi && zi_hour == ZiHour::NextDay {
459        date + 1
460    } else {
461        date
462    };
463    let day_cycle_of = |day: i64| (day - 11).rem_euclid(60) as usize;
464    let day_cycle = day_cycle_of(day);
465    let master = day_cycle % 10;
466    // 子 is 23:00-01:00, 丑 01:00-03:00, …
467    let hour_branch = (hour as usize).div_ceil(2) % 12;
468    let hour_day_stem = day_cycle_of(if late_zi { date + 1 } else { date }) % 10;
469    let hour_cycle = cycle_index((hour_day_stem % 5 * 2 + hour_branch) % 10, hour_branch);
470
471    let luck = male.map(|male| {
472        let forward = male == (year_cycle % 2 == 0);
473        let days = if forward {
474            next_term.0.seconds_since(&birth)
475        } else {
476            birth.seconds_since(&month_term.0)
477        } / 86_400.0;
478        let start_age = days / 3.0;
479        let at_age = |age: f64| birth.plus_days(age * TROPICAL_YEAR).isoformat();
480        let pillars = (1..=i64::from(options.luck_pillars))
481            .map(|k| {
482                let cycle = (month_cycle as i64 + if forward { k } else { -k }).rem_euclid(60);
483                let age = start_age + 10.0 * (k - 1) as f64;
484                LuckPillar {
485                    start_age: age,
486                    start: at_age(age),
487                    end: at_age(age + 10.0),
488                    pillar: pillar(cycle as usize, master, false),
489                }
490            })
491            .collect();
492        Luck {
493            direction: if forward { "forward" } else { "backward" },
494            start_age,
495            pillars,
496        }
497    });
498
499    Ok(Bazi {
500        time_basis: if options.solar_time { "solar" } else { "civil" },
501        zi_hour: match zi_hour {
502            ZiHour::NextDay => "next_day",
503            ZiHour::Split => "split",
504        },
505        civil_time: wall_clock(civil),
506        solar_time: wall_clock(solar),
507        year: pillar(year_cycle, master, false),
508        month: pillar(month_cycle, master, false),
509        day: pillar(day_cycle, master, true),
510        hour: pillar(hour_cycle, master, false),
511        day_master: STEMS[master],
512        day_master_element: ELEMENTS[stem_element(master)],
513        elements: balance([year_cycle, month_cycle, day_cycle, hour_cycle]),
514        month_term: term_moment(month_term),
515        next_term: term_moment(next_term),
516        lunar_date: lunar_date(calendar, day)?,
517        luck,
518    })
519}