rscm-core 0.5.0

Core traits and functionalities for the creation of reduced-complexity climate models
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Python bindings for typed state access
//!
//! This module provides Python wrappers for TimeseriesWindow, GridTimeseriesWindow,
//! and typed output slices (FourBoxSlice, HemisphericSlice).

use crate::spatial::{FourBoxRegion, HemisphericRegion};
use crate::state::{FourBoxSlice, HemisphericSlice, StateValue};
use crate::timeseries::FloatValue;
use numpy::{PyArray1, ToPyArray};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::{pymodule, Bound, PyResult};

// =============================================================================
// Python Typed Output Slices
// =============================================================================

/// Python wrapper for FourBoxSlice
///
/// Provides type-safe access to regional values with named keyword arguments.
///
/// Example:
///     slice = FourBoxSlice(
///         northern_ocean=15.0,
///         northern_land=14.0,
///         southern_ocean=10.0,
///         southern_land=9.0
///     )
#[pyclass]
#[pyo3(name = "FourBoxSlice")]
#[derive(Debug, Clone)]
pub struct PyFourBoxSlice(pub FourBoxSlice);

#[pymethods]
impl PyFourBoxSlice {
    #[new]
    #[pyo3(signature = (northern_ocean=f64::NAN, northern_land=f64::NAN, southern_ocean=f64::NAN, southern_land=f64::NAN))]
    fn new(
        northern_ocean: FloatValue,
        northern_land: FloatValue,
        southern_ocean: FloatValue,
        southern_land: FloatValue,
    ) -> Self {
        Self(FourBoxSlice::from_array([
            northern_ocean,
            northern_land,
            southern_ocean,
            southern_land,
        ]))
    }

    /// Create a slice with all regions set to the same value
    #[staticmethod]
    fn uniform(value: FloatValue) -> Self {
        Self(FourBoxSlice::uniform(value))
    }

    /// Create a slice from an array [northern_ocean, northern_land, southern_ocean, southern_land]
    #[staticmethod]
    fn from_array(values: [FloatValue; 4]) -> Self {
        Self(FourBoxSlice::from_array(values))
    }

    /// Get the northern ocean value
    #[getter]
    fn northern_ocean(&self) -> FloatValue {
        self.0.get(FourBoxRegion::NorthernOcean)
    }

    /// Set the northern ocean value
    #[setter]
    fn set_northern_ocean(&mut self, value: FloatValue) {
        self.0.set(FourBoxRegion::NorthernOcean, value);
    }

    /// Get the northern land value
    #[getter]
    fn northern_land(&self) -> FloatValue {
        self.0.get(FourBoxRegion::NorthernLand)
    }

    /// Set the northern land value
    #[setter]
    fn set_northern_land(&mut self, value: FloatValue) {
        self.0.set(FourBoxRegion::NorthernLand, value);
    }

    /// Get the southern ocean value
    #[getter]
    fn southern_ocean(&self) -> FloatValue {
        self.0.get(FourBoxRegion::SouthernOcean)
    }

    /// Set the southern ocean value
    #[setter]
    fn set_southern_ocean(&mut self, value: FloatValue) {
        self.0.set(FourBoxRegion::SouthernOcean, value);
    }

    /// Get the southern land value
    #[getter]
    fn southern_land(&self) -> FloatValue {
        self.0.get(FourBoxRegion::SouthernLand)
    }

    /// Set the southern land value
    #[setter]
    fn set_southern_land(&mut self, value: FloatValue) {
        self.0.set(FourBoxRegion::SouthernLand, value);
    }

    /// Get value by region index
    fn get(&self, region: usize) -> PyResult<FloatValue> {
        match region {
            0 => Ok(self.0.get(FourBoxRegion::NorthernOcean)),
            1 => Ok(self.0.get(FourBoxRegion::NorthernLand)),
            2 => Ok(self.0.get(FourBoxRegion::SouthernOcean)),
            3 => Ok(self.0.get(FourBoxRegion::SouthernLand)),
            _ => Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-3.",
                region
            ))),
        }
    }

    /// Set value by region index
    fn set(&mut self, region: usize, value: FloatValue) -> PyResult<()> {
        match region {
            0 => self.0.set(FourBoxRegion::NorthernOcean, value),
            1 => self.0.set(FourBoxRegion::NorthernLand, value),
            2 => self.0.set(FourBoxRegion::SouthernOcean, value),
            3 => self.0.set(FourBoxRegion::SouthernLand, value),
            _ => {
                return Err(PyValueError::new_err(format!(
                    "Invalid region index: {}. Must be 0-3.",
                    region
                )))
            }
        }
        Ok(())
    }

    /// Convert to numpy array
    fn to_array<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<FloatValue>> {
        self.0.as_array().to_pyarray(py)
    }

    /// Convert to list
    fn to_list(&self) -> Vec<FloatValue> {
        self.0.to_vec()
    }

    /// Convert to dict with region names as keys
    fn to_dict(&self) -> std::collections::HashMap<String, FloatValue> {
        let mut map = std::collections::HashMap::new();
        map.insert(
            "northern_ocean".to_string(),
            self.0.get(FourBoxRegion::NorthernOcean),
        );
        map.insert(
            "northern_land".to_string(),
            self.0.get(FourBoxRegion::NorthernLand),
        );
        map.insert(
            "southern_ocean".to_string(),
            self.0.get(FourBoxRegion::SouthernOcean),
        );
        map.insert(
            "southern_land".to_string(),
            self.0.get(FourBoxRegion::SouthernLand),
        );
        map
    }

    fn __repr__(&self) -> String {
        format!(
            "FourBoxSlice(northern_ocean={}, northern_land={}, southern_ocean={}, southern_land={})",
            self.0.get(FourBoxRegion::NorthernOcean),
            self.0.get(FourBoxRegion::NorthernLand),
            self.0.get(FourBoxRegion::SouthernOcean),
            self.0.get(FourBoxRegion::SouthernLand)
        )
    }

    fn __getitem__(&self, index: usize) -> PyResult<FloatValue> {
        self.get(index)
    }

    fn __setitem__(&mut self, index: usize, value: FloatValue) -> PyResult<()> {
        self.set(index, value)
    }

    fn __len__(&self) -> usize {
        4
    }
}

/// Python wrapper for HemisphericSlice
///
/// Provides type-safe access to hemispheric values with named keyword arguments.
///
/// Example:
///     slice = HemisphericSlice(northern=15.0, southern=10.0)
#[pyclass]
#[pyo3(name = "HemisphericSlice")]
#[derive(Debug, Clone)]
pub struct PyHemisphericSlice(pub HemisphericSlice);

#[pymethods]
impl PyHemisphericSlice {
    #[new]
    #[pyo3(signature = (northern=f64::NAN, southern=f64::NAN))]
    fn new(northern: FloatValue, southern: FloatValue) -> Self {
        Self(HemisphericSlice::from_array([northern, southern]))
    }

    /// Create a slice with both hemispheres set to the same value
    #[staticmethod]
    fn uniform(value: FloatValue) -> Self {
        Self(HemisphericSlice::uniform(value))
    }

    /// Create a slice from an array [northern, southern]
    #[staticmethod]
    fn from_array(values: [FloatValue; 2]) -> Self {
        Self(HemisphericSlice::from_array(values))
    }

    /// Get the northern hemisphere value
    #[getter]
    fn northern(&self) -> FloatValue {
        self.0.get(HemisphericRegion::Northern)
    }

    /// Set the northern hemisphere value
    #[setter]
    fn set_northern(&mut self, value: FloatValue) {
        self.0.set(HemisphericRegion::Northern, value);
    }

    /// Get the southern hemisphere value
    #[getter]
    fn southern(&self) -> FloatValue {
        self.0.get(HemisphericRegion::Southern)
    }

    /// Set the southern hemisphere value
    #[setter]
    fn set_southern(&mut self, value: FloatValue) {
        self.0.set(HemisphericRegion::Southern, value);
    }

    /// Get value by region index
    fn get(&self, region: usize) -> PyResult<FloatValue> {
        match region {
            0 => Ok(self.0.get(HemisphericRegion::Northern)),
            1 => Ok(self.0.get(HemisphericRegion::Southern)),
            _ => Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-1.",
                region
            ))),
        }
    }

    /// Set value by region index
    fn set(&mut self, region: usize, value: FloatValue) -> PyResult<()> {
        match region {
            0 => self.0.set(HemisphericRegion::Northern, value),
            1 => self.0.set(HemisphericRegion::Southern, value),
            _ => {
                return Err(PyValueError::new_err(format!(
                    "Invalid region index: {}. Must be 0-1.",
                    region
                )))
            }
        }
        Ok(())
    }

    /// Convert to numpy array
    fn to_array<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<FloatValue>> {
        self.0.as_array().to_pyarray(py)
    }

    /// Convert to list
    fn to_list(&self) -> Vec<FloatValue> {
        self.0.to_vec()
    }

    /// Convert to dict with region names as keys
    fn to_dict(&self) -> std::collections::HashMap<String, FloatValue> {
        let mut map = std::collections::HashMap::new();
        map.insert(
            "northern".to_string(),
            self.0.get(HemisphericRegion::Northern),
        );
        map.insert(
            "southern".to_string(),
            self.0.get(HemisphericRegion::Southern),
        );
        map
    }

    fn __repr__(&self) -> String {
        format!(
            "HemisphericSlice(northern={}, southern={})",
            self.0.get(HemisphericRegion::Northern),
            self.0.get(HemisphericRegion::Southern)
        )
    }

    fn __getitem__(&self, index: usize) -> PyResult<FloatValue> {
        self.get(index)
    }

    fn __setitem__(&mut self, index: usize, value: FloatValue) -> PyResult<()> {
        self.set(index, value)
    }

    fn __len__(&self) -> usize {
        2
    }
}

// =============================================================================
// Python StateValue
// =============================================================================

/// Python wrapper for StateValue enum
///
/// Represents a value that can be scalar or spatially-resolved (FourBox/Hemispheric).
///
/// Example:
///     scalar = StateValue.scalar(15.0)
///     four_box = StateValue.four_box(FourBoxSlice.uniform(10.0))
///     hemispheric = StateValue.hemispheric(HemisphericSlice(northern=15.0, southern=10.0))
#[pyclass]
#[pyo3(name = "StateValue")]
#[derive(Debug, Clone)]
pub struct PyStateValue(pub StateValue);

#[pymethods]
impl PyStateValue {
    /// Create a scalar StateValue
    #[staticmethod]
    fn scalar(value: FloatValue) -> Self {
        Self(StateValue::Scalar(value))
    }

    /// Create a FourBox StateValue from a FourBoxSlice
    #[staticmethod]
    fn four_box(slice: PyFourBoxSlice) -> Self {
        Self(StateValue::FourBox(slice.0))
    }

    /// Create a Hemispheric StateValue from a HemisphericSlice
    #[staticmethod]
    fn hemispheric(slice: PyHemisphericSlice) -> Self {
        Self(StateValue::Hemispheric(slice.0))
    }

    /// Check if this is a scalar value
    fn is_scalar(&self) -> bool {
        self.0.is_scalar()
    }

    /// Check if this is a FourBox grid value
    fn is_four_box(&self) -> bool {
        self.0.is_four_box()
    }

    /// Check if this is a Hemispheric grid value
    fn is_hemispheric(&self) -> bool {
        self.0.is_hemispheric()
    }

    /// Get the scalar value if this is a Scalar variant, otherwise None
    fn as_scalar(&self) -> Option<FloatValue> {
        self.0.as_scalar()
    }

    /// Get the FourBoxSlice if this is a FourBox variant, otherwise None
    fn as_four_box(&self) -> Option<PyFourBoxSlice> {
        self.0.as_four_box().map(|s| PyFourBoxSlice(*s))
    }

    /// Get the HemisphericSlice if this is a Hemispheric variant, otherwise None
    fn as_hemispheric(&self) -> Option<PyHemisphericSlice> {
        self.0.as_hemispheric().map(|s| PyHemisphericSlice(*s))
    }

    /// Convert to a scalar value, aggregating grid values if necessary
    ///
    /// For Scalar: returns the value directly
    /// For FourBox: returns the arithmetic mean of all 4 regional values
    ///              (sum of all regions divided by 4, giving equal weight to each region)
    /// For Hemispheric: returns the arithmetic mean of both hemispheres
    ///                  (sum of northern and southern divided by 2, giving equal weight to each)
    fn to_scalar(&self) -> FloatValue {
        self.0.to_scalar()
    }

    fn __repr__(&self) -> String {
        match &self.0 {
            StateValue::Scalar(v) => format!("StateValue.scalar({})", v),
            StateValue::FourBox(slice) => {
                format!(
                    "StateValue.four_box(FourBoxSlice(northern_ocean={}, northern_land={}, southern_ocean={}, southern_land={}))",
                    slice.get(FourBoxRegion::NorthernOcean),
                    slice.get(FourBoxRegion::NorthernLand),
                    slice.get(FourBoxRegion::SouthernOcean),
                    slice.get(FourBoxRegion::SouthernLand)
                )
            }
            StateValue::Hemispheric(slice) => {
                format!(
                    "StateValue.hemispheric(HemisphericSlice(northern={}, southern={}))",
                    slice.get(HemisphericRegion::Northern),
                    slice.get(HemisphericRegion::Southern)
                )
            }
        }
    }
}

// =============================================================================
// Python TimeseriesWindow
// =============================================================================

/// Python wrapper for TimeseriesWindow
///
/// Provides zero-cost view-like access to scalar timeseries data.
/// Since Python can't handle Rust lifetimes, this stores a copy of the
/// values and current position.
///
/// Example:
///     window = TimeseriesWindow(values=[1.0, 2.0, 3.0], current_index=2)
///     print(window.current)  # 3.0
///     print(window.previous)  # 2.0
#[pyclass]
#[pyo3(name = "TimeseriesWindow")]
#[derive(Debug, Clone)]
pub struct PyTimeseriesWindow {
    values: Vec<FloatValue>,
    current_index: usize,
}

#[pymethods]
impl PyTimeseriesWindow {
    #[new]
    #[pyo3(signature = (values, current_index))]
    pub fn new(values: Vec<FloatValue>, current_index: usize) -> PyResult<Self> {
        if current_index >= values.len() && !values.is_empty() {
            return Err(PyValueError::new_err(format!(
                "current_index {} out of bounds for values of length {}",
                current_index,
                values.len()
            )));
        }
        Ok(Self {
            values,
            current_index,
        })
    }

    /// Get the value at the start of the timestep (index N).
    ///
    /// Use this for:
    /// - State variables (reading your own previous state)
    /// - Exogenous inputs (external forcing data)
    fn at_start(&self) -> PyResult<FloatValue> {
        self.values
            .get(self.current_index)
            .copied()
            .ok_or_else(|| PyValueError::new_err("No value available at current index"))
    }

    /// Get the value at the end of the timestep (index N+1), if available.
    ///
    /// Use this for:
    /// - Upstream component outputs (values written during this timestep)
    ///
    /// Returns None if at the last timestep.
    fn at_end(&self) -> Option<FloatValue> {
        let next_index = self.current_index + 1;
        self.values.get(next_index).copied()
    }

    /// Get the previous value (at current_index - 1)
    ///
    /// Deprecated: Use `at_offset(-1)` for consistent timestep-relative access.
    #[getter]
    fn previous(&self) -> PyResult<FloatValue> {
        if self.current_index == 0 {
            return Err(PyValueError::new_err("No previous value available"));
        }
        self.values
            .get(self.current_index - 1)
            .copied()
            .ok_or_else(|| PyValueError::new_err("No previous value available"))
    }

    /// Get value at offset from current (negative = past, positive = future)
    fn at_offset(&self, offset: isize) -> PyResult<FloatValue> {
        let index = self.current_index as isize + offset;
        if index < 0 || index >= self.values.len() as isize {
            return Err(PyValueError::new_err(format!(
                "Offset {} results in index {} which is out of bounds",
                offset, index
            )));
        }
        Ok(self.values[index as usize])
    }

    /// Get last n values as numpy array (including current)
    fn last_n<'py>(&self, py: Python<'py>, n: usize) -> PyResult<Bound<'py, PyArray1<FloatValue>>> {
        if n == 0 {
            return Ok(Vec::<FloatValue>::new().to_pyarray(py));
        }
        let start = (self.current_index + 1).saturating_sub(n);
        let end = self.current_index + 1;
        let slice: Vec<FloatValue> = self.values[start..end].to_vec();
        Ok(slice.to_pyarray(py))
    }

    /// Get all values as numpy array
    fn to_array<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<FloatValue>> {
        self.values.clone().to_pyarray(py)
    }

    /// Get the current index
    #[getter]
    fn current_index(&self) -> usize {
        self.current_index
    }

    /// Get the number of values
    fn __len__(&self) -> usize {
        self.values.len()
    }

    fn __repr__(&self) -> String {
        format!(
            "TimeseriesWindow(len={}, current_index={}, current={})",
            self.values.len(),
            self.current_index,
            self.values
                .get(self.current_index)
                .map(|v| v.to_string())
                .unwrap_or_else(|| "N/A".to_string())
        )
    }
}

/// Python wrapper for GridTimeseriesWindow (FourBox)
///
/// Provides view-like access to grid timeseries data with regional access.
///
/// Example:
///     window = FourBoxTimeseriesWindow(values=\[\[1,2,3,4\], \[5,6,7,8\]\], current_index=1)
///     print(window.current)  # [5, 6, 7, 8]
///     print(window.region(0))  # TimeseriesWindow for northern ocean
#[pyclass]
#[pyo3(name = "FourBoxTimeseriesWindow")]
#[derive(Debug, Clone)]
pub struct PyFourBoxTimeseriesWindow {
    /// Values stored as [timestep][region]
    values: Vec<[FloatValue; 4]>,
    current_index: usize,
}

#[pymethods]
impl PyFourBoxTimeseriesWindow {
    #[new]
    #[pyo3(signature = (values, current_index))]
    pub fn new(values: Vec<[FloatValue; 4]>, current_index: usize) -> PyResult<Self> {
        if current_index >= values.len() && !values.is_empty() {
            return Err(PyValueError::new_err(format!(
                "current_index {} out of bounds for values of length {}",
                current_index,
                values.len()
            )));
        }
        Ok(Self {
            values,
            current_index,
        })
    }

    /// Get a single region's value at the start of the timestep (index N).
    ///
    /// Use this for:
    /// - State variables (reading your own previous state)
    /// - Exogenous inputs (external forcing data)
    fn at_start(&self, region: usize) -> PyResult<FloatValue> {
        if region >= 4 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-3.",
                region
            )));
        }
        self.values
            .get(self.current_index)
            .map(|v| v[region])
            .ok_or_else(|| PyValueError::new_err("No value available at current index"))
    }

    /// Get a single region's value at the end of the timestep (index N+1), if available.
    ///
    /// Use this for:
    /// - Upstream component outputs (values written during this timestep)
    ///
    /// Returns None if at the last timestep.
    fn at_end(&self, region: usize) -> PyResult<Option<FloatValue>> {
        if region >= 4 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-3.",
                region
            )));
        }
        let next_index = self.current_index + 1;
        Ok(self.values.get(next_index).map(|v| v[region]))
    }

    /// Get all regional values at the start of the timestep (index N).
    fn at_start_all(&self) -> PyResult<PyFourBoxSlice> {
        self.values
            .get(self.current_index)
            .map(|v| PyFourBoxSlice(FourBoxSlice::from_array(*v)))
            .ok_or_else(|| PyValueError::new_err("No value available at current index"))
    }

    /// Get all regional values at the end of the timestep (index N+1), if available.
    ///
    /// Returns None if at the last timestep.
    fn at_end_all(&self) -> Option<PyFourBoxSlice> {
        let next_index = self.current_index + 1;
        self.values
            .get(next_index)
            .map(|v| PyFourBoxSlice(FourBoxSlice::from_array(*v)))
    }

    /// Get the previous slice as FourBoxSlice
    ///
    /// Deprecated: Use `region(i).at_offset(-1)` for consistent timestep-relative access.
    #[getter]
    fn previous(&self) -> PyResult<PyFourBoxSlice> {
        if self.current_index == 0 {
            return Err(PyValueError::new_err("No previous value available"));
        }
        self.values
            .get(self.current_index - 1)
            .map(|v| PyFourBoxSlice(FourBoxSlice::from_array(*v)))
            .ok_or_else(|| PyValueError::new_err("No previous value available"))
    }

    /// Get a single region's timeseries as a TimeseriesWindow
    fn region(&self, region: usize) -> PyResult<PyTimeseriesWindow> {
        if region >= 4 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-3.",
                region
            )));
        }
        let values: Vec<FloatValue> = self.values.iter().map(|v| v[region]).collect();
        Ok(PyTimeseriesWindow {
            values,
            current_index: self.current_index,
        })
    }

    /// Get current index
    #[getter]
    fn current_index(&self) -> usize {
        self.current_index
    }

    fn __len__(&self) -> usize {
        self.values.len()
    }

    fn __repr__(&self) -> String {
        format!(
            "FourBoxTimeseriesWindow(len={}, current_index={})",
            self.values.len(),
            self.current_index
        )
    }
}

/// Python wrapper for GridTimeseriesWindow (Hemispheric)
#[pyclass]
#[pyo3(name = "HemisphericTimeseriesWindow")]
#[derive(Debug, Clone)]
pub struct PyHemisphericTimeseriesWindow {
    values: Vec<[FloatValue; 2]>,
    current_index: usize,
}

#[pymethods]
impl PyHemisphericTimeseriesWindow {
    #[new]
    #[pyo3(signature = (values, current_index))]
    pub fn new(values: Vec<[FloatValue; 2]>, current_index: usize) -> PyResult<Self> {
        if current_index >= values.len() && !values.is_empty() {
            return Err(PyValueError::new_err(format!(
                "current_index {} out of bounds for values of length {}",
                current_index,
                values.len()
            )));
        }
        Ok(Self {
            values,
            current_index,
        })
    }

    /// Get a single region's value at the start of the timestep (index N).
    ///
    /// Use this for:
    /// - State variables (reading your own previous state)
    /// - Exogenous inputs (external forcing data)
    fn at_start(&self, region: usize) -> PyResult<FloatValue> {
        if region >= 2 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-1.",
                region
            )));
        }
        self.values
            .get(self.current_index)
            .map(|v| v[region])
            .ok_or_else(|| PyValueError::new_err("No value available at current index"))
    }

    /// Get a single region's value at the end of the timestep (index N+1), if available.
    ///
    /// Use this for:
    /// - Upstream component outputs (values written during this timestep)
    ///
    /// Returns None if at the last timestep.
    fn at_end(&self, region: usize) -> PyResult<Option<FloatValue>> {
        if region >= 2 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-1.",
                region
            )));
        }
        let next_index = self.current_index + 1;
        Ok(self.values.get(next_index).map(|v| v[region]))
    }

    /// Get all regional values at the start of the timestep (index N).
    fn at_start_all(&self) -> PyResult<PyHemisphericSlice> {
        self.values
            .get(self.current_index)
            .map(|v| PyHemisphericSlice(HemisphericSlice::from_array(*v)))
            .ok_or_else(|| PyValueError::new_err("No value available at current index"))
    }

    /// Get all regional values at the end of the timestep (index N+1), if available.
    ///
    /// Returns None if at the last timestep.
    fn at_end_all(&self) -> Option<PyHemisphericSlice> {
        let next_index = self.current_index + 1;
        self.values
            .get(next_index)
            .map(|v| PyHemisphericSlice(HemisphericSlice::from_array(*v)))
    }

    /// Get the previous slice as HemisphericSlice
    ///
    /// Deprecated: Use `region(i).at_offset(-1)` for consistent timestep-relative access.
    #[getter]
    fn previous(&self) -> PyResult<PyHemisphericSlice> {
        if self.current_index == 0 {
            return Err(PyValueError::new_err("No previous value available"));
        }
        self.values
            .get(self.current_index - 1)
            .map(|v| PyHemisphericSlice(HemisphericSlice::from_array(*v)))
            .ok_or_else(|| PyValueError::new_err("No previous value available"))
    }

    /// Get a single region's timeseries as a TimeseriesWindow
    fn region(&self, region: usize) -> PyResult<PyTimeseriesWindow> {
        if region >= 2 {
            return Err(PyValueError::new_err(format!(
                "Invalid region index: {}. Must be 0-1.",
                region
            )));
        }
        let values: Vec<FloatValue> = self.values.iter().map(|v| v[region]).collect();
        Ok(PyTimeseriesWindow {
            values,
            current_index: self.current_index,
        })
    }

    /// Get current index
    #[getter]
    fn current_index(&self) -> usize {
        self.current_index
    }

    fn __len__(&self) -> usize {
        self.values.len()
    }

    fn __repr__(&self) -> String {
        format!(
            "HemisphericTimeseriesWindow(len={}, current_index={})",
            self.values.len(),
            self.current_index
        )
    }
}

// =============================================================================
// GridType Python Enum
// =============================================================================

/// Re-export GridType for Python
pub use crate::component::GridType;

#[pymodule]
pub fn state(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyFourBoxSlice>()?;
    m.add_class::<PyHemisphericSlice>()?;
    m.add_class::<PyStateValue>()?;
    m.add_class::<PyTimeseriesWindow>()?;
    m.add_class::<PyFourBoxTimeseriesWindow>()?;
    m.add_class::<PyHemisphericTimeseriesWindow>()?;
    Ok(())
}