18#include <QCoreApplication>
24using GAFile = std::unique_ptr<FILE, int (*)(FILE*)>;
27 return GAFile(fopen(path.c_str(),
mode), &fclose);
32inline double GAFitMeasure(
const std::vector<double>& fit_measures,
size_t index)
34 return index < fit_measures.size() ? fit_measures[index] : std::nan(
"");
55 ifstream file(filename);
59 GA_params.RCGA =
false;
62 filenames.pathname = Model->OutputPath();
64 while (file.eof() ==
false)
66 s = aquiutils::getline(file);
68 {
if (s[0] ==
"maxpop") GA_params.maxpop = atoi(s[1].c_str());
69 if (s[0] ==
"ngen") GA_params.nGen = atoi(s[1].c_str());
70 if (s[0] ==
"pcross") GA_params.pcross = atof(s[1].c_str());
71 if (s[0] ==
"pmute") GA_params.pmute = atof(s[1].c_str());
72 if (s[0] ==
"shakescale") GA_params.shakescale = atof(s[1].c_str());
73 if (s[0] ==
"shakescalered") GA_params.shakescalered = atof(s[1].c_str());
74 if (s[0] ==
"outputfile") filenames.outputfilename = s[1];
75 if (s[0] ==
"getfromfilename") filenames.getfromfilename = s[1].c_str();
76 if (s[0] ==
"initial_population") filenames.initialpopfilemame = s[1];
77 if (s[0] ==
"numthreads") numberOfThreads = atoi(s[1].c_str());
82 for (
int i=0; i<Model->Parameters().size(); i++)
86 if (Model->Parameters()[i]->GetPriorDistribution() ==
"lognormal")
87 { minval.push_back(log10(Model->Parameters()[i]->GetRange(
_range::low)));
88 maxval.push_back(log10(Model->Parameters()[i]->GetRange(
_range::high)));
93 minval.push_back(Model->Parameters()[i]->GetRange(
_range::low));
94 maxval.push_back(Model->Parameters()[i]->GetRange(
_range::high));
96 apply_to_all.push_back(
false);
97 if (Model->Parameters()[i]->GetPriorDistribution() ==
"lognormal")
102 paramname.push_back(Model->Parameters().getKeyAtIndex(i));
107 Ind.resize(GA_params.maxpop);
108 Ind_old.resize(GA_params.maxpop);
111 GA_params.cross_over_type = 1;
113 for (
int i=0; i<GA_params.maxpop; i++)
116 Ind[i].fit_measures.resize(model->ObservationsCount()*3);
118 Ind_old[i].fit_measures.resize(model->ObservationsCount()*3);
121 for (
int i = 0; i<GA_params.nParam; i++)
122 Setminmax(i, minval[i], maxval[i],4);
139 for (
unsigned int i=0; i<
Model->Parameters().size(); i++)
144 {
minval.push_back(log10(
Model->parameter(i)->GetVal(
"low")));
145 maxval.push_back(log10(
Model->parameter(i)->GetVal(
"high")));
150 minval.push_back(
Model->parameter(i)->GetVal(
"low"));
151 maxval.push_back(
Model->parameter(i)->GetVal(
"high"));
173 Ind[i].fit_measures.resize(model->ObservationsCount());
175 Ind_old[i].fit_measures.resize(model->ObservationsCount());
178 for (
int j = 0; j <
GA_params.nParam; j++)
189 for (
unsigned int i=0; i<
Model->Parameters().size(); i++)
193 {
minval.push_back(log10(
Model->parameter(i)->GetVal(
"low")));
194 maxval.push_back(log10(
Model->parameter(i)->GetVal(
"high")));
199 minval.push_back(
Model->parameter(i)->GetVal(
"low"));
200 maxval.push_back(
Model->parameter(i)->GetVal(
"high"));
222 Ind[i].fit_measures.resize(
Model->ObservationsCount());
224 Ind_old[i].fit_measures.resize(
Model->ObservationsCount());
227 for (
int j = 0; j <
GA_params.nParam; j++)
254 int nParam =
Ind[0].nParams;
257 for (
int i=0; i<n; i++)
261 for (
int j = 0; j<nParam; j++)
342 Ind[i].maxrange[a] = maxrange;
343 Ind[i].minrange[a] = minrange;
344 Ind[i].precision[a] = prec;
364 clock_t t0 = 0,t1 = 0;
367 for (
int k = 0; k <
GA_params.maxpop; k++)
369 for (
int i = 0; i <
GA_params.nParam; i++)
373 inp[k][i] =
Ind[k].x[i];
377 inp[k][i] = pow(10,
Ind[k].
x[i]);
381 Ind[k].actual_fitness = 0;
387 for (
int i = 0; i <
GA_params.nParam; i++)
388 Models[k].SetParameterValue(i, inp[k][i]);
398#pragma omp parallel for
406 CVector updated_params;
407 for (
int j=0; j<5; j++)
408 updated_params =
Models[k].GradientUpdate();
409 for (
int i = 0; i <
GA_params.nParam; i++)
413 inp[k][i] = updated_params[i];
414 Ind[k].x[i] = updated_params[i];
419 inp[k][i] = updated_params[i];
420 Ind[k].x[i] = log10(updated_params[i]);
434 fprintf(FileOut.get(),
"%i, ", k);
435 for (
int l=0; l<
Ind[0].nParams; l++)
437 fprintf(FileOut.get(),
"%le, ", pow(10,
Ind[k].
x[l]));
439 fprintf(FileOut.get(),
"%le, ",
Ind[k].x[l]);
440 fprintf(FileOut.get(),
"\n");
443 time_t t0 = time(
nullptr);
447 Ind[k].actual_fitness =
Models[k].GetObjectiveFunctionValue();
452 time_[k] = time(
nullptr)-t0;
461 if (omp_get_thread_num() == 0)
547 if (aquiutils::tolower(varname) ==
"maxpop" || varname ==
"Population") {
GA_params.maxpop = aquiutils::atoi(value);
setnumpop(
GA_params.maxpop);
return true;}
548 if (aquiutils::tolower(varname) ==
"ngen" || varname ==
"Number of Generations") {
GA_params.nGen = aquiutils::atoi(value);
return true;}
549 if (aquiutils::tolower(varname) ==
"pcross" || varname ==
"Cross-over probability") {
GA_params.pcross = aquiutils::atof(value);
return true;}
550 if (aquiutils::tolower(varname) ==
"pmute" || varname ==
"Mutation probability") {
GA_params.pmute = aquiutils::atof(value);
return true;}
551 if (aquiutils::tolower(varname) ==
"shakescale" || varname ==
"Shake coefficient") {
GA_params.shakescale = aquiutils::atof(value);
return true;}
552 if (aquiutils::tolower(varname) ==
"shakescalered" || varname ==
"Shake coefficient reduction factor") {
GA_params.shakescalered = aquiutils::atof(value);
return true;}
553 if (aquiutils::tolower(varname) ==
"outputfile" || varname ==
"GA output file") {
filenames.outputfilename = value;
return true;}
554 if (aquiutils::tolower(varname) ==
"getfromfilename") {
filenames.getfromfilename = value.c_str();
return true;}
555 if (aquiutils::tolower(varname) ==
"initial_population") {
filenames.initialpopfilemame = value;
return true;}
556 if (aquiutils::tolower(varname) ==
"numthreads" || varname ==
"Number of threads to be used") {
numberOfThreads = aquiutils::atoi(value.c_str());
return true;}
557 if (aquiutils::tolower(varname) ==
"steepest descent") {
559 if (aquiutils::tolower(value) ==
"true")
565 last_error =
"Property '" + varname +
"' was not found!";
572 for (map<string,string>::const_iterator it=arguments.begin(); it!=arguments.end(); it++)
582 sum +=
Ind[i].fitness;
591 fprintf(FileOut.get(),
"%s\n", s.c_str());
599 QCoreApplication::processEvents();
607 double shakescaleini =
GA_params.shakescale;
612 double ininumenhancements =
GA_params.numenhancements;
634 fprintf(FileOut.get(),
"ID, ");
635 for (
int k=0; k<
Ind[0].nParams; k++)
636 fprintf(FileOut.get(),
"%s, ",
paramname[k].c_str());
639 for (
unsigned int i=0; i<
Model->ObservationsCount();i++)
641 fprintf(FileOut.get(),
"%s, %s, %s", (
Model->observation(i)->GetName()+
"_MSE").c_str(), (
Model->observation(i)->GetName()+
"_R2").c_str(), (
Model->observation(i)->GetName()+
"_NSE").c_str());
643 fprintf(FileOut.get(),
"\n");
645 for (
int j1=0; j1<
GA_params.maxpop; j1++)
648 fprintf(FileOut.get(),
"%i, ", j1);
650 for (
int k=0; k<
Ind[0].nParams; k++)
652 fprintf(FileOut.get(),
"%le, ", pow(10,
Ind[j1].
x[k]));
654 fprintf(FileOut.get(),
"%le, ",
Ind[j1].x[k]);
656 fprintf(FileOut.get(),
"%le, %le, %i, ",
Ind[j1].actual_fitness,
Ind[j1].fitness,
Ind[j1].rank);
657 for (
unsigned int i=0; i<
Model->ObservationsCount();i++)
659 fprintf(FileOut.get(),
",%le, %le, %le",
GAFitMeasure(
Ind[j1].fit_measures, 3*i),
GAFitMeasure(
Ind[j1].fit_measures, 3*i+1),
GAFitMeasure(
Ind[j1].fit_measures, 3*i+2));
661 fprintf(FileOut.get(),
"\n");
673 rtw->SetYRange(0,
Ind[j].actual_fitness*1.1);
679 QCoreApplication::processEvents();
702 GA_params.numenhancements = ininumenhancements * 10;
747 FILE* out = FileOut ? FileOut.get() :
nullptr;
748 if (out) fprintf(out,
"Final Enhancements\n");
755 for (
int k = 0; k<
Ind[0].nParams; k++)
758 if (out) fprintf(out,
"%s, ",
paramname[k].c_str());
760 if (out) fprintf(out,
"%le, %le\n",
Ind[j].actual_fitness,
Ind[j].fitness);
762 for (
unsigned int i=0; i<
Model->ObservationsCount();i++)
764 if (out) fprintf(out,
",%le, %le, %le\n",
GAFitMeasure(
Ind[j].fit_measures, 3*i),
GAFitMeasure(
Ind[j].fit_measures, 3*i+1),
GAFitMeasure(
Ind[j].fit_measures, 3*i+2));
773 rtw->SetProgress(1.0);
774 QCoreApplication::processEvents();
787 double likelihood = 0;
791 for (
int i = 0; i < GA_params.nParam; i++)
792 Model1.SetParameterValue(i, inp[i]);
796 likelihood -= Model1.GetObjectiveFunctionValue();
841 ifstream file(filename);
844 while (file.eof() ==
false)
846 s = aquiutils::getline(file);
849 if (s[0] ==
"Final Enhancements")
852 s = aquiutils::getline(file);
854 write_to_detailed_GA(
"The number of parameters in GA output file does not match the number of unknown parameters");
916 double max_fitness = 1E+308 ;
919 if (max_fitness>
Ind[i].actual_fitness)
921 max_fitness =
Ind[i].actual_fitness;
934 sum += (a -
Ind[i].fitness)*(a -
Ind[i].fitness);
945 sum += (a - 1/
Ind[i].actual_fitness)*(a - 1/
Ind[i].actual_fitness);
955 sum +=
Ind[i].actual_fitness;
965 sum += 1/
Ind[i].actual_fitness;
979 if (
Ind[i].actual_fitness >
Ind[j].actual_fitness) r++;
992 Ind[i].fitness = pow(1.0/
static_cast<double>(
Ind[i].rank),
GA_params.N);
1003 sum+=
Ind[i].fitness;
1008 for (
int i=1; i<
GA_params.maxpop-1; i++)
1031 out.writetofile(
filenames.pathname +
"likelihood.txt");
1040 ifstream file(filename);
1044 while (file.eof() ==
false)
1046 s = aquiutils::getline(file);
1048 {
if (s[0] ==
"Final Enhancements")
1051 s = aquiutils::getline(file);
1066 ifstream file(filename);
1069 while (file.eof() ==
false)
1071 s = aquiutils::getline(file);
1076 for (
int j=0; j<s.size(); j++)
void cross2p(CBinary &B1, CBinary &B2, int p1, int p2)
void cross(CBinary &B1, CBinary &B2, int p)
std::unique_ptr< FILE, int(*)(FILE *)> GAFile
GAFile OpenGAFile(const std::string &path, const char *mode)
double GAFitMeasure(const std::vector< double > &fit_measures, size_t index)
void cross_RC_L(const CIndividual &I1, const CIndividual &I2, CIndividual &IR1, CIndividual &IR2)
double GetRndUnif(double xmin, double xmax)
double MaxFitness
Maximum fitness value in current population.
void fillfitdist()
Fill fitness distribution for roulette wheel selection.
bool SetProperty(const std::string &varname, const std::string &value)
Set GA property from string key-value pair.
std::vector< int > params
Parameter indices being optimized.
int maxfitness()
Find index of individual with maximum fitness.
T * Model
Pointer to the model being optimized.
void assignrank()
Assign ranks to individuals based on fitness.
int get_time_series(int i)
Get time series index for parameter.
double avg_actual_fitness()
Calculate average of actual (untransformed) fitness values.
std::vector< double > minval
Lower bounds for each parameter.
bool SetProperties(const std::map< std::string, std::string > &arguments)
Set multiple GA properties from map.
GA_Tweaking_parameters GA_params
GA algorithm configuration parameters.
std::vector< double > final_params
Final optimized parameter values.
void shake()
Apply shake/perturbation to population.
virtual ~CGA()
Destructor.
CGA & operator=(const CGA &C)
Assignment operator.
std::vector< CIndividual > Ind
Current population of individuals.
double sumfitness
Sum of all fitness values in current population.
GADistribution fitdist
Fitness distribution for parent selection.
ProgressReporter * rtw
Pointer to progress window for GUI updates.
void setnumpop(int n)
Set population size.
double evaluateforward()
Evaluate model forward (compute predictions).
std::vector< std::string > paramname
Names of parameters being optimized.
void Setminmax(int a, double minrange, double maxrange, int prec)
Set parameter bounds and precision.
double avg_inv_actual_fitness()
Calculate average of inverse actual fitness.
void crossoverRC()
Real-coded crossover operation.
CGA()
Default constructor.
std::vector< T > Models
Copies of model for parallel fitness evaluation.
void assignfitnesses()
Evaluate fitness for all individuals in population.
void setnparams(int n)
Set number of parameters.
std::string last_error
Last error message from GA execution.
int current_generation
Current generation counter.
int optimize()
Main optimization loop.
T Model_out
Output model configured with best parameters.
void getinifromoutput(std::string filename)
Initialize population from previous output file.
double stdfitness()
Calculate standard deviation of population fitness.
int getparamno(int i, int ts)
Get parameter index for variable and time series.
void mutate(double mu)
Apply mutation to population.
std::vector< CIndividual > Ind_old
Previous generation's population.
void initialize()
Initialize GA structures and allocate memory.
void crossover()
Perform crossover operation on population.
std::vector< bool > apply_to_all
Flags indicating if parameter applies to all entities.
int numberOfThreads
Number of threads for parallel fitness evaluation.
std::vector< std::vector< double > > initial_pop
Initial population loaded from file.
std::vector< double > maxval
Upper bounds for each parameter.
double variancefitness()
Calculate variance of population fitness.
std::vector< int > loged
Flags indicating if parameters are log-transformed.
double getfromoutput(std::string filename)
Read best solution from previous output file.
void write_to_detailed_GA(std::string s)
Write detailed GA information to file.
void InitiatePopulation()
Create initial population.
void assignfitness_rank(double N)
Assign fitness using rank-based scheme.
void getinitialpop(std::string filename)
Read initial population from file.
double avgfitness()
Calculate average fitness of population.
_filenames filenames
File paths for GA input/output.
std::vector< int > precision
std::vector< double > minrange
std::vector< double > maxrange
@ lognormal
Lognormal distribution: ln(x) ~ N(μ, σ²), for strictly positive variables.
@ low
Lower bound of the parameter range.
@ high
Upper bound of the parameter range.
int maxpop
Maximum population size (number of individuals).