Skip to content

Commit 1dbb83c

Browse files
committed
Fix formatting, clippy warnings, and doc warnings
- Run cargo fmt on all code - Add clippy allows for intentional patterns in lib.rs - Fix doc comments with unescaped brackets (array syntax) - Fix test assertion with logic bug (|| true) - Auto-fix simple clippy suggestions
1 parent fdabb38 commit 1dbb83c

30 files changed

Lines changed: 555 additions & 346 deletions

examples/checkpointing.rs

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
//! that may need to be interrupted and resumed.
66
77
use fugue_evo::prelude::*;
8-
use rand::SeedableRng;
98
use rand::rngs::StdRng;
9+
use rand::SeedableRng;
1010
use std::path::PathBuf;
1111

1212
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -52,8 +52,8 @@ fn run_with_checkpoints(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::err
5252

5353
// Create checkpoint manager
5454
let mut manager = CheckpointManager::new(checkpoint_dir, "evolution")
55-
.every(50) // Save every 50 generations
56-
.keep(3); // Keep last 3 checkpoints
55+
.every(50) // Save every 50 generations
56+
.keep(3); // Keep last 3 checkpoints
5757

5858
let max_generations = 200;
5959

@@ -72,10 +72,17 @@ fn run_with_checkpoints(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::err
7272
let p2_idx = selection.select(&selection_pool, &mut rng);
7373

7474
let (mut c1, mut c2) = crossover
75-
.crossover(&selection_pool[p1_idx].0, &selection_pool[p2_idx].0, &mut rng)
75+
.crossover(
76+
&selection_pool[p1_idx].0,
77+
&selection_pool[p2_idx].0,
78+
&mut rng,
79+
)
7680
.genome()
7781
.unwrap_or_else(|| {
78-
(selection_pool[p1_idx].0.clone(), selection_pool[p2_idx].0.clone())
82+
(
83+
selection_pool[p1_idx].0.clone(),
84+
selection_pool[p2_idx].0.clone(),
85+
)
7986
});
8087

8188
mutation.mutate(&mut c1, &mut rng);
@@ -102,8 +109,8 @@ fn run_with_checkpoints(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::err
102109

103110
// Create checkpoint with current population
104111
let individuals: Vec<Individual<RealVector>> = population.iter().cloned().collect();
105-
let checkpoint = Checkpoint::new(gen + 1, individuals)
106-
.with_evaluations((gen + 1) * 100);
112+
let checkpoint =
113+
Checkpoint::new(gen + 1, individuals).with_evaluations((gen + 1) * 100);
107114

108115
manager.save(&checkpoint)?;
109116
}
@@ -121,7 +128,7 @@ fn resume_from_checkpoint(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::e
121128
// Find the latest checkpoint file
122129
let entries: Vec<_> = std::fs::read_dir(checkpoint_dir)?
123130
.filter_map(|e| e.ok())
124-
.filter(|e| e.path().extension().map_or(false, |ext| ext == "ckpt"))
131+
.filter(|e| e.path().extension().is_some_and(|ext| ext == "ckpt"))
125132
.collect();
126133

127134
if entries.is_empty() {
@@ -145,7 +152,9 @@ fn resume_from_checkpoint(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::e
145152
println!(" Evaluations: {}", checkpoint.evaluations);
146153

147154
// Find best in loaded population
148-
let best_individual = checkpoint.population.iter()
155+
let best_individual = checkpoint
156+
.population
157+
.iter()
149158
.filter_map(|ind| ind.fitness.as_ref().map(|f| (ind, f.to_f64())))
150159
.max_by(|(_, f1), (_, f2)| f1.partial_cmp(f2).unwrap());
151160

@@ -154,11 +163,12 @@ fn resume_from_checkpoint(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::e
154163
}
155164

156165
// Continue evolution...
157-
let mut rng = StdRng::seed_from_u64(12345); // Different seed for continuation
166+
let mut rng = StdRng::seed_from_u64(12345); // Different seed for continuation
158167
let fitness = Sphere::new(10);
159168

160169
// Reconstruct population from checkpoint
161-
let mut population: Population<RealVector, f64> = Population::with_capacity(checkpoint.population.len());
170+
let mut population: Population<RealVector, f64> =
171+
Population::with_capacity(checkpoint.population.len());
162172
for ind in checkpoint.population {
163173
population.push(ind);
164174
}
@@ -183,10 +193,17 @@ fn resume_from_checkpoint(checkpoint_dir: &PathBuf) -> Result<(), Box<dyn std::e
183193
let p2_idx = selection.select(&selection_pool, &mut rng);
184194

185195
let (mut c1, mut c2) = crossover
186-
.crossover(&selection_pool[p1_idx].0, &selection_pool[p2_idx].0, &mut rng)
196+
.crossover(
197+
&selection_pool[p1_idx].0,
198+
&selection_pool[p2_idx].0,
199+
&mut rng,
200+
)
187201
.genome()
188202
.unwrap_or_else(|| {
189-
(selection_pool[p1_idx].0.clone(), selection_pool[p2_idx].0.clone())
203+
(
204+
selection_pool[p1_idx].0.clone(),
205+
selection_pool[p2_idx].0.clone(),
206+
)
190207
});
191208

192209
mutation.mutate(&mut c1, &mut rng);

examples/cma_es_example.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
//! distribution to efficiently search the fitness landscape.
99
1010
use fugue_evo::prelude::*;
11-
use rand::SeedableRng;
1211
use rand::rngs::StdRng;
12+
use rand::SeedableRng;
1313

1414
fn main() -> Result<(), Box<dyn std::error::Error>> {
1515
println!("=== CMA-ES Optimization Example ===\n");
@@ -24,15 +24,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
2424
println!("Global optimum: 0.0 at (1, 1, ..., 1)\n");
2525

2626
// Create CMA-ES optimizer
27-
let initial_mean = vec![0.0; DIM]; // Start at origin
28-
let initial_sigma = 0.5; // Initial step size
27+
let initial_mean = vec![0.0; DIM]; // Start at origin
28+
let initial_sigma = 0.5; // Initial step size
2929
let bounds = MultiBounds::symmetric(5.0, DIM);
3030

3131
// Create fitness function that CMA-ES can use
3232
let fitness = RosenbrockCmaEs { dim: DIM };
3333

34-
let mut cmaes = CmaEs::new(initial_mean, initial_sigma)
35-
.with_bounds(bounds);
34+
let mut cmaes = CmaEs::new(initial_mean, initial_sigma).with_bounds(bounds);
3635

3736
// Run optimization
3837
let best = cmaes.run_generations(&fitness, 1000, &mut rng)?;
@@ -79,6 +78,6 @@ impl CmaEsFitness for RosenbrockCmaEs {
7978
let term2 = 1.0 - genes[i];
8079
sum += 100.0 * term1 * term1 + term2 * term2;
8180
}
82-
sum // CMA-ES minimizes, so return positive value
81+
sum // CMA-ES minimizes, so return positive value
8382
}
8483
}

examples/hyperparameter_learning.rs

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
//! The system learns optimal mutation rates based on observed fitness improvements.
55
66
use fugue_evo::prelude::*;
7-
use rand::SeedableRng;
87
use rand::rngs::StdRng;
8+
use rand::SeedableRng;
99

1010
fn main() -> Result<(), Box<dyn std::error::Error>> {
1111
println!("=== Bayesian Hyperparameter Learning ===\n");
@@ -37,7 +37,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
3737
// Initial mutation rate from prior
3838
let mut current_mutation_rate = mutation_posterior.mean();
3939

40-
println!("Initial mutation rate (prior mean): {:.4}", current_mutation_rate);
40+
println!(
41+
"Initial mutation rate (prior mean): {:.4}",
42+
current_mutation_rate
43+
);
4144
println!();
4245

4346
let max_generations = 200;
@@ -68,10 +71,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
6871
let p2_idx = selection.select(&selection_pool, &mut rng);
6972

7073
let (mut c1, mut c2) = crossover
71-
.crossover(&selection_pool[p1_idx].0, &selection_pool[p2_idx].0, &mut rng)
74+
.crossover(
75+
&selection_pool[p1_idx].0,
76+
&selection_pool[p2_idx].0,
77+
&mut rng,
78+
)
7279
.genome()
7380
.unwrap_or_else(|| {
74-
(selection_pool[p1_idx].0.clone(), selection_pool[p2_idx].0.clone())
81+
(
82+
selection_pool[p1_idx].0.clone(),
83+
selection_pool[p2_idx].0.clone(),
84+
)
7585
});
7686

7787
let parent1_fitness = selection_pool[p1_idx].1;
@@ -94,8 +104,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
94104
mutation_posterior.observe(improved2);
95105

96106
total_mutations += 2;
97-
if improved1 { successful_mutations += 1; }
98-
if improved2 { successful_mutations += 1; }
107+
if improved1 {
108+
successful_mutations += 1;
109+
}
110+
if improved2 {
111+
successful_mutations += 1;
112+
}
99113

100114
new_pop.push(Individual::with_fitness(c1, child1_fitness));
101115
if new_pop.len() < 100 {
@@ -114,7 +128,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
114128
println!();
115129

116130
println!("Learned hyperparameters:");
117-
println!(" Final mutation rate (posterior mean): {:.4}", mutation_posterior.mean());
131+
println!(
132+
" Final mutation rate (posterior mean): {:.4}",
133+
mutation_posterior.mean()
134+
);
118135
let ci = mutation_posterior.credible_interval(0.95);
119136
println!(" 95% credible interval: [{:.4}, {:.4}]", ci.0, ci.1);
120137
println!();
@@ -145,7 +162,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
145162
}
146163

147164
fn run_with_fixed_rate(rate: f64, dim: usize) -> Result<f64, Box<dyn std::error::Error>> {
148-
let mut rng = StdRng::seed_from_u64(42); // Same seed for fair comparison
165+
let mut rng = StdRng::seed_from_u64(42); // Same seed for fair comparison
149166

150167
let fitness = Rastrigin::new(dim);
151168
let bounds = MultiBounds::symmetric(5.12, dim);
@@ -170,10 +187,17 @@ fn run_with_fixed_rate(rate: f64, dim: usize) -> Result<f64, Box<dyn std::error:
170187
let p2_idx = selection.select(&selection_pool, &mut rng);
171188

172189
let (mut c1, mut c2) = crossover
173-
.crossover(&selection_pool[p1_idx].0, &selection_pool[p2_idx].0, &mut rng)
190+
.crossover(
191+
&selection_pool[p1_idx].0,
192+
&selection_pool[p2_idx].0,
193+
&mut rng,
194+
)
174195
.genome()
175196
.unwrap_or_else(|| {
176-
(selection_pool[p1_idx].0.clone(), selection_pool[p2_idx].0.clone())
197+
(
198+
selection_pool[p1_idx].0.clone(),
199+
selection_pool[p2_idx].0.clone(),
200+
)
177201
});
178202

179203
mutation.mutate(&mut c1, &mut rng);

examples/island_model.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
//! Island models can help maintain diversity and escape local optima.
88
99
use fugue_evo::prelude::*;
10-
use rand::SeedableRng;
1110
use rand::rngs::StdRng;
11+
use rand::SeedableRng;
1212

1313
fn main() -> Result<(), Box<dyn std::error::Error>> {
1414
println!("=== Island Model Parallelism ===\n");
@@ -57,7 +57,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
5757
let bounds2 = MultiBounds::symmetric(5.12, DIM);
5858

5959
let single_result = SimpleGABuilder::<RealVector, f64, _, _, _, _, _>::new()
60-
.population_size(200) // Same total population
60+
.population_size(200) // Same total population
6161
.bounds(bounds2)
6262
.selection(TournamentSelection::new(3))
6363
.crossover(SbxCrossover::new(15.0))

examples/rastrigin_benchmark.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
//! at the origin.
99
1010
use fugue_evo::prelude::*;
11-
use rand::SeedableRng;
1211
use rand::rngs::StdRng;
12+
use rand::SeedableRng;
1313

1414
fn main() -> Result<(), Box<dyn std::error::Error>> {
1515
println!("=== Rastrigin Function Benchmark ===\n");
@@ -30,8 +30,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
3030
let result = SimpleGABuilder::<RealVector, f64, _, _, _, _, _>::new()
3131
.population_size(200)
3232
.bounds(bounds)
33-
.selection(TournamentSelection::new(5)) // Higher pressure
34-
.crossover(SbxCrossover::new(15.0)) // More exploration
33+
.selection(TournamentSelection::new(5)) // Higher pressure
34+
.crossover(SbxCrossover::new(15.0)) // More exploration
3535
.mutation(PolynomialMutation::new(20.0).with_probability(0.1))
3636
.fitness(fitness)
3737
.max_generations(500)

examples/sphere_optimization.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
//! that's easy to optimize but useful for verifying the GA is working correctly.
88
99
use fugue_evo::prelude::*;
10-
use rand::SeedableRng;
1110
use rand::rngs::StdRng;
11+
use rand::SeedableRng;
1212

1313
fn main() -> Result<(), Box<dyn std::error::Error>> {
1414
println!("=== Sphere Function Optimization ===\n");

examples/symbolic_regression.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
//! a target function from input-output examples.
88
99
use fugue_evo::prelude::*;
10-
use rand::SeedableRng;
1110
use rand::rngs::StdRng;
1211
use rand::Rng;
12+
use rand::SeedableRng;
1313

1414
fn main() -> Result<(), Box<dyn std::error::Error>> {
1515
println!("=== Symbolic Regression with GP ===\n");
@@ -20,7 +20,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
2020
let training_data: Vec<(f64, f64)> = (-5..=5)
2121
.map(|i| {
2222
let x = i as f64;
23-
let y = x * x + 2.0 * x + 1.0; // Target function
23+
let y = x * x + 2.0 * x + 1.0; // Target function
2424
(x, y)
2525
})
2626
.collect();
@@ -77,7 +77,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
7777

7878
let mut child = if rng.gen::<f64>() < crossover_rate {
7979
// Subtree crossover
80-
subtree_crossover(&parent1, &parent2, &mut rng)
80+
subtree_crossover(parent1, parent2, &mut rng)
8181
} else {
8282
parent1.clone()
8383
};
@@ -123,12 +123,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
123123

124124
// Test the discovered function
125125
println!("\nComparison on test points:");
126-
println!("{:>6} {:>12} {:>12} {:>12}", "x", "Target", "Predicted", "Error");
126+
println!(
127+
"{:>6} {:>12} {:>12} {:>12}",
128+
"x", "Target", "Predicted", "Error"
129+
);
127130
for x in [-3.5, -1.0, 0.0, 1.0, 2.5] {
128131
let target = x * x + 2.0 * x + 1.0;
129132
let predicted = best.0.evaluate(&[x]);
130133
let error = (target - predicted).abs();
131-
println!("{:6.1} {:12.4} {:12.4} {:12.6}", x, target, predicted, error);
134+
println!(
135+
"{:6.1} {:12.4} {:12.4} {:12.6}",
136+
x, target, predicted, error
137+
);
132138
}
133139

134140
Ok(())
@@ -149,7 +155,10 @@ fn tournament_select<'a>(
149155
) -> &'a TreeGenome<ArithmeticTerminal, ArithmeticFunction> {
150156
use rand::seq::SliceRandom;
151157
let contestants: Vec<_> = pop.choose_multiple(rng, size).collect();
152-
let best = contestants.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap()).unwrap();
158+
let best = contestants
159+
.iter()
160+
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
161+
.unwrap();
153162
&best.0
154163
}
155164

@@ -177,10 +186,7 @@ fn subtree_crossover(
177186
}
178187
}
179188

180-
fn point_mutate(
181-
tree: &mut TreeGenome<ArithmeticTerminal, ArithmeticFunction>,
182-
rng: &mut StdRng,
183-
) {
189+
fn point_mutate(tree: &mut TreeGenome<ArithmeticTerminal, ArithmeticFunction>, rng: &mut StdRng) {
184190
let positions = tree.root.positions();
185191
if positions.is_empty() {
186192
return;
@@ -222,7 +228,7 @@ impl SymbolicRegressionFitness {
222228
if predicted.is_finite() {
223229
(y - predicted).powi(2)
224230
} else {
225-
1e6 // Penalty for invalid values
231+
1e6 // Penalty for invalid values
226232
}
227233
})
228234
.sum::<f64>()

0 commit comments

Comments
 (0)