1use 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
27const HIDDEN_STEMS: [&[usize]; 12] = [
29 &[9], &[5, 9, 7], &[0, 2, 4], &[1], &[4, 1, 9], &[2, 6, 4], &[3, 5], &[5, 3, 1], &[6, 8, 4], &[7], &[4, 7, 3], &[8, 0], ];
42
43fn 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
53const 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
87const 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
103const BIRTH_BRANCH: [usize; 10] = [11, 6, 2, 9, 2, 9, 5, 0, 8, 3];
106
107const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119enum ZiHour {
120 NextDay,
122 Split,
124}
125
126#[derive(Debug, Clone)]
128pub struct BaziOptions<'a> {
129 pub solar_time: bool,
132 pub zi_hour: &'a str,
134 pub sex: Option<&'a str>,
137 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#[derive(Debug, Clone, PartialEq, Serialize)]
154pub struct HiddenStem {
155 pub stem: &'static str,
157 pub element: &'static str,
159 pub ten_god: &'static str,
161 pub weight: f64,
163}
164
165#[derive(Debug, Clone, PartialEq, Serialize)]
167pub struct Pillar {
168 pub stem: &'static str,
170 pub branch: &'static str,
172 pub cycle: u8,
174 pub element: &'static str,
176 pub polarity: &'static str,
178 pub branch_element: &'static str,
180 pub animal: &'static str,
182 pub ten_god: Option<&'static str>,
184 pub hidden_stems: Vec<HiddenStem>,
186 pub nayin: &'static str,
188 pub life_stage: &'static str,
190}
191
192#[derive(Debug, Clone, PartialEq, Serialize)]
195pub struct ElementBalance {
196 pub wood: f64,
198 pub fire: f64,
200 pub earth: f64,
202 pub metal: f64,
204 pub water: f64,
206}
207
208#[derive(Debug, Clone, PartialEq, Serialize)]
210pub struct TermMoment {
211 pub name: String,
213 pub utc: String,
215}
216
217#[derive(Debug, Clone, PartialEq, Serialize)]
219pub struct LunarDate {
220 pub year: i32,
222 pub month: u8,
224 pub leap: bool,
226 pub day: u8,
228 pub year_stem: &'static str,
230 pub year_branch: &'static str,
232 pub animal: &'static str,
235}
236
237#[derive(Debug, Clone, PartialEq, Serialize)]
239pub struct LuckPillar {
240 pub start_age: f64,
242 pub start: String,
244 pub end: String,
246 pub pillar: Pillar,
248}
249
250#[derive(Debug, Clone, PartialEq, Serialize)]
252pub struct Luck {
253 pub direction: &'static str,
255 pub start_age: f64,
257 pub pillars: Vec<LuckPillar>,
259}
260
261#[derive(Debug, Clone, PartialEq, Serialize)]
263pub struct Bazi {
264 pub time_basis: &'static str,
266 pub zi_hour: &'static str,
268 pub civil_time: String,
270 pub solar_time: String,
272 pub year: Pillar,
274 pub month: Pillar,
276 pub day: Pillar,
278 pub hour: Pillar,
280 pub day_master: &'static str,
282 pub day_master_element: &'static str,
284 pub elements: ElementBalance,
286 pub month_term: TermMoment,
288 pub next_term: TermMoment,
290 pub lunar_date: Option<LunarDate>,
292 pub luck: Option<Luck>,
294}
295
296fn invalid(message: &str) -> EngineError {
297 EngineError::InvalidInput(message.to_string())
298}
299
300fn 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
306fn 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
312fn 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
323fn 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
371type Dated<'a> = (UtcInstant, &'a SolarTerm);
373
374fn 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
411pub 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 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 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 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}