1dinvga.cpp

Go to the documentation of this file.
00001 /*!
00002  * \file
00003  * The program 1dinvga is the core joint inversion program for MT, receiver functions
00004  * and surface wave data. It reads in its settings from the configuration file <CODE> 1dinvga.conf </CODE>, described
00005  * below, and produces several log files and the final data, model(s) and plot file(s) for each
00006  * inverted dataset.
00007  * 
00008  <H2> General Configuration in 1dinvga.conf </H2>
00009  The options in <CODE> 1dinvga.conf </CODE> are as follows:
00010  <H3> General program options </H3>
00011  <TABLE>
00012  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD> 
00013  <TR> <TD>verbose</TD> <TD> false </TD> <TD> Print detailed information about all models used in the invbersion, only useful for debugging</TD></TR>
00014  <TR> <TD>outputbase</TD> <TD> </TD> <TD> The start of the name of all logfiles. This can also be specified on the command lin.e</TD> </TR> 
00015  <TR> <TD>threads</TD><TD> 1 </TD> <TD>If the program has been compiled with openmp support, this specifies the number of simultaneous threads. </TD></TR>
00016  </TABLE>
00017  
00018  <H3> Genetic algorithm options </H3>
00019  <TABLE>
00020  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00021  <TR> <TD>gatype</TD> <TD> </TD> <TD> Can be either <CODE>anneal</CODE> or <CODE> pareto</CODE>. If set to <CODE>anneal</CODE> we use an annealing type GA that minimizes
00022  a weighted sum of the objective functions with the weights specified below. For this type of GA we also have to specify inittemp and coolingratio.
00023  If set to <CODE> pareto</CODE>, we use NSGA-II as described by Deb et al. (2002). In this case inittemp and coolingratio are ignored. </TD></TR>
00024  <TR> <TD>inittemp</TD><TD> </TD> <TD>(For GA type <CODE>anneal</CODE>)The initial temperature in the cooling schedule. High values mean that there will be no big differences in
00025  probability between well fitting models and bad fitting models. Low values make those differences much more severe. If set to negative values the temperature
00026  will be determined from the average misfit values in the first iteration.   </TD> </TR>
00027  <TR> <TD>annealinggeneration</TD><TD> </TD><TD>(For GA type <CODE>anneal</CODE>) The generation number when the initial tempature is divided by coolingratio to enforce stronger
00028  discrimination between good and bad fitting models.</TD></TR>
00029  <TR> <TD>coolingratio</TD><<TD> </TD><TD>(For GA type <CODE>anneal</CODE>) The value by which inittemp is divided at generation <CODE>annealinggeneration</CODE>
00030  Higher values mean stronger discrimination.</TD>/TR>
00031  <TR> <TD>popsize</TD><TD> </TD><TD>The population size for the genetic algorithm. Typical values 50...1000 </TD></TR>
00032  <TR> <TD>generations</TD><<TD> </TD><TD>The number of generations for the GA to run.Typical values 50...500.  </TD>/TR>
00033  <TR> <TD>mutationprob</TD><TD> </TD><TD>The probability for a mutation within one member, typically 0.1...0.2. The probability for mutation of
00034  individual bits is calculated from this number depending on the length of the encoding specified below. </TD></TR>
00035  <TR> <TD>crossoverprob</TD><TD> </TD><TD>The probability for two model to perform crossover. Typically 0.4...0.7. </TD>/TR>
00036  <TR> <TD>elitist</TD><TD> </TD><TD>Do we want to keep the best model(s)  from the last generation (true), or fully depend
00037  on crossover and mutation with the risk of loosing good models (false).  </TD></TR>
00038  </TABLE>
00039  <H3> Data information</H3>
00040  
00041  <TABLE>
00042  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00043  <TR> <TD>recinfofile</TD><TD> </TD><TD>The file containing information about the receiver function data. This file is decribed below. </TD></TR>
00044  <TR> <TD>mtinputdata</TD><TD> </TD><TD>The name of the file containing the MT impedances </TD></TR>
00045  <TR> <TD>dispdata</TD><TD> </TD><TD>The name of the file containing the Rayleigh wave dispersion data</TD></TR>
00046  </TABLE>
00047  
00048  <H3> Error floor information </H3>
00049  <TABLE>
00050  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00051  <TR> <TD>tensorerror</TD> <TD> 0.02</TD> <TD>Error floor for MT impedances, if selected below </TD></TR>
00052  <TR> <TD>reserror  </TD> <TD>0.02 </TD> <TD>Error floor for MT apparent resistivities, if selected below </TD></TR>
00053  <TR> <TD>phaseerror </TD> <TD>0.02 </TD><TD>Error floor for MT phase, if selected below </TD></TR>
00054  <TR> <TD>surferror </TD><TD>0.02 </TD><TD>Error floor for Rayleigh wave dispersion data </TD></TR>
00055  </TABLE>
00056  
00057  <H3> Global receiver function parameters </H3>
00058  <TABLE>
00059  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00060  <TR> <TD>poisson</TD><TD> </TD><TD> Poissons ratio, we calculate Vp from Vs using this ratio</TD></TR>
00061  <TR> <TD>starttime</TD><TD> </TD><TD>Start of the fit window in seconds. Any data in the receiver function before this time is ignored. </TD></TR>
00062  <TR> <TD>endtime</TD><TD> </TD><TD>End of the fit window in seconds. Any data in the receiver function after this time is ignored. </TD></TR>
00063  <TR> <TD>recmethod</TD><TD> </TD><TD>Method used to calculate the measured data. Can be <CODE>specdiv</CODE> for spectral division, 
00064  or <CODE>iterdecon</CODE> for iterative deconvolution. </TD></TR>
00065  </TABLE>
00066  
00067  <H3> MT data parameters </H3>
00068  <TABLE>
00069  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00070  <TR> <TD>mode</TD><TD> </TD><TD>Which component of the tensor to fit. Can be <CODE>xy</CODE> or <CODE>yx</CODE>. </TD></TR>
00071  <TR> <TD>mtfit</TD><TD> </TD><TD>Which aspect of the MT data to fit. Possible values are shown in the table below.  </TD></TR>
00072  </TABLE>
00073 
00074  <H3> Possible mtfit values </H3>
00075  <TABLE>
00076  <TR> <TD> <B>Name</B> </TD>  <TD><B>Description</B></TD> </TR> 
00077  <TR> <TD> appres </TD>  <TD>Fit only apparent resistivity of selected mode</TD> </TR>
00078  <TR> <TD> phase </TD>  <TD>Fit only phase of selected mode</TD> </TR>
00079  <TR> <TD> resphase </TD>  <TD>Fit apparent resistivity  and phase of selected mode</TD> </TR>
00080  <TR> <TD> berd </TD>  <TD>Fit Berdichevskiy invariant. This is independent of selected mode./TD> </TR>
00081  <TR> <TD> det</TD>  <TD>Fit determinant of impedance tensor. This is independent of selected mode.</TD> </TR> 
00082  </TABLE>
00083  
00084  <H3> Regularization and fit information </H3>
00085  <TABLE>
00086  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00087  <TR> <TD>usevrefmodel </TD><TD> false </TD><TD>Do we want to regularize the seismic parameters by the difference to a reference model (true/false) ? </TD></TR>
00088  <TR> <TD>vrefmodel</TD><TD> </TD><TD>If true above, the name of the reference model file. </TD></TR>
00089  <TR> <TD>mtfitexponent </TD><TD> 2</TD><TD>The exponent for the difference  between measured and calculated data. Higher exponents penalize
00090  any departure from the measured data. This ensures a tighter fit, but also increases the influence of noise.</TD></TR>
00091  <TR> <TD>recfitexponent </TD><TD>2 </TD><TD>Same for receiver function data. </TD></TR>
00092  <TR> <TD>surffitexponent </TD><TD> 2</TD><TD>Same for dispersion data. </TD></TR>
00093  </TABLE>
00094  
00095  
00096  <H3> Parameter encoding </H3>
00097  The number of layers is determined by the number of entries, it has to be equal for all 
00098  encoding parameters.
00099  <TABLE>
00100  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00101  <TR> <TD>thickbase</TD><TD> </TD><TD>Minimum thickness for each layer in km </TD></TR>
00102  <TR> <TD>thickstep</TD><TD> </TD><TD>Stepsize for each layer in km </TD></TR>
00103  <TR> <TD>thicksizes</TD><TD> </TD><TD>Number of bits used to encode the thickness of each layer </TD></TR>
00104  <TR> <TD>resbase</TD><TD> </TD><TD>Base 10 logarithm of the minimum resistivity, i.e. 0 corresponds to 1 Ohm.m </TD></TR>
00105  <TR> <TD>resstep</TD><TD> </TD><TD>Stepsize for base 10 logarithm of resistivity  </TD></TR>
00106  <TR> <TD>ressizes</TD><TD> </TD><TD>Number of bits used to encode resistivity </TD></TR>
00107  <TR> <TD>svelbase</TD><TD> </TD><TD>Minimum S-Wave velocity for each layer in km/s </TD></TR>
00108  <TR> <TD>svelstep</TD><TD> </TD><TD>Stepsize for S_Wave velocity for each layer </TD></TR>
00109  <TR> <TD>svelsizes</TD><TD> </TD><TD>Number of bits used to encode Vs </TD></TR>
00110  </TABLE>
00111  
00112  <H3> Weighting of datasets </H3>
00113  <TABLE>
00114  <TR> <TD> <B>Name</B> </TD> <TD><B> Default</B></TD> <TD><B>Description</B></TD>
00115  <TR> <TD>weights</TD> <TD> </TD>  <TD>These are the weights for the different objective functions. The current version needs exactly 5 weights.
00116  They correspond to MT misfit, Receiver function misfit, Surface Wave Misfit, Seismic Regularization and MT regularization, respectively.
00117  If a weight is set to zero the calculation of the misfit is completely disabled and the inversion thus runs faster. For pareto type inversion
00118  the value of weight is irrelevant as long as it is different from zero. For annealing it determines the influence of the corresponding dataset. </TD></TR>
00119  <TR> <TD>recweight</TD> <TD> </TD> <TD>The receiver function class has the possibility to calculate absolute velocity information from the receiver function.
00120  This and the following weight determine in how far the traditional receiver function and the absolute velocity transformation determine the misfit
00121  for the receiver function. </TD></TR>
00122  <TR> <TD>absvelweight</TD> <TD> </TD> <TD> See above </TD></TR>
00123  </TABLE> 
00124  
00125  <H2> Recinfo file </H2>
00126  The recinfo file contains information about the different receiver functions we are trying to fit. Each
00127  line in the file corresponds to one receiver function and requires the following entries 
00128  <TABLE>
00129  <TR> <TD>Ray parameter in s/km </TD> <TD>\f$\Omega_0\f$ for gaussian filter </TD>
00130  <TD>\f$ \sigma\f$ for gaussian filter </TD> <TD> Waterlevel </TD> <TD>Relative error </TD> <TD>Shift in s </TD> <TD> Type of data </TD>
00131  <TD>Filename </TD></TR>
00132  </TABLE>
00133  Type of data is a single character. If it is 'a' we are also fitting absolute velocity information as calculated by the
00134  program rfvel and described in Svenningsen, GJI 170, 2007. In this case the following 
00135  additional fields are needed
00136  <TABLE>
00137  <TR> <TD>Weight for RF </TD> <TD>Weight for absolute velocities </TD> <TD>Filename for absolute velocities </TD> </TR>
00138  </TABLE>
00139  If data type is any other character we only fit receiver function information and the absolute velocity information cannot be there.
00140  <H2> Other features</H2>
00141  - You can gracefully stop the inversion anytime by creating a file called "abort" in the working directory. 
00142  The inversion will stop after the current iteration and will write out the usual information about best models etc.
00143  This is useful when the chosen number of generations was too high and the algorithm has already reached an acceptable solution. 
00144  The file is automatically deleted.
00145  */
00146 
00147 #include <iostream>
00148 #include <fstream>
00149 #include <algorithm>
00150 #include <numeric>
00151 #include <sstream>
00152 #include <string>
00153 #include "GA.h"
00154 #include "Iso1DMTObjective.h"
00155 #include "MTStation.h"
00156 #include "C1dInvGaConf.h"
00157 #include "AbsVelRecObjective.h"
00158 #include "Multi1DRecObjective.h"
00159 #include "SeismicDataComp.h"
00160 #include "CombinedRoughness.h"
00161 #include "SeismicModelDiff.h"
00162 #include "ResPkModel.h"
00163 #include "SurfaceWaveObjective.h"
00164 #include "SurfaceWaveData.h"
00165 #include "Adaptors.h"
00166 #include "MTFitSetup.h"
00167 #include <boost/bind.hpp>
00168 #include <boost/shared_ptr.hpp>
00169 #include <boost/filesystem.hpp>
00170 #include <boost/date_time/posix_time/posix_time.hpp>
00171 #include "Util.h"
00172 #include "MTRoughness.h"
00173 #include "SurfaceWaveData.h"
00174 #include "FileAbort.h"
00175 #include "SeisTools.h"
00176 enum tgatype
00177   { pareto,anneal};
00178 
00179 typedef boost::shared_ptr<GeneralObjective> pCGeneralObjective;
00180 using namespace std;
00181 
00182 void SetupAnnealingGA(boost::shared_ptr<GeneralGA> &GA,
00183     const C1dInvGaConf Configuration)
00184   {
00185     double InitTemperature = Configuration.inittemp;
00186     if (Configuration.inittemp < 0)
00187       {
00188         double avgcombfit = 0;
00189         GA->DoIteration(0, false);
00190         /*for (int i = 0; i < GA->GetAvgFit().size(); ++i)
00191          avgcombfit += GA->GetAvgFit().at(i);*/
00192         avgcombfit = accumulate(GA->GetAvgFit().begin(), GA->GetAvgFit().end(), 0.0);
00193         InitTemperature = avgcombfit * abs(Configuration.inittemp);
00194       }
00195     AnnealingGA *AnnealGA = dynamic_cast<AnnealingGA*>(GA.get());
00196     AnnealGA->SetParams(InitTemperature, Configuration.annealinggeneration,
00197         Configuration.coolingratio);
00198   }
00199 
00200 void SetupRecObjective(const string recinfofile,
00201     Multi1DRecObjective &RecObjective)
00202   {
00203     ifstream recinfo(recinfofile.c_str());
00204     double slowness, omega, sigma, cc, recerror, recweight, absweight;
00205     int shift;
00206     string recinputdata, absinputdata;
00207     char wantabsvel; // do we want absolute velocities as well
00208     while (recinfo.good())
00209       {
00210         wantabsvel = 'r';
00211         recinfo >> slowness >> omega >> sigma >> cc >> recerror >> shift
00212             >> wantabsvel >> recinputdata;
00213         if (wantabsvel == 'a') // if we want absolute velocities we have to read in additional information
00214           {
00215             recinfo >> recweight >> absweight >> absinputdata;
00216           }
00217         if (recinfo.good())
00218           {
00219             boost::shared_ptr<const SeismicDataComp>
00220                 RecData(new SeismicDataComp(recinputdata, SeismicDataComp::sac));
00221             Normalize(const_cast<SeismicDataComp*>(RecData.get())->GetData());
00222             if (wantabsvel == 'a')
00223               {
00224                 SurfaceWaveData AbsVelData;
00225                 AbsVelData.ReadAscii(absinputdata);
00226                 RecObjective.AddAbsVelFunction(RecData, AbsVelData, shift,
00227                     omega, sigma, cc, slowness, RecCalc::iterdecon, recerror,
00228                     absweight, recweight);
00229               }
00230             else
00231               {
00232                 RecObjective.AddRecFunction(RecData, shift, omega, sigma, cc,
00233                     slowness, RecCalc::iterdecon, recerror);
00234               }
00235           }
00236       }
00237   }
00238 
00239 int main(int argc, char *argv[])
00240   {
00241     boost::posix_time::ptime starttime =
00242         boost::posix_time::microsec_clock::local_time();
00243     string version = "$Id: 1dinvga.cpp 1696 2008-05-20 12:08:38Z mmoorkamp $";
00244     cout << endl << endl;
00245     cout << "Program " << version << endl;
00246     cout << "Genetic algorithm to jointly invert seismic and MT data " << endl;
00247     cout << "look at 1dinvga.conf for configuration and setup " << endl;
00248     cout << "The root name of log-files can be overwritten by using " << endl;
00249     cout << "1dinvga newrootname " << endl;
00250 
00251     C1dInvGaConf Configuration;
00252     MTStation MTData;
00253     //SeismicDataComp RecData;
00254     SurfaceWaveData RFAbsVel;
00255     SurfaceWaveData DispData;
00256     UniformRNG Random;
00257     Configuration.GetData("1dinvga.conf");
00258 
00259     ttranscribed transcribed;
00260     tgatype GAtype = pareto;
00261 
00262     string outputbase;
00263 
00264     if (argc > 1)
00265       outputbase = argv[1];
00266     else
00267       outputbase = Configuration.outputbase;
00268 
00269     ofstream misfitfile;
00270     ofstream valuefile;
00271     ofstream probfile;
00272     ofstream distancefile;
00273     ofstream fitstat((outputbase+".ftst").c_str());
00274     ofstream uniquepop((outputbase+".unpop").c_str());
00275     ofstream rankfile((outputbase+".rank").c_str());
00276     ofstream frontfile((outputbase+".front").c_str());
00277     ofstream bestfile((outputbase+".best").c_str());
00278 
00279     if (Configuration.verbose) // in most cases we do not need all of these values
00280       {
00281         misfitfile.open((outputbase+".msft").c_str());
00282         valuefile.open((outputbase+".vals").c_str());
00283         probfile.open((outputbase+".probs").c_str());
00284         distancefile.open((outputbase+".dist").c_str());
00285       }
00286 
00287     if ( (Configuration.thickbase.size() != Configuration.resbase.size())
00288         || (Configuration.thickbase.size() != Configuration.svelbase.size()))
00289       {
00290         cerr << "Configuration of genes is not consistent ! ";
00291         return 100;
00292       }
00293     const int nparam = 3;
00294     const int genes = (Configuration.thickbase.size()
00295         + Configuration.resbase.size() + Configuration.svelbase.size());
00296     const int popsize = Configuration.popsize;
00297     const int maxgen = Configuration.generations;
00298     const int paramlength = genes/nparam;
00299     ttranscribed basevalues(genes);
00300     ttranscribed stepsizes(genes);
00301     tsizev genesizes(genes);
00302 
00303     misfitfile << popsize << " " << maxgen << " " << endl;
00304     valuefile << genes << " "<< popsize << " " << maxgen << endl;
00305 
00306     copy(Configuration.resbase.begin(), Configuration.resbase.end(),
00307         basevalues.begin());
00308     copy(Configuration.resstep.begin(), Configuration.resstep.end(),
00309         stepsizes.begin());
00310     copy(Configuration.ressizes.begin(), Configuration.ressizes.end(),
00311         genesizes.begin());
00312 
00313     copy(Configuration.thickbase.begin(), Configuration.thickbase.end(),
00314         basevalues.begin()+paramlength);
00315     copy(Configuration.thickstep.begin(), Configuration.thickstep.end(),
00316         stepsizes.begin()+paramlength);
00317     copy(Configuration.thicksizes.begin(), Configuration.thicksizes.end(),
00318         genesizes.begin()+paramlength);
00319 
00320     copy(Configuration.svelbase.begin(), Configuration.svelbase.end(),
00321         basevalues.begin()+2*paramlength);
00322     copy(Configuration.svelstep.begin(), Configuration.svelstep.end(),
00323         stepsizes.begin()+2*paramlength);
00324     copy(Configuration.svelsizes.begin(), Configuration.svelsizes.end(),
00325         genesizes.begin()+2*paramlength);
00326 
00327     const int totalgenesize = accumulate(genesizes.begin(), genesizes.end(), 0);
00328     BinaryPopulation Population(popsize, totalgenesize, Random, true);
00329     BinaryTournamentSelect Select(Random, boost::bind(
00330         &GeneralPopulation::GetProbabilities, boost::ref(Population)),
00331         boost::bind(&GeneralPopulation::GetCrowdingDistances,
00332             boost::ref(Population)));
00333     StandardPropagation Propagator(&Select, &Population, &Random);
00334     double indmutationprob = 1.0 - pow(1.0 - Configuration.mutationprob, 1.
00335         /totalgenesize); // we specify the overall probability for mutation in config file 
00336     cout << "Individual Mutation set to: " << indmutationprob << endl;
00337     Propagator.SetParams(indmutationprob, Configuration.crossoverprob);
00338     GrayTranscribe Transcribe(basevalues, stepsizes, genesizes);
00339 
00340     //read in data
00341     try
00342       {
00343         boost::shared_ptr<Multi1DRecObjective> RecObjective(new Multi1DRecObjective());
00344         //we only read the data that has positive weights in the inversion
00345         if (Configuration.weights.at(0)> 0)
00346           {
00347             MTData.GetData(Configuration.mtinputdata);
00348           }
00349         if (Configuration.weights.at(1)> 0)
00350           {
00351             SetupRecObjective(Configuration.recinfofile,*RecObjective.get());
00352           }
00353         if (Configuration.weights.at(2)> 0)
00354           {
00355             DispData.ReadFile(Configuration.dispdata);
00356           }
00357         //setup MT Objective function
00358         boost::shared_ptr<Iso1DMTObjective> MTObjective(new Iso1DMTObjective(MTData));
00359         SetupMTFitParameters(Configuration,*MTObjective);
00360         MTObjective->SetFitExponent(Configuration.mtfitexponent);
00361 
00362         //setup RF objective function
00363         RecCalc::trfmethod rfmethod = RecCalc::specdiv;
00364         if (Configuration.recmethod == "iterdecon")
00365           {
00366             rfmethod = RecCalc::iterdecon;
00367           }
00368 
00369         RecObjective->SetPoisson(Configuration.poisson);
00370         RecObjective->SetTimeWindow(Configuration.starttime,Configuration.endtime);
00371 
00372         //setup surface wave data
00373         boost::shared_ptr<SurfaceWaveObjective> SurfObjective(new SurfaceWaveObjective(DispData));
00374         SurfObjective->SetFitExponent(Configuration.surffitexponent);
00375         SurfObjective->SetPoisson(Configuration.poisson);
00376         SurfObjective->SetErrorLevel(Configuration.surferror);
00377 
00378         //setup Regularization
00379         boost::shared_ptr<GeneralObjective> RecRegularization;
00380         if (!Configuration.usevrefmodel)
00381           {
00382             RecRegularization = boost::shared_ptr<GeneralObjective>(new CombinedRoughness);
00383           }
00384         else
00385           {
00386             if (!boost::filesystem::exists(Configuration.vrefmodel))
00387               {
00388                 cerr << "Cannot find reference model for regularization ! Exiting !" << endl;
00389                 return 100;
00390               }
00391             ResPkModel VRefModel;
00392             VRefModel.GetData(Configuration.vrefmodel);
00393             RecRegularization = boost::shared_ptr<GeneralObjective>(new SeismicModelDiff(VRefModel));
00394           }
00395         boost::shared_ptr<GeneralObjective> MTRegularization (new MTRoughness());
00396         vector<pCGeneralObjective> ObjVector;
00397         ObjVector.push_back(MTObjective);
00398         ObjVector.push_back(RecObjective);
00399         ObjVector.push_back(SurfObjective);
00400         ObjVector.push_back(RecRegularization);
00401         ObjVector.push_back(MTRegularization);
00402 
00403         boost::shared_ptr<GeneralGA> GA;
00404         if (Configuration.gatype == "pareto")
00405           {
00406             GAtype = pareto;
00407             boost::shared_ptr<ParetoGA> Pareto(new ParetoGA(&Propagator,&Population,&Transcribe,ObjVector));
00408             GA = Pareto;
00409           }
00410         else if (Configuration.gatype == "anneal")
00411           {
00412             GAtype = anneal;
00413             boost::shared_ptr<AnnealingGA> Annealing(new AnnealingGA(&Propagator,&Population,&Transcribe,ObjVector));
00414             GA = Annealing;
00415           }
00416         else
00417           {
00418             cerr << "Invalid GA type in configuration file." << endl;
00419             cerr << " Has to be either 'pareto' or 'anneal' !" << endl;
00420             return 100;
00421           }
00422         GA->SetWeights(Configuration.weights);
00423         //Setting up indices for forward modelling
00424         GeneralGA::tparamindv ParamIndices;
00425         const int nmtparam = 2 * Configuration.resbase.size();
00426         std::vector<int> LocalIndices;
00427         //generate Indices 0 .. nmtparam for MT Objective function
00428         generate_n(back_inserter(LocalIndices),nmtparam,IntSequence(0));
00429         ParamIndices.push_back(LocalIndices);
00430         const int nseisparam = 2 * Configuration.thickbase.size();
00431         LocalIndices.clear();
00432         // generate Indice thickbase .. thickbase+nseisparam for rf and surface wave data
00433         generate_n(back_inserter(LocalIndices),nseisparam,IntSequence(Configuration.thickbase.size()));
00434         ParamIndices.push_back(LocalIndices);
00435         ParamIndices.push_back(LocalIndices);
00436         const int nmodelparam = 3 * Configuration.thickbase.size();
00437         LocalIndices.clear();
00438         //generate Indices 0 .. nmodelparam for Regularization Objective function
00439         generate_n(back_inserter(LocalIndices),nmodelparam,IntSequence(0));
00440         ParamIndices.push_back(LocalIndices);
00441         ParamIndices.push_back(LocalIndices); // we push back twice, because both Regularization functionals work with all parameters
00442         GA->SetParameterIndices(ParamIndices);
00443         GA->SetThreads(Configuration.threads);
00444         GA->SetElitist(Configuration.elitist);
00445 
00446         if (GAtype == anneal)
00447           {
00448             SetupAnnealingGA(GA,Configuration);
00449             Population.InitPop();
00450           }
00451         //Population.PrintPopulation(cout);
00452         for (int i = 0; i < maxgen; ++i)
00453           {
00454             GA->DoIteration(i, i == (maxgen-1));
00455             if (Configuration.verbose) // in most cases we do not need all of these values
00456 
00457               {
00458                 GA->PrintMisfit(misfitfile);
00459                 GA->PrintTranscribed(valuefile);
00460                 Population.PrintProbabilities(probfile);
00461                 Population.PrintDistances(distancefile);
00462               }
00463             GA->PrintBestMisfit(frontfile);
00464 
00465             fitstat << i << " ";
00466             GA->PrintFitStat(fitstat);
00467             if (WantAbort()) //if we want to exit prematurely
00468 
00469               {
00470                 RemoveAbort();
00471                 i = maxgen; // set counter to last generation, so we do everything that follows
00472               }
00473           }
00474 
00475         int bestcount = 0;
00476         UniquePop FinalUnique;
00477         tfitvec bestfit(ObjVector.size());
00478         tpopmember member(Population.GetGenesize());
00479 
00480         vector<int> BestIndices(GA->GetBestModelIndices());
00481         const int noutmodels = GA->GetNBestmodels();
00482         const int nobjective = ObjVector.size();
00483         GeneralGA::tparamvector LocalParameters(nobjective);
00484         for (int i = 0; i < nobjective; ++i)
00485           {
00486             LocalParameters.at(i).resize(ParamIndices.at(i).size(),false);
00487           }
00488         ofstream finalmodels((outputbase+".final").c_str());
00489         for (int h= 0; h < noutmodels; ++h)
00490           {
00491             member = row(Population.GetPopulation(),BestIndices.at(h));
00492             cout << "Best: " << h << " Index : " << BestIndices.at(h) << " ";
00493 
00494             transcribed = Transcribe.GetValues(member);
00495             GA->SetupParams(transcribed,LocalParameters);
00496             for (int f = 0; f < nobjective; ++f)
00497               {
00498                 if (Configuration.weights.at(f)> 0)
00499                   {
00500                     bestfit(f) = ObjVector.at(f)->CalcPerformance(LocalParameters.at(f));
00501                   }
00502                 else
00503                   {
00504                     bestfit(f) = 0;
00505                   }
00506                 cout << bestfit(f) << " ";
00507               }
00508 
00509             if (FinalUnique.Insert(bestfit,transcribed))
00510               {
00511                 copy(bestfit.begin(),bestfit.end(),ostream_iterator<double>(finalmodels," "));
00512                 cout << " " << h;
00513                 finalmodels << " " << bestcount << endl;
00514                 ostringstream filename;
00515                 filename << "best_" << bestcount;
00516                 cout << " Saved as : " << filename.str();
00517                 if (Configuration.weights.at(0)> 0)
00518                   {
00519                     MTObjective->WriteModel(filename.str()+"_mt.mod");
00520                     MTObjective->WritePlot(filename.str()+"_mt.plot");
00521                     MTObjective->WriteData(filename.str());
00522                   }
00523                 if (Configuration.weights.at(1)> 0)
00524                   {
00525                     RecObjective->WriteData(filename.str()+".rec");
00526                     RecObjective->WriteModel(filename.str()+"_rec.mod");
00527                     RecObjective->WritePlot(filename.str()+"_rec");
00528                   }
00529                 if (Configuration.weights.at(2)> 0)
00530                   {
00531                     SurfObjective->WriteData(filename.str()+".disp");
00532                     SurfObjective->WriteModel(filename.str()+"_disp.mod");
00533                     SurfObjective->WritePlot(filename.str()+"_disp.plot");
00534                   }
00535                 filename.str("");
00536                 bestcount++;
00537               }
00538             cout << endl;
00539           }
00540         FinalUnique.PrintAll(bestfile);
00541         GA->PrintUniquePop(uniquepop);
00542         boost::posix_time::ptime endtime = boost::posix_time::microsec_clock::local_time();
00543         std::cout << "Total Runtime: " << endtime - starttime << std::endl;
00544       }
00545     catch(CFatalException &e)
00546       {
00547         cerr << e.what() << endl;
00548         return -1;
00549       }
00550   }

Generated on Fri Jul 4 15:30:20 2008 for GPLIB++ by  doxygen 1.5.5