iztro 0.9.0

Strongly typed Zi Wei Dou Shu chart generation aligned with iztro.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Renderer-neutral read models for stacked natal and horoscope chart facts.
//!
//! A [`ChartStackSnapshot`] is an owned, serializable view of existing chart
//! facts arranged into the fixed visual twelve-palace grid. It does not derive
//! temporal facts, mutate natal data, or prescribe a renderer.

use crate::core::model::ganzhi::{EarthlyBranch, FourPillars, HeavenlyStem, StemBranch};
use crate::core::model::{
    bureau::FiveElementBureau,
    calendar::BirthContext,
    chart::{
        Chart, DecorativeStarPlacement, HoroscopeChart, MutagenActivation, PalaceName,
        ScopedStarPlacement, StarPlacement, TemporalContext, TemporalLayer,
    },
    profile::MethodProfile,
    star::{
        Brightness, StarCategory, StarKind, StarName,
        mutagen::{Mutagen, Scope},
    },
};
use serde::{Deserialize, Serialize};

/// Branch order for the renderer-ready 4x4 visual palace grid.
///
/// The center four grid cells are intentionally absent because Zi Wei Dou Shu
/// charts place twelve palaces around the perimeter.
pub const VISUAL_BRANCH_ORDER: [EarthlyBranch; 12] = [
    EarthlyBranch::Si,
    EarthlyBranch::Wu,
    EarthlyBranch::Wei,
    EarthlyBranch::Shen,
    EarthlyBranch::Chen,
    EarthlyBranch::You,
    EarthlyBranch::Mao,
    EarthlyBranch::Xu,
    EarthlyBranch::Yin,
    EarthlyBranch::Chou,
    EarthlyBranch::Zi,
    EarthlyBranch::Hai,
];

/// Returns the fixed 4x4 perimeter-grid position for an Earthly Branch.
pub const fn palace_grid_position(branch: EarthlyBranch) -> PalaceGridPosition {
    match branch {
        EarthlyBranch::Si => PalaceGridPosition::new(0, 0),
        EarthlyBranch::Wu => PalaceGridPosition::new(0, 1),
        EarthlyBranch::Wei => PalaceGridPosition::new(0, 2),
        EarthlyBranch::Shen => PalaceGridPosition::new(0, 3),
        EarthlyBranch::Chen => PalaceGridPosition::new(1, 0),
        EarthlyBranch::You => PalaceGridPosition::new(1, 3),
        EarthlyBranch::Mao => PalaceGridPosition::new(2, 0),
        EarthlyBranch::Xu => PalaceGridPosition::new(2, 3),
        EarthlyBranch::Yin => PalaceGridPosition::new(3, 0),
        EarthlyBranch::Chou => PalaceGridPosition::new(3, 1),
        EarthlyBranch::Zi => PalaceGridPosition::new(3, 2),
        EarthlyBranch::Hai => PalaceGridPosition::new(3, 3),
    }
}

/// Owned, renderer-neutral snapshot of natal facts and temporal overlays.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ChartStackSnapshot {
    birth_context: BirthContext,
    birth_year: StemBranch,
    #[serde(default)]
    four_pillars: Option<FourPillars>,
    method_profile: MethodProfile,
    life_palace_branch: Option<EarthlyBranch>,
    body_palace_branch: Option<EarthlyBranch>,
    five_element_bureau: Option<FiveElementBureau>,
    layers: Vec<ChartLayerSnapshot>,
}

impl ChartStackSnapshot {
    /// Creates a one-layer stack snapshot from a natal chart.
    pub fn from_natal_chart(chart: &Chart) -> Self {
        Self {
            birth_context: chart.birth_context().clone(),
            birth_year: chart.birth_year(),
            four_pillars: chart.four_pillars().copied(),
            method_profile: chart.method_profile().clone(),
            life_palace_branch: chart.life_palace().map(|palace| palace.branch()),
            body_palace_branch: chart.body_palace_branch(),
            five_element_bureau: chart.five_element_bureau(),
            layers: vec![ChartLayerSnapshot::from_natal_chart(chart)],
        }
    }

    /// Creates a stack snapshot from a horoscope chart and its temporal layers.
    pub fn from_horoscope_chart(chart: &HoroscopeChart) -> Self {
        let natal = chart.natal();
        let mut layers = Vec::with_capacity(chart.layers().len() + 1);
        layers.push(ChartLayerSnapshot::from_natal_chart(natal));
        layers.extend(chart.layers().iter().enumerate().map(|(index, layer)| {
            ChartLayerSnapshot::from_temporal_layer(natal, layer, index + 1)
        }));

        Self {
            birth_context: natal.birth_context().clone(),
            birth_year: natal.birth_year(),
            four_pillars: natal.four_pillars().copied(),
            method_profile: natal.method_profile().clone(),
            life_palace_branch: natal.life_palace().map(|palace| palace.branch()),
            body_palace_branch: natal.body_palace_branch(),
            five_element_bureau: natal.five_element_bureau(),
            layers,
        }
    }

    /// Returns the birth context copied from the natal chart.
    pub const fn birth_context(&self) -> &BirthContext {
        &self.birth_context
    }

    /// Returns the birth-year stem-branch copied from the natal chart.
    pub const fn birth_year(&self) -> StemBranch {
        self.birth_year
    }

    /// Returns the natal four pillars copied from the natal chart, if present.
    pub const fn four_pillars(&self) -> Option<&FourPillars> {
        self.four_pillars.as_ref()
    }

    /// Returns the method profile copied from the natal chart.
    pub const fn method_profile(&self) -> &MethodProfile {
        &self.method_profile
    }

    /// Returns the Life Palace branch copied from the natal chart, if present.
    pub const fn life_palace_branch(&self) -> Option<EarthlyBranch> {
        self.life_palace_branch
    }

    /// Returns the Body Palace branch copied from the natal chart, if present.
    pub const fn body_palace_branch(&self) -> Option<EarthlyBranch> {
        self.body_palace_branch
    }

    /// Returns the five-element bureau copied from the natal chart, if present.
    pub const fn five_element_bureau(&self) -> Option<FiveElementBureau> {
        self.five_element_bureau
    }

    /// Returns the ordered stack layers.
    pub fn layers(&self) -> &[ChartLayerSnapshot] {
        &self.layers
    }

    /// Returns the first layer with the requested kind.
    pub fn layer(&self, kind: ChartLayerKind) -> Option<&ChartLayerSnapshot> {
        self.layers.iter().find(|layer| layer.kind == kind)
    }
}

/// One snapshot layer in a chart stack.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ChartLayerSnapshot {
    kind: ChartLayerKind,
    z_index: usize,
    context: Option<TemporalContext>,
    cells: Vec<PalaceLayerCellSnapshot>,
}

impl ChartLayerSnapshot {
    fn from_natal_chart(chart: &Chart) -> Self {
        let cells = VISUAL_BRANCH_ORDER
            .into_iter()
            .map(|branch| PalaceLayerCellSnapshot::from_natal_chart(chart, branch))
            .collect();

        Self {
            kind: ChartLayerKind::Natal,
            z_index: 0,
            context: None,
            cells,
        }
    }

    fn from_temporal_layer(chart: &Chart, layer: &TemporalLayer, z_index: usize) -> Self {
        let cells = VISUAL_BRANCH_ORDER
            .into_iter()
            .map(|branch| PalaceLayerCellSnapshot::from_temporal_layer(chart, layer, branch))
            .collect();

        Self {
            kind: ChartLayerKind::from_scope(layer.scope()),
            z_index,
            context: Some(*layer.context()),
            cells,
        }
    }

    /// Returns this layer's stack kind.
    pub const fn kind(&self) -> ChartLayerKind {
        self.kind
    }

    /// Returns this layer's z-index in the stack.
    pub const fn z_index(&self) -> usize {
        self.z_index
    }

    /// Returns this layer's temporal context, if it is non-natal.
    pub const fn context(&self) -> Option<&TemporalContext> {
        self.context.as_ref()
    }

    /// Returns cells ordered by [`VISUAL_BRANCH_ORDER`].
    pub fn cells(&self) -> &[PalaceLayerCellSnapshot] {
        &self.cells
    }
}

/// Layer kind used by renderer-neutral stack snapshots.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChartLayerKind {
    /// Natal chart layer.
    Natal,
    /// Nominal-age temporal overlay.
    Age,
    /// Decadal temporal overlay.
    Decadal,
    /// Yearly temporal overlay.
    Yearly,
    /// Monthly temporal overlay.
    Monthly,
    /// Daily temporal overlay.
    Daily,
    /// Hourly temporal overlay.
    Hourly,
}

impl ChartLayerKind {
    /// Maps a fact scope to the corresponding snapshot layer kind.
    pub const fn from_scope(scope: Scope) -> Self {
        match scope {
            Scope::Natal => Self::Natal,
            Scope::Age => Self::Age,
            Scope::Decadal => Self::Decadal,
            Scope::Yearly => Self::Yearly,
            Scope::Monthly => Self::Monthly,
            Scope::Daily => Self::Daily,
            Scope::Hourly => Self::Hourly,
        }
    }
}

/// Position of a palace cell in the fixed 4x4 perimeter grid.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct PalaceGridPosition {
    row: u8,
    column: u8,
}

impl PalaceGridPosition {
    /// Creates a grid position.
    pub const fn new(row: u8, column: u8) -> Self {
        Self { row, column }
    }

    /// Returns the zero-based row.
    pub const fn row(&self) -> u8 {
        self.row
    }

    /// Returns the zero-based column.
    pub const fn column(&self) -> u8 {
        self.column
    }
}

/// Renderer-neutral facts for one branch cell in one stack layer.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PalaceLayerCellSnapshot {
    branch: EarthlyBranch,
    grid_position: PalaceGridPosition,
    natal_palace_name: Option<PalaceName>,
    natal_palace_stem: Option<HeavenlyStem>,
    temporal_palace_name: Option<PalaceName>,
    roles: Vec<PalaceRoleSnapshot>,
    typed_stars: Vec<TypedStarSnapshot>,
    decorative_stars: Vec<DecorativeStarSnapshot>,
    scoped_stars: Vec<ScopedStarSnapshot>,
    temporal_decorative_stars: Vec<DecorativeStarSnapshot>,
    mutagen_activations: Vec<MutagenActivationSnapshot>,
}

impl PalaceLayerCellSnapshot {
    fn from_natal_chart(chart: &Chart, branch: EarthlyBranch) -> Self {
        let palace = chart
            .palaces()
            .iter()
            .find(|palace| palace.branch() == branch);
        let mut roles = Vec::new();
        if let Some(palace) = palace {
            roles.push(PalaceRoleSnapshot::new(PalaceRoleKind::NatalPalace(
                palace.name(),
            )));
        }
        if chart.is_body_palace_branch(branch) {
            roles.push(PalaceRoleSnapshot::new(PalaceRoleKind::NatalBodyPalace));
        }

        Self {
            branch,
            grid_position: palace_grid_position(branch),
            natal_palace_name: palace.map(|palace| palace.name()),
            natal_palace_stem: palace.map(|palace| palace.stem()),
            temporal_palace_name: None,
            roles,
            typed_stars: palace
                .map(|palace| {
                    palace
                        .stars()
                        .iter()
                        .map(TypedStarSnapshot::from_star_placement)
                        .collect()
                })
                .unwrap_or_default(),
            decorative_stars: palace
                .map(|palace| {
                    palace
                        .decorative_stars()
                        .iter()
                        .map(DecorativeStarSnapshot::from_decorative_star_placement)
                        .collect()
                })
                .unwrap_or_default(),
            scoped_stars: Vec::new(),
            temporal_decorative_stars: Vec::new(),
            mutagen_activations: Vec::new(),
        }
    }

    fn from_temporal_layer(chart: &Chart, layer: &TemporalLayer, branch: EarthlyBranch) -> Self {
        let palace = chart
            .palaces()
            .iter()
            .find(|palace| palace.branch() == branch);

        Self {
            branch,
            grid_position: palace_grid_position(branch),
            natal_palace_name: palace.map(|palace| palace.name()),
            natal_palace_stem: palace.map(|palace| palace.stem()),
            temporal_palace_name: layer
                .palace_layout()
                .and_then(|layout| layout.name_for_branch(branch)),
            roles: Vec::new(),
            typed_stars: Vec::new(),
            decorative_stars: Vec::new(),
            scoped_stars: layer
                .placements()
                .iter()
                .filter(|placement| placement.branch() == branch)
                .map(ScopedStarSnapshot::from_scoped_star_placement)
                .collect(),
            temporal_decorative_stars: layer
                .temporal_decorative_stars()
                .iter()
                .filter(|placement| placement.branch() == branch)
                .map(|placement| {
                    DecorativeStarSnapshot::from_decorative_star_placement(placement.placement())
                })
                .collect(),
            mutagen_activations: layer
                .activations()
                .iter()
                .filter(|activation| activation.target_branch() == branch)
                .map(MutagenActivationSnapshot::from_mutagen_activation)
                .collect(),
        }
    }

    /// Returns the branch represented by this cell.
    pub const fn branch(&self) -> EarthlyBranch {
        self.branch
    }

    /// Returns this cell's fixed visual grid position.
    pub const fn grid_position(&self) -> PalaceGridPosition {
        self.grid_position
    }

    /// Returns the natal palace name joined by branch, if present.
    pub const fn natal_palace_name(&self) -> Option<PalaceName> {
        self.natal_palace_name
    }

    /// Returns the natal palace stem joined by branch, if present.
    pub const fn natal_palace_stem(&self) -> Option<HeavenlyStem> {
        self.natal_palace_stem
    }

    /// Returns the temporal palace name this layer assigns to the branch, if any.
    ///
    /// This is an additive overlay fact, kept separate from
    /// [`natal_palace_name`](Self::natal_palace_name): it is `None` on the natal
    /// layer and on temporal layers that carry no palace-name layout.
    pub const fn temporal_palace_name(&self) -> Option<PalaceName> {
        self.temporal_palace_name
    }

    /// Returns role markers for this cell.
    pub fn roles(&self) -> &[PalaceRoleSnapshot] {
        &self.roles
    }

    /// Returns natal typed stars in this cell.
    pub fn typed_stars(&self) -> &[TypedStarSnapshot] {
        &self.typed_stars
    }

    /// Returns natal decorative stars in this cell.
    ///
    /// Natal-only: temporal decorative facts (e.g. yearly `yearlyDecStar`) are
    /// kept separate under [`temporal_decorative_stars`](Self::temporal_decorative_stars).
    pub fn decorative_stars(&self) -> &[DecorativeStarSnapshot] {
        &self.decorative_stars
    }

    /// Returns temporal decorative stars grouped into this cell.
    ///
    /// These are a temporal layer's untyped decorative facts (e.g. yearly
    /// `yearlyDecStar`), kept distinct from the natal
    /// [`decorative_stars`](Self::decorative_stars): empty on the natal layer and
    /// on temporal layers that add no decorative facts.
    pub fn temporal_decorative_stars(&self) -> &[DecorativeStarSnapshot] {
        &self.temporal_decorative_stars
    }

    /// Returns temporal scoped stars grouped into this cell.
    pub fn scoped_stars(&self) -> &[ScopedStarSnapshot] {
        &self.scoped_stars
    }

    /// Returns temporal mutagen activations grouped into this cell.
    pub fn mutagen_activations(&self) -> &[MutagenActivationSnapshot] {
        &self.mutagen_activations
    }
}

/// Role marker attached to a palace-layer cell.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PalaceRoleSnapshot {
    kind: PalaceRoleKind,
}

impl PalaceRoleSnapshot {
    /// Creates a role marker.
    pub const fn new(kind: PalaceRoleKind) -> Self {
        Self { kind }
    }

    /// Returns the role kind.
    pub const fn kind(&self) -> PalaceRoleKind {
        self.kind
    }
}

/// Role kinds attached to snapshot cells.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PalaceRoleKind {
    /// The cell contains the given natal palace.
    NatalPalace(PalaceName),
    /// The cell is the natal Body Palace branch.
    NatalBodyPalace,
}

/// Snapshot of a typed natal star placement.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct TypedStarSnapshot {
    name: StarName,
    kind: StarKind,
    category: StarCategory,
    brightness: Brightness,
    mutagen: Option<Mutagen>,
    scope: Scope,
}

impl TypedStarSnapshot {
    fn from_star_placement(placement: &StarPlacement) -> Self {
        Self {
            name: placement.name(),
            kind: placement.kind(),
            category: placement.category(),
            brightness: placement.brightness(),
            mutagen: placement.mutagen(),
            scope: placement.scope(),
        }
    }

    /// Returns the star name.
    pub const fn name(&self) -> StarName {
        self.name
    }

    /// Returns the fine star kind.
    pub const fn kind(&self) -> StarKind {
        self.kind
    }

    /// Returns the coarse star category.
    pub const fn category(&self) -> StarCategory {
        self.category
    }

    /// Returns the brightness state.
    pub const fn brightness(&self) -> Brightness {
        self.brightness
    }

    /// Returns the natal mutagen attached to the placement, if present.
    pub const fn mutagen(&self) -> Option<Mutagen> {
        self.mutagen
    }

    /// Returns the placement scope.
    pub const fn scope(&self) -> Scope {
        self.scope
    }
}

/// Snapshot of an untyped decorative star placement.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct DecorativeStarSnapshot {
    name: StarName,
    family: crate::core::model::chart::DecorativeStarFamily,
    scope: Scope,
}

impl DecorativeStarSnapshot {
    fn from_decorative_star_placement(placement: &DecorativeStarPlacement) -> Self {
        Self {
            name: placement.name(),
            family: placement.family(),
            scope: placement.scope(),
        }
    }

    /// Returns the decorative star name.
    pub const fn name(&self) -> StarName {
        self.name
    }

    /// Returns the decorative star family.
    pub const fn family(&self) -> crate::core::model::chart::DecorativeStarFamily {
        self.family
    }

    /// Returns the placement scope.
    pub const fn scope(&self) -> Scope {
        self.scope
    }
}

/// Snapshot of a branch-scoped temporal star placement.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ScopedStarSnapshot {
    name: StarName,
    kind: StarKind,
    category: StarCategory,
    brightness: Brightness,
    mutagen: Option<Mutagen>,
    scope: Scope,
}

impl ScopedStarSnapshot {
    fn from_scoped_star_placement(placement: &ScopedStarPlacement) -> Self {
        Self {
            name: placement.placement().name(),
            kind: placement.placement().kind(),
            category: placement.placement().category(),
            brightness: placement.placement().brightness(),
            mutagen: placement.placement().mutagen(),
            scope: placement.scope(),
        }
    }

    /// Returns the star name.
    pub const fn name(&self) -> StarName {
        self.name
    }

    /// Returns the fine star kind.
    pub const fn kind(&self) -> StarKind {
        self.kind
    }

    /// Returns the coarse star category.
    pub const fn category(&self) -> StarCategory {
        self.category
    }

    /// Returns the brightness state.
    pub const fn brightness(&self) -> Brightness {
        self.brightness
    }

    /// Returns the mutagen attached to the scoped placement, if present.
    pub const fn mutagen(&self) -> Option<Mutagen> {
        self.mutagen
    }

    /// Returns the placement scope.
    pub const fn scope(&self) -> Scope {
        self.scope
    }
}

/// Snapshot of a temporal mutagen activation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct MutagenActivationSnapshot {
    source_scope: Scope,
    target_star: StarName,
    target_branch: EarthlyBranch,
    mutagen: Mutagen,
}

impl MutagenActivationSnapshot {
    fn from_mutagen_activation(activation: &MutagenActivation) -> Self {
        Self {
            source_scope: activation.source_scope(),
            target_star: activation.target_star(),
            target_branch: activation.target_branch(),
            mutagen: activation.mutagen(),
        }
    }

    /// Returns the temporal scope that produced this activation.
    pub const fn source_scope(&self) -> Scope {
        self.source_scope
    }

    /// Returns the star targeted by the activation.
    pub const fn target_star(&self) -> StarName {
        self.target_star
    }

    /// Returns the target branch.
    pub const fn target_branch(&self) -> EarthlyBranch {
        self.target_branch
    }

    /// Returns the mutagen applied to the target star.
    pub const fn mutagen(&self) -> Mutagen {
        self.mutagen
    }
}