48static std::string
makeFrameName(
const std::string& baseName,
size_t iter) {
49 std::ostringstream oss;
50 oss << baseName <<
"_iter_" << iter <<
".dat";
64 const std::vector<opt::GA::Individual>& pop) {
66 std::string dir =
"./ga_frames";
68 std::filesystem::create_directories(dir);
69 }
catch (
const std::exception&) {}
71 std::string filename = dir +
"/" +
makeFrameName(baseName, iter);
72 std::ofstream out(filename);
74 std::cerr <<
"Warning: Could not create file " << filename << std::endl;
77 for (
const auto& ind : pop) {
78 if (ind.genome.size() >= 2) {
79 out << ind.genome[0] <<
" " << ind.genome[1] <<
"\n";
86 const std::vector<opt::GA::Individual>& pop) {
88 std::string dir =
"./ga_frames";
90 std::filesystem::create_directories(dir);
91 }
catch (
const std::exception&) {}
93 std::string filename = dir +
"/" +
makeFrameName(baseName, iter);
94 std::ofstream out(filename);
96 std::cerr <<
"Warning: Could not create file " << filename << std::endl;
99 for (
const auto& ind : pop) {
100 if (ind.genome.size() >= 3) {
101 out << ind.genome[0] <<
" " << ind.genome[1] <<
" " << ind.genome[2] <<
"\n";
110 std::cout <<
"Optimization Problem: Minimize Sphere Function in 2D" << std::endl;
111 std::cout <<
"Search Space: [-10, 10] per dimension" << std::endl;
112 std::cout <<
"Running optimizer..." << std::endl;
116 for (
auto val : coords) sum += val * val;
122 ga.
setMode(opt::OptimizationMode::MINIMIZE);
125 if (iteration == 0 || iteration % 10 == 0) {
126 std::cout <<
"[Sphere Test | Step " << std::setw(3) << iteration <<
"] "
127 <<
"Best Value: " << std::scientific << std::setprecision(5)
128 << current_best.
value << std::defaultfloat << std::endl;
132 auto start = std::chrono::high_resolution_clock::now();
134 auto end = std::chrono::high_resolution_clock::now();
135 std::chrono::duration<double, std::milli> duration = end - start;
137 std::cout <<
"\nOptimization Completed in " << duration.count() <<
" ms." << std::endl;
138 std::cout <<
"Best Value Found: " << std::fixed << std::setprecision(10) << best_sol.
value << std::endl;
139 std::cout <<
"Best Position: [ ";
140 for (
auto val : best_sol.
params) {
141 std::cout << std::fixed << std::setprecision(5) << val <<
" ";
143 std::cout <<
"]" << std::endl;
147 std::cout <<
"\n-------------------------------------------" << std::endl;
148 std::cout <<
"TEST 2: Boundary Constraint Test (Linear Plane)" << std::endl;
149 std::cout <<
"Objective: f(x,y) = x + y (Minimization)" << std::endl;
150 std::cout <<
"Search Space: [-10, 10] per dimension" << std::endl;
151 std::cout <<
"Expected Result: -20.0 at [-10.0, -10.0]" << std::endl;
152 std::cout <<
"Running optimizer..." << std::endl;
156 for (
auto val : coords) sum += val;
162 ga.
setMode(opt::OptimizationMode::MINIMIZE);
165 if (iteration % 20 == 0) {
166 std::cout <<
"[Boundary Test | Step " << std::setw(3) << iteration <<
"] "
167 <<
"Val: " << std::fixed << std::setprecision(4) << current_best.
value << std::endl;
171 auto start = std::chrono::high_resolution_clock::now();
173 auto end = std::chrono::high_resolution_clock::now();
174 std::chrono::duration<double, std::milli> duration = end - start;
176 std::cout <<
"Optimization Completed in " << duration.count() <<
" ms." << std::endl;
177 std::cout <<
"Best Value Found: " << std::fixed << std::setprecision(5) << best_sol.
value << std::endl;
178 std::cout <<
"Best Position: [ ";
179 for (
auto val : best_sol.
params) {
180 std::cout << std::fixed << std::setprecision(5) << val <<
" ";
182 std::cout <<
"]" << std::endl;
184 if (std::abs(best_sol.
value - (-20.0)) < 1e-3) {
185 std::cout <<
">> SUCCESS: Boundary minimum found correctly!" << std::endl;
187 std::cout <<
">> WARNING: Did not reach the exact boundary." << std::endl;
192 std::cout <<
"\n-------------------------------------------" << std::endl;
193 std::cout <<
"TEST 3: High-Dimensional Stress Test (Rastrigin Function)" << std::endl;
194 std::cout <<
"Dimension: " <<
dim <<
"D" << std::endl;
195 std::cout <<
"Search Space: [-5.12, 5.12] per dimension" << std::endl;
196 std::cout <<
"Goal: Find global minimum 0.0 (avoiding local traps)" << std::endl;
201 double pi = 3.14159265358979323846;
202 for (
auto x : coords) sum += (x * x) - (A * std::cos(2.0 * pi * x));
203 return A *
dim + sum;
222 local_ga.
setMode(opt::OptimizationMode::MINIMIZE);
226 std::cout <<
"[Rastrigin " << i <<
"] Best: "
227 << std::scientific << std::setprecision(4) << sol.
value
228 << std::defaultfloat << std::endl;
232 std::cout <<
"Running optimizer (this might take longer)..." << std::endl;
234 auto start = std::chrono::high_resolution_clock::now();
236 auto end = std::chrono::high_resolution_clock::now();
237 std::chrono::duration<double, std::milli> duration = end - start;
239 std::cout <<
"Optimization Completed in " << duration.count() <<
" ms." << std::endl;
240 std::cout <<
"Best Value Found: " << std::fixed << std::setprecision(5) << best_sol.
value << std::endl;
242 if (best_sol.
value < 1e-2) {
243 std::cout <<
">> SUCCESS: Global minimum found!" << std::endl;
244 }
else if (best_sol.
value < 5.0) {
245 std::cout <<
">> ACCEPTABLE: Found a good local minimum, but not global." << std::endl;
247 std::cout <<
">> FAIL: Stuck in a high local minimum." << std::endl;
252 std::cout <<
"===========================================" << std::endl;
253 std::cout <<
" Visual GA Benchmark (2D Animation)" << std::endl;
254 std::cout <<
"===========================================" << std::endl;
270 double pi = 3.14159265358979323846;
271 for (
double val : x) sum += val*val - A*std::cos(2*pi*val);
276 ga.
setBounds({-5.12, -5.12}, {5.12, 5.12});
277 ga.
setMode(opt::OptimizationMode::MINIMIZE);
279 std::string baseName =
"ga_vis";
280 std::string gridFile =
"ga_grid.dat";
282 std::cout <<
"Generating background grid (heatmap)..." << std::endl;
287 std::cout <<
"Saved frame " << gen <<
"/" << config.
max_generations <<
"\r" << std::flush;
290 std::cout <<
"Running optimization..." << std::endl;
292 std::cout <<
"\nOptimization finished." << std::endl;
294 std::cout <<
"Launching Gnuplot animation..." << std::endl;
300 std::cout <<
"===========================================" << std::endl;
301 std::cout <<
" Visual GA Benchmark (3D Animation)" << std::endl;
302 std::cout <<
"===========================================" << std::endl;
318 double pi = 3.14159265358979323846;
319 for (
double val : x) sum += val * val - A * std::cos(2 * pi * val);
320 return 3.0 * A + sum;
323 double min_b = -5.12;
327 ga.
setBounds({min_b, min_b, min_b}, {max_b, max_b, max_b});
328 ga.
setMode(opt::OptimizationMode::MINIMIZE);
330 std::string baseName =
"ga_vis_3d";
331 std::string slicesFile =
"ga_slices_3d.dat";
333 std::cout <<
"Generating 3D function slices (walls)..." << std::endl;
339 std::cout <<
"Generating Frame " << gen <<
"/" << config.
max_generations <<
"\r" << std::flush;
343 std::cout <<
"Running 3D optimization..." << std::endl;
345 std::cout <<
"\nOptimization finished." << std::endl;
347 std::cout <<
"Launching Gnuplot 3D animation..." << std::endl;
349 "GA 3D Rastrigin", min_b, max_b);
353 std::cout <<
"=========================================" << std::endl;
354 std::cout <<
" Genetic Algorithm (GA) Benchmark" << std::endl;
355 std::cout <<
"=========================================" << std::endl;
380 }
catch (
const std::exception& e) {
381 std::cerr <<
"Optimization failed: " << e.what() << std::endl;
Benchmarking framework for Monte Carlo integration algorithms.
Genetic Algorithm optimizer.
void setMode(OptimizationMode mode) override
Set optimization mode (minimize or maximize).
void setBounds(const Coordinates &lower, const Coordinates &upper) override
Set lower/upper bounds of the search hyper-rectangle.
Solution optimize() override
Run GA for max_generations.
void setCallback(StepCallback cb) override
Register a callback invoked after each generation.
void setObjectiveFunction(ObjectiveFunction func) override
Set the objective function to optimize.
const std::vector< Individual > & getPopulation() const
Access the current population.
void runBoundaryTest(opt::GA &ga, const opt::Coordinates &lower, const opt::Coordinates &upper)
void runOptimizationBenchmarksGA()
static std::string makeFrameName(const std::string &baseName, size_t iter)
Generate frame filename for GA population evolution.
void runVisualGA3DBenchmark()
void runVisualGABenchmark()
void runRastriginTest(opt::GA &, int dim)
void runSphereTest(opt::GA &ga, const opt::Coordinates &lower, const opt::Coordinates &upper)
static void savePopulationFrame3D(const std::string &baseName, size_t iter, const std::vector< opt::GA::Individual > &pop)
static void savePopulationFrame2D(const std::string &baseName, size_t iter, const std::vector< opt::GA::Individual > &pop)
Save population snapshot for 2D visualization.
constexpr int dim
Default dimensionality for integration.
std::function< Real(const Coordinates &)> ObjectiveFunction
Objective function signature.
std::vector< Real > Coordinates
A point in the N-dimensional search space.
double Real
Scalar precision used across optimizers.
void createPSOAnimationScript3D(const std::string &scriptName, const std::string &slicesFile, const std::string &swarmBasename, size_t max_iter, const std::string &title, double min_bound, double max_bound)
void saveFunctionGrid(const std::string &filename, const Func &func, double x_min, double x_max, double y_min, double y_max, int resolution=100)
void createPSOAnimationScript(const std::string &scriptName, const std::string &gridFile, const std::string &swarmBasename, size_t max_iter, const std::string &title)
void saveFunctionSlices3D(const std::string &filename, const Func &func, double min, double max, int resolution=50)
Configuration parameters for GA.
size_t elitism_count
Number of top individuals copied unchanged to next generation.
size_t tournament_k
Tournament size for selection (k >= 2).
Real mutation_rate
Per-gene mutation probability.
size_t population_size
Size of the population.
Real crossover_rate
Probability of performing crossover in reproduction.
Real mutation_sigma
Mutation magnitude (scaled by coordinate span).
size_t max_generations
Number of generations to evolve.
Represents a candidate solution in the search space.
Coordinates params
Parameter vector (coordinates in the search space).
Real value
Evaluated objective value for params.