docs(examples): add toy_nsga2, random_search, and custom_optimizer
The three runnable examples called out in spec §18.5 / §19. All open with `use heuropt::prelude::*;` so they double as a check that the prelude is sufficient on its own: - toy_nsga2.rs: Schaffer N.1 solved with NSGA-II. - random_search.rs: 2D sphere solved with RandomSearch. - custom_optimizer.rs: a minimal hill-climber implementing `Optimizer<P>` directly, demonstrating spec §2.3.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
//! Run a 2D sphere problem under `RandomSearch`.
|
||||
//!
|
||||
//! Run with:
|
||||
//!
|
||||
//! ```bash
|
||||
//! cargo run --example random_search
|
||||
//! ```
|
||||
|
||||
use heuropt::prelude::*;
|
||||
|
||||
struct Sphere2D;
|
||||
|
||||
impl Problem for Sphere2D {
|
||||
type Decision = Vec<f64>;
|
||||
|
||||
fn objectives(&self) -> ObjectiveSpace {
|
||||
ObjectiveSpace::new(vec![Objective::minimize("f")])
|
||||
}
|
||||
|
||||
fn evaluate(&self, x: &Vec<f64>) -> Evaluation {
|
||||
Evaluation::new(vec![x.iter().map(|v| v * v).sum()])
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let initializer = RealBounds::new(vec![(-5.0, 5.0), (-5.0, 5.0)]);
|
||||
let config = RandomSearchConfig { iterations: 500, batch_size: 1, seed: 7 };
|
||||
let mut optimizer = RandomSearch::new(config, initializer);
|
||||
|
||||
let result = optimizer.run(&Sphere2D);
|
||||
|
||||
let best = result.best.expect("single-objective always has a best");
|
||||
println!("Total evaluations: {}", result.evaluations);
|
||||
println!("Best decision: {:?}", best.decision);
|
||||
println!("Best f: {:.6}", best.evaluation.objectives[0]);
|
||||
}
|
||||
Reference in New Issue
Block a user