|
SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
|
Genetic Algorithm optimizer for global parameter estimation. More...
#include <GA/GA.h>

Public Member Functions | |
| CGA () | |
| Default constructor. | |
| virtual | ~CGA () |
| Destructor. | |
| CGA (const CGA &C) | |
| Copy constructor. | |
| CGA & | operator= (const CGA &C) |
| Assignment operator. | |
| CGA (std::string filename, const T &model) | |
| Constructor from configuration file and model. | |
| CGA (T *model) | |
| Constructor from model pointer. | |
| void | initialize () |
| Initialize GA structures and allocate memory. | |
| double | getfromoutput (std::string filename) |
| Read best solution from previous output file. | |
| void | getinifromoutput (std::string filename) |
| Initialize population from previous output file. | |
| void | getinitialpop (std::string filename) |
| Read initial population from file. | |
| int | optimize () |
| Main optimization loop. | |
| bool | SetProperty (const std::string &varname, const std::string &value) |
| Set GA property from string key-value pair. | |
| bool | SetProperties (const std::map< std::string, std::string > &arguments) |
| Set multiple GA properties from map. | |
| void | InitiatePopulation () |
| Create initial population. | |
| void | SetRunTimeWindow (ProgressReporter *_rtw) |
| Set progress window for GUI updates. | |
Public Attributes | |
| double | sumfitness {} |
| Sum of all fitness values in current population. | |
| double | MaxFitness |
| Maximum fitness value in current population. | |
| GA_Tweaking_parameters | GA_params |
| GA algorithm configuration parameters. | |
| _filenames | filenames |
| File paths for GA input/output. | |
| std::vector< double > | calc_output_percentiles |
| Percentiles to calculate for output distributions. | |
| std::vector< std::vector< double > > | initial_pop |
| Initial population loaded from file. | |
| std::vector< double > | final_params |
| Final optimized parameter values. | |
| std::vector< int > | params |
| Parameter indices being optimized. | |
| std::vector< int > | loged |
| Flags indicating if parameters are log-transformed. | |
| std::vector< int > | to_ts |
| Time series index for each parameter (if applicable). | |
| std::vector< double > | fixedinputvale |
| Fixed values for non-optimized parameters. | |
| std::vector< double > | minval |
| Lower bounds for each parameter. | |
| std::vector< double > | maxval |
| Upper bounds for each parameter. | |
| std::vector< bool > | apply_to_all |
| Flags indicating if parameter applies to all entities. | |
| std::vector< std::vector< int > > | outcompare |
| Output comparison indices (legacy, may be unused). | |
| std::vector< CIndividual > | Ind |
| Current population of individuals. | |
| std::vector< CIndividual > | Ind_old |
| Previous generation's population. | |
| std::vector< std::string > | paramname |
| Names of parameters being optimized. | |
| std::vector< T > | Models |
| Copies of model for parallel fitness evaluation. | |
| T | Model_out |
| Output model configured with best parameters. | |
| T * | Model = nullptr |
| Pointer to the model being optimized. | |
| std::string | last_error |
| Last error message from GA execution. | |
Private Member Functions | |
| void | Setminmax (int a, double minrange, double maxrange, int prec) |
| Set parameter bounds and precision. | |
| void | fitnessdistini () |
| Initialize fitness distribution for selection. | |
| void | crossover () |
| Perform crossover operation on population. | |
| double | avgfitness () |
| Calculate average fitness of population. | |
| void | mutate (double mu) |
| Apply mutation to population. | |
| void | assignfitnesses () |
| Evaluate fitness for all individuals in population. | |
| int | maxfitness () |
| Find index of individual with maximum fitness. | |
| double | variancefitness () |
| Calculate variance of population fitness. | |
| double | stdfitness () |
| Calculate standard deviation of population fitness. | |
| double | avg_actual_fitness () |
| Calculate average of actual (untransformed) fitness values. | |
| void | write_to_detailed_GA (std::string s) |
| Write detailed GA information to file. | |
| void | setnumpop (int n) |
| Set population size. | |
| double | avg_inv_actual_fitness () |
| Calculate average of inverse actual fitness. | |
| int | optimize (int nGens, char DefOutPutFileName[]) |
| Optimize for specified number of generations. | |
| void | setnparams (int n) |
| Set number of parameters. | |
| void | assignfixedvalues () |
| Assign fixed values to non-optimized parameters. | |
| void | assignrank () |
| Assign ranks to individuals based on fitness. | |
| void | assignfitness_rank (double N) |
| Assign fitness using rank-based scheme. | |
| void | shake () |
| Apply shake/perturbation to population. | |
| void | crossoverRC () |
| Real-coded crossover operation. | |
| void | getfromfile (char filename[]) |
| Read population from file. | |
| void | fillfitdist () |
| Fill fitness distribution for roulette wheel selection. | |
| double | assignfitnesses (std::vector< double > inp) |
| Evaluate fitness for specific parameter vector. | |
| double | Gradient_Descent (std::vector< double > inp) |
| Perform gradient descent local search. | |
| int | getparamno (int i, int ts) |
| Get parameter index for variable and time series. | |
| int | get_act_paramno (int i) |
| Get active parameter number. | |
| int | get_time_series (int i) |
| Get time series index for parameter. | |
| double | evaluateforward () |
| Evaluate model forward (compute predictions). | |
| double | evaluateforward_mixed (std::vector< double > v) |
| Evaluate model with mixed parameters. | |
Private Attributes | |
| int | current_generation = 0 |
| Current generation counter. | |
| GADistribution | fitdist |
| Fitness distribution for parent selection. | |
| int | numberOfThreads {} |
| Number of threads for parallel fitness evaluation. | |
| ProgressReporter * | rtw = nullptr |
| Pointer to progress window for GUI updates. | |
Genetic Algorithm optimizer for global parameter estimation.
The CGA class implements a sophisticated genetic algorithm with both binary and real-coded representations for solving complex optimization problems in sediment source fingerprinting.
Genetic Algorithms are population-based metaheuristic optimization methods inspired by natural evolution:
GA provides global optimization for source apportionment when:
GA finds parameter values that minimize error between predicted and observed tracer concentrations, subject to constraints (e.g., contributions sum to 100%).
Fitness function (for minimization):
Selection probability (fitness proportionate):
Rank-based fitness:
where N is selection pressure parameter (typically 1.5-2.0)
| T | Model class type (e.g., SourceSinkData) that provides:
|
Example usage:
| CGA< T >::CGA | ( | ) |
Default constructor.
Creates uninitialized GA object. Must call other initialization methods before running.
Definition at line 38 of file GA.hpp.
References fitdist, GA_params, Ind, Ind_old, MaxFitness, and numberOfThreads.
Referenced by CGA(), and operator=().
Copy constructor.
| C | The CGA object to copy from |
Creates deep copy including population, settings, and model copies.
Definition at line 276 of file GA.hpp.
References CGA(), filenames, fitdist, GA_params, Ind, Ind_old, loged, MaxFitness, GA_Tweaking_parameters::maxpop, paramname, and params.
| CGA< T >::CGA | ( | std::string | filename, |
| const T & | model ) |
Constructor from configuration file and model.
| filename | Path to GA configuration file |
| model | Reference to model to optimize |
Initializes GA from configuration file containing parameters, ranges, and algorithm settings.
| CGA< T >::CGA | ( | T * | model | ) |
Constructor from model pointer.
| model | Pointer to model to optimize |
Preferred constructor linking GA to specific model instance.
Definition at line 128 of file GA.hpp.
References apply_to_all, filenames, fitdist, GA_params, Ind, Ind_old, loged, lognormal, MaxFitness, maxval, minval, Model, numberOfThreads, paramname, params, and Setminmax().
|
private |
Assign fitness using rank-based scheme.
| N | Selection pressure parameter |
Calculates fitness from rank using linear ranking formula: fitness(rank) = N - 2(N-1)(rank-1)/(pop_size-1)
Reduces selection pressure compared to raw fitness, preventing premature convergence.
| N | Selection pressure (typically 1.5-2.0) |
Definition at line 987 of file GA.hpp.
References assignrank(), GA_params, and Ind.
Referenced by assignfitnesses().
|
private |
Evaluate fitness for all individuals in population.
Calculates objective function value for each individual. Can be parallelized across multiple threads.
Definition at line 350 of file GA.hpp.
References assignfitness_rank(), counter, filenames, GA_params, Ind, loged, maxfitness(), Model_out, Models, numberOfThreads, OpenGAFile(), rtw, sumfitness, and x.
Referenced by evaluateforward(), getfromoutput(), and optimize().
|
private |
Evaluate fitness for specific parameter vector.
| inp | Parameter values to evaluate |
Single-point fitness evaluation (not on entire population). Used for local search refinement.
|
private |
Assign fixed values to non-optimized parameters.
For each individual, sets non-variable parameters to their fixed values from fixedinputvale vector.
|
private |
Assign ranks to individuals based on fitness.
Sorts population by fitness and assigns ranks (1 = best). Used for rank-based selection methods.
Definition at line 972 of file GA.hpp.
References GA_params, and Ind.
Referenced by assignfitness_rank().
|
private |
|
private |
Calculate average of inverse actual fitness.
Used for certain fitness scaling schemes where lower raw values are better (minimization).
Definition at line 961 of file GA.hpp.
References GA_params, and Ind.
Referenced by stdfitness().
|
private |
Calculate average fitness of population.
Used for monitoring convergence and population quality.
Definition at line 578 of file GA.hpp.
References GA_params, and Ind.
Referenced by variancefitness().
|
private |
Perform crossover operation on population.
Applies crossover operator to selected parent pairs to generate offspring. Type of crossover determined by GA_params.cross_over_type.
Definition at line 492 of file GA.hpp.
References cross(), cross2p(), fitdist, GA_params, Ind, Ind_old, maxfitness(), and x.
Referenced by optimize().
|
private |
Real-coded crossover operation.
Performs crossover for real-valued (continuous) representation using arithmetic or blend crossover operators.
Definition at line 521 of file GA.hpp.
References cross_RC_L(), fitdist, GA_params, GetRndUnif(), Ind, Ind_old, maxfitness(), and x.
Referenced by optimize().
|
private |
|
private |
Evaluate model with mixed parameters.
| v | Parameter vector (subset or transformed) |
Variation of forward evaluation for special parameter handling.
|
private |
Fill fitness distribution for roulette wheel selection.
Constructs cumulative distribution function (CDF) from individual fitness values for probabilistic parent selection.
Definition at line 998 of file GA.hpp.
References fitdist, GA_params, and Ind.
Referenced by optimize().
|
private |
Initialize fitness distribution for selection.
Sets up cumulative fitness distribution (CDF) used in roulette wheel selection for choosing parents.
|
private |
Get active parameter number.
| i | Parameter index |
|
private |
|
private |
Read population from file.
| filename | Path to population file |
Loads population state from checkpoint or previous run.
| double CGA< T >::getfromoutput | ( | std::string | filename | ) |
Read best solution from previous output file.
| filename | Path to GA output file |
Extracts best individual from previous run for warm-starting or comparison.
Definition at line 839 of file GA.hpp.
References assignfitnesses(), final_params, GA_params, and write_to_detailed_GA().
| void CGA< T >::getinifromoutput | ( | std::string | filename | ) |
Initialize population from previous output file.
| filename | Path to output file containing population data |
Reads population from GA output file format. Extracts parameter values from previous run's final generation to use as starting population.
Definition at line 1038 of file GA.hpp.
References GA_params, initial_pop, and loged.
Referenced by initialize().
| void CGA< T >::getinitialpop | ( | std::string | filename | ) |
Read initial population from file.
| filename | Path to population file |
Loads pre-specified starting population from file. Used when GA_params.readfromgafile is true.
Definition at line 1064 of file GA.hpp.
References initial_pop, and x.
|
private |
Get parameter index for variable and time series.
| i | Variable index |
| ts | Time series index |
Definition at line 866 of file GA.hpp.
References apply_to_all.
|
private |
Perform gradient descent local search.
| inp | Starting parameter values |
Applies gradient-based refinement to individual for hybrid GA. Accelerates convergence in neighborhood of optimum.
| void CGA< T >::initialize | ( | ) |
Initialize GA structures and allocate memory.
Sets up:
Definition at line 318 of file GA.hpp.
References filenames, GA_params, getinifromoutput(), Ind, initial_pop, and loged.
Referenced by optimize().
| void CGA< T >::InitiatePopulation | ( | ) |
Create initial population.
Generates starting population using one of:
Definition at line 185 of file GA.hpp.
References apply_to_all, fitdist, GA_params, Ind, Ind_old, loged, lognormal, MaxFitness, maxval, minval, Model, paramname, params, and Setminmax().
|
private |
Find index of individual with maximum fitness.
Identifies elite individual for preservation or output.
Definition at line 914 of file GA.hpp.
References GA_params, and Ind.
Referenced by assignfitnesses(), crossover(), crossoverRC(), and optimize().
|
private |
Apply mutation to population.
| mu | Mutation probability per gene |
Randomly perturbs parameters of individuals with probability mu. Maintains genetic diversity and enables exploration.
| mu | Probability of mutating each parameter (0-1) |
Definition at line 906 of file GA.hpp.
References GA_params, Ind, and mutate().
Referenced by mutate(), and optimize().
| int CGA< T >::optimize | ( | ) |
Main optimization loop.
Executes complete GA workflow:
Definition at line 596 of file GA.hpp.
References assignfitnesses(), crossover(), crossoverRC(), current_generation, filenames, fillfitdist(), final_params, GA_params, GAFitMeasure(), Ind, initialize(), loged, MaxFitness, maxfitness(), Model, Models, mutate(), OpenGAFile(), paramname, rtw, shake(), write_to_detailed_GA(), and x.
|
private |
Optimize for specified number of generations.
| nGens | Number of generations to evolve |
| DefOutPutFileName | Default output filename |
Alternative optimize interface with explicit generation count and output file specification.
|
private |
Set parameter bounds and precision.
| a | Parameter index |
| minrange | Lower bound |
| maxrange | Upper bound |
| prec | Precision/discretization level (for binary encoding) |
Configures search space boundaries for individual parameter.
Definition at line 338 of file GA.hpp.
References GA_params, and Ind.
Referenced by CGA(), and InitiatePopulation().
|
private |
|
private |
Set population size.
| n | Number of individuals |
Allocates memory for population of size n.
Definition at line 249 of file GA.hpp.
References fitdist, GA_params, Ind, Ind_old, CIndividual::maxrange, CIndividual::minrange, and CIndividual::precision.
Referenced by SetProperty().
| bool CGA< T >::SetProperties | ( | const std::map< std::string, std::string > & | arguments | ) |
Set multiple GA properties from map.
| arguments | Map of property names to values |
Batch property setting for configuration management.
Definition at line 570 of file GA.hpp.
References SetProperty().
| bool CGA< T >::SetProperty | ( | const std::string & | varname, |
| const std::string & | value ) |
Set GA property from string key-value pair.
| varname | Property name (e.g., "population_size", "mutation_rate") |
| value | Property value as string |
Allows configuration from text files or user input. Supports all fields in GA_params structure.
Definition at line 545 of file GA.hpp.
References filenames, GA_params, last_error, numberOfThreads, and setnumpop().
Referenced by SetProperties().
|
inline |
Set progress window for GUI updates.
| _rtw | Pointer to ProgressReporter object |
Links GA to progress dialog for real-time status updates including:
Definition at line 689 of file GA.h.
References rtw.
|
private |
Apply shake/perturbation to population.
Randomly perturbs all individuals to escape local optima or restore diversity. Perturbation magnitude controlled by GA_params.shakescale.
Useful when population has converged but not to optimum.
Definition at line 898 of file GA.hpp.
References GA_params, Ind, and shake().
Referenced by optimize(), and shake().
|
private |
Calculate standard deviation of population fitness.
Square root of fitness variance. Easier to interpret as it's in same units as fitness.
Definition at line 940 of file GA.hpp.
References avg_inv_actual_fitness(), GA_params, and Ind.
|
private |
Calculate variance of population fitness.
Measure of population diversity. Low variance indicates convergence (all individuals similar). High variance indicates diverse population.
Definition at line 929 of file GA.hpp.
References avgfitness(), GA_params, and Ind.
|
private |
Write detailed GA information to file.
| s | String to append to detailed log |
Logs generation-by-generation statistics for analysis:
Definition at line 587 of file GA.hpp.
References filenames, and OpenGAFile().
Referenced by getfromoutput(), and optimize().
| std::vector<bool> CGA< T >::apply_to_all |
Flags indicating if parameter applies to all entities.
Used for shared parameters across multiple sources or observations.
Definition at line 463 of file GA.h.
Referenced by CGA(), getparamno(), and InitiatePopulation().
| std::vector<double> CGA< T >::calc_output_percentiles |
|
private |
Current generation counter.
Tracks which generation is currently being evolved. Used for output, termination, and adaptive operators.
Definition at line 982 of file GA.h.
Referenced by optimize().
| _filenames CGA< T >::filenames |
File paths for GA input/output.
Configuration structure containing paths for initialization files, results output, and checkpoint files.
Definition at line 385 of file GA.h.
Referenced by CGA(), CGA(), assignfitnesses(), evaluateforward(), initialize(), operator=(), optimize(), SetProperty(), and write_to_detailed_GA().
| std::vector<double> CGA< T >::final_params |
Final optimized parameter values.
Best solution found by GA (parameter vector of best individual from final generation).
Definition at line 410 of file GA.h.
Referenced by getfromoutput(), and optimize().
|
private |
Fitness distribution for parent selection.
Cumulative distribution function used in roulette wheel selection.
Definition at line 989 of file GA.h.
Referenced by CGA(), CGA(), CGA(), crossover(), crossoverRC(), fillfitdist(), InitiatePopulation(), operator=(), and setnumpop().
| std::vector<double> CGA< T >::fixedinputvale |
| GA_Tweaking_parameters CGA< T >::GA_params |
GA algorithm configuration parameters.
All tuning parameters controlling GA behavior. Modify before calling initialize() or optimize().
Definition at line 377 of file GA.h.
Referenced by CGA(), CGA(), CGA(), assignfitness_rank(), assignfitnesses(), assignrank(), avg_actual_fitness(), avg_inv_actual_fitness(), avgfitness(), crossover(), crossoverRC(), evaluateforward(), fillfitdist(), get_time_series(), getfromoutput(), getinifromoutput(), initialize(), InitiatePopulation(), maxfitness(), mutate(), operator=(), optimize(), Setminmax(), setnparams(), setnumpop(), SetProperty(), shake(), stdfitness(), and variancefitness().
| std::vector<CIndividual> CGA< T >::Ind |
Current population of individuals.
Active population of candidate solutions being evolved. Size: GA_params.maxpop
Definition at line 478 of file GA.h.
Referenced by CGA(), CGA(), CGA(), assignfitness_rank(), assignfitnesses(), assignrank(), avg_actual_fitness(), avg_inv_actual_fitness(), avgfitness(), crossover(), crossoverRC(), fillfitdist(), initialize(), InitiatePopulation(), maxfitness(), mutate(), operator=(), optimize(), Setminmax(), setnparams(), setnumpop(), shake(), stdfitness(), and variancefitness().
| std::vector<CIndividual> CGA< T >::Ind_old |
Previous generation's population.
Backup of population from previous generation for comparison and elitism strategies.
Definition at line 486 of file GA.h.
Referenced by CGA(), CGA(), CGA(), crossover(), crossoverRC(), InitiatePopulation(), operator=(), setnparams(), and setnumpop().
| std::vector<std::vector<double> > CGA< T >::initial_pop |
Initial population loaded from file.
Parameter values for starting population when readfromgafile is true. Structure: initial_pop[individual][parameter]
Definition at line 402 of file GA.h.
Referenced by getinifromoutput(), getinitialpop(), and initialize().
| std::string CGA< T >::last_error |
Last error message from GA execution.
If GA fails or encounters issues, error description stored here.
Definition at line 676 of file GA.h.
Referenced by SetProperty().
| std::vector<int> CGA< T >::loged |
Flags indicating if parameters are log-transformed.
If loged[i] is true, parameter i is optimized in log-space. Useful for parameters spanning multiple orders of magnitude.
Definition at line 426 of file GA.h.
Referenced by CGA(), CGA(), assignfitnesses(), getinifromoutput(), initialize(), InitiatePopulation(), operator=(), and optimize().
| double CGA< T >::MaxFitness |
Maximum fitness value in current population.
Tracks the best individual's fitness for convergence monitoring and termination criteria.
Definition at line 369 of file GA.h.
Referenced by CGA(), CGA(), CGA(), InitiatePopulation(), operator=(), and optimize().
| std::vector<double> CGA< T >::maxval |
Upper bounds for each parameter.
Maximum allowable values defining search space boundaries. For source contributions: typically 1.0 or 100.0
Definition at line 456 of file GA.h.
Referenced by CGA(), and InitiatePopulation().
| std::vector<double> CGA< T >::minval |
Lower bounds for each parameter.
Minimum allowable values defining search space boundaries. For source contributions: typically 0.0
Definition at line 448 of file GA.h.
Referenced by CGA(), and InitiatePopulation().
| T* CGA< T >::Model = nullptr |
Pointer to the model being optimized.
Reference to model that provides fitness evaluation.
Definition at line 516 of file GA.h.
Referenced by CGA(), InitiatePopulation(), and optimize().
| T CGA< T >::Model_out |
Output model configured with best parameters.
Model instance set to optimal parameter values after optimization.
Definition at line 509 of file GA.h.
Referenced by assignfitnesses().
| std::vector<T> CGA< T >::Models |
Copies of model for parallel fitness evaluation.
Each individual gets its own model copy for thread-safe evaluation. Size: GA_params.maxpop
Definition at line 502 of file GA.h.
Referenced by assignfitnesses(), and optimize().
|
private |
Number of threads for parallel fitness evaluation.
Controls parallelization of fitness calculations across population.
Definition at line 996 of file GA.h.
Referenced by CGA(), CGA(), assignfitnesses(), and SetProperty().
| std::vector<std::vector<int> > CGA< T >::outcompare |
| std::vector<std::string> CGA< T >::paramname |
Names of parameters being optimized.
Human-readable labels for each parameter (e.g., "Agricultural", "Forest", "Urban") used in output files and visualization.
Definition at line 494 of file GA.h.
Referenced by CGA(), CGA(), InitiatePopulation(), operator=(), and optimize().
| std::vector<int> CGA< T >::params |
Parameter indices being optimized.
Maps GA parameter space to model parameter space. Allows optimizing subset of parameters while fixing others.
Definition at line 418 of file GA.h.
Referenced by CGA(), CGA(), evaluateforward(), InitiatePopulation(), and operator=().
|
private |
Pointer to progress window for GUI updates.
If not nullptr, GA updates progress bar and displays current generation, best fitness, convergence plot, etc.
Definition at line 1005 of file GA.h.
Referenced by assignfitnesses(), optimize(), and SetRunTimeWindow().
| double CGA< T >::sumfitness {} |
Sum of all fitness values in current population.
Used for fitness proportionate selection (roulette wheel). Updated after each fitness evaluation.
Definition at line 361 of file GA.h.
Referenced by assignfitnesses().
| std::vector<int> CGA< T >::to_ts |