egobox 0.37.8

A python binding for egobox crates
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
use egobox_ego::OBJECTIVE_FUNCTION_ERROR;
use numpy::{PyArray1, PyArray2};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pyclass_enum, gen_stub_pymethods};

#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, PartialEq)]
pub enum Recombination {
    /// prediction is taken from the expert with highest responsability
    /// resulting in a model with discontinuities
    Hard = 0,
    /// Prediction is a combination experts prediction wrt their responsabilities,
    /// an optional heaviside factor might be used control steepness of the change between
    /// experts regions.
    Smooth = 1,
}

impl<'a, 'py> FromPyObject<'a, 'py> for Recombination {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(value.clone());
        }
        match obj.extract::<u8>() {
            Ok(0) => Ok(Self::Hard),
            Ok(1) => Ok(Self::Smooth),
            Ok(v) => Err(PyValueError::new_err(format!(
                "recombination integer value must be in [0, 1], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "recombination must be a Recombination enum or an integer in [0, 1]",
            )),
        }
    }
}

/// RegressionSpec is a bitfield that specifies which regression terms to include in the model.
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Clone, Default, Debug)]
pub(crate) struct RegressionSpec(pub(crate) u8);

#[gen_stub_pymethods]
#[pymethods]
impl RegressionSpec {
    #[classattr]
    pub(crate) const ALL: u8 = egobox_moe::RegressionSpec::ALL.bits();
    #[classattr]
    pub(crate) const CONSTANT: u8 = egobox_moe::RegressionSpec::CONSTANT.bits();
    #[classattr]
    pub(crate) const LINEAR: u8 = egobox_moe::RegressionSpec::LINEAR.bits();
    #[classattr]
    pub(crate) const QUADRATIC: u8 = egobox_moe::RegressionSpec::QUADRATIC.bits();
}

/// CorrelationSpec is a bitfield that specifies which correlation terms to include in the model.
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Clone, Default, Debug)]
pub(crate) struct CorrelationSpec(pub(crate) u8);

#[gen_stub_pymethods]
#[pymethods]
impl CorrelationSpec {
    #[classattr]
    pub(crate) const ALL: u8 = egobox_moe::CorrelationSpec::ALL.bits();
    #[classattr]
    pub(crate) const SQUARED_EXPONENTIAL: u8 =
        egobox_moe::CorrelationSpec::SQUAREDEXPONENTIAL.bits();
    #[classattr]
    pub(crate) const ABSOLUTE_EXPONENTIAL: u8 =
        egobox_moe::CorrelationSpec::ABSOLUTEEXPONENTIAL.bits();
    #[classattr]
    pub(crate) const MATERN32: u8 = egobox_moe::CorrelationSpec::MATERN32.bits();
    #[classattr]
    pub(crate) const MATERN52: u8 = egobox_moe::CorrelationSpec::MATERN52.bits();
}

/// InfillStrategy specifies the acquisition function to use for infill optimization.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum InfillStrategy {
    /// Expected Improvement
    /// see Mockus et al. (1978) "The application of Bayesian methods for seeking the extremum"
    Ei = 1,
    /// Warnes and Barnes 2nd EI improvement, shift EI by the GP mean
    /// easier to optimize than EI but may not explore as much as EI
    /// see Warnes and Barnes (2020) "A new acquisition function for batch Bayesian optimization"
    Wb2 = 2,
    /// Warnes and Barnes 2nd scaling to improve exploration
    Wb2s = 3,
    /// Logarithm of Expected Improvement
    /// see Ament et al. (2020) "Logarithmic Expected Improvement for Robust and Noisy Bayesian Optimization"
    LogEi = 4,
}

impl<'a, 'py> FromPyObject<'a, 'py> for InfillStrategy {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Ei),
            Ok(2) => Ok(Self::Wb2),
            Ok(3) => Ok(Self::Wb2s),
            Ok(4) => Ok(Self::LogEi),
            Ok(v) => Err(PyValueError::new_err(format!(
                "infill_strategy integer value must be in [1, 4], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "infill_strategy must be an InfillStrategy enum or an integer in [1, 4]",
            )),
        }
    }
}

/// ConstraintStrategy specifies the strategy to use for handling constraints in infill optimization.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum ConstraintStrategy {
    /// Mean of the GP is used to evaluate the constraint, which is equivalent to ignoring the uncertainty on the constraint
    Mc = 1,
    /// Upper trusted bound of the GP is used to evaluate the constraint, which takes into account the uncertainty on the constraint
    Utb = 2,
}

impl<'a, 'py> FromPyObject<'a, 'py> for ConstraintStrategy {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Mc),
            Ok(2) => Ok(Self::Utb),
            Ok(v) => Err(PyValueError::new_err(format!(
                "cstr_strategy integer value must be in [1, 2], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "cstr_strategy must be a ConstraintStrategy enum or an integer in [1, 2]",
            )),
        }
    }
}

/// QEiStrategy specifies the strategy to use for handling constraints in infill optimization.
/// see QEI is the multi-point extension of EI, see Chevalier and Ginsbourger (2013)
/// "Fast Computation of the Multi-Points Expected Improvement with Applications in Batch Selection"
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum QEiStrategy {
    /// Kriging Believer, the next point is added to the GP with its predicted mean value,
    /// which is equivalent to assuming that the prediction is perfect
    Kb = 1,
    /// Kriging Believer lower bound, the next point is added to the GP with
    /// its predicted mean value minus a multiple of the predicted standard deviation,
    /// which is equivalent to assuming that the prediction is pessimistic
    Kblb = 2,
    /// Kriging Believer upper bound, the next point is added to the GP with
    /// its predicted mean value plus a multiple of the predicted standard deviation,
    /// which is equivalent to assuming that the prediction is optimistic
    Kbub = 3,
    /// Constant Liar, the next point is added to the GP by using the current minimum
    /// value observed in the DOE, which is equivalent to assuming that
    /// the prediction is the current best value
    Clmin = 4,
}

impl<'a, 'py> FromPyObject<'a, 'py> for QEiStrategy {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Kb),
            Ok(2) => Ok(Self::Kblb),
            Ok(3) => Ok(Self::Kbub),
            Ok(4) => Ok(Self::Clmin),
            Ok(v) => Err(PyValueError::new_err(format!(
                "qei strategy integer value must be in [1, 4], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "qei strategy must be a QEiStrategy enum or an integer in [1, 4]",
            )),
        }
    }
}

/// InfillOptimizer specifies the optimization algorithm to use for infill optimization.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum InfillOptimizer {
    /// Gradient free optimization algorithm that uses a simplex of n+1 points for n-dimensional optimization
    Cobyla = 1,
    /// Gradient based optimization algorithm that uses a quasi-Newton method to optimize the acquisition function
    Slsqp = 2,
}

impl<'a, 'py> FromPyObject<'a, 'py> for InfillOptimizer {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Cobyla),
            Ok(2) => Ok(Self::Slsqp),
            Ok(v) => Err(PyValueError::new_err(format!(
                "infill_optimizer integer value must be in [1, 2], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "infill_optimizer must be an InfillOptimizer enum or an integer in [1, 2]",
            )),
        }
    }
}

/// Expected Feasible Improvement (EFI) is an acquisition function that takes into account the feasibility of the points in the optimization process.
/// It is defined as the product of the Expected Improvement (EI) weighted by the probability of viability
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub(crate) enum FeasibleInfillStrategy {
    /// Do not use feasibility information
    None = 1,
    /// Use Expected Feasible Improvement with full probability of feasibility
    EfiP = 2,
    /// Use Expected Feasible Improvement with 0.3 weighted probability of feasibility, which is more exploratory than EfiP
    EfiFe = 3,
}

impl<'a, 'py> FromPyObject<'a, 'py> for FeasibleInfillStrategy {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::None),
            Ok(2) => Ok(Self::EfiP),
            Ok(3) => Ok(Self::EfiFe),
            Ok(v) => Err(PyValueError::new_err(format!(
                "feasible_infill_strategy integer value must be in [1, 3], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "feasible_infill_strategy must be a FeasibleInfillStrategy enum or an integer in [1, 3]",
            )),
        }
    }
}

/// FailsafeStrategy specifies the strategy to use for handling failures during infill optimization.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub(crate) enum FailsafeStrategy {
    /// The point is ignored, the optimization continues but may fail to explore
    /// another region of the search space
    Rejection = 1,
    /// The point is added to the DOE with a penalized value, which allows
    /// the optimization to continue exploring other regions of the search space
    Imputation = 2,
    /// The viability of the point is modeled with a surrogate, which allows the optimization
    /// to learn which regions of the search space are more likely to fail and avoid them in the future
    Viability = 3,
}

impl<'a, 'py> FromPyObject<'a, 'py> for FailsafeStrategy {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Rejection),
            Ok(2) => Ok(Self::Imputation),
            Ok(3) => Ok(Self::Viability),
            Ok(v) => Err(PyValueError::new_err(format!(
                "failsafe_strategy integer value must be in [1, 3], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "failsafe_strategy must be a FailsafeStrategy enum or an integer in [1, 3]",
            )),
        }
    }
}

/// Verbose specifies the level of verbosity for logging.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub(crate) enum Verbose {
    Error = 0,
    Warning = 1,
    Info = 2,
    Debug = 3,
    Trace = 4,
}

impl<'a, 'py> FromPyObject<'a, 'py> for Verbose {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, PyErr> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(0) => Ok(Self::Error),
            Ok(1) => Ok(Self::Warning),
            Ok(2) => Ok(Self::Info),
            Ok(3) => Ok(Self::Debug),
            Ok(4) => Ok(Self::Trace),
            Ok(v) => Err(PyValueError::new_err(format!(
                "verbose integer value must be in [0, 4], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "verbose must be a Verbose enum or an integer in [0, 4]",
            )),
        }
    }
}

impl From<Verbose> for log::LevelFilter {
    fn from(value: Verbose) -> Self {
        match value {
            Verbose::Error => log::LevelFilter::Error,
            Verbose::Warning => log::LevelFilter::Warn,
            Verbose::Info => log::LevelFilter::Info,
            Verbose::Debug => log::LevelFilter::Debug,
            Verbose::Trace => log::LevelFilter::Trace,
        }
    }
}

/// XType specifies the type of the input variables.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum XType {
    Float = 1,
    Int = 2,
    Ord = 3,
    Enum = 4,
}

impl<'a, 'py> FromPyObject<'a, 'py> for XType {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Float),
            Ok(2) => Ok(Self::Int),
            Ok(3) => Ok(Self::Ord),
            Ok(4) => Ok(Self::Enum),
            Ok(v) => Err(PyValueError::new_err(format!(
                "xtype integer value must be in [1, 4], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "xtype must be an XType enum or an integer in [1, 4]",
            )),
        }
    }
}

/// XSpec specifies the type and limits of the input variables (aka design space).
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(FromPyObject, Debug)]
pub(crate) struct XSpec {
    #[pyo3(get)]
    pub(crate) xtype: XType,
    #[pyo3(get)]
    pub(crate) xlimits: Vec<f64>,
    #[pyo3(get)]
    pub(crate) tags: Vec<String>,
}

#[gen_stub_pymethods]
#[pymethods]
impl XSpec {
    #[new]
    #[pyo3(signature = (xtype, xlimits=vec![], tags=vec![]))]
    pub(crate) fn new(xtype: XType, xlimits: Vec<f64>, tags: Vec<String>) -> Self {
        XSpec {
            xtype,
            xlimits,
            tags,
        }
    }
}

/// SparseMethod specifies the method to use for sparse Gaussian process regression.
/// See "Sparse Gaussian Process Regression for Big Data" by V. Vanhatalo, J. Riihimäki, J. Hartikainen, and A. Vehtari (2010)
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[gen_stub_pyclass_enum]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum SparseMethod {
    /// FITC (Fully Independent Training Conditional) method, which uses a subset of the training data to make predictions, resulting in a faster but less accurate model
    Fitc = 1,
    /// VFE (Variational Free Energy) method, which uses a variational approach to approximate the posterior, resulting in a more accurate but slower model
    Vfe = 2,
}

impl<'a, 'py> FromPyObject<'a, 'py> for SparseMethod {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(value) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(*value);
        }
        match obj.extract::<u8>() {
            Ok(1) => Ok(Self::Fitc),
            Ok(2) => Ok(Self::Vfe),
            Ok(v) => Err(PyValueError::new_err(format!(
                "sparse method integer value must be in [1, 2], got {v}"
            ))),
            Err(_) => Err(PyTypeError::new_err(
                "method must be a SparseMethod enum or an integer in [1, 2]",
            )),
        }
    }
}

/// CstrSpec specifies how a constraint should be interpreted by the optimizer.
///
/// Instead of requiring constraints to be formulated as c <= 0,
/// users can specify constraint bounds directly.
///
/// # Examples
///
/// ```python
/// import egobox as egx
///
/// # c <= 5.0
/// spec1 = egx.CstrSpec.leq(5.0)
///
/// # c >= 2.0
/// spec2 = egx.CstrSpec.geq(2.0)
///
/// # c = 4.0 (equality constraint, expands to two internal constraints)
/// spec3 = egx.CstrSpec.eq(4.0)
///
/// # 1.0 <= c <= 3.0 (double-sided, expands to two internal constraints)
/// spec4 = egx.CstrSpec.btw(1.0, 3.0)
/// ```
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Debug, Clone)]
pub(crate) struct CstrSpec {
    pub(crate) inner: egobox_ego::CstrSpec,
}

impl<'a, 'py> FromPyObject<'a, 'py> for CstrSpec {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(spec) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(spec.clone());
        }

        let dict = obj.cast::<pyo3::types::PyDict>()?;
        if dict.len() != 1 {
            return Err(PyValueError::new_err(
                "CstrSpec dict form must contain exactly one key among: leq, geq, eq, btw",
            ));
        }

        if let Some(value) = dict.get_item("leq")? {
            return Ok(CstrSpec::leq(value.extract()?));
        }
        if let Some(value) = dict.get_item("geq")? {
            return Ok(CstrSpec::geq(value.extract()?));
        }
        if let Some(value) = dict.get_item("eq")? {
            return Ok(CstrSpec::eq(value.extract()?));
        }
        if let Some(value) = dict.get_item("btw")? {
            let (lower, upper): (f64, f64) = value.extract()?;
            return Ok(CstrSpec::btw(lower, upper));
        }

        Err(PyValueError::new_err(
            "Unknown CstrSpec dict key. Expected one of: leq, geq, eq, btw",
        ))
    }
}

#[gen_stub_pymethods]
#[pymethods]
impl CstrSpec {
    /// Constraint c <= bound, transformed to c - bound <= 0
    #[staticmethod]
    pub fn leq(bound: f64) -> Self {
        CstrSpec {
            inner: egobox_ego::CstrSpec::Leq(bound),
        }
    }

    /// Constraint c >= bound, transformed to bound - c <= 0
    #[staticmethod]
    pub fn geq(bound: f64) -> Self {
        CstrSpec {
            inner: egobox_ego::CstrSpec::Geq(bound),
        }
    }

    /// Equality constraint c = value, expands to two internal constraints:
    /// c - value <= 0 and value - c <= 0
    #[staticmethod]
    pub fn eq(value: f64) -> Self {
        CstrSpec {
            inner: egobox_ego::CstrSpec::Eq(value),
        }
    }

    /// Double-sided constraint lower <= c <= upper, expands to two internal constraints:
    /// lower - c <= 0 and c - upper <= 0
    #[staticmethod]
    pub fn btw(lower: f64, upper: f64) -> Self {
        CstrSpec {
            inner: egobox_ego::CstrSpec::Btw(lower, upper),
        }
    }

    fn __repr__(&self) -> String {
        format!("{:?}", self.inner)
    }
}

/// RunInfo contains information about a single run of the optimization algorithm,
/// the name of the function being optimized and the run number (useful for logging and saving results).
/// This is given by the user when calling the optimization function and is used for logging and saving results.
/// This information is also returned in the RunStatus to allow the user to correlate the results
/// with the function and run number.
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Debug, Clone)]
pub(crate) struct RunInfo {
    /// A name for the function being optimized, used for logging and saving results
    #[pyo3(get, set)]
    pub(crate) fname: String,
    /// A number for the run, used for logging and saving results
    #[pyo3(get, set)]
    pub(crate) num: usize,
}

impl<'a, 'py> FromPyObject<'a, 'py> for RunInfo {
    type Error = PyErr;

    fn extract(obj: pyo3::Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
        if let Ok(info) = obj.extract::<PyRef<'py, Self>>() {
            return Ok(info.clone());
        }

        let dict = obj.cast::<pyo3::types::PyDict>()?;
        let mut info = RunInfo {
            fname: "fobj".to_string(),
            num: 1,
        };

        for key_any in dict.keys().iter() {
            let key = key_any.extract::<String>()?;
            match key.as_str() {
                "fname" => info.fname = dict.get_item("fname")?.unwrap().extract()?,
                "num" => info.num = dict.get_item("num")?.unwrap().extract()?,
                _ => {
                    return Err(PyValueError::new_err(format!(
                        "unknown run_info key '{key}'"
                    )));
                }
            }
        }

        Ok(info)
    }
}

#[gen_stub_pymethods]
#[pymethods]
impl RunInfo {
    #[new]
    #[pyo3(signature = (fname="fobj".to_string(), num = 1))]
    pub fn new(fname: String, num: usize) -> Self {
        RunInfo { fname, num }
    }
}

/// ExitStatus specifies the reason for the termination of the optimization algorithm.
#[gen_stub_pyclass_enum]
#[pyclass(skip_from_py_object, eq, eq_int, rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum ExitStatus {
    /// Reached maximum number of iterations
    MaxItersReached = 1,
    /// Reached target cost function value
    TargetCostReached = 2,
    /// Algorithm manually interrupted with SIGINT (Ctrl+C), SIGTERM or SIGHUP
    Interrupt = 3,
    /// Algorithm peek at the same point twice. We consider it is converged.
    SolverConverged = 4,
    /// Timeout reached
    Timeout = 5,
    /// Solver unexpected exit. See logs for details.
    UnexpectedExit = 6,
    /// Objective function returned an error. See logs for details.
    ObjectiveFunctionError = 7,
}

impl From<argmin::core::TerminationStatus> for ExitStatus {
    fn from(value: argmin::core::TerminationStatus) -> Self {
        use argmin::core::{TerminationReason, TerminationStatus};
        match value {
            TerminationStatus::Terminated(reason) => match reason {
                TerminationReason::MaxItersReached => ExitStatus::MaxItersReached,
                TerminationReason::TargetCostReached => ExitStatus::TargetCostReached,
                TerminationReason::SolverConverged => ExitStatus::SolverConverged,
                TerminationReason::Timeout => ExitStatus::Timeout,
                TerminationReason::SolverExit(val) if val == OBJECTIVE_FUNCTION_ERROR => {
                    ExitStatus::ObjectiveFunctionError
                }
                TerminationReason::SolverExit(_) => unreachable!("Unexpected solver exit reason"),
                TerminationReason::Interrupt => ExitStatus::Interrupt,
            },
            TerminationStatus::NotTerminated => ExitStatus::UnexpectedExit,
        }
    }
}

/// RunStatus contains information about the status of a run of the optimization algorithm
/// It is returned by the optimizer together with the optimization results.
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Debug, Clone)]
pub(crate) struct RunStatus {
    /// Information about the run, provided by the user when calling the optimization function
    #[pyo3(get)]
    pub(crate) info: RunInfo,
    /// Exit status of the optimization algorithm, which indicates the reason for termination of the algorithm
    #[pyo3(get)]
    pub(crate) exit: ExitStatus,
    /// Number of points in the initial DOE, which is useful to correlate with the results and understand the behavior of the optimization algorithm
    #[pyo3(get)]
    pub(crate) init_doe_size: usize,
    /// Best iteration of the optimization algorithm, allows to retrieve optimal values in the optimization history
    #[pyo3(get)]
    pub(crate) best_iter: usize,
    /// Total number of iterations performed by the optimization algorithm
    #[pyo3(get)]
    pub(crate) total_iters: usize,
    /// Elapsed time of the optimization algorithm in seconds
    #[pyo3(get)]
    pub(crate) elapsed_time: f64,
}

/// OptimResult contains the results of a run of the optimization algorithm,
/// including the optimal point and value found, the DOE points and values which
/// includes initial points and the optimization history.
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Debug)]
pub(crate) struct OptimResult {
    /// Optimal x point found by the optimization algorithm
    #[pyo3(get)]
    pub(crate) x_opt: Py<PyArray1<f64>>,
    /// Optimal y point found by the optimization algorithm
    #[pyo3(get)]
    pub(crate) y_opt: Py<PyArray1<f64>>,
    /// DOE x points, including initial points and optimization history
    #[pyo3(get)]
    pub(crate) x_doe: Py<PyArray2<f64>>,
    /// DOE y points, including initial points and optimization history
    #[pyo3(get)]
    pub(crate) y_doe: Py<PyArray2<f64>>,
}

/// Egor optimization output
///
#[gen_stub_pyclass]
#[pyclass(skip_from_py_object)]
#[derive(Debug)]
pub(crate) struct EgorOptim {
    /// Result of optimization run
    #[pyo3(get)]
    pub(crate) result: Py<OptimResult>,
    /// Status of optimization run
    #[pyo3(get)]
    pub(crate) status: RunStatus,
}