151 #include <boost/bind.hpp>
152 #include <boost/shared_ptr.hpp>
153 #include <boost/filesystem.hpp>
154 #include <boost/date_time/posix_time/posix_time.hpp>
166 #include "Adaptors.h"
171 #include "FileAbort.h"
180 using namespace gplib;
191 const int annealinggeneration,
const double coolingratio)
194 double InitTemperature = inittemp;
198 double avgcombfit = 0;
199 GA->DoIteration(0,
false);
201 avgcombfit = accumulate(GA->GetAvgFit().begin(), GA->GetAvgFit().end(),
204 InitTemperature = avgcombfit * abs(inittemp);
208 AnnealGA->
SetParams(InitTemperature, annealinggeneration, coolingratio);
216 ifstream recinfo(recinfofile.c_str());
217 double slowness, sigma, cc, recerror, recweight, absweight;
219 string recinputdata, absinputdata;
222 while (recinfo.good())
227 recinfo >> slowness >> sigma >> cc >> recerror >> shift >> wantabsvel
230 if (wantabsvel ==
'a')
232 recinfo >> recweight >> absweight >> absinputdata;
238 boost::shared_ptr<const SeismicDataComp>
RecData(
241 if (wantabsvel ==
'a')
248 sigma, cc, slowness, rfmethod, recerror, normrec,
249 absweight, recweight);
255 if (wantabsvel ==
's')
257 InWave = ResPkModel::SWave;
261 slowness, rfmethod, recerror, normrec, InWave);
267 int main(
int argc,
char *argv[])
270 boost::posix_time::ptime starttime =
271 boost::posix_time::microsec_clock::local_time();
273 string version =
"$Id: 1dinvga.cpp 1888 2015-04-09 13:40:29Z mmoorkamp $";
274 cout << endl << endl;
275 cout <<
"Program " << version << endl;
276 cout <<
"Genetic algorithm to jointly invert seismic and MT data " << endl;
277 cout <<
"look at 1dinvga.conf for configuration and setup " << endl;
278 cout <<
"The root name of log-files can be overwritten by using " << endl;
279 cout <<
"1dinvga newrootname " << endl;
293 std::ifstream conffile(
"1dinvga.conf");
297 conffile.seekg(0, std::ios::beg);
300 conffile.seekg(0, std::ios::beg);
303 conffile.seekg(0, std::ios::beg);
306 conffile.seekg(0, std::ios::beg);
315 outputbase = argv[1];
320 ofstream fitstat((outputbase +
".ftst").c_str());
321 ofstream rankfile((outputbase +
".rank").c_str());
322 ofstream frontfile((outputbase +
".front").c_str());
327 ofstream distancefile;
332 misfitfile.open((outputbase +
".msft").c_str());
333 valuefile.open((outputbase +
".vals").c_str());
334 probfile.open((outputbase +
".probs").c_str());
335 distancefile.open((outputbase +
".dist").c_str());
341 cerr <<
"Configuration of genes is not consistent ! ";
345 const int nparam = 3;
347 const int genes = (JointConf.
thickbase.size()
349 const int popsize = GaConf.
popsize;
351 const int paramlength = genes / nparam;
356 misfitfile << popsize <<
" " << maxgen <<
" " << endl;
357 valuefile << genes <<
" " << popsize <<
" " << maxgen << endl;
367 basevalues.begin() + paramlength);
369 stepsizes.begin() + paramlength);
371 genesizes.begin() + paramlength);
374 basevalues.begin() + 2 * paramlength);
376 stepsizes.begin() + 2 * paramlength);
378 genesizes.begin() + 2 * paramlength);
380 const int totalgenesize = accumulate(genesizes.begin(), genesizes.end(), 0);
384 &GeneralPopulation::GetProbabilities, boost::ref(Population)),
385 boost::bind(&GeneralPopulation::GetCrowdingDistances, boost::ref(
388 double indmutationprob = 1.0 - std::pow(1.0 - GaConf.
mutationprob, 1.
390 cout <<
"Individual Mutation set to: " << indmutationprob << endl;
400 if (JointConf.
weights.at(0) > 0)
404 if (JointConf.
weights.at(1) > 0)
409 rfmethod = RecCalc::iterdecon;
415 if (JointConf.
weights.at(2) > 0)
426 RecObjective->SetPoisson(JointConf.
poisson);
427 RecObjective->SetTimeWindow(RecConf.
starttime,
431 boost::shared_ptr<SurfaceWaveObjective> SurfObjective(
434 SurfObjective->SetPoisson(JointConf.
poisson);
435 SurfObjective->SetErrorLevel(SurfConf.
surferror);
438 boost::shared_ptr<GeneralObjective> RecRegularization;
443 RecRegularization = boost::shared_ptr<GeneralObjective>(
450 if (!boost::filesystem::exists(JointConf.
vrefmodel))
453 <<
"Cannot find reference model for regularization ! Exiting !"
461 RecRegularization = boost::shared_ptr<GeneralObjective>(
466 boost::shared_ptr<GeneralObjective> MTRegularization(
new MTRoughness());
468 vector<pCGeneralObjective> ObjVector;
469 ObjVector.push_back(MTObjective);
470 ObjVector.push_back(RecObjective);
471 ObjVector.push_back(SurfObjective);
472 ObjVector.push_back(RecRegularization);
473 ObjVector.push_back(MTRegularization);
475 boost::shared_ptr<GeneralGA> GA;
476 const size_t nthreads =1;
477 if (GaConf.
gatype ==
"pareto")
480 boost::shared_ptr<ParetoGA> Pareto(
new ParetoGA(&Propagator,
481 &Population, &Transcribe, ObjVector, nthreads));
484 else if (GaConf.
gatype ==
"anneal")
487 boost::shared_ptr<AnnealingGA> Annealing(
new AnnealingGA(
488 &Propagator, &Population, &Transcribe, ObjVector,
494 cerr <<
"Invalid GA type in configuration file." << endl;
495 cerr <<
" Has to be either 'pareto' or 'anneal' !" << endl;
498 GA->SetWeights(JointConf.
weights);
501 const int nmtparam = 2 * JointConf.
resbase.size();
502 std::vector<int> LocalIndices;
504 generate_n(back_inserter(LocalIndices), nmtparam, IntSequence(0));
505 ParamIndices.push_back(LocalIndices);
506 const int nseisparam = 2 * JointConf.
thickbase.size();
507 LocalIndices.clear();
509 generate_n(back_inserter(LocalIndices), nseisparam, IntSequence(
511 ParamIndices.push_back(LocalIndices);
512 ParamIndices.push_back(LocalIndices);
513 const int nmodelparam = 3 * JointConf.
thickbase.size();
514 LocalIndices.clear();
516 generate_n(back_inserter(LocalIndices), nmodelparam, IntSequence(0));
517 ParamIndices.push_back(LocalIndices);
518 ParamIndices.push_back(LocalIndices);
519 GA->SetParameterIndices(ParamIndices);
520 GA->SetElitist(GaConf.
elitist);
525 Population.InitPop();
528 for (
int i = 0; i < maxgen; ++i)
530 GA->DoIteration(i, i == (maxgen - 1));
533 GA->PrintMisfit(misfitfile);
534 GA->PrintTranscribed(valuefile);
535 Population.PrintProbabilities(probfile);
536 Population.PrintDistances(distancefile);
538 GA->PrintBestMisfit(frontfile);
541 GA->PrintFitStat(fitstat);
556 tfitvec bestfit(ObjVector.size());
559 vector<int> BestIndices(GA->GetBestModelIndices());
560 const int noutmodels = GA->GetNBestmodels();
561 const int nobjective = ObjVector.size();
566 for (
int i = 0; i < nobjective; ++i)
568 LocalParameters.at(i).resize(ParamIndices.at(i).size(),
false);
571 ofstream finalmodels((outputbase +
".final").c_str());
573 for (
int h = 0;
h < noutmodels; ++
h)
576 member = row(Population.GetPopulation(), BestIndices.at(
h));
578 transcribed = Transcribe.
GetValues(member);
580 GA->SetupParams(transcribed, LocalParameters);
582 if (!FinalUnique.
Find(transcribed, bestfit))
585 cout <<
"Best: " <<
h <<
" Index : " << BestIndices.at(
h)
589 for (
int f = 0;
f < nobjective; ++
f)
593 bestfit(
f) = ObjVector.at(
f)->CalcPerformance(
594 LocalParameters.at(
f));
600 cout << setw(6) << setfill(
' ') << setprecision(4)
601 << bestfit(
f) <<
" ";
605 copy(bestfit.begin(), bestfit.end(), ostream_iterator<double> (
608 finalmodels <<
" " << bestcount << endl;
609 ostringstream filename;
610 filename <<
"best_" << bestcount;
614 cout <<
" Saved as : " << filename.str();
615 if (JointConf.
weights.at(0) > 0)
617 MTObjective->WriteModel(filename.str() +
"_mt.mod");
618 MTObjective->WritePlot(filename.str() +
"_mt.plot");
619 MTObjective->WriteData(filename.str());
621 if (JointConf.
weights.at(1) > 0)
623 RecObjective->WriteData(filename.str() +
".rec");
624 RecObjective->WriteModel(filename.str() +
"_rec.mod");
625 RecObjective->WritePlot(filename.str() +
"_rec");
627 if (JointConf.
weights.at(2) > 0)
629 SurfObjective->WriteData(filename.str() +
".disp");
630 SurfObjective->WriteModel(filename.str() +
"_disp.mod");
631 SurfObjective->WritePlot(filename.str() +
"_disp.plot");
635 FinalUnique.
Insert(bestfit, transcribed);
644 ofstream bestfile((outputbase +
".best").c_str());
647 ofstream uniquepop((outputbase +
".unpop").c_str());
648 GA->PrintUniquePop(uniquepop);
651 boost::posix_time::ptime endtime =
652 boost::posix_time::microsec_clock::local_time();
653 std::cout <<
"Total Runtime: " << endtime - starttime << std::endl;
656 cerr << e.what() << endl;
trfmethod
There are several ways to calculate receiver functions.
void GetData(std::ifstream &instream)
Calculate the roughness for the MT part of a joint MT-seismic model as used by 1dinvga.
void SetupMTFitParameters(const tConfObject &Configuration, C1DMTObjective &Objective)
virtual void ReadModel(const std::string filename)
Read the model in its native format from a file.
ublas::vector< double > ttranscribed
void AddRecFunction(boost::shared_ptr< const SeismicDataComp > TheRecData, int myshift, double mysigma, double myc, double myslowness, RecCalc::trfmethod method, double errorlevel, bool normalized, ResPkModel::WaveType InWave)
Add another reciever function to fit.
bool Insert(const tfitvec &fitness, const ttranscribed &popmember)
Implements binary tournament selection for genetic algorithms.
void f(vector< double > &v1, vector< double > &v2, vector< double > &v3, vector< double > &v4)
A population that is encoded as a simple binary string.
void AddAbsVelFunction(boost::shared_ptr< const SeismicDataComp > TheRecData, SurfaceWaveData &AbsVel, const int myshift, const double mysigma, const double myc, const double myslowness, const RecCalc::trfmethod method, const double errorlevel, const bool normalized, const double absvelweight, const double recweight)
Add another receiver function with absolute velocity transformation.
This class calculates the misfit between observed surface wave dispersion data and the data calculate...
std::vector< double > thickstep
bool Find(const ttranscribed &popmember, tfitvec &fitness)
std::vector< double > thickbase
std::vector< double > resstep
AnnealingGA implements a genetic algorithm with an annealing style objective function.
This class is used to model several receiver functions simultaneously.
void GetData(std::ifstream &instream)
virtual void GetData(const std::string filename)
read in data from file, determines format by ending
CombinedRoughness calculates the roughness of a joint MT- receiver functions model without considerat...
void h(vector< double > &v1, vector< double > &v2, vector< double > &v3, vector< double > &v4)
std::vector< double > weights
A class to read, write and store fundamental mode surface wave dispersion data.
void SetParams(const double mutation, const double crossover)
boost::shared_ptr< PlottableObjective > MTObjective
virtual ttranscribed GetValues(const tpopmember &member)
Re-Implements the function from BinaryTranscribe.
void SetupAnnealingGA(boost::shared_ptr< GeneralGA > &GA, const double inittemp, const int annealinggeneration, const double coolingratio)
Set the annealing GA temperature parameter, we should only call this function if we are SURE that it ...
std::vector< gplib::rvec > tparamvector
We provide some typedefs that are used in other parts as well.
std::vector< double > svelstep
This is the standard propagation class that generates a new population from the old one...
C1DRecObjective RecObjective(RecData, Configuration.shift, Configuration.omega, Configuration.sigma, Configuration.wlevel, Configuration.slowness)
The class MTStation is used to store the transfer functions and related information for a MT-site...
ublas::vector< bool > tpopmember
SeismicModelDiff calculates the roughness of a joint MT- receiver functions model compared to a seism...
std::vector< std::vector< int > > tparamindv
void GetData(std::ifstream &instream)
void PrintAll(std::ostream &output)
void SetupRecObjective(const string recinfofile, Multi1DRecObjective &RecObjective, const bool normrec, RecCalc::trfmethod rfmethod)
Use the information stored in recinforfile to setup the multi receiver function objective function...
std::vector< double > svelbase
void GetData(std::ifstream &instream)
std::vector< int > ressizes
virtual void ReadAscii(const std::string &filename)
Read a file in general ascii format, i.e lines with period velocity each.
This class stores a single unique copy of each population member that is added to it...
void GetData(std::ifstream &instream)
This class implements the Gray code representation of a binary string and the corresponding transcrip...
std::vector< double > resbase
ublas::vector< double > tfitvec
Implements a genetic algorithm based on the concept of pareto-optimality, best suited for multi-objec...
This class implements the forward calculation for a 1D isotropic MT model.
int main(int argc, char *argv[])
void ReadFile(const std::string &filename)
Read data from file, depending on the extension.
std::vector< int > svelsizes
ublas::vector< int > tsizev
This class stores and writes model for the respktn 1D seismic code that we use for receiver function ...
void SetParams(const double InitT, const int AnnealG, const double AnnealR)
Set the parameters for the annealing process.
std::vector< int > thicksizes
boost::shared_ptr< GeneralObjective > pCGeneralObjective
The basic exception class for all errors that arise in gplib.