fx-durable-ga 0.1.6

Durable GA event driven optimization loop on PostgreSQL
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
use super::Gene;
use rand::{Rng, rngs::ThreadRng};
use serde::{Deserialize, Serialize};
use tracing::instrument;

/// Errors that can occur when creating gene bounds.
#[derive(Debug, thiserror::Error)]
pub enum GeneBoundError {
    #[error(
        "InvalidBounds: lower bound must be smaller than upper. lower = {lower}, upper={upper}"
    )]
    InvalidBound { lower: f64, upper: f64 },
    #[error("StepsOverflow: steps is too large. steps={steps}, max={max}")]
    StepsOverflow { steps: u32, max: i32 },
    #[error("ZeroSteps: number of steps must be greater than 0")]
    ZeroSteps,
    #[error("ValueOutOfBounds: value {value} is outside bounds [{lower}, {upper}]")]
    ValueOutOfBounds { value: f64, lower: f64, upper: f64 },
}

impl GeneBoundError {
    /// Creates a steps overflow error.
    pub(crate) fn steps_overflow(steps: u32) -> Self {
        Self::StepsOverflow {
            steps,
            max: i32::MAX,
        }
    }

    /// Creates an invalid bound error.
    pub(crate) fn invalid_bound(lower: f64, upper: f64) -> Self {
        Self::InvalidBound { lower, upper }
    }

    /// Creates a zero steps error.
    pub(crate) fn zero_steps() -> Self {
        Self::ZeroSteps
    }

    /// Creates a value out of bounds error.
    pub(crate) fn value_out_of_bounds(value: f64, lower: f64, upper: f64) -> Self {
        Self::ValueOutOfBounds {
            value,
            lower,
            upper,
        }
    }
}

/// Defines the search space bounds and discretization for a single gene parameter.
///
/// Each gene in a genetic algorithm represents one optimization parameter. `GeneBounds`
/// specifies the valid range of values and how finely to discretize that range.
/// Uses fixed-point arithmetic internally for precise decimal handling without floating-point errors.
///
/// # Discretization
///
/// The genetic algorithm works with discrete gene values (integers from 0 to steps-1).
/// These are mapped to continuous values in your specified range. More steps provide
/// finer resolution but increase the search space size.
///
/// # Examples
///
/// ```rust
/// use fx_durable_ga::models::GeneBounds;
///
/// // Trading strategy parameter: risk tolerance from 0.1% to 2.5% with 0.01% precision
/// let risk_bounds = GeneBounds::decimal(0.001, 0.025, 241, 5)?;
///
/// // Portfolio allocation: 0% to 100% in 1% increments
/// let allocation_bounds = GeneBounds::decimal(0.0, 1.0, 101, 2)?;
///
/// // Discrete choice: algorithm variant selection (4 options)
/// let variant_bounds = GeneBounds::integer(0, 3, 4)?;
/// # Ok::<(), fx_durable_ga::models::GeneBoundError>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(test, derive(PartialEq))]
pub struct GeneBounds {
    /// Lower bound scaled by scale_factor (for precision)
    pub(crate) lower_scaled: i64,
    /// Upper bound scaled by scale_factor (for precision)
    pub(crate) upper_scaled: i64,
    /// Number of discrete steps in the range
    pub(crate) steps: u32,
    /// Scale factor for decimal precision (e.g., 1_000_000 for 6 decimal places)
    pub(crate) scale_factor: i64,
}

impl GeneBounds {
    /// Creates bounds with decimal precision using fixed-point arithmetic.
    /// Precision specifies the number of decimal places (e.g., 6 for microsecond precision).
    #[instrument(level = "debug", fields(lower = lower, upper = upper, steps = steps, precision = precision))]
    pub fn decimal(
        lower: f64,
        upper: f64,
        steps: u32,
        precision: u8,
    ) -> Result<Self, GeneBoundError> {
        Self::validate_bounds(lower, upper, steps)?;

        let scale_factor = 10_i64.pow(precision as u32);
        let lower_scaled = (lower * scale_factor as f64).round() as i64;
        let upper_scaled = (upper * scale_factor as f64).round() as i64;

        Ok(Self {
            lower_scaled,
            upper_scaled,
            steps,
            scale_factor,
        })
    }

    /// Creates integer-only bounds with no fractional precision.
    #[instrument(level = "debug", fields(lower = lower, upper = upper, steps = steps))]
    pub fn integer(lower: i32, upper: i32, steps: u32) -> Result<Self, GeneBoundError> {
        Self::validate_bounds(lower, upper, steps)?;

        // Convert to new format: scale factor of 1 means integer precision
        Ok(Self {
            lower_scaled: lower as i64,
            upper_scaled: upper as i64,
            steps: steps as u32,
            scale_factor: 1,
        })
    }

    /// Validates that bounds are sensible and within system limits.
    fn validate_bounds<T>(lower: T, upper: T, steps: u32) -> Result<(), GeneBoundError>
    where
        T: PartialOrd + Copy + Into<f64>,
    {
        if lower > upper {
            return Err(GeneBoundError::invalid_bound(lower.into(), upper.into()));
        }

        if steps == 0 {
            return Err(GeneBoundError::zero_steps());
        }

        if steps > i32::MAX as u32 {
            return Err(GeneBoundError::steps_overflow(steps));
        }

        if lower == upper && steps > 1 {
            return Err(GeneBoundError::invalid_bound(lower.into(), upper.into()));
        }

        Ok(())
    }

    /// Converts a discrete gene value to its corresponding decimal value in the real range.
    pub fn decode_f64(&self, gene: Gene) -> f64 {
        let range = self.upper_scaled - self.lower_scaled;
        let scaled_value = self.lower_scaled + (gene * range) / (self.steps - 1) as i64;
        scaled_value as f64 / self.scale_factor as f64
    }

    /// Generates a random gene value within the discrete range [0, steps-1].
    #[instrument(level = "debug", skip(rng), fields(steps = self.steps))]
    pub(crate) fn random(&self, rng: &mut ThreadRng) -> Gene {
        rng.random_range(0..self.steps as i64)
    }

    /// Returns the number of discrete steps as an i32.
    pub(crate) fn steps(&self) -> i32 {
        self.steps as i32
    }

    /// Converts a normalized [0,1] sample to a discrete gene index [0, steps-1].
    pub fn from_sample(&self, sample: f64) -> Gene {
        // Map [0,1] sample to discrete gene index [0, steps-1]
        (sample * (self.steps - 1) as f64).round() as Gene
    }

    /// Encodes an f64 value directly to a gene index using the bounds' range.
    ///
    /// Returns an error if the value is outside the bounds' [lower, upper] range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use fx_durable_ga::models::GeneBounds;
    ///
    /// let bounds = GeneBounds::decimal(0.001, 1.0, 1000, 3)?;
    /// let gene = bounds.encode_f64(0.5)?; // Encodes 0.5 to appropriate gene index
    /// let decoded = bounds.decode_f64(gene);  // Should be approximately 0.5
    /// # Ok::<(), fx_durable_ga::models::GeneBoundError>(())
    /// ```
    pub fn encode_f64(&self, value: f64) -> Result<Gene, GeneBoundError> {
        let lower = self.lower_scaled as f64 / self.scale_factor as f64;
        let upper = self.upper_scaled as f64 / self.scale_factor as f64;

        if value < lower || value > upper {
            return Err(GeneBoundError::value_out_of_bounds(value, lower, upper));
        }

        let range = (self.upper_scaled - self.lower_scaled) as f64;
        let scaled_input = (value * self.scale_factor as f64).round() as i64;
        let normalized = (scaled_input - self.lower_scaled) as f64 / range;

        Ok(self.from_sample(normalized))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bounds_ordering_validation() {
        // lower > upper should fail for both types
        assert!(GeneBounds::decimal(0.5, 0.23, 10, 6).is_err());
        assert!(GeneBounds::integer(10, 5, 10).is_err());
    }

    #[test]
    fn test_zero_steps_validation() {
        // zero steps should fail for both types
        assert!(GeneBounds::decimal(0.0, 1.0, 0, 6).is_err());
        assert!(GeneBounds::integer(0, 10, 0).is_err());
    }

    #[test]
    fn test_steps_overflow_validation() {
        // steps overflow should fail for both types
        assert!(GeneBounds::decimal(0.0, 1.0, u32::MAX, 6).is_err());
        assert!(GeneBounds::integer(0, 10, u32::MAX).is_err());
    }

    #[test]
    fn test_equal_bounds_validation() {
        // equal bounds with steps > 1 should fail
        assert!(GeneBounds::decimal(0.5, 0.5, 2, 6).is_err());
        assert!(GeneBounds::integer(5, 5, 2).is_err());

        // equal bounds with steps = 1 should succeed
        assert!(GeneBounds::decimal(0.5, 0.5, 1, 6).is_ok());
        assert!(GeneBounds::integer(5, 5, 1).is_ok());
    }

    #[test]
    fn test_from_sample_boundaries() {
        let bounds = GeneBounds::decimal(0.0, 10.0, 100, 3).unwrap();
        assert_eq!(bounds.from_sample(0.0), 0);
        assert_eq!(bounds.from_sample(1.0), 99);
        assert_eq!(bounds.from_sample(0.5), 50);
    }

    #[test]
    fn test_from_sample_single_step() {
        let bounds = GeneBounds::decimal(0.0, 1.0, 1, 3).unwrap();
        assert_eq!(bounds.from_sample(0.0), 0);
        assert_eq!(bounds.from_sample(1.0), 0);
    }

    #[test]
    fn test_from_sample_different_step_counts() {
        let bounds = GeneBounds::decimal(0.0, 5.0, 10, 2).unwrap();
        assert_eq!(bounds.from_sample(0.0), 0);
        assert_eq!(bounds.from_sample(1.0), 9);
        assert_eq!(bounds.from_sample(0.5), 5);
    }

    #[test]
    fn test_bounds_inclusion() {
        // Test that both lower and upper bounds are included in the range
        let bounds = GeneBounds::decimal(0.0, 1.0, 2, 3).unwrap();

        // With 2 steps, we should get exactly the lower and upper bounds
        assert_eq!(bounds.decode_f64(0), 0.0); // Lower bound included
        assert_eq!(bounds.decode_f64(1), 1.0); // Upper bound included

        // Verify from_sample maps correctly to these discrete values
        assert_eq!(bounds.from_sample(0.0), 0); // Maps to lower bound
        assert_eq!(bounds.from_sample(1.0), 1); // Maps to upper bound

        // Test with more steps to show even distribution
        let bounds_5 = GeneBounds::decimal(0.0, 4.0, 5, 1).unwrap();
        assert_eq!(bounds_5.decode_f64(0), 0.0); // 0.0
        assert_eq!(bounds_5.decode_f64(1), 1.0); // 1.0
        assert_eq!(bounds_5.decode_f64(2), 2.0); // 2.0
        assert_eq!(bounds_5.decode_f64(3), 3.0); // 3.0
        assert_eq!(bounds_5.decode_f64(4), 4.0); // 4.0 (upper bound included)
    }

    #[test]
    fn test_integer_bounds_internal_representation() {
        let bounds = GeneBounds::integer(1, 10, 10).unwrap();
        assert_eq!(bounds.lower_scaled, 1);
        assert_eq!(bounds.upper_scaled, 10);
        assert_eq!(bounds.steps, 10);
        assert_eq!(bounds.scale_factor, 1);
        assert_eq!(bounds.steps(), 10);
    }

    #[test]
    fn test_decimal_bounds_internal_representation() {
        let bounds = GeneBounds::decimal(0.23, 0.5, 500, 6).unwrap();
        assert_eq!(bounds.lower_scaled, 230000); // 0.23 * 1_000_000
        assert_eq!(bounds.upper_scaled, 500000); // 0.5 * 1_000_000
        assert_eq!(bounds.steps, 500);
        assert_eq!(bounds.scale_factor, 1_000_000);
    }

    #[test]
    fn test_decode_f64_conversion() {
        // Test decimal conversion
        let bounds = GeneBounds::decimal(0.0, 10.0, 11, 1).unwrap(); // 11 steps: 0,1,2,...,10

        assert_eq!(bounds.decode_f64(0), 0.0); // First step
        assert_eq!(bounds.decode_f64(5), 5.0); // Middle step
        assert_eq!(bounds.decode_f64(10), 10.0); // Last step

        // Test with higher precision
        let precise_bounds = GeneBounds::decimal(0.0, 1.0, 101, 3).unwrap(); // 0.000 to 1.000
        assert!((precise_bounds.decode_f64(0) - 0.0).abs() < 0.001);
        assert!((precise_bounds.decode_f64(50) - 0.5).abs() < 0.01);
        assert!((precise_bounds.decode_f64(100) - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_random_generates_different_values() {
        let bounds = GeneBounds::integer(0, 1000, 100).unwrap(); // Large range
        let mut rng = rand::rng();

        let gene1 = bounds.random(&mut rng);
        let gene2 = bounds.random(&mut rng);

        // With 100 possible values, random genes are extremely unlikely to be equal
        assert_ne!(gene1, gene2);

        // Verify bounds
        assert!(gene1 >= 0 && gene1 < 100);
        assert!(gene2 >= 0 && gene2 < 100);
    }

    #[test]
    fn test_encode_f64_decimal_bounds() {
        let bounds = GeneBounds::decimal(0.0, 1.0, 11, 2).unwrap(); // 0.00 to 1.00, 11 steps

        // Test boundary values
        assert_eq!(bounds.encode_f64(0.0).unwrap(), 0);
        assert_eq!(bounds.encode_f64(1.0).unwrap(), 10);

        // Test middle value
        let gene = bounds.encode_f64(0.5).unwrap();
        assert_eq!(gene, 5);

        // Test roundtrip
        let decoded = bounds.decode_f64(gene);
        assert!((decoded - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_encode_f64_integer_bounds() {
        let bounds = GeneBounds::integer(10, 20, 11).unwrap(); // 10 to 20, 11 steps

        // Test boundary values
        assert_eq!(bounds.encode_f64(10.0).unwrap(), 0);
        assert_eq!(bounds.encode_f64(20.0).unwrap(), 10);

        // Test middle value
        let gene = bounds.encode_f64(15.0).unwrap();
        assert_eq!(gene, 5);

        // Test roundtrip
        let decoded = bounds.decode_f64(gene);
        assert!((decoded - 15.0).abs() < 0.1);
    }

    #[test]
    fn test_encode_f64_out_of_bounds() {
        let bounds = GeneBounds::decimal(0.001, 1.0, 1000, 3).unwrap();

        // Test values outside bounds
        assert!(bounds.encode_f64(0.0).is_err()); // Below lower bound
        assert!(bounds.encode_f64(1.1).is_err()); // Above upper bound

        // Test exact boundary values work
        assert!(bounds.encode_f64(0.001).is_ok());
        assert!(bounds.encode_f64(1.0).is_ok());
    }

    #[test]
    fn test_encode_f64_precision() {
        let bounds = GeneBounds::decimal(0.0, 1.0, 1001, 3).unwrap(); // 0.000 to 1.000, 1001 steps

        // Test high precision value
        let gene = bounds.encode_f64(0.123).unwrap();
        let decoded = bounds.decode_f64(gene);

        // Should be very close due to high step count
        assert!((decoded - 0.123).abs() < 0.002);
    }

    #[test]
    fn test_encode_f64_error_message() {
        let bounds = GeneBounds::decimal(0.5, 1.5, 100, 2).unwrap();

        let result = bounds.encode_f64(0.3);
        assert!(result.is_err());

        let error = result.unwrap_err();
        let error_msg = format!("{}", error);
        assert!(error_msg.contains("0.3"));
        assert!(error_msg.contains("0.5"));
        assert!(error_msg.contains("1.5"));
    }
}