SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
GA.hpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4
5
6// GA.cpp: implementation of the CGA class.
8#include "GA.h"
9#include <memory>
10#include <cmath>
11#include <cstdio>
12#include <stdlib.h>
13#ifndef mac_version
14#include <omp.h>
15#endif
16
17#include "parameter.h"
18#include <QCoreApplication>
19
20#include "progressreporter.h"
21
22// Files are opened through this handle so they are always closed exactly
23// once and a failed fopen is never written to.
24using GAFile = std::unique_ptr<FILE, int (*)(FILE*)>;
25inline GAFile OpenGAFile(const std::string& path, const char* mode)
26{
27 return GAFile(fopen(path.c_str(), mode), &fclose);
28}
29
30// fit_measures holds MSE, R2 and NSE for each observation when it is filled;
31// a missing value is written as nan rather than read past the end.
32inline double GAFitMeasure(const std::vector<double>& fit_measures, size_t index)
33{
34 return index < fit_measures.size() ? fit_measures[index] : std::nan("");
35}
36
37template<class T>
39{
40 GA_params.maxpop = 100;
41 Ind.resize(GA_params.maxpop);
42 Ind_old.resize(GA_params.maxpop);
44 GA_params.N = 1; //MM N=1 by default
45 GA_params.pcross = 1;
46 GA_params.cross_over_type = 1;
47 MaxFitness = 0;
48 numberOfThreads = 16;
49}
50
51template<class T>
52CGA<T>::CGA(string filename, const T &model)
53{
54 Model = model;
55 ifstream file(filename);
56 GA_params.nParam = 0;
57 GA_params.pcross = 1;
58 GA_params.N = 1;
59 GA_params.RCGA = false;
60 loged.clear();
61 numberOfThreads = 20;
62 filenames.pathname = Model->OutputPath();
64 while (file.eof() == false)
65 {
66 s = aquiutils::getline(file);
67 if (s.size()>0)
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());
78 }
79 }
80
81 file.close();
82 for (int i=0; i<Model->Parameters().size(); i++)
83 {
84 GA_params.nParam++;
85 params.push_back(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)));
89
90 }
91 else
92 {
93 minval.push_back(Model->Parameters()[i]->GetRange(_range::low));
94 maxval.push_back(Model->Parameters()[i]->GetRange(_range::high));
95 }
96 apply_to_all.push_back(false);
97 if (Model->Parameters()[i]->GetPriorDistribution() == "lognormal")
98 loged.push_back(1);
99 else
100 loged.push_back(0);
101
102 paramname.push_back(Model->Parameters().getKeyAtIndex(i));
103
104 }
105
106
107 Ind.resize(GA_params.maxpop);
108 Ind_old.resize(GA_params.maxpop);
109
110 fitdist = GADistribution(GA_params.maxpop);
111 GA_params.cross_over_type = 1;
112
113 for (int i=0; i<GA_params.maxpop; i++)
114 {
115 Ind[i] = CIndividual(GA_params.nParam);
116 Ind[i].fit_measures.resize(model->ObservationsCount()*3);
117 Ind_old[i] = CIndividual(GA_params.nParam);
118 Ind_old[i].fit_measures.resize(model->ObservationsCount()*3);
119 }
120
121 for (int i = 0; i<GA_params.nParam; i++)
122 Setminmax(i, minval[i], maxval[i],4);
123
124 MaxFitness = 0;
125}
126
127template<class T>
128CGA<T>::CGA(T *model)
129{
130 Model = model;
131 GA_params.nParam = 0;
132 GA_params.pcross = 1;
133 GA_params.N = 1;
134 GA_params.RCGA = false;
135 numberOfThreads = 20;
136 loged.clear();
137 filenames.pathname = Model->GetOutputPath();
138 GA_params.maxpop = max(1,GA_params.maxpop);
139 for (unsigned int i=0; i<Model->Parameters().size(); i++)
140 {
141 GA_params.nParam++;
142 params.push_back(i);
143 if (Model->parameter(i)->GetPriorDistribution().distribution == distribution_type::lognormal)
144 { minval.push_back(log10(Model->parameter(i)->GetVal("low")));
145 maxval.push_back(log10(Model->parameter(i)->GetVal("high")));
146
147 }
148 else
149 {
150 minval.push_back(Model->parameter(i)->GetVal("low"));
151 maxval.push_back(Model->parameter(i)->GetVal("high"));
152 }
153 apply_to_all.push_back(false);
154 if (Model->parameter(i)->GetPriorDistribution().distribution == distribution_type::lognormal)
155 loged.push_back(1);
156 else
157 loged.push_back(0);
158
159 paramname.push_back(Model->GetParameterName(i));
160
161 }
162
163
164 Ind.resize(GA_params.maxpop);
165 Ind_old.resize(GA_params.maxpop);
166
168 GA_params.cross_over_type = 1;
169
170 for (int i=0; i<GA_params.maxpop; i++)
171 {
172 Ind[i] = CIndividual(GA_params.nParam);
173 Ind[i].fit_measures.resize(model->ObservationsCount());
174 Ind_old[i] = CIndividual(GA_params.nParam);
175 Ind_old[i].fit_measures.resize(model->ObservationsCount());
176 }
177
178 for (int j = 0; j < GA_params.nParam; j++)
179 Setminmax(j, minval[j], maxval[j], 4);
180
181 MaxFitness = 0;
182}
183
184template<class T>
186{
187 GA_params.nParam = Model->Parameters().size();
188 loged.clear();
189 for (unsigned int i=0; i<Model->Parameters().size(); i++)
190 {
191 params.push_back(i);
192 if (Model->parameter(i)->GetPriorDistribution().distribution == distribution_type::lognormal)
193 { minval.push_back(log10(Model->parameter(i)->GetVal("low")));
194 maxval.push_back(log10(Model->parameter(i)->GetVal("high")));
195
196 }
197 else
198 {
199 minval.push_back(Model->parameter(i)->GetVal("low"));
200 maxval.push_back(Model->parameter(i)->GetVal("high"));
201 }
202 apply_to_all.push_back(false);
203 if (Model->parameter(i)->GetPriorDistribution().distribution == distribution_type::lognormal)
204 loged.push_back(1);
205 else
206 loged.push_back(0);
207
208 paramname.push_back(Model->GetParameterName(i));
209
210 }
211
212
213 Ind.resize(GA_params.maxpop);
214 Ind_old.resize(GA_params.maxpop);
215
217 GA_params.cross_over_type = 1;
218
219 for (int i=0; i<GA_params.maxpop; i++)
220 {
221 Ind[i] = CIndividual(GA_params.nParam);
222 Ind[i].fit_measures.resize(Model->ObservationsCount());
223 Ind_old[i] = CIndividual(GA_params.nParam);
224 Ind_old[i].fit_measures.resize(Model->ObservationsCount());
225 }
226
227 for (int j = 0; j < GA_params.nParam; j++)
228 Setminmax(j, minval[j], maxval[j], 4);
229
230 MaxFitness = 0;
231}
232
233template<class T>
234void CGA<T>::setnparams(int n_params)
235{
236 Ind.resize(GA_params.maxpop);
237 Ind_old.resize(GA_params.maxpop);
238 for (int i=0; i<GA_params.maxpop; i++)
239 {
240 Ind[i] = CIndividual(n_params);
241 Ind_old[i] = CIndividual(n_params);
242
243 }
244
245
246}
247
248template<class T>
250{
251 GA_params.maxpop = n;
252 CIndividual TempInd = Ind[0];
253
254 int nParam = Ind[0].nParams;
255 Ind.resize(GA_params.maxpop);
256 Ind_old.resize(GA_params.maxpop);
257 for (int i=0; i<n; i++)
258 {
259 Ind[i] = CIndividual(GA_params.nParam);
260 Ind_old[i] = CIndividual(GA_params.nParam);
261 for (int j = 0; j<nParam; j++)
262 {
263 Ind[i].minrange[j] = TempInd.minrange[j];
264 Ind[i].maxrange[j] = TempInd.maxrange[j];
265 Ind[i].precision[j] = TempInd.precision[j];
266 Ind_old[i].minrange[j] = TempInd.minrange[j];
267 Ind_old[i].maxrange[j] = TempInd.maxrange[j];
268 Ind_old[i].precision[j] = TempInd.precision[j];
269 }
270
271 }
273}
274
275template<class T>
277{
278 GA_params.maxpop = C.GA_params.maxpop;
279 Ind.resize(GA_params.maxpop);
280 Ind_old.resize(GA_params.maxpop);
281 Ind = C.Ind;
284 params = C.params;
285 loged = C.loged;
286 fitdist = C.fitdist;
289
290}
291
292template<class T>
294{
295 if (this == &C)
296 return *this;
299 Ind = C.Ind;
300 Ind_old = C.Ind_old;
301 params = C.params;
302 loged = C.loged;
303 fitdist = C.fitdist;
306
307 return *this;
308
309}
310
311template<class T>
313{
314
315}
316
317template<class T>
319{
320 for (int i=0; i<GA_params.maxpop; i++)
321 {
322 Ind[i].initialize();
323 }
324
325 if (filenames.initialpopfilemame!="")
326 {
327 getinifromoutput(filenames.pathname+filenames.initialpopfilemame);
328 for (int i=0; i<initial_pop.size(); i++)
329 for (int j=0; j<max(int(initial_pop[i].size()),GA_params.nParam); j++)
330 if (loged[j]==1)
331 Ind[i].x[j] = log10(initial_pop[i][j]);
332 else
333 Ind[i].x[j] = initial_pop[i][j];
334 }
335}
336
337template<class T>
338void CGA<T>::Setminmax(int a, double minrange, double maxrange, int prec)
339{
340 for (int i=0; i<GA_params.maxpop; i++)
341 {
342 Ind[i].maxrange[a] = maxrange;
343 Ind[i].minrange[a] = minrange;
344 Ind[i].precision[a] = prec;
345 }
346
347}
348
349template<class T>
351{
352 sumfitness = 0;
353
355
356 inp.resize(GA_params.maxpop);
357
358
359 for (int k=0; k<GA_params.maxpop; k++)
360 inp[k].resize(GA_params.nParam);
361
362 vector<double> time_(GA_params.maxpop);
363 vector<int> epochs(GA_params.maxpop);
364 clock_t t0 = 0,t1 = 0;
365 //Models.clear();
366
367 for (int k = 0; k < GA_params.maxpop; k++)
368 {
369 for (int i = 0; i < GA_params.nParam; i++)
370 {
371 if (loged[i] != 1)
372 {
373 inp[k][i] = Ind[k].x[i]; //Ind
374 }
375 else
376 {
377 inp[k][i] = pow(10, Ind[k].x[i]);
378 }
379 }
380
381 Ind[k].actual_fitness = 0;
382
383 //Models[k] = *Model;
384 //Models[k].SetSilent(true);
385 //Models[k].SetRecordResults(false);
386 //Models[k].SetNumThreads(1);
387 for (int i = 0; i < GA_params.nParam; i++)
388 Models[k].SetParameterValue(i, inp[k][i]);
389 //Models[k].ApplyParameters();
390
391 }
392
393
394#ifndef NO_OPENMP
395 omp_set_num_threads(numberOfThreads);
396#endif
397int counter=0;
398#pragma omp parallel for //private(ts,l)
399 for (int k=0; k<GA_params.maxpop; k++)
400 {
401
402 if (GA_params.Steepest_Descent && k<min(GA_params.maxpop/10,1))
403 {
404 // if (k==0)
405 // qDebug()<<"Prior Likelihood: " <<Models[k].GetObjectiveFunctionValue();
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++)
410 {
411 if (loged[i] != 1)
412 {
413 inp[k][i] = updated_params[i];
414 Ind[k].x[i] = updated_params[i];
415
416 }
417 else
418 {
419 inp[k][i] = updated_params[i];
420 Ind[k].x[i] = log10(updated_params[i]);
421 }
422 }
423
424 // if (k==0)
425 // qDebug()<<"Posterior Likelihood: " <<Models[k].GetObjectiveFunctionValue();
426
427 }
428
429#pragma omp critical
430 {
431 GAFile FileOut = OpenGAFile(filenames.pathname+"detail_GA.txt","a");
432 if (FileOut)
433 {
434 fprintf(FileOut.get(), "%i, ", k);
435 for (int l=0; l<Ind[0].nParams; l++)
436 if (loged[l]==1)
437 fprintf(FileOut.get(), "%le, ", pow(10,Ind[k].x[l]));
438 else
439 fprintf(FileOut.get(), "%le, ", Ind[k].x[l]);
440 fprintf(FileOut.get(), "\n");
441 }
442 }
443 time_t t0 = time(nullptr);
444
445
446
447 Ind[k].actual_fitness = Models[k].GetObjectiveFunctionValue();
448 //for (unsigned int i=0; i<Models[k].fit_measures.size(); i++)
449 // Ind[k].fit_measures[i] = Models[k].fit_measures[i];
450
451// epochs[k] += Models[k].EpochCount();
452 time_[k] = time(nullptr)-t0;
453#pragma omp atomic
454 counter++;
455#pragma omp critical
456 {
457#ifdef Q_GUI_SUPPORT
458 if (rtw != nullptr)
459 {
460#ifndef NO_OPENMP
461 if (omp_get_thread_num() == 0)
462#endif
463 {
464// rtw->SetProgress2(double(counter + 1) / GA_params.maxpop);
465// QCoreApplication::processEvents();
466 }
467 }
468#endif
469
470 {
471// FileOut = fopen((filenames.pathname+"detail_GA.txt").c_str(),"a");
472// fprintf(FileOut, "%i, fitness=%e, time=%e, internal_time=%e, failed=%i\n", k, Ind[k].actual_fitness, time_[k], double(Models[k].GetSimulationDuration()), Models[k].GetSolutionFailed());
473// fclose(FileOut);
474 }
475
476 }
477 }
479#ifdef Q_version
480// if (rtw != nullptr)
481// {
482// rtw->SetProgress(1);
483// QCoreApplication::processEvents();
484// }
485#endif
486 inp.clear();
488
489}
490
491template<class T>
493{
494
495 Ind_old = Ind;
496 int a = maxfitness();
497 Ind[0] = Ind_old[a];
498 Ind[1] = Ind_old[a];
499 for (int i=2; i<GA_params.maxpop; i+=2)
500 {
502 int j1 = fitdist.GetRand();
503 int j2 = fitdist.GetRand();
504 double x = fitdist.GetRndUniF(0,1);
505 if (x<GA_params.pcross)
506 if (GA_params.cross_over_type == 1)
507 cross(Ind_old[j1], Ind_old[j2], Ind[i], Ind[min(i+1,GA_params.maxpop-1)]); //1 Breaking point
508 else
509 cross2p(Ind_old[j1], Ind_old[j2], Ind[i], Ind[min(i + 1, GA_params.maxpop - 1)]); //2 Breaking point
510 else
511 {
512 Ind[i] = Ind_old[j1];
513 Ind[i+1] = Ind_old[j2];
514 }
515
516 }
517
518}
519
520template<class T>
522{
523
524 for (int i=0; i<GA_params.maxpop; i++)
525 Ind_old[i] = Ind[i];
526 int a = maxfitness();
527 Ind[0] = Ind_old[a];
528 Ind[1] = Ind_old[a];
529 for (int i=2; i<GA_params.maxpop; i+=2)
530 {
531 int j1 = fitdist.GetRand();
532 int j2 = fitdist.GetRand();
533 double x = GetRndUnif(0,1);
534 if (x<GA_params.pcross)
535 cross_RC_L(Ind_old[j1], Ind_old[j2], Ind[i], Ind[i+1]);
536 else
537 {
538 Ind[i] = Ind_old[j1];
539 Ind[i+1] = Ind_old[j2];
540 }
541 }
542}
543
544template<class T>
545bool CGA<T>::SetProperty(const string &varname, const string &value)
546{
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") {
558
559 if (aquiutils::tolower(value) == "true")
560 GA_params.Steepest_Descent = true;
561 else
562 GA_params.Steepest_Descent = false;
563 return true;
564 }
565 last_error = "Property '" + varname + "' was not found!";
566 return false;
567}
568
569template<class T>
570bool CGA<T>::SetProperties(const map<string,string> &arguments)
571{
572 for (map<string,string>::const_iterator it=arguments.begin(); it!=arguments.end(); it++)
573 SetProperty(it->first, it->second);
574 return true;
575}
576
577template<class T>
579{
580 double sum=0;
581 for (int i=0; i<GA_params.maxpop; i++)
582 sum += Ind[i].fitness;
583 return sum/GA_params.maxpop;
584}
585
586template<class T>
588{
589 GAFile FileOut = OpenGAFile(filenames.pathname + "detail_GA.txt", "a");
590 if (FileOut)
591 fprintf(FileOut.get(), "%s\n", s.c_str());
592
593}
594
595template<class T>
597{
598 #ifdef Q_GUI_SUPPORT
599 QCoreApplication::processEvents();
600 #endif // Q_GUI_SUPPORT
601 string RunFileName = filenames.pathname + filenames.outputfilename;
602
603 // Truncate both output files
604 OpenGAFile(RunFileName, "w");
605 OpenGAFile(filenames.pathname + "detail_GA.txt", "w");
606
607 double shakescaleini = GA_params.shakescale;
608
609 vector<double> X(Ind[0].nParams);
610
611 initialize();
612 double ininumenhancements = GA_params.numenhancements;
613 GA_params.numenhancements = 0;
614
615 CMatrix Fitness(GA_params.nGen, 3);
616
617 Models.clear();
618 Models.resize(GA_params.maxpop);
619 for (int k=0; k<GA_params.maxpop; k++)
620 Models[k] = *Model;
622 {
623
624 write_to_detailed_GA("Assigning fitnesses ...");
625
627
628 write_to_detailed_GA("Assigning fitnesses done!");
629 printf("Generation: %i\n", current_generation);
630 GAFile FileOut = OpenGAFile(RunFileName, "a");
631 if (FileOut)
632 {
633 fprintf(FileOut.get(), "Generation: %i\n", current_generation);
634 fprintf(FileOut.get(), "ID, ");
635 for (int k=0; k<Ind[0].nParams; k++)
636 fprintf(FileOut.get(), "%s, ", paramname[k].c_str());
637
638 //fprintf(FileOut.get(), "%s, %s, %s, ", "likelihood", "Fitness", "Rank");
639 for (unsigned int i=0; i<Model->ObservationsCount();i++)
640 {
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());
642 }
643 fprintf(FileOut.get(), "\n");
644 write_to_detailed_GA("Generation: " + aquiutils::numbertostring(current_generation));
645 for (int j1=0; j1<GA_params.maxpop; j1++)
646 {
647
648 fprintf(FileOut.get(), "%i, ", j1);
649
650 for (int k=0; k<Ind[0].nParams; k++)
651 if (loged[k] == 1)
652 fprintf(FileOut.get(), "%le, ", pow(10, Ind[j1].x[k]));
653 else
654 fprintf(FileOut.get(), "%le, ", Ind[j1].x[k]);
655
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++)
658 {
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));
660 }
661 fprintf(FileOut.get(), "\n");
662 }
663 }
664
665 int j = maxfitness();
666
667 Fitness[current_generation][0] = Ind[j].actual_fitness;
668
669#ifdef Q_GUI_SUPPORT
670 if (rtw)
671 { if (current_generation==0)
672 {
673 rtw->SetYRange(0,Ind[j].actual_fitness*1.1);
674 rtw->SetXRange(0,GA_params.nGen);
675 }
676 rtw->SetProgress(double(current_generation)/double(GA_params.nGen));
677 rtw->AppendPoint(current_generation+1,Ind[j].actual_fitness);
678 //rtw->Replot();
679 QCoreApplication::processEvents();
680 }
681#endif
682 if (current_generation>10)
683 {
684 if ((Fitness[current_generation][0] == Fitness[current_generation - 3][0]) && GA_params.shakescale>pow(10.0, -Ind[0].precision[0]))
685 GA_params.shakescale *= GA_params.shakescalered;
686
687
688 if ((Fitness[current_generation][0]>Fitness[current_generation - 1][0]) && (GA_params.shakescale<shakescaleini))
689 GA_params.shakescale /= GA_params.shakescalered;
690 GA_params.numenhancements = 0;
691 }
692
693 if (current_generation>50)
694 {
695 if (Fitness[current_generation][0] == Fitness[current_generation - 20][0])
696 {
697 GA_params.numenhancements *= 1.05;
698 if (GA_params.numenhancements == 0) GA_params.numenhancements = ininumenhancements;
699 }
700
701 if (Fitness[current_generation][0] == Fitness[current_generation - 50][0])
702 GA_params.numenhancements = ininumenhancements * 10;
703 }
704
705 Fitness[current_generation][1] = GA_params.shakescale;
706 Fitness[current_generation][2] = GA_params.pmute;
707
708 if (current_generation>20)
709 {
710 if (GA_params.shakescale == Fitness[current_generation - 20][1])
711 GA_params.shakescale = shakescaleini;
712 }
713
714
715 j = maxfitness();
716 MaxFitness = Ind[j].actual_fitness;
717
718 Fitness[current_generation][0] = Ind[j].actual_fitness;
719
720
721 fillfitdist();
722
723 write_to_detailed_GA("Cross-over ...");
724
725 if (GA_params.RCGA == true)
726 crossoverRC();
727 else
728 crossover();
729
730 write_to_detailed_GA("Cross-over done! ");
731
732 write_to_detailed_GA("Mutation ...");
733
734 mutate(GA_params.pmute);
735 write_to_detailed_GA("Mutation done!");
736 write_to_detailed_GA("Shake...!");
737 shake();
738 write_to_detailed_GA("Shake done!");
739
740
741 }
742
744 int j = maxfitness();
745 {
746 GAFile FileOut = OpenGAFile(RunFileName, "a");
747 FILE* out = FileOut ? FileOut.get() : nullptr;
748 if (out) fprintf(out, "Final Enhancements\n");
749
750
751 MaxFitness = Ind[j].actual_fitness;
752 final_params.resize(GA_params.nParam);
753
754
755 for (int k = 0; k<Ind[0].nParams; k++)
756 {
757 if (loged[k] == 1) final_params[k] = pow(10, Ind[j].x[k]); else final_params[k] = Ind[j].x[k];
758 if (out) fprintf(out, "%s, ", paramname[k].c_str());
759 if (out) fprintf(out, "%le, ", final_params[k]);
760 if (out) fprintf(out, "%le, %le\n", Ind[j].actual_fitness, Ind[j].fitness);
761 }
762 for (unsigned int i=0; i<Model->ObservationsCount();i++)
763 {
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));
765 }
766 } // closes the run file
767
769
770#ifdef Q_GUI_SUPPORT
771 if (rtw)
772 {
773 rtw->SetProgress(1.0);
774 QCoreApplication::processEvents();
775 }
776#endif
777
778 Models.clear();
779
780 return maxfitness();
781}
782
783template<class T>
785{
786
787 double likelihood = 0;
788 T Model1;
789 Model1 = *Model;
790
791 for (int i = 0; i < GA_params.nParam; i++)
792 Model1.SetParameterValue(i, inp[i]);
793
794 //Model1.ApplyParameters();
795 //Model1.Solve();
796 likelihood -= Model1.GetObjectiveFunctionValue();
797
798 Model_out = Model1;
799 //Model_out.TransferResultsFrom(&Model1);
800 return likelihood;
801
802}
803
804/*
805template<class T>
806vector<T>& CGA<T>::assignfitnesses_p(vector<double> inp) //Generates an instance of the model with the provided parameters
807{
808 double likelihood = 0;
809 vector<T> Models(1);
810 for (int ts = 0; ts<1; ts++)
811 {
812 Models[ts] = Model;
813
814 int l = 0;
815 for (int i = 0; i<GA_params.nParam; i++)
816 Models[ts].SetParam(params[i], inp[getparamno(i, ts)]);
817 Models[ts].FinalizeSetParams();
818 likelihood -= Models[ts].EvaluateObjectiveFunction();
819 }
820 return Models;
821}
822
823template<class T>
824int CGA<T>::get_act_paramno(int i)
825{
826 int l = -1;
827 for (int j = 0; j<GA_params.nParam; j++)
828 {
829 if (apply_to_all[j]) l++; else l += 1;
830 if (l >= i)
831 {
832 if (apply_to_all[j]) l -= 1; else l--;
833 return j;
834 }
835 }
836}
837*/
838template<class T>
839double CGA<T>::getfromoutput(string filename)
840{
841 ifstream file(filename);
843 final_params.resize(GA_params.nParam);
844 while (file.eof() == false)
845 {
846 s = aquiutils::getline(file);
847 if (s.size()>0)
848 {
849 if (s[0] == "Final Enhancements")
850 for (int i = 0; i<GA_params.nParam; i++)
851 {
852 s = aquiutils::getline(file);
853 if (s.size() == 0)
854 write_to_detailed_GA("The number of parameters in GA output file does not match the number of unknown parameters");
855 else
856 final_params[i] = atof(s[1].c_str());
857 }
858 }
859 }
860 double ret = assignfitnesses(final_params);
861 return ret;
862}
863
864
865template<class T>
866int CGA<T>::getparamno(int i, int ts)
867{
868 // apply_to_all is false for every parameter in SedSAT3 (a single model);
869 // it is left from a multi-series design where a parameter could apply to
870 // all series at once. Each parameter therefore takes one slot.
871 int l = i;
872
873 if (apply_to_all[i])
874 return l;
875 else
876 return l + ts;
877
878}
879template<class T>
881{
882 // One slot per parameter (see getparamno)
883 int l = 0;
884 for (int j = 0; j<GA_params.nParam; j++)
885 {
886 l += 1;
887 if (l >= i)
888 {
889 l--;
890 return i - l;
891 }
892 }
893 return 0;
894}
895
896
897template<class T>
899{
900 for (int i=1; i<GA_params.maxpop; i++)
901 Ind[i].shake(GA_params.shakescale);
902
903}
904
905template<class T>
906void CGA<T>::mutate(double mu)
907{
908 for (int i=2; i<GA_params.maxpop; i++)
909 Ind[i].mutate(mu);
910
911}
912
913template<class T>
915{
916 double max_fitness = 1E+308 ;
917 int i_max = 0;
918 for (int i=0; i<GA_params.maxpop; i++)
919 if (max_fitness>Ind[i].actual_fitness)
920 {
921 max_fitness = Ind[i].actual_fitness;
922 i_max = i;
923 }
924 return i_max;
925
926}
927
928template<class T>
930{
931 double sum = 0;
932 double a = avgfitness();
933 for (int i=0; i<GA_params.maxpop; i++)
934 sum += (a - Ind[i].fitness)*(a - Ind[i].fitness);
935 return sum;
936
937}
938
939template<class T>
941{
942 double sum = 0;
943 double a = avg_inv_actual_fitness();
944 for (int i=0; i<GA_params.maxpop; i++)
945 sum += (a - 1/Ind[i].actual_fitness)*(a - 1/Ind[i].actual_fitness);
946 return sqrt(sum)/GA_params.maxpop/a;
947
948}
949
950template<class T>
952{
953 double sum=0;
954 for (int i=0; i<GA_params.maxpop; i++)
955 sum += Ind[i].actual_fitness;
956 return sum/GA_params.maxpop;
957
958}
959
960template<class T>
962{
963 double sum=0;
964 for (int i=0; i<GA_params.maxpop; i++)
965 sum += 1/Ind[i].actual_fitness;
966 return sum/GA_params.maxpop;
967
968}
969
970
971template<class T>
973{
974 for (int i=0; i<GA_params.maxpop; i++)
975 {
976 int r = 1;
977 for (int j=0; j<GA_params.maxpop; j++)
978 {
979 if (Ind[i].actual_fitness > Ind[j].actual_fitness) r++;
980 }
981 Ind[i].rank = r;
982 }
983
984}
985
986template<class T>
988{
989 assignrank();
990 for (int i=0; i<GA_params.maxpop; i++)
991 {
992 Ind[i].fitness = pow(1.0/static_cast<double>(Ind[i].rank),GA_params.N);
993 }
994}
995
996
997template<class T>
999{
1000 double sum=0;
1001 for (int i=0; i<GA_params.maxpop; i++)
1002 {
1003 sum+=Ind[i].fitness;
1004 }
1005
1006 fitdist.s[0] = 0;
1007 fitdist.e[0] = Ind[0].fitness/sum;
1008 for (int i=1; i<GA_params.maxpop-1; i++)
1009 {
1010 fitdist.e[i] = fitdist.e[i-1] + Ind[i].fitness/sum;
1011 fitdist.s[i] = fitdist.e[i-1];
1012 }
1013 fitdist.s[GA_params.maxpop-1] = fitdist.e[GA_params.maxpop-2];
1014 fitdist.e[GA_params.maxpop-1] = 1;
1015
1016}
1017
1018template<class T>
1020{
1021 vector<double> v(1);
1022 v[0] = 1;
1023 CVector out(1);
1024 int x_nParam = GA_params.nParam;
1025 vector<int> x_params = params;
1026 GA_params.nParam = 1;
1027 params.resize(1);
1028 params[0] = 100;
1029 out[0] = assignfitnesses(v);
1030
1031 out.writetofile(filenames.pathname + "likelihood.txt");
1032 params = x_params;
1033 GA_params.nParam = x_nParam;
1034 return out[0];
1035}
1036
1037template<class T>
1038void CGA<T>::getinifromoutput(string filename)
1039{
1040 ifstream file(filename);
1042 initial_pop.resize(1);
1043 initial_pop[0].resize(GA_params.nParam);
1044 while (file.eof() == false)
1045 {
1046 s = aquiutils::getline(file);
1047 if (s.size()>0)
1048 { if (s[0] == "Final Enhancements")
1049 for (int i=0; i<GA_params.nParam; i++)
1050 {
1051 s = aquiutils::getline(file);
1052 if (loged[i]==1)
1053 initial_pop[0][i] = atof(s[1].c_str());
1054 else
1055 initial_pop[0][i] = atof(s[1].c_str());
1056
1057 }
1058 }
1059 }
1060
1061}
1062
1063template<class T>
1064void CGA<T>::getinitialpop(string filename)
1065{
1066 ifstream file(filename);
1068
1069 while (file.eof() == false)
1070 {
1071 s = aquiutils::getline(file);
1072
1073 if (s.size()>0)
1074 {
1076 for (int j=0; j<s.size(); j++)
1077 initial_pop.push_back(aquiutils::ATOF(s));
1078
1079 }
1080 }
1081 file.close();
1082}
1083
1084
void cross2p(CBinary &B1, CBinary &B2, int p1, int p2)
Definition Binary.cpp:195
void cross(CBinary &B1, CBinary &B2, int p)
Definition Binary.cpp:147
std::unique_ptr< FILE, int(*)(FILE *)> GAFile
Definition GA.hpp:24
GAFile OpenGAFile(const std::string &path, const char *mode)
Definition GA.hpp:25
double GAFitMeasure(const std::vector< double > &fit_measures, size_t index)
Definition GA.hpp:32
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.
Definition GA.h:369
void fillfitdist()
Fill fitness distribution for roulette wheel selection.
Definition GA.hpp:998
bool SetProperty(const std::string &varname, const std::string &value)
Set GA property from string key-value pair.
Definition GA.hpp:545
std::vector< int > params
Parameter indices being optimized.
Definition GA.h:418
int maxfitness()
Find index of individual with maximum fitness.
Definition GA.hpp:914
T * Model
Pointer to the model being optimized.
Definition GA.h:516
void assignrank()
Assign ranks to individuals based on fitness.
Definition GA.hpp:972
int get_time_series(int i)
Get time series index for parameter.
Definition GA.hpp:880
double avg_actual_fitness()
Calculate average of actual (untransformed) fitness values.
Definition GA.hpp:951
std::vector< double > minval
Lower bounds for each parameter.
Definition GA.h:448
bool SetProperties(const std::map< std::string, std::string > &arguments)
Set multiple GA properties from map.
Definition GA.hpp:570
GA_Tweaking_parameters GA_params
GA algorithm configuration parameters.
Definition GA.h:377
std::vector< double > final_params
Final optimized parameter values.
Definition GA.h:410
void shake()
Apply shake/perturbation to population.
Definition GA.hpp:898
virtual ~CGA()
Destructor.
Definition GA.hpp:312
CGA & operator=(const CGA &C)
Assignment operator.
Definition GA.hpp:293
std::vector< CIndividual > Ind
Current population of individuals.
Definition GA.h:478
double sumfitness
Sum of all fitness values in current population.
Definition GA.h:361
GADistribution fitdist
Fitness distribution for parent selection.
Definition GA.h:989
ProgressReporter * rtw
Pointer to progress window for GUI updates.
Definition GA.h:1005
void setnumpop(int n)
Set population size.
Definition GA.hpp:249
double evaluateforward()
Evaluate model forward (compute predictions).
Definition GA.hpp:1019
std::vector< std::string > paramname
Names of parameters being optimized.
Definition GA.h:494
void Setminmax(int a, double minrange, double maxrange, int prec)
Set parameter bounds and precision.
Definition GA.hpp:338
double avg_inv_actual_fitness()
Calculate average of inverse actual fitness.
Definition GA.hpp:961
void crossoverRC()
Real-coded crossover operation.
Definition GA.hpp:521
CGA()
Default constructor.
Definition GA.hpp:38
std::vector< T > Models
Copies of model for parallel fitness evaluation.
Definition GA.h:502
void assignfitnesses()
Evaluate fitness for all individuals in population.
Definition GA.hpp:350
void setnparams(int n)
Set number of parameters.
Definition GA.hpp:234
std::string last_error
Last error message from GA execution.
Definition GA.h:676
int current_generation
Current generation counter.
Definition GA.h:982
int optimize()
Main optimization loop.
Definition GA.hpp:596
T Model_out
Output model configured with best parameters.
Definition GA.h:509
void getinifromoutput(std::string filename)
Initialize population from previous output file.
Definition GA.hpp:1038
double stdfitness()
Calculate standard deviation of population fitness.
Definition GA.hpp:940
int getparamno(int i, int ts)
Get parameter index for variable and time series.
Definition GA.hpp:866
void mutate(double mu)
Apply mutation to population.
Definition GA.hpp:906
std::vector< CIndividual > Ind_old
Previous generation's population.
Definition GA.h:486
void initialize()
Initialize GA structures and allocate memory.
Definition GA.hpp:318
void crossover()
Perform crossover operation on population.
Definition GA.hpp:492
std::vector< bool > apply_to_all
Flags indicating if parameter applies to all entities.
Definition GA.h:463
int numberOfThreads
Number of threads for parallel fitness evaluation.
Definition GA.h:996
std::vector< std::vector< double > > initial_pop
Initial population loaded from file.
Definition GA.h:402
std::vector< double > maxval
Upper bounds for each parameter.
Definition GA.h:456
double variancefitness()
Calculate variance of population fitness.
Definition GA.hpp:929
std::vector< int > loged
Flags indicating if parameters are log-transformed.
Definition GA.h:426
double getfromoutput(std::string filename)
Read best solution from previous output file.
Definition GA.hpp:839
void write_to_detailed_GA(std::string s)
Write detailed GA information to file.
Definition GA.hpp:587
void InitiatePopulation()
Create initial population.
Definition GA.hpp:185
void assignfitness_rank(double N)
Assign fitness using rank-based scheme.
Definition GA.hpp:987
void getinitialpop(std::string filename)
Read initial population from file.
Definition GA.hpp:1064
double avgfitness()
Calculate average fitness of population.
Definition GA.hpp:578
_filenames filenames
File paths for GA input/output.
Definition GA.h:385
std::vector< int > precision
Definition Individual.h:25
std::vector< double > minrange
Definition Individual.h:26
std::vector< double > maxrange
Definition Individual.h:26
STL class.
@ lognormal
Lognormal distribution: ln(x) ~ N(μ, σ²), for strictly positive variables.
@ low
Lower bound of the parameter range.
Definition parameter.h:17
@ high
Upper bound of the parameter range.
Definition parameter.h:18
int maxpop
Maximum population size (number of individuals).
Definition GA.h:48