fcmaes-rust 0.2.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/Cargo.lock +10 -9
  2. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/Cargo.toml +3 -3
  3. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/PKG-INFO +1 -1
  4. fcmaes_rust-0.3.0/crates/fcmaes-core/examples/stop_compatibility.rs +94 -0
  5. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/biteopt.rs +47 -1
  6. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/cmaes.rs +14 -1
  7. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/crfmnes.rs +16 -1
  8. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/da.rs +4 -4
  9. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/de.rs +49 -4
  10. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/lib.rs +1 -1
  11. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/pgpe.rs +16 -1
  12. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/retry.rs +17 -1
  13. fcmaes_rust-0.3.0/crates/fcmaes-core/tests/cooperative_stop.rs +203 -0
  14. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/LICENSE +0 -0
  15. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/Cargo.toml +0 -0
  16. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/LICENSE +0 -0
  17. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/NOTICE.pareto +0 -0
  18. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/PARETO_ARCHIVE.md +0 -0
  19. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/README.md +0 -0
  20. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/examples/pareto_bench.rs +0 -0
  21. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/examples/pareto_mode.rs +0 -0
  22. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/fitness.rs +0 -0
  23. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/indicators.rs +0 -0
  24. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/mapelites.rs +0 -0
  25. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/mode.rs +0 -0
  26. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/moretry.rs +0 -0
  27. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/pareto.rs +0 -0
  28. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/pareto_tests.rs +0 -0
  29. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/src/rng.rs +0 -0
  30. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/tests/data/pareto_archive_2d.csv +0 -0
  31. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-core/tests/pareto_fixture.rs +0 -0
  32. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-gtop/Cargo.toml +0 -0
  33. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-gtop/src/lib.rs +0 -0
  34. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/Cargo.toml +0 -0
  35. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/python_tests/test_binding_contract.py +0 -0
  36. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/python_tests/test_bindings.py +0 -0
  37. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/python_tests/test_type_stubs.py +0 -0
  38. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/acma.rs +0 -0
  39. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/biteopt.rs +0 -0
  40. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/common.rs +0 -0
  41. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/crfmnes.rs +0 -0
  42. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/da.rs +0 -0
  43. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/de.rs +0 -0
  44. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/gtop.rs +0 -0
  45. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/lib.rs +0 -0
  46. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/mapelites.rs +0 -0
  47. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/mode.rs +0 -0
  48. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/moretry.rs +0 -0
  49. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/pgpe.rs +0 -0
  50. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/crates/fcmaes-py/src/retry.rs +0 -0
  51. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/pyproject.toml +0 -0
  52. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/python/README.md +0 -0
  53. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/python/fcmaes_rust/__init__.py +0 -0
  54. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/python/fcmaes_rust/_fcmaes_ext.pyi +0 -0
  55. {fcmaes_rust-0.2.1 → fcmaes_rust-0.3.0}/python/fcmaes_rust/py.typed +0 -0
@@ -433,7 +433,7 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
433
433
 
434
434
  [[package]]
435
435
  name = "fcmaes-core"
436
- version = "0.2.1"
436
+ version = "0.3.0"
437
437
  dependencies = [
438
438
  "libm",
439
439
  "nalgebra",
@@ -445,7 +445,7 @@ dependencies = [
445
445
 
446
446
  [[package]]
447
447
  name = "fcmaes-examples"
448
- version = "0.2.1"
448
+ version = "0.3.0"
449
449
  dependencies = [
450
450
  "fcmaes-core",
451
451
  "fcmaes-gtop",
@@ -457,11 +457,11 @@ dependencies = [
457
457
 
458
458
  [[package]]
459
459
  name = "fcmaes-gtop"
460
- version = "0.2.1"
460
+ version = "0.3.0"
461
461
 
462
462
  [[package]]
463
463
  name = "fcmaes-job-worker"
464
- version = "0.2.1"
464
+ version = "0.3.0"
465
465
  dependencies = [
466
466
  "fcmaes-core",
467
467
  "fcmaes-native-worker",
@@ -487,7 +487,7 @@ dependencies = [
487
487
 
488
488
  [[package]]
489
489
  name = "fcmaes-py"
490
- version = "0.2.1"
490
+ version = "0.3.0"
491
491
  dependencies = [
492
492
  "fcmaes-core",
493
493
  "fcmaes-gtop",
@@ -1148,8 +1148,8 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
1148
1148
 
1149
1149
  [[package]]
1150
1150
  name = "optimization-job-api"
1151
- version = "0.3.0"
1152
- source = "git+https://github.com/dietmarwo/optimization-jobs?rev=37b30e428c5fdd017975e0093cc261243148257f#37b30e428c5fdd017975e0093cc261243148257f"
1151
+ version = "0.4.1"
1152
+ source = "git+https://github.com/dietmarwo/optimization-jobs?rev=78970a290f63f90a3f3d6ecbfe23f5e1ef24a235#78970a290f63f90a3f3d6ecbfe23f5e1ef24a235"
1153
1153
  dependencies = [
1154
1154
  "fs2",
1155
1155
  "libc",
@@ -1160,8 +1160,8 @@ dependencies = [
1160
1160
 
1161
1161
  [[package]]
1162
1162
  name = "optimization-runner"
1163
- version = "0.3.0"
1164
- source = "git+https://github.com/dietmarwo/optimization-jobs?rev=37b30e428c5fdd017975e0093cc261243148257f#37b30e428c5fdd017975e0093cc261243148257f"
1163
+ version = "0.4.1"
1164
+ source = "git+https://github.com/dietmarwo/optimization-jobs?rev=78970a290f63f90a3f3d6ecbfe23f5e1ef24a235#78970a290f63f90a3f3d6ecbfe23f5e1ef24a235"
1165
1165
  dependencies = [
1166
1166
  "clap",
1167
1167
  "fs2",
@@ -1169,6 +1169,7 @@ dependencies = [
1169
1169
  "optimization-job-api",
1170
1170
  "serde",
1171
1171
  "serde_json",
1172
+ "sha2",
1172
1173
  "tempfile",
1173
1174
  ]
1174
1175
 
@@ -7,7 +7,7 @@ codegen-units = 1
7
7
  lto = "thin"
8
8
 
9
9
  [workspace.package]
10
- version = "0.2.1"
10
+ version = "0.3.0"
11
11
  edition = "2024"
12
12
  rust-version = "1.88"
13
13
  license = "MIT"
@@ -20,8 +20,8 @@ fcmaes-core = { path = "crates/fcmaes-core" }
20
20
  fcmaes-gtop = { path = "crates/fcmaes-gtop" }
21
21
  # The shared job API (envelope, result contract, worker SDK, runner) lives in
22
22
  # github.com/dietmarwo/optimization-jobs; change the revision there first.
23
- optimization-job-api = { git = "https://github.com/dietmarwo/optimization-jobs", rev = "37b30e428c5fdd017975e0093cc261243148257f" }
24
- optimization-runner = { git = "https://github.com/dietmarwo/optimization-jobs", rev = "37b30e428c5fdd017975e0093cc261243148257f" }
23
+ optimization-job-api = { git = "https://github.com/dietmarwo/optimization-jobs", rev = "78970a290f63f90a3f3d6ecbfe23f5e1ef24a235" }
24
+ optimization-runner = { git = "https://github.com/dietmarwo/optimization-jobs", rev = "78970a290f63f90a3f3d6ecbfe23f5e1ef24a235" }
25
25
 
26
26
  # The runner and its workers hash their staged executables (tens of MB in
27
27
  # debug builds) on every job start; unoptimized SHA-256 made debug start-up
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fcmaes-rust
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: Programming Language :: Python :: 3.11
@@ -0,0 +1,94 @@
1
+ //! Fixed-seed compatibility records for the cooperative-stop release.
2
+ use fcmaes_core::*;
3
+ fn main() {
4
+ let objective = |x: &[f64]| x.iter().map(|v| v * v).sum::<f64>();
5
+ for seed in 1..=20 {
6
+ let fit = || Fitness::bounded(4, 1, &[-5.; 4], &[5.; 4]);
7
+ macro_rules! record {
8
+ ($name:expr,$r:expr) => {{
9
+ let r = $r;
10
+ println!(
11
+ "{} {} {:?} {:016x} {} {} {}",
12
+ $name,
13
+ seed,
14
+ r.x,
15
+ r.y.to_bits(),
16
+ r.evaluations,
17
+ r.iterations,
18
+ r.stop
19
+ );
20
+ }};
21
+ }
22
+ let p = BiteParams {
23
+ seed,
24
+ max_evaluations: 1000,
25
+ ..Default::default()
26
+ };
27
+ record!(
28
+ "bite",
29
+ BiteOpt::new(&[-5.; 4], &[5.; 4], None, &p).optimize(&objective)
30
+ );
31
+ record!(
32
+ "deep",
33
+ DeepBiteOpt::new(&[-5.; 4], &[5.; 4], None, &p, 3).optimize(&objective)
34
+ );
35
+ let p = DeParams {
36
+ seed,
37
+ max_evaluations: 1000,
38
+ ..Default::default()
39
+ };
40
+ record!(
41
+ "de",
42
+ De::new(fit(), &[], &[], None, &p).optimize(&objective)
43
+ );
44
+ record!(
45
+ "delayed",
46
+ De::new(fit(), &[], &[], None, &p).optimize_delayed(&objective, 4)
47
+ );
48
+ record!(
49
+ "cmaes",
50
+ Cmaes::new(
51
+ fit(),
52
+ &[0.; 4],
53
+ &[0.3],
54
+ &CmaesParams {
55
+ seed,
56
+ popsize: 8,
57
+ max_evaluations: 1000,
58
+ ..Default::default()
59
+ }
60
+ )
61
+ .optimize(&objective, 1)
62
+ );
63
+ record!(
64
+ "crfmnes",
65
+ Crfmnes::new(
66
+ fit(),
67
+ &[0.; 4],
68
+ 0.3,
69
+ &CrfmnesParams {
70
+ seed,
71
+ popsize: 8,
72
+ max_evaluations: 1000,
73
+ ..Default::default()
74
+ }
75
+ )
76
+ .optimize_batch(|xs| xs.iter().map(|x| objective(x)).collect())
77
+ );
78
+ record!(
79
+ "pgpe",
80
+ Pgpe::new(
81
+ fit(),
82
+ &[0.; 4],
83
+ &[0.3],
84
+ &PgpeParams {
85
+ seed,
86
+ popsize: 8,
87
+ max_evaluations: 1000,
88
+ ..Default::default()
89
+ }
90
+ )
91
+ .optimize_batch(|xs| xs.iter().map(|x| objective(x)).collect())
92
+ );
93
+ }
94
+ }
@@ -116,6 +116,8 @@ enum PopSel {
116
116
  /// Outcome of a BiteOpt run.
117
117
  #[derive(Clone, Debug)]
118
118
  pub struct BiteResult {
119
+ /// The cooperative stop predicate fired; evaluated points are retained.
120
+ pub stopped: bool,
119
121
  /// Best decision vector found.
120
122
  pub x: Vec<f64>,
121
123
  /// Objective value at [`x`](Self::x).
@@ -2398,12 +2400,34 @@ impl BiteOpt {
2398
2400
  /// # Panics
2399
2401
  ///
2400
2402
  /// Panics if `eval_batch` does not return one cost per row.
2401
- pub fn optimize_batch<F>(&mut self, batch: usize, mut eval_batch: F) -> BiteResult
2403
+ pub fn optimize_batch<F>(&mut self, batch: usize, eval_batch: F) -> BiteResult
2404
+ where
2405
+ F: FnMut(&[Vec<f64>]) -> Vec<f64>,
2406
+ {
2407
+ self.optimize_batch_until(batch, eval_batch, &|| false)
2408
+ }
2409
+
2410
+ /// Batched optimization with a cooperative stop checked before each batch.
2411
+ /// An in-flight batch is incorporated in full, with exact evaluation counts.
2412
+ ///
2413
+ /// # Panics
2414
+ /// Panics if `eval_batch` does not return one cost per row.
2415
+ pub fn optimize_batch_until<F>(
2416
+ &mut self,
2417
+ batch: usize,
2418
+ mut eval_batch: F,
2419
+ stop: &dyn Fn() -> bool,
2420
+ ) -> BiteResult
2402
2421
  where
2403
2422
  F: FnMut(&[Vec<f64>]) -> Vec<f64>,
2404
2423
  {
2405
2424
  let batch = batch.max(1);
2406
2425
  while self.evaluations < self.max_evaluations && self.stop == 0 {
2426
+ if stop() {
2427
+ let mut result = self.result();
2428
+ result.stopped = true;
2429
+ return result;
2430
+ }
2407
2431
  let rows = self.ask(batch);
2408
2432
  if rows.is_empty() {
2409
2433
  break;
@@ -2452,7 +2476,17 @@ impl BiteOpt {
2452
2476
 
2453
2477
  /// Run until the evaluation budget or a stop condition is reached.
2454
2478
  pub fn optimize(&mut self, obj: &impl Objective) -> BiteResult {
2479
+ self.optimize_until(obj, &|| false)
2480
+ }
2481
+
2482
+ /// Like [`Self::optimize`], checking `stop` before every evaluation.
2483
+ pub fn optimize_until(&mut self, obj: &impl Objective, stop: &dyn Fn() -> bool) -> BiteResult {
2455
2484
  while self.evaluations < self.max_evaluations && self.stop == 0 {
2485
+ if stop() {
2486
+ let mut result = self.result();
2487
+ result.stopped = true;
2488
+ return result;
2489
+ }
2456
2490
  self.optimize_step(obj);
2457
2491
  self.iterations += 1;
2458
2492
  self.evaluations += 1;
@@ -2463,6 +2497,7 @@ impl BiteOpt {
2463
2497
 
2464
2498
  fn result(&self) -> BiteResult {
2465
2499
  BiteResult {
2500
+ stopped: false,
2466
2501
  x: self.best_values.clone(),
2467
2502
  y: self.best_cost,
2468
2503
  evaluations: self.evaluations,
@@ -2583,7 +2618,17 @@ impl DeepBiteOpt {
2583
2618
 
2584
2619
  /// One-shot optimization until the (total) evaluation budget or a stop.
2585
2620
  pub fn optimize(&mut self, obj: &impl Objective) -> BiteResult {
2621
+ self.optimize_until(obj, &|| false)
2622
+ }
2623
+
2624
+ /// Deep BiteOpt with a cooperative stop before every evaluation.
2625
+ pub fn optimize_until(&mut self, obj: &impl Objective, stop: &dyn Fn() -> bool) -> BiteResult {
2586
2626
  while self.total_evaluations() < self.max_evaluations && self.stop == 0 {
2627
+ if stop() {
2628
+ let mut result = self.result();
2629
+ result.stopped = true;
2630
+ return result;
2631
+ }
2587
2632
  self.pick_push();
2588
2633
  let opt_idx = self.cur_opt;
2589
2634
  let (sc, push) = self.opts[opt_idx].step_collect(obj, self.m > 1);
@@ -2696,6 +2741,7 @@ impl DeepBiteOpt {
2696
2741
  pub fn result(&self) -> BiteResult {
2697
2742
  let b = self.best();
2698
2743
  BiteResult {
2744
+ stopped: false,
2699
2745
  x: b.best_values.clone(),
2700
2746
  y: b.best_cost,
2701
2747
  evaluations: self.evaluations,
@@ -609,9 +609,22 @@ impl Cmaes {
609
609
  /// Run the full generational loop, evaluating each population through
610
610
  /// `obj` with the requested worker count.
611
611
  pub fn optimize(&mut self, obj: &impl Objective, workers: i32) -> AcmaResult {
612
+ self.optimize_until(obj, workers, &|| false)
613
+ }
614
+
615
+ /// Like [`Self::optimize`], stopping before the next population.
616
+ pub fn optimize_until(
617
+ &mut self,
618
+ obj: &impl Objective,
619
+ workers: i32,
620
+ stop: &dyn Fn() -> bool,
621
+ ) -> AcmaResult {
612
622
  self.iterations = 0;
613
623
  self.fitfun.reset_evaluations();
614
624
  while self.fitfun.evaluations() < self.max_evaluations && !self.fitfun.terminate() {
625
+ if stop() {
626
+ break;
627
+ }
615
628
  let xs = self.ask_all();
616
629
  let ys = self
617
630
  .fitfun
@@ -765,7 +778,7 @@ mod tests {
765
778
  .map(|s| run("rosen", rosen as fn(&[f64]) -> f64, 5, -5.0, 5.0, s))
766
779
  .collect();
767
780
  vals.sort_by(|a, b| a.partial_cmp(b).unwrap());
768
- assert!(vals[2] < 1.0, "rosenbrock median too large: {:?}", vals);
781
+ assert!(vals[2] < 1.0, "rosenbrock median too large: {vals:?}");
769
782
  }
770
783
 
771
784
  #[test]
@@ -509,13 +509,28 @@ impl Crfmnes {
509
509
 
510
510
  /// Run the generational loop, evaluating each population through
511
511
  /// `eval_batch(decoded_rows) -> ys`.
512
- pub fn optimize_batch<F>(&mut self, mut eval_batch: F) -> CrfmnesResult
512
+ pub fn optimize_batch<F>(&mut self, eval_batch: F) -> CrfmnesResult
513
+ where
514
+ F: FnMut(&[Vec<f64>]) -> Vec<f64>,
515
+ {
516
+ self.optimize_batch_until(eval_batch, &|| false)
517
+ }
518
+
519
+ /// Like [`Self::optimize_batch`], stopping before the next population.
520
+ pub fn optimize_batch_until<F>(
521
+ &mut self,
522
+ mut eval_batch: F,
523
+ stop: &dyn Fn() -> bool,
524
+ ) -> CrfmnesResult
513
525
  where
514
526
  F: FnMut(&[Vec<f64>]) -> Vec<f64>,
515
527
  {
516
528
  self.iterations = 1;
517
529
  self.fitfun.reset_evaluations();
518
530
  while self.fitfun.evaluations() < self.max_evaluations && !self.fitfun.terminate() {
531
+ if stop() {
532
+ break;
533
+ }
519
534
  self.ask();
520
535
  let rows = self.decode_columns(&self.x);
521
536
  let mut ys = eval_batch(&rows);
@@ -488,8 +488,8 @@ impl<'a, O: Objective> Da<'a, O> {
488
488
  for i in (0..kh).rev() {
489
489
  let a = rho[i] * dot(&s_hist[i], &q);
490
490
  alpha[i] = a;
491
- for j in 0..self.dim {
492
- q[j] -= a * y_hist[i][j];
491
+ for (qj, yj) in q.iter_mut().zip(&y_hist[i]) {
492
+ *qj -= a * yj;
493
493
  }
494
494
  }
495
495
  let gamma = if kh > 0 {
@@ -503,8 +503,8 @@ impl<'a, O: Objective> Da<'a, O> {
503
503
  }
504
504
  for i in 0..kh {
505
505
  let beta = rho[i] * dot(&y_hist[i], &q);
506
- for j in 0..self.dim {
507
- q[j] += (alpha[i] - beta) * s_hist[i][j];
506
+ for (qj, sj) in q.iter_mut().zip(&s_hist[i]) {
507
+ *qj += (alpha[i] - beta) * sj;
508
508
  }
509
509
  }
510
510
  let d: Vec<f64> = q.iter().map(|v| -v).collect();
@@ -40,6 +40,8 @@ use crate::rng::Rng;
40
40
  /// Outcome of a Differential Evolution run.
41
41
  #[derive(Clone, Debug)]
42
42
  pub struct DeResult {
43
+ /// The cooperative stop predicate fired; every dispatched point is counted.
44
+ pub stopped: bool,
43
45
  /// Best decoded decision vector found.
44
46
  pub x: Vec<f64>,
45
47
  /// Objective value at [`x`](Self::x).
@@ -465,6 +467,13 @@ impl De {
465
467
  /// [`DeParams::max_evaluations`] by up to `2 * popsize - 1` evaluations;
466
468
  /// use [`optimize_delayed`](De::optimize_delayed) for an exact limit.
467
469
  pub fn optimize(&mut self, obj: &impl Objective) -> DeResult {
470
+ self.optimize_until(obj, &|| false)
471
+ }
472
+
473
+ /// Serial DE with a cooperative stop before each evaluation, including
474
+ /// temporal-locality trials. The usual generational budget is unchanged.
475
+ pub fn optimize_until(&mut self, obj: &impl Objective, stop: &dyn Fn() -> bool) -> DeResult {
476
+ let mut evaluated_best = (Vec::new(), f64::INFINITY);
468
477
  self.iterations = 1;
469
478
  self.fitfun.reset_evaluations();
470
479
  while self.fitfun.evaluations() < self.max_evaluations && !self.fitfun.terminate() {
@@ -473,6 +482,15 @@ impl De {
473
482
  }
474
483
  self.oscillate();
475
484
  for p in 0..self.popsize {
485
+ if stop() {
486
+ let mut result = self.make_result(self.fitfun.evaluations());
487
+ result.stopped = true;
488
+ if evaluated_best.1 < result.y {
489
+ result.x = evaluated_best.0;
490
+ result.y = evaluated_best.1;
491
+ }
492
+ return result;
493
+ }
476
494
  let xp = self.pop_x[p].clone();
477
495
  let xb = self.pop_x[self.best_i].clone();
478
496
  let (r1, r2) = self.pick_two(p);
@@ -490,10 +508,20 @@ impl De {
490
508
  }
491
509
  self.modify(&mut x);
492
510
  let mut y = self.fitfun.eval_encoded_scalar(&x, obj);
511
+ if y.is_finite() && y < evaluated_best.1 {
512
+ evaluated_best = (x.clone(), y);
513
+ }
493
514
  if y.is_finite() && y < self.pop_y[p] {
494
515
  // temporal locality: an extra trial along the last move
495
516
  let x2t = self.next_improve(&xb, &x, &xp);
496
- let y2 = self.fitfun.eval_encoded_scalar(&x2t, obj);
517
+ let y2 = if stop() {
518
+ f64::INFINITY
519
+ } else {
520
+ self.fitfun.eval_encoded_scalar(&x2t, obj)
521
+ };
522
+ if y2.is_finite() && y2 < evaluated_best.1 {
523
+ evaluated_best = (x2t.clone(), y2);
524
+ }
497
525
  if y2.is_finite() && y2 < y {
498
526
  y = y2;
499
527
  x = x2t;
@@ -546,6 +574,20 @@ impl De {
546
574
  ///
547
575
  /// Resumes a panic of the objective in the caller.
548
576
  pub fn optimize_delayed(&mut self, obj: &impl Objective, workers: usize) -> DeResult {
577
+ self.optimize_delayed_until(obj, workers, &|| false)
578
+ }
579
+
580
+ /// Delayed DE with a cooperative stop before dispatch. At most `workers`
581
+ /// evaluations are in flight; all are drained and told in ask order.
582
+ ///
583
+ /// # Panics
584
+ /// Resumes an objective panic in the caller.
585
+ pub fn optimize_delayed_until(
586
+ &mut self,
587
+ obj: &impl Objective,
588
+ workers: usize,
589
+ stop: &(dyn Fn() -> bool + Sync),
590
+ ) -> DeResult {
549
591
  use std::collections::BTreeMap;
550
592
  use std::sync::mpsc;
551
593
  type Evaluated = (u64, std::thread::Result<f64>);
@@ -572,7 +614,7 @@ impl De {
572
614
  asked.push_back((id, p, x));
573
615
  *dispatched += 1;
574
616
  };
575
- while dispatched < budget.min(workers) {
617
+ while dispatched < budget.min(workers) && !stop() {
576
618
  dispatch(self, &mut asked, &mut dispatched);
577
619
  }
578
620
  while let Some(&(oldest, _, _)) = asked.front() {
@@ -604,17 +646,20 @@ impl De {
604
646
  };
605
647
  self.tell_one(y, &x, p);
606
648
  told += 1;
607
- if self.stop == 0 && dispatched < budget && !self.fitfun.terminate() {
649
+ if self.stop == 0 && dispatched < budget && !self.fitfun.terminate() && !stop() {
608
650
  dispatch(self, &mut asked, &mut dispatched);
609
651
  }
610
652
  }
611
653
  });
612
654
  self.external_evaluations += told;
613
- self.make_result(told)
655
+ let mut result = self.make_result(told);
656
+ result.stopped = stop();
657
+ result
614
658
  }
615
659
 
616
660
  fn make_result(&self, evaluations: u64) -> DeResult {
617
661
  DeResult {
662
+ stopped: false,
618
663
  x: self.best_x.clone(),
619
664
  y: self.best_y,
620
665
  evaluations,
@@ -53,7 +53,7 @@ pub use pareto::{
53
53
  pub use pgpe::{Pgpe, PgpeParams, PgpeResult};
54
54
  pub use retry::{
55
55
  AdvancedRetryConfig, RetryBounds, RetryConfig, RetryContext, RetryEntry, RetryImprovement,
56
- RetryResult, RetryRunResult, advanced_retry, retry, retry_run_seed,
56
+ RetryResult, RetryRunResult, advanced_retry, retry, retry_run_seed, retry_until,
57
57
  };
58
58
  pub use rng::Rng;
59
59
 
@@ -384,7 +384,19 @@ impl Pgpe {
384
384
  }
385
385
 
386
386
  /// Generational loop evaluating each population through a batch closure.
387
- pub fn optimize_batch<F>(&mut self, mut eval_batch: F) -> PgpeResult
387
+ pub fn optimize_batch<F>(&mut self, eval_batch: F) -> PgpeResult
388
+ where
389
+ F: FnMut(&[Vec<f64>]) -> Vec<f64>,
390
+ {
391
+ self.optimize_batch_until(eval_batch, &|| false)
392
+ }
393
+
394
+ /// Like [`Self::optimize_batch`], stopping before the next population.
395
+ pub fn optimize_batch_until<F>(
396
+ &mut self,
397
+ mut eval_batch: F,
398
+ stop: &dyn Fn() -> bool,
399
+ ) -> PgpeResult
388
400
  where
389
401
  F: FnMut(&[Vec<f64>]) -> Vec<f64>,
390
402
  {
@@ -394,6 +406,9 @@ impl Pgpe {
394
406
  && !self.fitfun.terminate()
395
407
  && self.stop == 0
396
408
  {
409
+ if stop() {
410
+ break;
411
+ }
397
412
  let rows = self.ask_pop_internal();
398
413
  let mut ys = eval_batch(&rows);
399
414
  for v in ys.iter_mut() {
@@ -448,6 +448,22 @@ pub fn retry<O, F>(
448
448
  config: &RetryConfig,
449
449
  optimize: F,
450
450
  ) -> RetryResult
451
+ where
452
+ O: Fn(&[f64]) -> f64 + Sync,
453
+ F: Fn(&O, &RetryContext) -> RetryRunResult + Sync + Send,
454
+ {
455
+ retry_until(objective, bounds, config, optimize, &|| false)
456
+ }
457
+
458
+ /// Like [`retry`], but stops claiming new runs when `stop` fires.
459
+ /// Pass the same predicate into the inner optimizer to stop active runs too.
460
+ pub fn retry_until<O, F>(
461
+ objective: &O,
462
+ bounds: &RetryBounds,
463
+ config: &RetryConfig,
464
+ optimize: F,
465
+ stop: &(dyn Fn() -> bool + Sync),
466
+ ) -> RetryResult
451
467
  where
452
468
  O: Fn(&[f64]) -> f64 + Sync,
453
469
  F: Fn(&O, &RetryContext) -> RetryRunResult + Sync + Send,
@@ -467,7 +483,7 @@ where
467
483
  run_parallel(workers, |worker_id| {
468
484
  let mut worker_rng = spawned_worker_rng(config.seed, worker_id);
469
485
  loop {
470
- if stopped.load(AtomicOrdering::Relaxed) {
486
+ if stopped.load(AtomicOrdering::Relaxed) || stop() {
471
487
  break;
472
488
  }
473
489
  let run_id = next_run.fetch_add(1, AtomicOrdering::Relaxed);
@@ -0,0 +1,203 @@
1
+ use fcmaes_core::{BiteOpt, BiteParams, De, DeParams, DeepBiteOpt, Fitness};
2
+ use std::sync::{
3
+ Mutex,
4
+ atomic::{AtomicUsize, Ordering},
5
+ };
6
+
7
+ #[test]
8
+ fn stop_retains_exactly_the_evaluated_best() {
9
+ for k in [0, 1, 7, 51, 200] {
10
+ for engine in ["bite", "deep", "de"] {
11
+ let calls = AtomicUsize::new(0);
12
+ let best = Mutex::new(f64::INFINITY);
13
+ let objective = |x: &[f64]| {
14
+ let y = x.iter().map(|x| x * x).sum::<f64>();
15
+ let mut saved = best.lock().unwrap();
16
+ *saved = saved.min(y);
17
+ calls.fetch_add(1, Ordering::SeqCst);
18
+ y
19
+ };
20
+ let stop = || calls.load(Ordering::SeqCst) >= k;
21
+ let (x, y, n, stopped) = match engine {
22
+ "bite" => {
23
+ let r = BiteOpt::new(
24
+ &[-5.; 3],
25
+ &[5.; 3],
26
+ None,
27
+ &BiteParams {
28
+ max_evaluations: 1000,
29
+ ..Default::default()
30
+ },
31
+ )
32
+ .optimize_until(&objective, &stop);
33
+ (r.x, r.y, r.evaluations, r.stopped)
34
+ }
35
+ "deep" => {
36
+ let r = DeepBiteOpt::new(
37
+ &[-5.; 3],
38
+ &[5.; 3],
39
+ None,
40
+ &BiteParams {
41
+ max_evaluations: 1000,
42
+ ..Default::default()
43
+ },
44
+ 3,
45
+ )
46
+ .optimize_until(&objective, &stop);
47
+ (r.x, r.y, r.evaluations, r.stopped)
48
+ }
49
+ _ => {
50
+ let r = De::new(
51
+ Fitness::bounded(3, 1, &[-5.; 3], &[5.; 3]),
52
+ &[],
53
+ &[],
54
+ None,
55
+ &DeParams {
56
+ max_evaluations: 1000,
57
+ ..Default::default()
58
+ },
59
+ )
60
+ .optimize_until(&objective, &stop);
61
+ (r.x, r.y, r.evaluations, r.stopped)
62
+ }
63
+ };
64
+ assert!(stopped, "{engine} k={k}");
65
+ assert_eq!(n, k as u64, "{engine} k={k}");
66
+ assert_eq!(calls.load(Ordering::SeqCst), k);
67
+ if k > 0 {
68
+ assert_eq!(y, *best.lock().unwrap(), "{engine} k={k}");
69
+ assert_eq!(y, x.iter().map(|x| x * x).sum::<f64>());
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ #[test]
76
+ fn batches_drain_in_flight_work_and_count_it() {
77
+ for batch in [1, 4, 16] {
78
+ for engine in ["bite", "de"] {
79
+ let calls = AtomicUsize::new(0);
80
+ let objective = |x: &[f64]| {
81
+ calls.fetch_add(1, Ordering::SeqCst);
82
+ x.iter().map(|v| v * v).sum::<f64>()
83
+ };
84
+ let stop = || calls.load(Ordering::SeqCst) >= 37;
85
+ let (n, stopped) = if engine == "bite" {
86
+ let r = BiteOpt::new(
87
+ &[-5.; 3],
88
+ &[5.; 3],
89
+ None,
90
+ &BiteParams {
91
+ max_evaluations: 1000,
92
+ ..Default::default()
93
+ },
94
+ )
95
+ .optimize_batch_until(
96
+ batch,
97
+ |xs| xs.iter().map(|x| objective(x)).collect(),
98
+ &stop,
99
+ );
100
+ (r.evaluations, r.stopped)
101
+ } else {
102
+ let r = De::new(
103
+ Fitness::bounded(3, 1, &[-5.; 3], &[5.; 3]),
104
+ &[],
105
+ &[],
106
+ None,
107
+ &DeParams {
108
+ max_evaluations: 1000,
109
+ ..Default::default()
110
+ },
111
+ )
112
+ .optimize_delayed_until(&objective, batch, &stop);
113
+ (r.evaluations, r.stopped)
114
+ };
115
+ assert!(stopped);
116
+ assert_eq!(n as usize, calls.load(Ordering::SeqCst));
117
+ assert!(
118
+ (37..37 + batch).contains(&(n as usize)),
119
+ "{engine} {batch} {n}"
120
+ );
121
+ }
122
+ }
123
+ }
124
+
125
+ #[test]
126
+ fn never_stop_preserves_results_bit_for_bit() {
127
+ let objective = |x: &[f64]| x.iter().map(|v| v * v).sum::<f64>();
128
+ for seed in 1..=10 {
129
+ let p = BiteParams {
130
+ seed,
131
+ max_evaluations: 1000,
132
+ ..Default::default()
133
+ };
134
+ let mut a = BiteOpt::new(&[-5.; 3], &[5.; 3], None, &p);
135
+ let mut b = BiteOpt::new(&[-5.; 3], &[5.; 3], None, &p);
136
+ assert_eq!(
137
+ format!("{:?}", a.optimize(&objective)),
138
+ format!("{:?}", b.optimize_until(&objective, &|| false))
139
+ );
140
+ let p = DeParams {
141
+ seed,
142
+ max_evaluations: 1000,
143
+ ..Default::default()
144
+ };
145
+ let make = || {
146
+ De::new(
147
+ Fitness::bounded(3, 1, &[-5.; 3], &[5.; 3]),
148
+ &[],
149
+ &[],
150
+ None,
151
+ &p,
152
+ )
153
+ };
154
+ assert_eq!(
155
+ format!("{:?}", make().optimize(&objective)),
156
+ format!("{:?}", make().optimize_until(&objective, &|| false))
157
+ );
158
+ assert_eq!(
159
+ format!("{:?}", make().optimize_delayed(&objective, 4)),
160
+ format!(
161
+ "{:?}",
162
+ make().optimize_delayed_until(&objective, 4, &|| false)
163
+ )
164
+ );
165
+ }
166
+ }
167
+
168
+ #[test]
169
+ fn retry_until_stops_claiming_new_runs() {
170
+ use fcmaes_core::{RetryBounds, RetryConfig, RetryRunResult, retry_until};
171
+ let calls = AtomicUsize::new(0);
172
+ let objective = |x: &[f64]| x[0];
173
+ let bounds = RetryBounds::new(vec![-1.], vec![1.]).unwrap();
174
+ let config = RetryConfig {
175
+ num_retries: 10,
176
+ workers: 1,
177
+ ..Default::default()
178
+ };
179
+ let result = retry_until(
180
+ &objective,
181
+ &bounds,
182
+ &config,
183
+ |_, context| {
184
+ calls.fetch_add(1, Ordering::SeqCst);
185
+ RetryRunResult {
186
+ x: vec![0.0],
187
+ y: context.run_id as f64,
188
+ evaluations: 1,
189
+ }
190
+ },
191
+ &|| calls.load(Ordering::SeqCst) >= 2,
192
+ );
193
+ assert_eq!(result.runs, 2);
194
+ assert_eq!(result.evaluations, 2);
195
+ let result = retry_until(
196
+ &objective,
197
+ &bounds,
198
+ &config,
199
+ |_, _| panic!("stopped retry must not be claimed"),
200
+ &|| true,
201
+ );
202
+ assert_eq!(result.runs, 0);
203
+ }
File without changes
File without changes