MOOCHO (Single Doxygen Collection) Version of the Day
MultiPeriodNLPThyraEpetraAdvDiffReactOptMain.cpp
Go to the documentation of this file.
00001 #include "GLpApp_AdvDiffReactOptModelCreator.hpp"
00002 #include "MoochoPack_MoochoThyraSolver.hpp"
00003 #include "Thyra_EpetraModelEvaluator.hpp"
00004 #include "Thyra_EpetraLinearOp.hpp"
00005 #include "Thyra_DefaultClusteredSpmdProductVectorSpace.hpp"
00006 #include "Thyra_DefaultMultiPeriodModelEvaluator.hpp"
00007 #include "Thyra_VectorSpaceTester.hpp"
00008 #include "Stratimikos_DefaultLinearSolverBuilder.hpp"
00009 #include "Thyra_DefaultInverseModelEvaluator.hpp"
00010 #include "Thyra_DefaultScaledAdjointLinearOp.hpp"
00011 #include "Thyra_DefaultMultipliedLinearOp.hpp"
00012 #include "Thyra_TestingTools.hpp"
00013 #include "Teuchos_OpaqueWrapper.hpp"
00014 #include "Teuchos_GlobalMPISession.hpp"
00015 #include "Teuchos_CommandLineProcessor.hpp"
00016 #include "Teuchos_StandardCatchMacros.hpp"
00017 #include "Teuchos_VerboseObject.hpp"
00018 #include "Teuchos_Tuple.hpp"
00019 #include "Teuchos_Utils.hpp"
00020 #include "Teuchos_DefaultComm.hpp"
00021 #ifdef HAVE_MPI
00022 #  include "Teuchos_DefaultMpiComm.hpp"
00023 #  include "Epetra_MpiComm.h"
00024 #else
00025 #  include "Teuchos_DefaultSerialComm.hpp"
00026 #  include "Epetra_SerialComm.h"
00027 #endif
00028 
00029 namespace {
00030 
00031 typedef AbstractLinAlgPack::value_type  Scalar;
00032 
00033 } // namespace
00034 
00035 int main( int argc, char* argv[] )
00036 {
00037 
00038   using Teuchos::rcp;
00039   using Teuchos::rcp_dynamic_cast;
00040   using Teuchos::rcp_implicit_cast;
00041   using Teuchos::null;
00042   using Teuchos::RCP;
00043   using Teuchos::outArg;
00044   using Teuchos::Array;
00045   using Teuchos::tuple;
00046   using Teuchos::ParameterList;
00047   using Teuchos::OpaqueWrapper;
00048   using Teuchos::OSTab;
00049   using Teuchos::CommandLineProcessor;
00050   using Teuchos::toString;
00051   using Thyra::VectorBase;
00052   using Thyra::ProductVectorBase;
00053   typedef Thyra::ModelEvaluatorBase MEB;
00054   typedef Thyra::Ordinal Ordinal;
00055   using Thyra::ModelEvaluator;
00056   using MoochoPack::MoochoSolver;
00057   using MoochoPack::MoochoThyraSolver;
00058 
00059   Teuchos::GlobalMPISession mpiSession(&argc,&argv);
00060 
00061   const int procRank = mpiSession.getRank();
00062   const int numProcs = mpiSession.getNProc();
00063 
00064   Teuchos::Time timer("");
00065   
00066   bool result, success = true;
00067 
00068   RCP<Teuchos::FancyOStream>
00069     out = Teuchos::VerboseObjectBase::getDefaultOStream();
00070 
00071   try {
00072   
00073     Stratimikos::DefaultLinearSolverBuilder   lowsfCreator;
00074     GLpApp::AdvDiffReactOptModelCreator     epetraModelCreator;
00075 
00076     // Create the solver object
00077     MoochoThyraSolver solver;
00078 
00079     //
00080     // Get options from the command line
00081     //
00082 
00083     CommandLineProcessor  clp;
00084     clp.throwExceptions(false);
00085     clp.addOutputSetupOptions(true);
00086 
00087     epetraModelCreator.setupCLP(&clp);
00088     lowsfCreator.setupCLP(&clp);
00089     solver.setupCLP(&clp);
00090 
00091     int numProcsPerCluster = -1;
00092     clp.setOption( "num-procs-per-cluster", &numProcsPerCluster,
00093       "Number of processes in a cluster (<=0 means only one cluster)." );
00094     int numPeriodsPerCluster = 1;
00095     clp.setOption( "num-periods-per-cluster", &numPeriodsPerCluster,
00096       "Number of periods in a cluster." );
00097     bool dumpAll = false;
00098     clp.setOption( "dump-all", "no-dump-all", &dumpAll,
00099       "Set to true, then a bunch of debugging output will be created for the clustered vector tests." );
00100     bool skipSolve = false;
00101     clp.setOption( "skip-solve", "no-skip-solve", &skipSolve,
00102       "Temporary flag for skip solve for testing." );
00103     double perturbedParamScaling = 1.0;
00104     clp.setOption( "p-perturb-scaling", &perturbedParamScaling,
00105       "Scaling for perturbed paramters from the initial forward solve." );
00106     bool doMultiPeriod = true;
00107     clp.setOption( "multi-period", "no-multi-period", &doMultiPeriod,
00108       "Do a mulit-period solve or not." );
00109     bool useOuterInverse = true;
00110     clp.setOption( "use-outer-inverse", "use-inner-inverse", &useOuterInverse,
00111       "Determines if the outer inverse model will be used or the inner inverse." );
00112     double periodParamScale = 1.0;
00113     clp.setOption( "period-param-scale", &periodParamScale,
00114       "Sets the scaling factor to scale z[i] from one period to the next." );
00115     bool initialSolveContinuation = false;
00116     clp.setOption( "init-solve-continuation", "init-solve-all-at-once", &initialSolveContinuation,
00117       "Determines if the inital solve is done using continuation or all at once." );
00118     bool useStatelessPeriodModel = false;
00119     clp.setOption( "use-stateless-period-model", "use-statefull-period-model", &useStatelessPeriodModel,
00120       "Determines if a stateless or a statefull period model should be used or not." );
00121     double stateInvError = 1e-8;
00122     clp.setOption( "state-inv-error", &stateInvError,
00123       "The error in the l2 norm of the state inverse solution error." );
00124     double paramInvError = 1e-8;
00125     clp.setOption( "param-inv-error", &paramInvError,
00126       "The error in the l2 norm of the parameter inverse solution error." );
00127 
00128     CommandLineProcessor::EParseCommandLineReturn
00129       parse_return = clp.parse(argc,argv,&std::cerr);
00130 
00131     if( parse_return != CommandLineProcessor::PARSE_SUCCESSFUL )
00132       return parse_return;
00133 
00134     lowsfCreator.readParameters(out.get());
00135     solver.readParameters(out.get());
00136 
00137     *out
00138       << "\n***"
00139       << "\n*** NLPThyraEpetraAdvDiffReactOptMain, Global numProcs = "<<numProcs
00140       << "\n***\n";
00141 
00142     int clusterRank = -1;
00143     int numClusters = -1;
00144 
00145 #ifdef HAVE_MPI
00146 
00147     RCP<OpaqueWrapper<MPI_Comm> >
00148       intraClusterMpiComm = Teuchos::opaqueWrapper<MPI_Comm>(MPI_COMM_WORLD),
00149       interClusterMpiComm = Teuchos::null;
00150     
00151     {
00152       if ( numProcsPerCluster <= 0 ) {
00153         *out
00154           << "\nnumProcsPerCluster = " << numProcsPerCluster
00155           << " <= 0: Setting to " << numProcs << "...\n";
00156         numProcsPerCluster = numProcs;
00157       }
00158       *out << "\nCreating communicator for local cluster of "<<numProcsPerCluster<<" processes ...\n";
00159       numClusters = numProcs/numProcsPerCluster;
00160       const int remainingProcs = numProcs%numProcsPerCluster;
00161       TEST_FOR_EXCEPTION(
00162         remainingProcs!=0,std::logic_error
00163         ,"Error, The number of processes per cluster numProcsPerCluster="<<numProcsPerCluster
00164         << " does not divide into the global number of processes numProcs="<<numProcs
00165         << " and instead has remainder="<<remainingProcs<<"!"
00166         );
00167       // Determine which cluster this process is part of and what the global
00168       // process ranges are.
00169       clusterRank = procRank / numProcsPerCluster; // Integer division!
00170       *out << "\nclusterRank = " << clusterRank << "\n";
00171       const int firstClusterProcRank = clusterRank * numProcsPerCluster;
00172       const int lastClusterProcRank = firstClusterProcRank + numProcsPerCluster - 1;
00173       *out << "\nclusterProcRange = ["<<firstClusterProcRank<<","<<lastClusterProcRank<<"]\n";
00174       // Create the communicator for this cluster of processes
00175       *out << "\nCreating intraClusterMpiComm ...";
00176       MPI_Comm rawIntraClusterMpiComm = MPI_COMM_NULL;
00177       MPI_Comm_split(
00178         MPI_COMM_WORLD        // comm
00179         ,clusterRank          // color (will all be put in the same output comm)
00180         ,0                    // key (not important here)
00181         ,&rawIntraClusterMpiComm // newcomm
00182         );
00183       intraClusterMpiComm = Teuchos::opaqueWrapper(rawIntraClusterMpiComm,MPI_Comm_free);
00184       {
00185         *out << "\nintraClusterMpiComm:";
00186         Teuchos::OSTab tab(out);
00187         int rank, size;
00188         MPI_Comm_size(*intraClusterMpiComm,&size);
00189         MPI_Comm_rank(*intraClusterMpiComm,&rank);
00190         *out << "\nsize="<<size;
00191         *out << "\nrank="<<rank;
00192         *out << "\n";
00193       }
00194       // Create the communicator for just the root process in each cluster
00195       *out << "\nCreating interClusterMpiComm ...";
00196       MPI_Comm rawInterClusterMpiComm = MPI_COMM_NULL;
00197       MPI_Comm_split(
00198         MPI_COMM_WORLD                                  // comm
00199         ,procRank==firstClusterProcRank?0:MPI_UNDEFINED // color
00200         ,0                                              // key
00201         ,&rawInterClusterMpiComm                           // newcomm
00202         );
00203       if(rawInterClusterMpiComm!=MPI_COMM_NULL)
00204         interClusterMpiComm = Teuchos::opaqueWrapper(rawInterClusterMpiComm,MPI_Comm_free);
00205       else
00206         interClusterMpiComm = Teuchos::opaqueWrapper(rawInterClusterMpiComm);
00207       {
00208         *out << "\ninterClusterMpiComm:";
00209         Teuchos::OSTab tab(out);
00210         if(*interClusterMpiComm==MPI_COMM_NULL) {
00211           *out << " NULL\n";
00212         }
00213         else {
00214           int rank, size;
00215           MPI_Comm_size(*interClusterMpiComm,&size);
00216           MPI_Comm_rank(*interClusterMpiComm,&rank);
00217           *out << "\nsize="<<size;
00218           *out << "\nrank="<<rank;
00219           *out << "\n";
00220         }
00221       }
00222     }
00223 
00224 #endif
00225 
00226     RCP<Epetra_Comm> comm = Teuchos::null;
00227 #ifdef HAVE_MPI
00228     comm = Teuchos::rcp(new Epetra_MpiComm(*intraClusterMpiComm));
00229     Teuchos::set_extra_data(intraClusterMpiComm, "mpiComm", outArg(comm));
00230 #else
00231     comm = Teuchos::rcp(new Epetra_SerialComm());
00232 #endif
00233     
00234     //
00235     // Create the Thyra::ModelEvaluator object
00236     //
00237     
00238     *out << "\nCreate the GLpApp::AdvDiffReactOptModel wrapper object ...\n";
00239     
00240     RCP<GLpApp::AdvDiffReactOptModel>
00241       epetraModel = epetraModelCreator.createModel(comm);
00242 
00243     *out << "\nCreate the Thyra::LinearOpWithSolveFactory object ...\n";
00244 
00245     RCP<Thyra::LinearOpWithSolveFactoryBase<Scalar> >
00246       lowsFactory = lowsfCreator.createLinearSolveStrategy("");
00247     // ToDo: Set the output stream before calling above!
00248     
00249     *out << "\nCreate the Thyra::EpetraModelEvaluator wrapper object ...\n";
00250     
00251     RCP<Thyra::EpetraModelEvaluator>
00252       epetraThyraModel = rcp(new Thyra::EpetraModelEvaluator()); // Sets default options!
00253     epetraThyraModel->setOStream(out);
00254     epetraThyraModel->initialize(epetraModel,lowsFactory);
00255 
00256     *out
00257       << "\nnx = " << epetraThyraModel->get_x_space()->dim()
00258       << "\nnp = " << epetraThyraModel->get_p_space(0)->dim() << "\n";
00259 
00260     //
00261     // Create the parallel product spaces for x and f
00262     //
00263 
00264     RCP<const Thyra::ProductVectorSpaceBase<Scalar> >
00265       x_bar_space, f_bar_space;
00266     
00267 #ifdef HAVE_MPI
00268 
00269     // For now just build and test these vector spaces if we are not doing a
00270     // solve!  We have a lot more work to do to the "Clustered" support
00271     // software before this will work for a solve.
00272     
00273     if (skipSolve) {
00274       
00275       *out << "\nCreate block parallel vector spaces for multi-period model.x and model.f ...\n";
00276       RCP<const Teuchos::Comm<Ordinal> >
00277         intraClusterComm = rcp(new Teuchos::MpiComm<Ordinal>(intraClusterMpiComm)),
00278         interClusterComm = Teuchos::createMpiComm<Ordinal>(interClusterMpiComm);
00279       x_bar_space = Teuchos::rcp(
00280         new Thyra::DefaultClusteredSpmdProductVectorSpace<Scalar>(
00281           intraClusterComm
00282           ,0 // clusterRootRank
00283           ,interClusterComm
00284           ,1 // numBlocks
00285           ,tuple<RCP<const Thyra::VectorSpaceBase<Scalar> > >(
00286             epetraThyraModel->get_x_space()
00287             ).getRawPtr()
00288           )
00289         );
00290       f_bar_space = Teuchos::rcp(
00291         new Thyra::DefaultClusteredSpmdProductVectorSpace<Scalar>(
00292           intraClusterComm
00293           ,0 // clusterRootRank
00294           ,interClusterComm
00295           ,1 // numBlocks
00296           ,tuple<RCP<const Thyra::VectorSpaceBase<Scalar> > >(
00297             epetraThyraModel->get_f_space()
00298             ).getRawPtr()
00299           )
00300         );
00301       
00302       Thyra::VectorSpaceTester<Scalar> vectorSpaceTester;
00303       vectorSpaceTester.show_all_tests(true);
00304       vectorSpaceTester.dump_all(dumpAll);
00305 
00306 #ifdef RTOPPACK_SPMD_APPLY_OP_DUMP
00307       RTOpPack::show_mpi_apply_op_dump = dumpAll;
00308 #endif
00309 #ifdef THYRA_SPMD_VECTOR_BASE_DUMP
00310       Thyra::SpmdVectorBase<Scalar>::show_dump = dumpAll;
00311 #endif
00312 
00313       *out << "\nTesting the vector space x_bar_space ...\n";
00314       result = vectorSpaceTester.check(*x_bar_space,OSTab(out).get());
00315       if(!result) success = false;
00316 
00317       *out << "\nTesting the vector space f_bar_space ...\n";
00318       result = vectorSpaceTester.check(*f_bar_space,OSTab(out).get());
00319       if(!result) success = false;
00320       
00321       RCP<const VectorBase<Scalar> >
00322         x0 = epetraThyraModel->getNominalValues().get_x();
00323       
00324 /* 2008/02/21: rabartl: I have commented this out since it is causing an MPI error?
00325 
00326       double nrm_x0;
00327 
00328       *out << "\nTiming a global reduction across just this cluster: ||x0||_1 = ";
00329       timer.start(true);
00330       nrm_x0 = Thyra::norm_1(*x0);
00331       *out << nrm_x0 << "\n";
00332       timer.stop();
00333       *out << "\n    time = " << timer.totalElapsedTime() << " seconds\n";
00334       
00335       *out << "\nTiming a global reduction across the entire set of processes: ||x0||_1 = ";
00336       timer.start(true);
00337       RTOpPack::ROpNorm1<Scalar> norm_1_op;
00338       RCP<RTOpPack::ReductTarget> norm_1_targ = norm_1_op.reduct_obj_create();
00339       const Teuchos::RCP<const Teuchos::Comm<Teuchos_Ordinal> > comm
00340         = Teuchos::DefaultComm<Ordinal>::getComm();
00341       const Teuchos::ArrayView<const Teuchos::Ptr<const VectorBase<Scalar> > >
00342         vecs = Teuchos::tuple(Teuchos::ptrInArg(*x0));
00343       Teuchos::dyn_cast<const Thyra::SpmdVectorBase<Scalar> >(*x0).applyOpImplWithComm(
00344         comm.ptr(),
00345         norm_1_op, vecs, Teuchos::null, norm_1_targ.ptr(),
00346         0, -1, 0
00347         );
00348       nrm_x0 = norm_1_op(*norm_1_targ);
00349       *out << nrm_x0 << "\n";
00350       timer.stop();
00351       *out << "\n    time = " << timer.totalElapsedTime() << " seconds\n";
00352 
00353 */
00354 
00355 #ifdef RTOPPACK_SPMD_APPLY_OP_DUMP
00356       RTOpPack::show_mpi_apply_op_dump = false;
00357 #endif
00358 #ifdef THYRA_SPMD_VECTOR_BASE_DUMP
00359       Thyra::SpmdVectorBase<Scalar>::show_dump = false;
00360 #endif
00361 
00362     }
00363 
00364 #endif // HAVE_MPI
00365     
00366     if(skipSolve) {
00367 
00368       if(success)
00369         *out << "\nEnd Result: TEST PASSED" << endl;
00370       else
00371         *out << "\nEnd Result: TEST FAILED" << endl;
00372 
00373       return ( success ? 0 : 1 );
00374 
00375     }
00376 
00377     const int N = numPeriodsPerCluster;
00378 
00379     Array<RCP<Thyra::ModelEvaluator<Scalar> > >
00380       inverseThyraModels(N);
00381     if (useOuterInverse) {
00382       *out << "\nUsing Thyra::DefaultInverseModelEvaluator for the objective function ...\n";
00383       if ( useStatelessPeriodModel ) {
00384         *out << "\nBuilding a single Thyra::DefaultInverseModelEvaluator object where the matching vector will be maintained externally ...\n";
00385       }
00386       else {
00387         *out << "\nBuilding multiple Thyra::DefaultInverseModelEvaluator objects where the matching vector is held internally ...\n";
00388       }
00389       RCP<ParameterList> invMEPL = Teuchos::parameterList();
00390       invMEPL->set( "Observation Multiplier", 1.0 );
00391       invMEPL->set( "Parameter Multiplier", epetraModel->getDataPool()->getbeta() );
00392       if ( useStatelessPeriodModel )
00393         invMEPL->set( "Observation Target as Parameter", true );
00394       RCP<const Thyra::EpetraLinearOp>
00395         H = Thyra::epetraLinearOp(epetraModel->getDataPool()->getH(),"H"),
00396         R = Thyra::epetraLinearOp(epetraModel->getDataPool()->getR(),"R");
00397       RCP<const Thyra::MultiVectorBase<Scalar> >
00398         B_bar = Thyra::create_MultiVector(
00399           epetraModel->get_B_bar(),
00400           R->spmdRange()
00401           );
00402       RCP<const Thyra::LinearOpBase<Scalar> >
00403         R_bar = Thyra::multiply<Scalar>(Thyra::adjoint<Scalar>(B_bar),R,B_bar);
00404       for ( int i = 0; i < N; ++i ) {
00405         if ( ( useStatelessPeriodModel && i==0 ) || !useStatelessPeriodModel ) {
00406           RCP<Thyra::DefaultInverseModelEvaluator<Scalar> >
00407             _inverseThyraModel = Thyra::defaultInverseModelEvaluator<Scalar>(
00408               epetraThyraModel );
00409           _inverseThyraModel->setParameterList(invMEPL);
00410           _inverseThyraModel->set_observationMatchWeightingOp(H);
00411           _inverseThyraModel->set_parameterRegularizationWeightingOp(R_bar);
00412           inverseThyraModels[i] = _inverseThyraModel;
00413         }
00414         else {
00415 #ifdef TEUCHOS_DEBUG
00416           TEST_FOR_EXCEPT( ! ( useStatelessPeriodModel && i > 0 ) );
00417 #endif
00418           inverseThyraModels[i] = inverseThyraModels[0];
00419         }
00420       }
00421     }
00422     else {
00423       *out << "\nUsing built-in inverse objective function ...\n";
00424       TEST_FOR_EXCEPTION(
00425         N != 1, std::logic_error,
00426         "Error, you can't have N = "<<N<<" > 1\n"
00427         "and be using an internal inverse objective!" );
00428       inverseThyraModels[0] = epetraThyraModel;
00429     }
00430 
00431     const int p_index = 0;
00432     const int z_index = 1;
00433     const int z_p_index = 1; // Ordinal of the reaction rate parameter parameter subvector
00434     const int z_x_index = 2; // Ordinal of the state matching subvector parameter
00435     Array<int> z_indexes;
00436     if (useStatelessPeriodModel)
00437       z_indexes = tuple<int>(z_p_index, z_x_index);
00438     else
00439       z_indexes = tuple<int>(z_p_index);
00440     Array<Array<RCP<const VectorBase<Scalar> > > > z;
00441     const int g_index = ( useOuterInverse ? 1 : 0 );
00442     Array<Scalar> weights;
00443     RCP<VectorBase<Scalar> >
00444       z_base = inverseThyraModels[0]->getNominalValues().get_p(z_index)->clone_v();
00445     *out << "\nz_base =\n" << Teuchos::describe(*z_base,Teuchos::VERB_EXTREME);
00446     Scalar scale_z_i = 1.0;
00447     for ( int i = 0; i < N; ++i ) {
00448       weights.push_back(1.0);
00449       const RCP<VectorBase<Scalar> > z_i = z_base->clone_v();
00450       Vt_S( z_i.ptr(), scale_z_i );
00451       *out << "\nz["<<i<<"] =\n" << Teuchos::describe(*z_i,Teuchos::VERB_EXTREME);
00452       if ( useStatelessPeriodModel ) {
00453         z.push_back(
00454           tuple<RCP<const VectorBase<Scalar> > >(
00455             z_i,
00456             null // We will set this again later!
00457             )
00458           );
00459       }
00460       else {
00461         z.push_back(
00462           tuple<RCP<const VectorBase<Scalar> > >(z_i)
00463           );
00464       }
00465       scale_z_i *= periodParamScale;
00466     }
00467 
00468     RCP<Thyra::ModelEvaluator<Scalar> >
00469       thyraModel = inverseThyraModels[0];
00470 
00471     if (doMultiPeriod) {
00472       thyraModel =
00473         rcp(
00474           new Thyra::DefaultMultiPeriodModelEvaluator<Scalar>(
00475             N, inverseThyraModels, z_indexes, z, g_index, weights,
00476             x_bar_space, f_bar_space
00477             )
00478           );
00479     }
00480     
00481     MoochoSolver::ESolutionStatus solution_status;
00482 
00483     //
00484     *out << "\n***\n*** Solving the initial forward problem\n***\n";
00485     //
00486 
00487     // Set the solve mode to solve the forward problem
00488     solver.setSolveMode(MoochoThyraSolver::SOLVE_MODE_FORWARD);
00489 
00490     // Save the solution for model.x and model.p to be used later
00491     RCP<const VectorBase<Scalar> >
00492       x_opt, // Will be set below
00493       x_init, // Will be set below
00494       p_opt = inverseThyraModels[0]->getNominalValues().get_p(0)->clone_v();
00495 
00496     *out << "\np_opt =\n" << Teuchos::describe(*p_opt,Teuchos::VERB_EXTREME);
00497     
00498     if ( initialSolveContinuation ) {
00499       
00500       *out << "\nSolving individual period problems one at time using continuation ...\n";
00501 
00502       RCP<ProductVectorBase<Scalar> >
00503         x_opt_prod = rcp_dynamic_cast<ProductVectorBase<Scalar> >(
00504          createMember( thyraModel->get_x_space() ), true );
00505 
00506       RCP<const VectorBase<Scalar> > period_x;
00507 
00508       for ( int i = 0; i < N; ++i ) {
00509 
00510         *out << "\nSolving period i = " << i << " using guess from last period ...\n";
00511       
00512         // Set the deliminator for the output files!
00513         solver.getSolver().set_output_context("fwd-init-"+toString(i));
00514 
00515         // Set the period model
00516         solver.setModel(inverseThyraModels[i]);
00517         
00518         // Set the initial guess and the parameter values
00519         MEB::InArgs<Scalar> initialGuess = inverseThyraModels[i]->createInArgs();
00520         initialGuess.set_p(z_index,z[i][0]->clone_v());
00521         initialGuess.set_p(p_index,p_opt->clone_v());
00522         if ( i == 0 ) {
00523           // For the first period just use whatever initial guess is built
00524           // into the model
00525         }
00526         else {
00527           // Set the final solution for x from the last period!
00528           initialGuess.set_x(period_x);
00529         }
00530         solver.setInitialGuess(initialGuess);
00531 
00532         // Solve the period model
00533         solution_status = solver.solve();
00534         TEST_FOR_EXCEPT( solution_status != MoochoSolver::SOLVE_RETURN_SOLVED );
00535 
00536         // Save the final solution for the next period!
00537         period_x = solver.getFinalPoint().get_x()->clone_v();
00538         assign( x_opt_prod->getNonconstVectorBlock(i).ptr(), *period_x );
00539         if ( useStatelessPeriodModel )
00540           z[i][1] = period_x->clone_v(); // This is our matching vector!
00541         
00542       }
00543 
00544       x_opt = x_opt_prod;
00545       x_init = x_opt->clone_v();
00546 
00547       if ( useStatelessPeriodModel ) {
00548         rcp_dynamic_cast<Thyra::DefaultMultiPeriodModelEvaluator<Scalar> >(
00549           thyraModel
00550           )->reset_z(z);
00551       }
00552 
00553     }
00554     else {
00555 
00556       *out << "\nSolving all periods simultaniously ...\n";
00557       
00558       // Set the deliminator for the output files!
00559       solver.getSolver().set_output_context("fwd-init");
00560       
00561       // Set the model
00562       solver.setModel(thyraModel);
00563       
00564       // Set the initial guess from files (if specified on commandline)
00565       solver.readInitialGuess(out.get());
00566       
00567       // Solve the initial forward problem
00568       solution_status = solver.solve();
00569       TEST_FOR_EXCEPT( solution_status != MoochoSolver::SOLVE_RETURN_SOLVED );
00570 
00571       // Save the solution for model.x and model.p to be used later
00572       x_opt = solver.getFinalPoint().get_x()->clone_v();
00573       x_init = solver.getFinalPoint().get_x()->clone_v();
00574       
00575     }
00576     
00577     //
00578     *out << "\n***\n*** Solving the perturbed forward problem\n***\n";
00579     //
00580     
00581     // Set the deliminator for the output files!
00582     solver.getSolver().set_output_context("fwd");
00583     
00584     // Set the solve mode to solve the forward problem
00585     solver.setSolveMode(MoochoThyraSolver::SOLVE_MODE_FORWARD);
00586     
00587     // Set the model
00588     solver.setModel(thyraModel);
00589     
00590     // Set the initial guess and the perturbed parameters
00591     RCP<VectorBase<Scalar> >
00592       p_init = p_opt->clone_v();
00593     {
00594       MEB::InArgs<Scalar> initialGuess = thyraModel->createInArgs();
00595       initialGuess.setArgs(thyraModel->getNominalValues());
00596       initialGuess.set_x(x_init);
00597       Thyra::Vt_S(p_init.ptr(), perturbedParamScaling);
00598       initialGuess.set_p(0,p_init);
00599       //*out << "\nInitial Guess:\n" << Teuchos::describe(initialGuess,Teuchos::VERB_EXTREME);
00600       solver.setInitialGuess(initialGuess);
00601     }
00602 
00603     // Solve the perturbed forward problem
00604     solution_status = solver.solve();
00605     
00606     // Save the solution for model.x and model.p to be used later
00607     x_init = solver.getFinalPoint().get_x()->clone_v();
00608     p_init = solver.getFinalPoint().get_p(0)->clone_v();
00609 
00610     *out
00611       << "\nrelVectorErr(x_perturb,x_opt) = " << Thyra::relVectorErr(*x_init,*x_opt)
00612       << "\nrelVectorErr(p_perturb,p_opt) = " << Thyra::relVectorErr(*p_init,*p_opt)
00613       << "\n";
00614     
00615     //
00616     *out << "\n***\n*** Solving the perturbed inverse problem\n***\n";
00617     //
00618 
00619     // Set the deliminator for the output files!
00620     solver.getSolver().set_output_context("inv");
00621 
00622     //TEST_FOR_EXCEPT("ToDo: We need to use the DefaultInverseModelEvaluator to set the matching vector correctly!");
00623 
00624     // Set the matching vector
00625     if ( N > 1 ) {
00626       TEST_FOR_EXCEPTION(
00627         !useOuterInverse, std::logic_error,
00628         "Error, if N > 1, you have to use the outer inverse objective function\n"
00629         "since each target vector will be different!" );
00630       RCP<const ProductVectorBase<Scalar> >
00631         x_opt_prod = rcp_dynamic_cast<const ProductVectorBase<Scalar> >(
00632           rcp_implicit_cast<const VectorBase<Scalar> >(x_opt), true
00633           ); // This cast can *not* fail!
00634       for ( int i = 0; i < N; ++i ) {
00635         rcp_dynamic_cast<Thyra::DefaultInverseModelEvaluator<Scalar> >(
00636           inverseThyraModels[i], true
00637           )->set_observationTarget(x_opt_prod->getVectorBlock(i));
00638       }
00639     }
00640     else if ( 1 == N ) {
00641       RCP<const ProductVectorBase<Scalar> >
00642         x_opt_prod = rcp_dynamic_cast<const ProductVectorBase<Scalar> >(
00643           rcp_implicit_cast<const VectorBase<Scalar> >(x_opt)
00644           ); // This cast can fail!
00645       RCP<const VectorBase<Scalar> >
00646         x_opt_i =
00647         ( !is_null(x_opt_prod)
00648           ? x_opt_prod->getVectorBlock(0)
00649           : rcp_implicit_cast<const VectorBase<Scalar> >(x_opt)
00650           );
00651       if (useOuterInverse) {
00652         rcp_dynamic_cast<Thyra::DefaultInverseModelEvaluator<Scalar> >(
00653           inverseThyraModels[0], true
00654           )->set_observationTarget(x_opt_i);
00655       }
00656       else {
00657         epetraModel->set_q(
00658           Thyra::get_Epetra_Vector(*epetraModel->get_x_map(), x_opt_i)
00659           );
00660       }
00661     }
00662     else {
00663       TEST_FOR_EXCEPT("Error, should not get here!");
00664     }
00665     
00666     // Set the solve mode to solve the inverse problem
00667     solver.setSolveMode(MoochoThyraSolver::SOLVE_MODE_OPTIMIZE);
00668    
00669     // Set the model
00670     solver.setModel(thyraModel);
00671 
00672     // Set the initial guess for model.x and model.p
00673     {
00674       MEB::InArgs<Scalar> initialGuess = thyraModel->createInArgs();
00675       initialGuess.setArgs(thyraModel->getNominalValues());
00676       initialGuess.set_x(x_init);
00677       initialGuess.set_p(0,p_init);
00678       //*out << "\nInitial Guess:\n" << Teuchos::describe(initialGuess,Teuchos::VERB_EXTREME);
00679       solver.setInitialGuess(initialGuess);
00680     }
00681     
00682     // Solve the inverse problem
00683     solution_status = solver.solve();
00684     TEST_FOR_EXCEPT( solution_status != MoochoSolver::SOLVE_RETURN_SOLVED );
00685 
00686     //
00687     *out << "\n***\n*** Testing the error in the inversion\n***\n";
00688     //
00689     
00690     // Get the inverted for solution and compare it to the optimal solution
00691 
00692     RCP<const VectorBase<Scalar> >
00693       x_inv = solver.getFinalPoint().get_x(),
00694       p_inv = solver.getFinalPoint().get_p(0);
00695 
00696     *out << "\np_opt =\n" << Teuchos::describe(*p_opt,Teuchos::VERB_EXTREME);
00697     *out << "\np_inv =\n" << Teuchos::describe(*p_inv,Teuchos::VERB_EXTREME);
00698 
00699     const Scalar
00700       x_err = Thyra::relVectorErr( *x_inv, *x_opt ),
00701       p_err = Thyra::relVectorErr( *p_inv, *p_opt );
00702 
00703     const bool
00704       x_test_passed = ( x_err <= stateInvError ),
00705       p_test_passed = ( p_err <= paramInvError );
00706 
00707     *out
00708       << "\nrelVectorErr(x_inv,x_opt) = " << x_err << " <= " << stateInvError
00709       << " : " << Thyra::passfail(x_test_passed)
00710       << "\nrelVectorErr(p_inv,p_opt) = " << p_err << " <= " << paramInvError
00711       << " : " << Thyra::passfail(p_test_passed)
00712       << "\n";
00713     
00714     // Write the final solution
00715     solver.writeFinalSolution(out.get());
00716     
00717     // Write the final parameters to file
00718     lowsfCreator.writeParamsFile(*lowsFactory);
00719     solver.writeParamsFile();
00720     
00721     TEST_FOR_EXCEPT(
00722       solution_status != MoochoSolver::SOLVE_RETURN_SOLVED
00723       );
00724     
00725   }
00726   TEUCHOS_STANDARD_CATCH_STATEMENTS(true,*out,success)
00727 
00728   if(success)
00729     *out << "\nEnd Result: TEST PASSED" << endl;
00730   else
00731     *out << "\nEnd Result: TEST FAILED" << endl;
00732   
00733   return ( success ? 0 : 1 );
00734   
00735 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines