ganesh 0.26.3

Minimization and sampling in Rust, simplified
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! Python-facing summary export traits for downstream wrapper crates.
#![allow(clippy::doc_markdown, clippy::missing_errors_doc)]

use pyo3::{
    exceptions::PyValueError,
    pyclass, pymethods,
    types::{PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyModule, PyModuleMethods},
    Bound, IntoPyObject, Py, PyAny, PyResult, Python,
};
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    algorithms::mcmc::ChainStorageMode,
    core::{
        MCMCDiagnostics, MCMCSummary, MinimizationSummary, MultiStartSummary,
        SimulatedAnnealingSummary,
    },
    python::numeric::{matrix_to_python, tensor3_to_python, vector_to_python},
};

/// Export a native `ganesh` summary into Python-facing forms.
///
/// Downstream wrapper crates can implement this trait for selected summary types and expose either
/// dictionary-style summaries, typed `#[pyclass]` wrappers, or both.
pub trait IntoPySummary {
    /// Convert the summary into a Python dictionary.
    fn to_py_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>>;

    /// Convert the summary into a typed Python wrapper object.
    fn to_py_class<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>>;
}

/// Register the built-in Python summary wrapper classes in a native module.
pub fn register_summary_types(module: &Bound<'_, PyModule>) -> PyResult<()> {
    module.add_class::<PyMinimizationSummary>()?;
    module.add_class::<PyMCMCSummary>()?;
    module.add_class::<PyMultiStartSummary>()?;
    module.add_class::<PySimulatedAnnealingSummary>()?;
    Ok(())
}

fn serialize_pickle<T>(value: &T) -> PyResult<Vec<u8>>
where
    T: Serialize,
{
    serde_pickle::to_vec(value, Default::default())
        .map_err(|err| PyValueError::new_err(format!("failed to serialize Python summary: {err}")))
}

#[allow(dead_code)]
fn deserialize_pickle<T>(state: &[u8], type_name: &str) -> PyResult<T>
where
    T: DeserializeOwned,
{
    serde_pickle::from_slice(state, Default::default()).map_err(|err| {
        PyValueError::new_err(format!("failed to restore pickled {type_name}: {err}"))
    })
}

fn reduce_with_restore<'py, T>(
    py: Python<'py>,
    restore_name: &str,
    value: &T,
) -> PyResult<Py<PyAny>>
where
    T: Serialize,
{
    let module = py.import("ganesh._ganesh")?;
    let restore = module.getattr(restore_name)?;
    let state = serialize_pickle(value)?;
    Ok((restore, (PyBytes::new(py, &state),))
        .into_pyobject(py)?
        .into_any()
        .unbind())
}

#[allow(dead_code)]
pub(crate) fn restore_minimization_summary(state: &[u8]) -> PyResult<PyMinimizationSummary> {
    let summary: MinimizationSummary = deserialize_pickle(state, "MinimizationSummary")?;
    Ok(PyMinimizationSummary::from(summary))
}

#[allow(dead_code)]
pub(crate) fn restore_mcmc_summary(state: &[u8]) -> PyResult<PyMCMCSummary> {
    let summary: MCMCSummary = deserialize_pickle(state, "MCMCSummary")?;
    Ok(PyMCMCSummary::from(summary))
}

#[allow(dead_code)]
pub(crate) fn restore_multistart_summary(state: &[u8]) -> PyResult<PyMultiStartSummary> {
    let summary: MultiStartSummary = deserialize_pickle(state, "MultiStartSummary")?;
    Ok(PyMultiStartSummary::from(summary))
}

#[allow(dead_code)]
pub(crate) fn restore_simulated_annealing_summary(
    state: &[u8],
) -> PyResult<PySimulatedAnnealingSummary> {
    let summary: SimulatedAnnealingSummary<crate::DVector<crate::Float>> =
        deserialize_pickle(state, "SimulatedAnnealingSummary")?;
    Ok(PySimulatedAnnealingSummary::from(summary))
}

fn bounds_to_python(
    bounds: &crate::core::transforms::Bounds,
) -> Vec<(Option<crate::Float>, Option<crate::Float>)> {
    bounds.iter().map(|(bound, _)| bound.as_options()).collect()
}

fn message_to_python<'py>(
    py: Python<'py>,
    message: &crate::traits::StatusMessage,
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    dict.set_item("status_type", message.status_type.to_string())?;
    dict.set_item("text", message.text.clone())?;
    dict.set_item("success", message.success())?;
    Ok(dict)
}

fn chain_storage_to_python<'py>(
    py: Python<'py>,
    chain_storage: ChainStorageMode,
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    match chain_storage {
        ChainStorageMode::Full => {
            dict.set_item("mode", "Full")?;
        }
        ChainStorageMode::Rolling { window } => {
            dict.set_item("mode", "Rolling")?;
            dict.set_item("window", window)?;
        }
        ChainStorageMode::Sampled {
            keep_every,
            max_samples,
        } => {
            dict.set_item("mode", "Sampled")?;
            dict.set_item("keep_every", keep_every)?;
            dict.set_item("max_samples", max_samples)?;
        }
    }
    Ok(dict)
}

fn diagnostics_to_python<'py>(
    py: Python<'py>,
    diagnostics: &MCMCDiagnostics,
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    dict.set_item("r_hat", vector_to_python(py, diagnostics.r_hat.as_slice())?)?;
    dict.set_item("ess", vector_to_python(py, diagnostics.ess.as_slice())?)?;
    dict.set_item(
        "acceptance_rates",
        vector_to_python(py, diagnostics.acceptance_rates.as_slice())?,
    )?;
    dict.set_item("mean_acceptance_rate", diagnostics.mean_acceptance_rate)?;
    Ok(dict)
}

fn chain_to_python(chain: &[Vec<crate::DVector<crate::Float>>]) -> Vec<Vec<Vec<crate::Float>>> {
    chain
        .iter()
        .map(|walker| {
            walker
                .iter()
                .map(|position| position.as_slice().to_vec())
                .collect::<Vec<_>>()
        })
        .collect()
}

fn flat_chain_to_python(chain: &[crate::DVector<crate::Float>]) -> Vec<Vec<crate::Float>> {
    chain
        .iter()
        .map(|position| position.as_slice().to_vec())
        .collect()
}

/// Python-facing typed wrapper for [`MinimizationSummary`].
///
/// Notes
/// -----
/// This wrapper is returned by Python-facing optimization APIs. Numeric vector
/// and matrix fields are exposed as `NumPy` arrays.
#[pyclass(skip_from_py_object, module = "ganesh", name = "MinimizationSummary")]
#[derive(Clone)]
pub struct PyMinimizationSummary {
    summary: MinimizationSummary,
}

#[pymethods]
impl PyMinimizationSummary {
    /// Optional parameter bounds.
    ///
    /// Returns
    /// -------
    /// list[tuple[float | None, float | None]] | None
    ///     Bounds represented as ``(lower, upper)`` pairs, where ``None``
    ///     means unbounded on that side.
    #[getter]
    pub fn bounds(&self) -> Option<Vec<(Option<crate::Float>, Option<crate::Float>)>> {
        self.summary.bounds.as_ref().map(bounds_to_python)
    }

    /// Optional parameter names.
    ///
    /// Returns
    /// -------
    /// list[str] | None
    #[getter]
    pub fn parameter_names(&self) -> Option<Vec<String>> {
        self.summary.parameter_names.clone()
    }

    /// Summary status type.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn status_type(&self) -> String {
        self.summary.message.status_type.to_string()
    }

    /// Human-readable status message.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn message_text(&self) -> String {
        self.summary.message.text.clone()
    }

    /// Whether the run reported success.
    ///
    /// Returns
    /// -------
    /// bool
    #[getter]
    pub const fn success(&self) -> bool {
        self.summary.message.success()
    }

    /// Initial parameter vector.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn x0<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        vector_to_python(py, self.summary.x0.as_slice())
    }

    /// Final parameter vector.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn x<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        vector_to_python(py, self.summary.x.as_slice())
    }

    /// Parameter standard deviations.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn std<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        vector_to_python(py, self.summary.std.as_slice())
    }

    /// Final objective value.
    ///
    /// Returns
    /// -------
    /// float
    #[getter]
    pub const fn fx(&self) -> crate::Float {
        self.summary.fx
    }

    /// Number of cost-function evaluations.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn cost_evals(&self) -> usize {
        self.summary.cost_evals
    }

    /// Number of gradient evaluations.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn gradient_evals(&self) -> usize {
        self.summary.gradient_evals
    }

    /// Estimated covariance matrix.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn covariance<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let covariance = self
            .summary
            .covariance
            .row_iter()
            .map(|row| row.iter().copied().collect::<Vec<_>>())
            .collect::<Vec<_>>();
        matrix_to_python(py, &covariance)
    }

    /// Export the wrapped summary as a plain Python dictionary.
    ///
    /// Returns
    /// -------
    /// dict
    pub fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        self.summary.to_py_dict(py)
    }

    /// Support Python pickle round-tripping for this summary wrapper.
    pub fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Py<PyAny>> {
        reduce_with_restore(py, "_restore_minimization_summary", &self.summary)
    }
}

impl From<MinimizationSummary> for PyMinimizationSummary {
    fn from(summary: MinimizationSummary) -> Self {
        Self { summary }
    }
}

impl From<PyMinimizationSummary> for MinimizationSummary {
    fn from(summary: PyMinimizationSummary) -> Self {
        summary.summary
    }
}

impl From<&PyMinimizationSummary> for MinimizationSummary {
    fn from(summary: &PyMinimizationSummary) -> Self {
        summary.summary.clone()
    }
}

/// Python-facing typed wrapper for [`MCMCSummary`].
///
/// Notes
/// -----
/// Numeric arrays are exposed as `NumPy` arrays. Chain post-processing methods
/// use keyword-only ``burn`` and ``thin`` arguments so the retained-chain view
/// is explicit at each call site.
#[pyclass(skip_from_py_object, module = "ganesh", name = "MCMCSummary")]
#[derive(Clone)]
pub struct PyMCMCSummary {
    summary: MCMCSummary,
}

#[pymethods]
impl PyMCMCSummary {
    /// Optional parameter bounds.
    ///
    /// Returns
    /// -------
    /// list[tuple[float | None, float | None]] | None
    #[getter]
    pub fn bounds(&self) -> Option<Vec<(Option<crate::Float>, Option<crate::Float>)>> {
        self.summary.bounds.as_ref().map(bounds_to_python)
    }

    /// Optional parameter names.
    ///
    /// Returns
    /// -------
    /// list[str] | None
    #[getter]
    pub fn parameter_names(&self) -> Option<Vec<String>> {
        self.summary.parameter_names.clone()
    }

    /// Summary status type.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn status_type(&self) -> String {
        self.summary.message.status_type.to_string()
    }

    /// Human-readable status message.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn message_text(&self) -> String {
        self.summary.message.text.clone()
    }

    /// Whether the run reported success.
    ///
    /// Returns
    /// -------
    /// bool
    #[getter]
    pub const fn success(&self) -> bool {
        self.summary.message.success()
    }

    /// Chain-storage description.
    ///
    /// Returns
    /// -------
    /// dict
    pub fn chain_storage<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        chain_storage_to_python(py, self.summary.chain_storage)
    }

    /// Number of cost-function evaluations.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn cost_evals(&self) -> usize {
        self.summary.cost_evals
    }

    /// Number of gradient evaluations.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn gradient_evals(&self) -> usize {
        self.summary.gradient_evals
    }

    /// Retained-chain dimensions.
    ///
    /// Returns
    /// -------
    /// tuple[int, int, int]
    ///     Dimensions in ``(n_walkers, n_steps, n_variables)`` order.
    #[getter]
    pub const fn dimension(&self) -> (usize, usize, usize) {
        self.summary.dimension
    }

    /// Compute convergence and efficiency diagnostics.
    ///
    /// Parameters
    /// ----------
    /// burn : int | None, optional
    ///     Number of retained steps discarded from the front of each walker
    ///     chain.
    /// thin : int | None, optional
    ///     Retain every ``thin``-th sample after burn-in.
    ///
    /// Returns
    /// -------
    /// dict
    ///     Dictionary with ``r_hat``, ``ess``, ``acceptance_rates``, and
    ///     ``mean_acceptance_rate`` entries.
    #[pyo3(signature = (*, burn=None, thin=None))]
    pub fn diagnostics<'py>(
        &self,
        py: Python<'py>,
        burn: Option<usize>,
        thin: Option<usize>,
    ) -> PyResult<Bound<'py, PyDict>> {
        let diagnostics = self.summary.diagnostics(burn, thin);
        diagnostics_to_python(py, &diagnostics)
    }

    /// Get the retained chain after optional burn-in and thinning.
    ///
    /// Parameters
    /// ----------
    /// burn : int | None, optional
    ///     Number of retained steps discarded from the front of each walker
    ///     chain.
    /// thin : int | None, optional
    ///     Retain every ``thin``-th sample after burn-in.
    /// flat : bool, default=False
    ///     If ``False``, return the chain with shape
    ///     ``(n_walkers, n_steps, n_dim)``. If ``True``, flatten the walker and
    ///     step dimensions and return shape ``(n_samples, n_dim)``.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[pyo3(signature = (*, burn=None, thin=None, flat=false))]
    pub fn chain<'py>(
        &self,
        py: Python<'py>,
        burn: Option<usize>,
        thin: Option<usize>,
        flat: bool,
    ) -> PyResult<Bound<'py, PyAny>> {
        if flat {
            return matrix_to_python(
                py,
                &flat_chain_to_python(&self.summary.get_flat_chain(burn, thin)),
            );
        }
        tensor3_to_python(py, &chain_to_python(&self.summary.get_chain(burn, thin)))
    }

    /// Export the wrapped summary as a plain Python dictionary.
    ///
    /// Returns
    /// -------
    /// dict
    pub fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        self.summary.to_py_dict(py)
    }

    /// Support Python pickle round-tripping for this summary wrapper.
    pub fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Py<PyAny>> {
        reduce_with_restore(py, "_restore_mcmc_summary", &self.summary)
    }
}

impl From<MCMCSummary> for PyMCMCSummary {
    fn from(summary: MCMCSummary) -> Self {
        Self { summary }
    }
}

impl From<PyMCMCSummary> for MCMCSummary {
    fn from(summary: PyMCMCSummary) -> Self {
        summary.summary
    }
}

impl From<&PyMCMCSummary> for MCMCSummary {
    fn from(summary: &PyMCMCSummary) -> Self {
        summary.summary.clone()
    }
}

/// Python-facing typed wrapper for [`MultiStartSummary`].
///
/// Notes
/// -----
/// Each completed run is exposed as a [`MinimizationSummary`] wrapper.
#[pyclass(skip_from_py_object, module = "ganesh", name = "MultiStartSummary")]
#[derive(Clone)]
pub struct PyMultiStartSummary {
    summary: MultiStartSummary,
}

#[pymethods]
impl PyMultiStartSummary {
    /// Completed run summaries.
    ///
    /// Returns
    /// -------
    /// list[`MinimizationSummary`]
    #[getter]
    pub fn runs<'py>(&self, py: Python<'py>) -> PyResult<Vec<Py<PyMinimizationSummary>>> {
        self.summary
            .runs
            .iter()
            .cloned()
            .map(PyMinimizationSummary::from)
            .map(|summary| Py::new(py, summary))
            .collect()
    }

    /// Index of the best completed run.
    ///
    /// Returns
    /// -------
    /// int | None
    #[getter]
    pub const fn best_run_index(&self) -> Option<usize> {
        self.summary.best_run_index
    }

    /// Best completed run summary.
    ///
    /// Returns
    /// -------
    /// `MinimizationSummary` | None
    #[getter]
    pub fn best_run<'py>(&self, py: Python<'py>) -> PyResult<Option<Py<PyMinimizationSummary>>> {
        self.summary
            .best()
            .cloned()
            .map(PyMinimizationSummary::from)
            .map(|summary| Py::new(py, summary))
            .transpose()
    }

    /// Number of completed restarts, excluding the first run.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn restart_count(&self) -> usize {
        self.summary.restart_count
    }

    /// Number of completed runs.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub fn completed_runs(&self) -> usize {
        self.summary.completed_runs()
    }

    /// Export the wrapped summary as a plain Python dictionary.
    ///
    /// Returns
    /// -------
    /// dict
    pub fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        self.summary.to_py_dict(py)
    }

    /// Support Python pickle round-tripping for this summary wrapper.
    pub fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Py<PyAny>> {
        reduce_with_restore(py, "_restore_multistart_summary", &self.summary)
    }
}

impl From<MultiStartSummary> for PyMultiStartSummary {
    fn from(summary: MultiStartSummary) -> Self {
        Self { summary }
    }
}

impl From<PyMultiStartSummary> for MultiStartSummary {
    fn from(summary: PyMultiStartSummary) -> Self {
        summary.summary
    }
}

impl From<&PyMultiStartSummary> for MultiStartSummary {
    fn from(summary: &PyMultiStartSummary) -> Self {
        summary.summary.clone()
    }
}

/// Python-facing typed wrapper for [`SimulatedAnnealingSummary<crate::DVector<crate::Float>>`].
///
/// Notes
/// -----
/// Numeric vector fields are exposed as `NumPy` arrays.
#[pyclass(
    skip_from_py_object,
    module = "ganesh",
    name = "SimulatedAnnealingSummary"
)]
#[derive(Clone)]
pub struct PySimulatedAnnealingSummary {
    summary: SimulatedAnnealingSummary<crate::DVector<crate::Float>>,
}

#[pymethods]
impl PySimulatedAnnealingSummary {
    /// Optional parameter bounds.
    ///
    /// Returns
    /// -------
    /// list[tuple[float | None, float | None]] | None
    #[getter]
    pub fn bounds(&self) -> Option<Vec<(Option<crate::Float>, Option<crate::Float>)>> {
        self.summary.bounds.as_ref().map(bounds_to_python)
    }

    /// Summary status type.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn status_type(&self) -> String {
        self.summary.message.status_type.to_string()
    }

    /// Human-readable status message.
    ///
    /// Returns
    /// -------
    /// str
    #[getter]
    pub fn message_text(&self) -> String {
        self.summary.message.text.clone()
    }

    /// Whether the run reported success.
    ///
    /// Returns
    /// -------
    /// bool
    #[getter]
    pub const fn success(&self) -> bool {
        self.summary.message.success()
    }

    /// Initial state vector.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn x0<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        vector_to_python(py, self.summary.x0.as_slice())
    }

    /// Best state found during the run.
    ///
    /// Returns
    /// -------
    /// numpy.ndarray
    #[getter]
    pub fn x<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        vector_to_python(py, self.summary.x.as_slice())
    }

    /// Best objective value.
    ///
    /// Returns
    /// -------
    /// float
    #[getter]
    pub const fn fx(&self) -> crate::Float {
        self.summary.fx
    }

    /// Number of cost-function evaluations.
    ///
    /// Returns
    /// -------
    /// int
    #[getter]
    pub const fn cost_evals(&self) -> usize {
        self.summary.cost_evals
    }

    /// Export the wrapped summary as a plain Python dictionary.
    ///
    /// Returns
    /// -------
    /// dict
    pub fn to_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        self.summary.to_py_dict(py)
    }

    /// Support Python pickle round-tripping for this summary wrapper.
    pub fn __reduce__<'py>(&self, py: Python<'py>) -> PyResult<Py<PyAny>> {
        reduce_with_restore(py, "_restore_simulated_annealing_summary", &self.summary)
    }
}

impl From<SimulatedAnnealingSummary<crate::DVector<crate::Float>>> for PySimulatedAnnealingSummary {
    fn from(summary: SimulatedAnnealingSummary<crate::DVector<crate::Float>>) -> Self {
        Self { summary }
    }
}

impl From<PySimulatedAnnealingSummary> for SimulatedAnnealingSummary<crate::DVector<crate::Float>> {
    fn from(summary: PySimulatedAnnealingSummary) -> Self {
        summary.summary
    }
}

impl From<&PySimulatedAnnealingSummary>
    for SimulatedAnnealingSummary<crate::DVector<crate::Float>>
{
    fn from(summary: &PySimulatedAnnealingSummary) -> Self {
        summary.summary.clone()
    }
}

impl IntoPySummary for MinimizationSummary {
    fn to_py_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        dict.set_item("bounds", self.bounds.as_ref().map(bounds_to_python))?;
        dict.set_item("parameter_names", self.parameter_names.clone())?;
        dict.set_item("message", message_to_python(py, &self.message)?)?;

        dict.set_item("x0", vector_to_python(py, self.x0.as_slice())?)?;
        dict.set_item("x", vector_to_python(py, self.x.as_slice())?)?;
        dict.set_item("std", vector_to_python(py, self.std.as_slice())?)?;
        dict.set_item("fx", self.fx)?;
        dict.set_item("cost_evals", self.cost_evals)?;
        dict.set_item("gradient_evals", self.gradient_evals)?;
        let covariance = self
            .covariance
            .row_iter()
            .map(|row| row.iter().copied().collect::<Vec<_>>())
            .collect::<Vec<_>>();
        dict.set_item("covariance", matrix_to_python(py, &covariance)?)?;
        Ok(dict)
    }

    fn to_py_class<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let wrapper = Py::new(py, PyMinimizationSummary::from(self.clone()))?;
        Ok(wrapper.into_bound(py).into_any())
    }
}

impl IntoPySummary for MCMCSummary {
    fn to_py_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        dict.set_item("bounds", self.bounds.as_ref().map(bounds_to_python))?;
        dict.set_item("parameter_names", self.parameter_names.clone())?;
        dict.set_item("message", message_to_python(py, &self.message)?)?;
        dict.set_item(
            "chain",
            tensor3_to_python(py, &chain_to_python(&self.chain))?,
        )?;
        dict.set_item(
            "chain_storage",
            chain_storage_to_python(py, self.chain_storage)?,
        )?;
        dict.set_item("cost_evals", self.cost_evals)?;
        dict.set_item("gradient_evals", self.gradient_evals)?;
        dict.set_item("dimension", self.dimension)?;
        Ok(dict)
    }

    fn to_py_class<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let wrapper = Py::new(py, PyMCMCSummary::from(self.clone()))?;
        Ok(wrapper.into_bound(py).into_any())
    }
}

impl IntoPySummary for MultiStartSummary {
    fn to_py_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        let runs = self
            .runs
            .iter()
            .map(|run| run.to_py_dict(py).map(|bound| bound.unbind()))
            .collect::<PyResult<Vec<_>>>()?;
        let best_run = self
            .best()
            .map(|run| run.to_py_dict(py).map(|bound| bound.unbind()))
            .transpose()?;
        dict.set_item("runs", runs)?;
        dict.set_item("best_run_index", self.best_run_index)?;
        dict.set_item("best_run", best_run)?;
        dict.set_item("restart_count", self.restart_count)?;
        dict.set_item("completed_runs", self.completed_runs())?;
        Ok(dict)
    }

    fn to_py_class<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let wrapper = Py::new(py, PyMultiStartSummary::from(self.clone()))?;
        Ok(wrapper.into_bound(py).into_any())
    }
}

impl IntoPySummary for SimulatedAnnealingSummary<crate::DVector<crate::Float>> {
    fn to_py_dict<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let dict = PyDict::new(py);
        dict.set_item("bounds", self.bounds.as_ref().map(bounds_to_python))?;
        dict.set_item("message", message_to_python(py, &self.message)?)?;
        dict.set_item("x0", vector_to_python(py, self.x0.as_slice())?)?;
        dict.set_item("x", vector_to_python(py, self.x.as_slice())?)?;
        dict.set_item("fx", self.fx)?;
        dict.set_item("cost_evals", self.cost_evals)?;
        Ok(dict)
    }

    fn to_py_class<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let wrapper = Py::new(py, PySimulatedAnnealingSummary::from(self.clone()))?;
        Ok(wrapper.into_bound(py).into_any())
    }
}

impl<'py> IntoPyObject<'py> for MinimizationSummary {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = pyo3::PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok(Py::new(py, PyMinimizationSummary::from(self))?
            .into_bound(py)
            .into_any())
    }
}

impl<'py> IntoPyObject<'py> for MCMCSummary {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = pyo3::PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok(Py::new(py, PyMCMCSummary::from(self))?
            .into_bound(py)
            .into_any())
    }
}

impl<'py> IntoPyObject<'py> for MultiStartSummary {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = pyo3::PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok(Py::new(py, PyMultiStartSummary::from(self))?
            .into_bound(py)
            .into_any())
    }
}

impl<'py> IntoPyObject<'py> for SimulatedAnnealingSummary<crate::DVector<crate::Float>> {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = pyo3::PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok(Py::new(py, PySimulatedAnnealingSummary::from(self))?
            .into_bound(py)
            .into_any())
    }
}

#[cfg(test)]
mod tests {
    use pyo3::{types::PyAnyMethods, Py};

    use super::*;
    use crate::{core::transforms::Bounds, traits::StatusMessage, DMatrix, DVector};

    fn sample_summary() -> MinimizationSummary {
        MinimizationSummary {
            bounds: Some(Bounds::new_default([
                (Some(-1.0), Some(1.0)),
                (None, Some(2.0)),
            ])),
            parameter_names: Some(vec!["alpha".into(), "beta".into()]),
            message: StatusMessage::default().set_success_with_message("ok"),
            x0: DVector::from_vec(vec![1.0, 2.0]),
            x: DVector::from_vec(vec![0.5, 1.5]),
            std: DVector::from_vec(vec![0.1, 0.2]),
            fx: 1.25,
            cost_evals: 10,
            gradient_evals: 4,
            covariance: DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1.0]),
        }
    }

    #[test]
    fn native_summary_into_pyobject_returns_typed_wrapper() {
        crate::python::attach_for_tests(|py| {
            let wrapper = sample_summary().into_pyobject(py).unwrap();
            let wrapper = wrapper.extract::<Py<PyMinimizationSummary>>().unwrap();
            let wrapper = wrapper.bind(py).borrow();
            assert_eq!(wrapper.fx(), 1.25);
            assert_eq!(wrapper.status_type(), "Success");
        });
    }

    #[test]
    fn summary_wrapper_roundtrip_converts_back_to_native() {
        let native = sample_summary();
        let wrapper = PyMinimizationSummary::from(native.clone());
        let roundtrip = MinimizationSummary::from(wrapper);
        assert_eq!(roundtrip.fx, native.fx);
        assert_eq!(roundtrip.cost_evals, native.cost_evals);
        assert_eq!(roundtrip.message.text, native.message.text);
    }

    #[test]
    fn borrowed_summary_wrapper_converts_back_to_native() {
        let wrapper = PyMinimizationSummary::from(sample_summary());
        let native = MinimizationSummary::from(&wrapper);
        assert_eq!(native.fx, 1.25);
        assert_eq!(native.parameter_names.unwrap(), vec!["alpha", "beta"]);
    }
}