int main(int argc, char ** argv)
{
#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", NULL);
#else
  QUESO::FullEnvironment env("", "", NULL);
#endif

  QUESO::VectorSpace<> paramSpace1(env, "param1_", 4, NULL);
  QUESO::VectorSpace<> paramSpace2(env, "param2_", 2, NULL);

  QUESO::GslVector paramMins1(paramSpace1.zeroVector());
  paramMins1[0] = 1e2;
  paramMins1[1] = -1e5;
  paramMins1[2] = 4e-3;
  paramMins1[3] = 1;

  QUESO::GslVector paramMaxs1(paramSpace1.zeroVector());
  paramMaxs1[0] = 2e2;
  paramMaxs1[1] = 1e5;
  paramMaxs1[2] = 6e-3;
  paramMaxs1[3] = 11;

  QUESO::BoxSubset<> paramDomain1("", paramSpace1, paramMins1, paramMaxs1);

  QUESO::GslVector paramMins2(paramSpace2.zeroVector());
  paramMins2[0] = -1e5;
  paramMins2[1] = 2e-3;

  QUESO::GslVector paramMaxs2(paramSpace2.zeroVector());
  paramMaxs2[0] = 1e5;
  paramMaxs2[1] = 4e-3;

  QUESO::BoxSubset<> paramDomain2("", paramSpace2, paramMins2, paramMaxs2);

  QUESO::VectorSpace<> paramSpace(env, "param_", 6, NULL);

  QUESO::ConcatenationSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("",paramSpace,paramDomain1,paramDomain2);

  QUESO::GslVector centroid(paramSpace.zeroVector());
  paramDomain.centroid(centroid);

  const char *msg = "ConcatenationSubset centroid is incorrect";
  queso_require_less_equal_msg(std::abs(centroid[0]-1.5e2), TOL, msg);
  queso_require_less_equal_msg(std::abs(centroid[1]), TOL, msg);
  queso_require_less_equal_msg(std::abs(centroid[2]-5e-3), TOL, msg);
  queso_require_less_equal_msg(std::abs(centroid[3]-6), TOL, msg);
  queso_require_less_equal_msg(std::abs(centroid[4]), TOL, msg);
  queso_require_less_equal_msg(std::abs(centroid[5]-3e-3), TOL, msg);

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
void compute(const QUESO::FullEnvironment& env) {

  // Step 1 of 6: Instantiate the parameter space
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix>
    paramSpace(env, "param_", 2, NULL);

  // Step 2 of 6: Instantiate the parameter domain
  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(-INFINITY);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet( INFINITY);
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("param_",paramSpace,paramMins,paramMaxs);

  // Step 3 of 6: Instantiate the qoi space
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix>
    qoiSpace(env, "qoi_", 1, NULL);

  // Step 4 of 6: Instantiate the qoi function object
  qoiRoutine_DataType qoiRoutine_Data;
  qoiRoutine_Data.coef1 = 1.;
  qoiRoutine_Data.coef2 = 1.;
  QUESO::GenericVectorFunction<QUESO::GslVector,QUESO::GslMatrix,
                               QUESO::GslVector,QUESO::GslMatrix>
    qoiFunctionObj("qoi_",
                   paramDomain,
                   qoiSpace,
                   qoiRoutine,
                   (void *) &qoiRoutine_Data);

  // Step 5 of 6: Instantiate the forward problem
  // Parameters are Gaussian RV
  QUESO::GslVector meanVector( paramSpace.zeroVector() );
  meanVector[0] = -1;
  meanVector[1] = 2;

  QUESO::GslMatrix covMatrix = QUESO::GslMatrix(paramSpace.zeroVector());
  covMatrix(0,0) = 4.;
  covMatrix(0,1) = 0.;
  covMatrix(1,0) = 0.;
  covMatrix(1,1) = 1.;

  QUESO::GaussianVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    paramRv("param_",paramDomain,meanVector,covMatrix);

  QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    qoiRv("qoi_", qoiSpace);

  QUESO::StatisticalForwardProblem<QUESO::GslVector,QUESO::GslMatrix,
                                   QUESO::GslVector,QUESO::GslMatrix>
    fp("", NULL, paramRv, qoiFunctionObj, qoiRv);

  // Step 6 of 6: Solve the forward problem
  fp.solveWithMonteCarlo(NULL);

  return;
}
Exemple #3
0
void compute(const QUESO::FullEnvironment& env) {
  // Step 1 of 5: Instantiate the parameter space
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix>
    paramSpace(env, "param_", 2, NULL);

  // Step 2 of 5: Instantiate the parameter domain
  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(-INFINITY);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet( INFINITY);
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("param_",paramSpace,paramMins,paramMaxs);

  // Step 3 of 5: Instantiate the likelihood function object
  QUESO::GslVector meanVector(paramSpace.zeroVector());
  meanVector[0] = -1;
  meanVector[1] =  2;
  
  QUESO::GslMatrix covMatrix(paramSpace.zeroVector());
  covMatrix(0,0) = 4.; covMatrix(0,1) = 0.;
  covMatrix(1,0) = 0.; covMatrix(1,1) = 1.;
  
  likelihoodRoutine_DataType likelihoodRoutine_Data;
  likelihoodRoutine_Data.meanVector = &meanVector;
  likelihoodRoutine_Data.covMatrix  = &covMatrix;
  
  QUESO::GenericScalarFunction<QUESO::GslVector,QUESO::GslMatrix>
    likelihoodFunctionObj("like_",
                          paramDomain,
                          likelihoodRoutine,
                          (void *) &likelihoodRoutine_Data,
                          true); // routine computes [ln(function)]

  // Step 4 of 5: Instantiate the inverse problem
  QUESO::UniformVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    priorRv("prior_", paramDomain);
  QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    postRv("post_", paramSpace);
  QUESO::StatisticalInverseProblem<QUESO::GslVector,QUESO::GslMatrix>
    ip("", NULL, priorRv, likelihoodFunctionObj, postRv);

  // Step 5 of 5: Solve the inverse problem
  QUESO::GslVector paramInitials(paramSpace.zeroVector());
  paramInitials[0] = 0.1;
  paramInitials[1] = -1.4;
  
  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());
  proposalCovMatrix(0,0) = 8.; proposalCovMatrix(0,1) = 4.;
  proposalCovMatrix(1,0) = 4.; proposalCovMatrix(1,1) = 16.;
  
  ip.solveWithBayesMetropolisHastings(NULL,paramInitials, &proposalCovMatrix);
 
  return;
}
int main(int argc, char ** argv) {
  MPI_Init(&argc, &argv);

  // Step 0 of 5: Set up environment
  QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL);

  // Step 1 of 5: Instantiate the parameter space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", 1, NULL);

  // Step 2 of 5: Set up the prior
  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(min_val);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  // Uniform prior here.  Could be a different prior.
  QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_",
      paramDomain);

  // Step 3 of 5: Set up the likelihood using the class above
  Likelihood<QUESO::GslVector, QUESO::GslMatrix> lhood("llhd_", paramDomain);
  
  // Step 4 of 5: Instantiate the inverse problem
  QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix>
    postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix>
    ip("", NULL, priorRv, lhood, postRv);

  // Step 5 of 5: Solve the inverse problem
  QUESO::GslVector paramInitials(paramSpace.zeroVector());

  // Initial condition of the chain
  paramInitials[0] = 0.0;
  paramInitials[1] = 0.0;
  
  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());

  for (unsigned int i = 0; i < 2; i++) {
    // Might need to tweak this
    proposalCovMatrix(i, i) = 0.1;
  }
  
  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

  MPI_Finalize();
 
  return 0;
}
Exemple #5
0
int main(int argc, char ** argv)
{
#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", NULL);
#else
  QUESO::FullEnvironment env("", "", NULL);
#endif

  QUESO::VectorSpace<> paramSpace(env, "param_", 1, NULL);

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(0.0);

  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(1.0);

  QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMins, paramMaxs);

  // We should test the other cases of alpha and beta
  QUESO::GslVector alpha(paramSpace.zeroVector());
  alpha[0] = 2.0;

  QUESO::GslVector beta(paramSpace.zeroVector());
  beta[0] = 3.0;

  QUESO::BetaJointPdf<> pdf("", paramDomain, alpha, beta);

  QUESO::GslVector mean(paramSpace.zeroVector());
  pdf.distributionMean(mean);

  const char *msg = "BetaJointPdf mean is incorrect";
  double real_mean = alpha[0] / (alpha[0] + beta[0]);
  queso_require_less_equal_msg(std::abs(mean[0]-real_mean), TOL, msg);

  QUESO::GslMatrix var(paramSpace.zeroVector());
  pdf.distributionVariance(var);

  const char *msgv = "BetaJointPdf variance is incorrect";
  double real_var = alpha[0] * beta[0] / (alpha[0] + beta[0]) /
          (alpha[0] + beta[0]) / (alpha[0] + beta[0] + 1);

  queso_require_less_equal_msg(std::abs(var(0,0)-real_var), TOL, msgv);

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
Exemple #6
0
void compute(const QUESO::FullEnvironment& env) {

    //step 1: instatiate parameter space
    QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix>
    paramSpace(env, "param_", 1, NULL);

    //step 2: instantiate the parameter domain
    QUESO::GslVector paramMins(paramSpace.zeroVector());
    paramMins.cwSet(0.001);
    QUESO::GslVector paramMaxs(paramSpace.zeroVector());
    paramMaxs.cwSet(100.); //TODO: this is not working with gsl sampling right now in FP
    QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("param_", paramSpace, paramMins, paramMaxs);

    //step 3: instantiate the qoi space
    QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix>
    qoiSpace(env, "qoi_", 1, NULL);

    //step 4: instantiate the qoi function object
    qoiRoutine_DataType qoiRoutine_Data;
    qoiRoutine_Data.coef1 = 1.;
    QUESO::GenericVectorFunction<QUESO::GslVector,QUESO::GslMatrix,
          QUESO::GslVector,QUESO::GslMatrix>
          qoiFunctionObj("qoi_",
                         paramDomain,
                         qoiSpace,
                         qoiRoutine,
                         (void *) &qoiRoutine_Data);

    //step 5: instantiate the forward problem
    //parameter is Jeffreys RV
    QUESO::JeffreysVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    paramRv("param_", paramDomain);

    QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    qoiRv("qoi_",qoiSpace);

    QUESO::StatisticalForwardProblem<QUESO::GslVector,QUESO::GslMatrix,
          QUESO::GslVector,QUESO::GslMatrix>
          fp("", NULL, paramRv, qoiFunctionObj, qoiRv);

    //step 6: solve the forward problem
    fp.solveWithMonteCarlo(NULL);
}
int main(int argc, char ** argv) {
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL);

  QUESO::VectorSpace<> paramSpace(env, "param_", 1, NULL);

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());

  double min_val = 0.0;
  double max_val = 1.0;
  paramMins.cwSet(min_val);
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMins, paramMaxs);

  QUESO::UniformVectorRV<> priorRv("prior_", paramDomain);

  Likelihood<> lhood("llhd_", paramDomain);

  QUESO::GenericVectorRV<> postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<> ip("", NULL, priorRv, lhood, postRv);

  QUESO::GslVector paramInitials(paramSpace.zeroVector());
  paramInitials[0] = 0.0;

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());
  proposalCovMatrix(0, 0) = 0.1;

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

  MPI_Finalize();

  return 0;
}
Exemple #8
0
int main(int argc, char* argv[])
{
#ifndef QUESO_HAS_MPI
  // Skip this test if we're not in parallel
  return 77;
#else

  MPI_Init(&argc, &argv);

  std::string inputFileName = argv[1];
  const char * test_srcdir = std::getenv("srcdir");
  if (test_srcdir)
    inputFileName = test_srcdir + ('/' + inputFileName);

  // Initialize QUESO environment
  QUESO::FullEnvironment env(MPI_COMM_WORLD, inputFileName, "", NULL);

  //================================================================
  // Statistical inverse problem (SIP): find posterior PDF for 'g'
  //================================================================

  //------------------------------------------------------
  // SIP Step 1 of 6: Instantiate the parameter space
  //------------------------------------------------------
  QUESO::VectorSpace<> paramSpace(env, "param_", 1, NULL);

  //------------------------------------------------------
  // SIP Step 2 of 6: Instantiate the parameter domain
  //------------------------------------------------------
  QUESO::GslVector paramMinValues(paramSpace.zeroVector());
  QUESO::GslVector paramMaxValues(paramSpace.zeroVector());

  paramMinValues[0] = 8.;
  paramMaxValues[0] = 11.;

  QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMinValues,
      paramMaxValues);

  //------------------------------------------------------
  // SIP Step 3 of 6: Instantiate the likelihood function
  // object to be used by QUESO.
  //------------------------------------------------------
  Likelihood<> lhood("like_", paramDomain);

  //------------------------------------------------------
  // SIP Step 4 of 6: Define the prior RV
  //------------------------------------------------------
  QUESO::UniformVectorRV<> priorRv("prior_", paramDomain);

  //------------------------------------------------------
  // SIP Step 5 of 6: Instantiate the inverse problem
  //------------------------------------------------------
  // Extra prefix before the default "rv_" prefix
  QUESO::GenericVectorRV<> postRv("post_", paramSpace);

  // No extra prefix before the default "ip_" prefix
  QUESO::StatisticalInverseProblem<> ip("", NULL, priorRv, lhood, postRv);

  //------------------------------------------------------
  // SIP Step 6 of 6: Solve the inverse problem, that is,
  // set the 'pdf' and the 'realizer' of the posterior RV
  //------------------------------------------------------
  QUESO::GslVector paramInitials(paramSpace.zeroVector());
  priorRv.realizer().realization(paramInitials);

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());
  proposalCovMatrix(0,0) = std::pow(std::abs(paramInitials[0]) / 20.0, 2.0);

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

  //================================================================
  // Statistical forward problem (SFP): find the max distance
  // traveled by an object in projectile motion; input pdf for 'g'
  // is the solution of the SIP above.
  //================================================================

  //------------------------------------------------------
  // SFP Step 1 of 6: Instantiate the parameter *and* qoi spaces.
  // SFP input RV = FIP posterior RV, so SFP parameter space
  // has been already defined.
  //------------------------------------------------------
  QUESO::VectorSpace<> qoiSpace(env, "qoi_", 1, NULL);

  //------------------------------------------------------
  // SFP Step 2 of 6: Instantiate the parameter domain
  //------------------------------------------------------

  // Not necessary because input RV of the SFP = output RV of SIP.
  // Thus, the parameter domain has been already defined.

  //------------------------------------------------------
  // SFP Step 3 of 6: Instantiate the qoi object
  // to be used by QUESO.
  //------------------------------------------------------
  Qoi<> qoi("qoi_", paramDomain, qoiSpace);

  //------------------------------------------------------
  // SFP Step 4 of 6: Define the input RV
  //------------------------------------------------------

  // Not necessary because input RV of SFP = output RV of SIP
  // (postRv).

  //------------------------------------------------------
  // SFP Step 5 of 6: Instantiate the forward problem
  //------------------------------------------------------
  QUESO::GenericVectorRV<> qoiRv("qoi_", qoiSpace);

  QUESO::StatisticalForwardProblem<> fp("", NULL, postRv, qoi, qoiRv);

  //------------------------------------------------------
  // SFP Step 6 of 6: Solve the forward problem
  //------------------------------------------------------
  fp.solveWithMonteCarlo(NULL);

  MPI_Finalize();

  return 0;
#endif  // QUESO_HAS_MPI
}
Exemple #9
0
int main(int argc, char ** argv) {
#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
#endif

  QUESO::EnvOptionsValues envOptions;
  envOptions.m_numSubEnvironments = 1;
  envOptions.m_subDisplayFileName = "test_outputNoInputFile/display";
  envOptions.m_subDisplayAllowAll = 1;
  envOptions.m_displayVerbosity = 2;
  envOptions.m_syncVerbosity = 0;
  envOptions.m_seed = 0;

#ifdef QUESO_HAS_MPI
  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", &envOptions);
#else
  QUESO::FullEnvironment env("", "", &envOptions);
#endif

  unsigned int dim = 2;
  QUESO::VectorSpace<> paramSpace(env, "param_", dim, NULL);

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());

  double min_val = -10.0;
  double max_val = 10.0;
  paramMins.cwSet(min_val);
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMins, paramMaxs);

  QUESO::UniformVectorRV<> priorRv("prior_", paramDomain);

  Likelihood<> lhood("llhd_", paramDomain);

  QUESO::GenericVectorRV<> postRv("post_", paramSpace);

  QUESO::SipOptionsValues sipOptions;
  sipOptions.m_computeSolution = 1;
  sipOptions.m_dataOutputFileName = "test_outputNoInputFile/sipOutput";
  sipOptions.m_dataOutputAllowedSet.clear();
  sipOptions.m_dataOutputAllowedSet.insert(0);

  QUESO::StatisticalInverseProblem<> ip("", &sipOptions, priorRv, lhood,
      postRv);

  QUESO::GslVector paramInitials(paramSpace.zeroVector());
  paramInitials[0] = 0.0;
  paramInitials[1] = 0.0;

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());

  proposalCovMatrix(0, 0) = 1.0;
  proposalCovMatrix(0, 1) = 0.0;
  proposalCovMatrix(1, 0) = 0.0;
  proposalCovMatrix(1, 1) = 1.0;

  QUESO::MhOptionsValues mhOptions;
  mhOptions.m_dataOutputFileName = "test_outputNoInputFile/sipOutput";
  mhOptions.m_dataOutputAllowAll = 1;
  mhOptions.m_rawChainGenerateExtra = 0;
  mhOptions.m_rawChainDisplayPeriod = 50000;
  mhOptions.m_rawChainMeasureRunTimes = 1;
  mhOptions.m_rawChainDataOutputFileName = "test_outputNoInputFile/ip_raw_chain";
  mhOptions.m_rawChainDataOutputAllowAll = 1;
  mhOptions.m_displayCandidates = 0;
  mhOptions.m_tkUseLocalHessian = 0;
  mhOptions.m_tkUseNewtonComponent = 1;
  mhOptions.m_filteredChainGenerate = 0;
  mhOptions.m_rawChainSize = 1000;
  mhOptions.m_putOutOfBoundsInChain = false;
  mhOptions.m_drMaxNumExtraStages = 1;
  mhOptions.m_drScalesForExtraStages.resize(1);
  mhOptions.m_drScalesForExtraStages[0] = 5.0;
  mhOptions.m_amInitialNonAdaptInterval = 100;
  mhOptions.m_amAdaptInterval = 100;
  mhOptions.m_amEta = (double) 2.4 * 2.4 / dim;  // From Gelman 95
  mhOptions.m_amEpsilon = 1.e-8;
  mhOptions.m_doLogitTransform = false;
  mhOptions.m_algorithm = "random_walk";
  mhOptions.m_tk = "random_walk";

  ip.solveWithBayesMetropolisHastings(&mhOptions, paramInitials,
      &proposalCovMatrix);

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
int main(int argc, char ** argv) {
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "test_gaussian_likelihoods/queso_input.txt", "", NULL);

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", 1, NULL);

  double min_val = -INFINITY;
  double max_val = INFINITY;

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(min_val);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  // Set up observation space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> obsSpace(env,
      "obs_", 2, NULL);

  // Fill up observation vector
  QUESO::GslVector observations(obsSpace.zeroVector());
  observations[0] = 1.0;
  observations[1] = 1.0;

  // Fill up covariance 'matrix'
  QUESO::GslVector covariance(obsSpace.zeroVector());
  covariance[0] = 1.0;
  covariance[1] = 2.0;

  // Pass in observations to Gaussian likelihood object
  Likelihood<QUESO::GslVector, QUESO::GslMatrix> lhood("llhd_", paramDomain,
      observations, covariance);

  double lhood_value;
  double truth_value;
  QUESO::GslVector point(paramSpace.zeroVector());
  point[0] = 0.0;
  lhood_value = lhood.actualValue(point, NULL, NULL, NULL, NULL);
  truth_value = std::exp(-3.0);

  if (std::abs(lhood_value - truth_value) > TOL) {
    std::cerr << "Scalar Gaussian test case failure." << std::endl;
    std::cerr << "Computed likelihood value is: " << lhood_value << std::endl;
    std::cerr << "Likelihood value should be: " << truth_value << std::endl;
    queso_error();
  }

  point[0] = -2.0;
  lhood_value = lhood.actualValue(point, NULL, NULL, NULL, NULL);
  truth_value = 1.0;

  if (std::abs(lhood_value - truth_value) > TOL) {
    std::cerr << "Scalar Gaussian test case failure." << std::endl;
    std::cerr << "Computed likelihood value is: " << lhood_value << std::endl;
    std::cerr << "Likelihood value should be: " << truth_value << std::endl;
    queso_error();
  }

  MPI_Finalize();

  return 0;
}
Exemple #11
0
void compute(const QUESO::FullEnvironment& env) {

  struct timeval timevalNow;
  gettimeofday(&timevalNow, NULL);
  std::cout << std::endl << "Beginning run of 'Hysteretic' example at "
            << ctime(&timevalNow.tv_sec);

  //------------------------------------------------------
  // Step 1 of 5: Instantiate the parameter space
  //------------------------------------------------------
  QUESO::VectorSpace<> paramSpaceA(env, "paramA_", 1, NULL);
  QUESO::VectorSpace<> paramSpaceB(env, "paramB_", 14, NULL);
  QUESO::VectorSpace<> paramSpace (env, "param_", 15, NULL);

  //------------------------------------------------------
  // Step 2 of 5: Instantiate the parameter domain
  //------------------------------------------------------
  QUESO::GslVector paramMinsA(paramSpaceA.zeroVector());
  paramMinsA.cwSet(0);
  QUESO::GslVector paramMaxsA(paramSpaceA.zeroVector());
  paramMaxsA.cwSet(5);
  QUESO::BoxSubset<> paramDomainA("paramA_",paramSpaceA,paramMinsA,paramMaxsA);

  QUESO::GslVector paramMinsB(paramSpaceB.zeroVector());
  paramMinsB.cwSet(-INFINITY);
  QUESO::GslVector paramMaxsB(paramSpaceB.zeroVector());
  paramMaxsB.cwSet( INFINITY);
  QUESO::BoxSubset<> paramDomainB("paramB_",paramSpaceB,paramMinsB,paramMaxsB);

  QUESO::ConcatenationSubset<> paramDomain("",paramSpace,paramDomainA,paramDomainB);

  //------------------------------------------------------
  // Step 3 of 5: Instantiate the likelihood function object
  //------------------------------------------------------
  std::cout << "\tInstantiating the Likelihood; calling internally the hysteretic model"
	    << std::endl;

  Likelihood<> likelihood("like_", paramDomain);

  likelihood.floor.resize(4,NULL);
  unsigned int numTimeSteps = 401;
  for (unsigned int i = 0; i < 4; ++i) {
    likelihood.floor[i] = new std::vector<double>(numTimeSteps,0.);
  }
  likelihood.accel.resize(numTimeSteps,0.);
  FILE *inp;
  inp = fopen("an.txt","r");
  unsigned int numObservations = 0;
  double tmpA;
  while (fscanf(inp,"%lf",&tmpA) != EOF) {
    likelihood.accel[numObservations] = tmpA;
    numObservations++;
  }

  numObservations=1;
  FILE *inp1_1;
  inp1_1=fopen("measured_data1_1.txt","r");
  while (fscanf(inp1_1,"%lf",&tmpA) != EOF) {
    (*likelihood.floor[0])[numObservations]=tmpA;
     numObservations++;
  }

  numObservations=0;
  FILE *inp1_2;
  inp1_2=fopen("measured_data1_2.txt","r");
  while (fscanf(inp1_2,"%lf",&tmpA) != EOF) {
    (*likelihood.floor[1])[numObservations]=tmpA;
    numObservations++;
  }

  numObservations=0;
  FILE *inp1_3;
  inp1_3=fopen("measured_data1_3.txt","r");
  while (fscanf(inp1_3,"%lf",&tmpA) != EOF) {
    (*likelihood.floor[2])[numObservations]=tmpA;
    numObservations++;
  }

  numObservations=0;
  FILE *inp1_4;
  inp1_4=fopen("measured_data1_4.txt","r");
  while (fscanf(inp1_4,"%lf",&tmpA) != EOF) {
    (*likelihood.floor[3])[numObservations]=tmpA;
    numObservations++;
  }


  //------------------------------------------------------
  // Step 4 of 5: Instantiate the inverse problem
  //------------------------------------------------------
  std::cout << "\tInstantiating the SIP" << std::endl;

  QUESO::UniformVectorRV<> priorRvA("priorA_", paramDomainA);

  QUESO::GslVector meanVec(paramSpaceB.zeroVector());
  QUESO::GslVector diagVec(paramSpaceB.zeroVector());

  diagVec.cwSet(0.6*0.6);

  QUESO::GslMatrix covMatrix(diagVec);

  QUESO::GaussianVectorRV<> priorRvB("priorB_", paramDomainB,meanVec,covMatrix);

  QUESO::ConcatenatedVectorRV<> priorRv("prior_", priorRvA, priorRvB, paramDomain);

  QUESO::GenericVectorRV<> postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<> ip("", NULL, priorRv, likelihood, postRv);

  //------------------------------------------------------
  // Step 5 of 5: Solve the inverse problem
  //------------------------------------------------------
  std::cout << "\tSolving the SIP with Multilevel method" << std::endl;

  ip.solveWithBayesMLSampling();

  gettimeofday(&timevalNow, NULL);
  std::cout << "Ending run of 'Hysteretic' example at "
              << ctime(&timevalNow.tv_sec) << std::endl;
  return;
}
Exemple #12
0
void
uqAppl(const QUESO::BaseEnvironment& env)
{
  if (env.fullRank() == 0) {
    std::cout << "Beginning run of 'uqTgaExample' example\n"
              << std::endl;
  }

  //int iRC;
  struct timeval timevalRef;
  struct timeval timevalNow;

  //******************************************************
  // Task 1 of 5: instantiation of basic classes
  //******************************************************

  // Instantiate the parameter space
  std::vector<std::string> paramNames(2,"");
  paramNames[0] = "A_param";
  paramNames[1] = "E_param";
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix> paramSpace(env,"param_",paramNames.size(),&paramNames);

  // Instantiate the parameter domain
  QUESO::GslVector paramMinValues(paramSpace.zeroVector());
  paramMinValues[0] = 2.40e+11;
  paramMinValues[1] = 1.80e+05;
  QUESO::GslVector paramMaxValues(paramSpace.zeroVector());
  paramMaxValues[0] = 2.80e+11;
  paramMaxValues[1] = 2.20e+05;
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix> paramDomain("param_",
                                        paramSpace,
                                        paramMinValues,
                                        paramMaxValues);

  // Instantiate the qoi space
  std::vector<std::string> qoiNames(1,"");
  qoiNames[0] = "TimeFor25PercentOfMass";
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix> qoiSpace(env,"qoi_",qoiNames.size(),&qoiNames);

  // Instantiate the validation cycle
  QUESO::ValidationCycle<QUESO::GslVector,QUESO::GslMatrix,QUESO::GslVector,QUESO::GslMatrix> cycle(env,
                                                "", // No extra prefix
                                                paramSpace,
                                                qoiSpace);

  //********************************************************
  // Task 2 of 5: calibration stage
  //********************************************************

  /*iRC = */gettimeofday(&timevalRef, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Beginning 'calibration stage' at " << ctime(&timevalRef.tv_sec)
              << std::endl;
  }

  // Inverse problem: instantiate the prior rv
  QUESO::UniformVectorRV<QUESO::GslVector,QUESO::GslMatrix> calPriorRv("cal_prior_", // Extra prefix before the default "rv_" prefix
                                                                       paramDomain);

  // Inverse problem: instantiate the likelihood
  Likelihood<> calLikelihood("cal_like_",
                           paramDomain,
                           "inputData/scenario_5_K_min.dat",
                           "inputData/scenario_25_K_min.dat",
                           "inputData/scenario_50_K_min.dat");


  // Inverse problem: instantiate it (posterior rv is instantiated internally)
  cycle.instantiateCalIP(NULL,
                         calPriorRv,
                         calLikelihood);

  // Inverse problem: solve it, that is, set 'pdf' and 'realizer' of the posterior rv
  QUESO::GslVector paramInitialValues(paramSpace.zeroVector());
  if (env.numSubEnvironments() == 1) {
    // For regression test purposes
    paramInitialValues[0] = 2.41e+11;
    paramInitialValues[1] = 2.19e+05;
  }
  else {
    calPriorRv.realizer().realization(paramInitialValues);
  }

  QUESO::GslMatrix* calProposalCovMatrix = cycle.calIP().postRv().imageSet().vectorSpace().newProposalMatrix(NULL,&paramInitialValues);
  cycle.calIP().solveWithBayesMetropolisHastings(NULL,
                                                 paramInitialValues,
                                                 calProposalCovMatrix);
  delete calProposalCovMatrix;

  // Forward problem: instantiate it (parameter rv = posterior rv of inverse problem; qoi rv is instantiated internally)
  double beta_prediction         = 250.;
  double criticalMass_prediction = 0.;
  double criticalTime_prediction = 3.9;

  qoiRoutine_Data calQoiRoutine_Data;
  calQoiRoutine_Data.m_beta         = beta_prediction;
  calQoiRoutine_Data.m_criticalMass = criticalMass_prediction;
  calQoiRoutine_Data.m_criticalTime = criticalTime_prediction;

  cycle.instantiateCalFP(NULL,
                         qoiRoutine,
                         (void *) &calQoiRoutine_Data);

  // Forward problem: solve it, that is, set 'realizer' and 'cdf' of the qoi rv
  cycle.calFP().solveWithMonteCarlo(NULL); // no extra user entities needed for Monte Carlo algorithm

  /*iRC = */gettimeofday(&timevalNow, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Ending 'calibration stage' at "        << ctime(&timevalNow.tv_sec)
              << "Total 'calibration stage' run time = " << timevalNow.tv_sec - timevalRef.tv_sec
              << " seconds\n"
              << std::endl;
  }

  //********************************************************
  // Task 3 of 5: validation stage
  //********************************************************
  /*iRC = */gettimeofday(&timevalRef, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Beginning 'validation stage' at " << ctime(&timevalRef.tv_sec)
              << std::endl;
  }

  // Inverse problem: no need to instantiate the prior rv (= posterior rv of calibration inverse problem)

  // Inverse problem: instantiate the likelihood function object
  Likelihood<> valLikelihood("val_like_",
                             paramDomain,
                             "inputData/scenario_100_K_min.dat",
                             NULL,
                             NULL);

  // Inverse problem: instantiate it (posterior rv is instantiated internally)
  cycle.instantiateValIP(NULL,valLikelihood);

  // Inverse problem: solve it, that is, set 'pdf' and 'realizer' of the posterior rv
  const QUESO::SequentialVectorRealizer<QUESO::GslVector,QUESO::GslMatrix>* tmpRealizer = dynamic_cast< const QUESO::SequentialVectorRealizer<QUESO::GslVector,QUESO::GslMatrix>* >(&(cycle.calIP().postRv().realizer()));
  QUESO::GslMatrix* valProposalCovMatrix = cycle.calIP().postRv().imageSet().vectorSpace().newProposalMatrix(&tmpRealizer->unifiedSampleVarVector(),  // Use 'realizer()' because post. rv was computed with MH
                                                                                                             &tmpRealizer->unifiedSampleExpVector()); // Use these values as the initial values
  cycle.valIP().solveWithBayesMetropolisHastings(NULL,
                                                 tmpRealizer->unifiedSampleExpVector(),
                                                 valProposalCovMatrix);
  delete valProposalCovMatrix;

  // Forward problem: instantiate it (parameter rv = posterior rv of inverse problem; qoi rv is instantiated internally)
  qoiRoutine_Data valQoiRoutine_Data;
  valQoiRoutine_Data.m_beta         = beta_prediction;
  valQoiRoutine_Data.m_criticalMass = criticalMass_prediction;
  valQoiRoutine_Data.m_criticalTime = criticalTime_prediction;

  cycle.instantiateValFP(NULL,
                         qoiRoutine,
                         (void *) &valQoiRoutine_Data);

  // Forward problem: solve it, that is, set 'realizer' and 'cdf' of the qoi rv
  cycle.valFP().solveWithMonteCarlo(NULL); // no extra user entities needed for Monte Carlo algorithm

  /*iRC = */gettimeofday(&timevalNow, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Ending 'validation stage' at "        << ctime(&timevalNow.tv_sec)
              << "Total 'validation stage' run time = " << timevalNow.tv_sec - timevalRef.tv_sec
              << " seconds\n"
              << std::endl;
  }

  //********************************************************
  // Task 4 of 5: comparison stage
  //********************************************************

  /*iRC = */gettimeofday(&timevalRef, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Beginning 'comparison stage' at " << ctime(&timevalRef.tv_sec)
              << std::endl;
  }

  uqAppl_LocalComparisonStage(cycle);
  if (env.numSubEnvironments() > 1) {
    uqAppl_UnifiedComparisonStage(cycle);
  }

  /*iRC = */gettimeofday(&timevalNow, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Ending 'comparison stage' at "        << ctime(&timevalNow.tv_sec)
              << "Total 'comparison stage' run time = " << timevalNow.tv_sec - timevalRef.tv_sec
              << " seconds\n"
              << std::endl;
  }

  //******************************************************
  // Task 5 of 5: release memory before leaving routine.
  //******************************************************

  if (env.fullRank() == 0) {
    std::cout << "Finishing run of 'uqTgaExample' example"
              << std::endl;
  }

  return;
}
Exemple #13
0
int main(int argc, char ** argv) {
  std::string inputFileName = "test_gaussian_likelihoods/queso_input.txt";
  const char * test_srcdir = std::getenv("srcdir");
  if (test_srcdir)
    inputFileName = test_srcdir + ('/' + inputFileName);

#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, inputFileName, "", NULL);
#else
  QUESO::FullEnvironment env(inputFileName, "", NULL);
#endif

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", 1, NULL);

  double min_val = -INFINITY;
  double max_val = INFINITY;

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(min_val);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  // Set up observation space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> obsSpace(env,
      "obs_", 1, NULL);

  // Fill up observation vector
  QUESO::GslVector observations(obsSpace.zeroVector());
  observations[0] = 1.0;

  // Pass in observations to Gaussian likelihood object
  Likelihood<QUESO::GslVector, QUESO::GslMatrix> lhood("llhd_", paramDomain,
      observations, 1.0);

  double lhood_value;
  double truth_value;
  QUESO::GslVector point(paramSpace.zeroVector());
  point[0] = 0.0;
  lhood_value = lhood.actualValue(point, NULL, NULL, NULL, NULL);
  truth_value = std::exp(-2.0);

  if (std::abs(lhood_value - truth_value) > TOL) {
    std::cerr << "Scalar Gaussian test case failure." << std::endl;
    std::cerr << "Computed likelihood value is: " << lhood_value << std::endl;
    std::cerr << "Likelihood value should be: " << truth_value << std::endl;
    queso_error();
  }

  point[0] = -2.0;
  lhood_value = lhood.actualValue(point, NULL, NULL, NULL, NULL);
  truth_value = 1.0;

  if (std::abs(lhood_value - truth_value) > TOL) {
    std::cerr << "Scalar Gaussian test case failure." << std::endl;
    std::cerr << "Computed likelihood value is: " << lhood_value << std::endl;
    std::cerr << "Likelihood value should be: " << truth_value << std::endl;
    queso_error();
  }

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
int main(int argc, char ** argv)
{
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, "test_InterpolationSurrogate/queso_input.txt", "", NULL);

  int return_flag = 0;

  std::string vs_prefix = "param_";

  // Filename for writing/reading surrogate data
  std::string filename1 = "test_write_InterpolationSurrogateBuilder_1.dat";
  std::string filename2 = "test_write_InterpolationSurrogateBuilder_2.dat";

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix>
      paramSpace(env,vs_prefix.c_str(), 4, NULL);

  // Point at which we will test the surrogate evaluation
  QUESO::GslVector domainVector(paramSpace.zeroVector());
  domainVector[0] = -0.4;
  domainVector[1] = 3.0;
  domainVector[2] = 1.5;
  domainVector[3] = 1.65;

  double exact_val_1 = four_d_fn_1(domainVector[0],domainVector[1],domainVector[2],domainVector[3]);
  double exact_val_2 = four_d_fn_2(domainVector[0],domainVector[1],domainVector[2],domainVector[3]);

  double tol = 2.0*std::numeric_limits<double>::epsilon();

  // First test surrogate build directly from the computed values
  {
    QUESO::GslVector paramMins(paramSpace.zeroVector());
    paramMins[0] = -1;
    paramMins[1] = -0.5;
    paramMins[2] = 1.1;
    paramMins[3] = -2.1;

    QUESO::GslVector paramMaxs(paramSpace.zeroVector());
    paramMaxs[0] = 0.9;
    paramMaxs[1] = 3.14;
    paramMaxs[2] = 2.1;
    paramMaxs[3] = 4.1;

    QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix>
      paramDomain("param_", paramSpace, paramMins, paramMaxs);

    std::vector<unsigned int> n_points(4);
    n_points[0] = 11;
    n_points[1] = 51;
    n_points[2] = 31;
    n_points[3] = 41;

    // One dataset for each of the two functions
    const unsigned int n_datasets = 2;

    QUESO::InterpolationSurrogateDataSet<QUESO::GslVector, QUESO::GslMatrix>
      data(paramDomain,n_points,n_datasets);

    MyInterpolationBuilder<QUESO::GslVector,QUESO::GslMatrix>
      builder( data );

    builder.build_values();

    QUESO::LinearLagrangeInterpolationSurrogate<QUESO::GslVector,QUESO::GslMatrix>
      four_d_surrogate_1( data.get_dataset(0) );

    QUESO::LinearLagrangeInterpolationSurrogate<QUESO::GslVector,QUESO::GslMatrix>
      four_d_surrogate_2( data.get_dataset(1) );

    double test_val_1 = four_d_surrogate_1.evaluate(domainVector);
    double test_val_2 = four_d_surrogate_2.evaluate(domainVector);

    return_flag  = return_flag ||
      test_val( test_val_1, exact_val_1, tol, "test_build_1" ) ||
      test_val( test_val_2, exact_val_2, tol, "test_build_2" );

    // Write the output to test reading next
    QUESO::InterpolationSurrogateIOASCII<QUESO::GslVector,QUESO::GslMatrix>
      data_writer;

    data_writer.write( filename1, data.get_dataset(0) );
    data_writer.write( filename2, data.get_dataset(1) );
  }

  // Now read the data and test
  {
    QUESO::InterpolationSurrogateIOASCII<QUESO::GslVector,QUESO::GslMatrix>
      data_reader_1, data_reader_2;

    data_reader_1.read( filename1, env, vs_prefix.c_str() );
    data_reader_2.read( filename2, env, vs_prefix.c_str() );


    // Build a new surrogate
    QUESO::LinearLagrangeInterpolationSurrogate<QUESO::GslVector,QUESO::GslMatrix>
      four_d_surrogate_1( data_reader_1.data() );

    QUESO::LinearLagrangeInterpolationSurrogate<QUESO::GslVector,QUESO::GslMatrix>
      four_d_surrogate_2( data_reader_2.data() );

    double test_val_1 = four_d_surrogate_1.evaluate(domainVector);
    double test_val_2 = four_d_surrogate_2.evaluate(domainVector);

    return_flag  = return_flag ||
      test_val( test_val_1, exact_val_1, tol, "test_read_1" ) ||
      test_val( test_val_2, exact_val_2, tol, "test_read_2" );
  }

  return return_flag;
}
int main(int argc, char ** argv)
{
  std::string inputFileName = "test_InterpolationSurrogate/queso_input.txt";
  const char * test_srcdir = std::getenv("srcdir");
  if (test_srcdir)
    inputFileName = test_srcdir + ('/' + inputFileName);

#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, inputFileName, "", NULL);
#else
  QUESO::FullEnvironment env(inputFileName, "", NULL);
#endif

  int return_flag = 0;

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix>
    paramSpace(env,"param_", 3, NULL);

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins[0] = -1;
  paramMins[1] = -0.5;
  paramMins[2] = 1.1;

  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs[0] = 0.9;
  paramMaxs[1] = 3.14;
  paramMaxs[2] = 2.1;

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix>
    paramDomain("param_", paramSpace, paramMins, paramMaxs);

  std::vector<unsigned int> n_points(3);
  n_points[0] = 101;
  n_points[1] = 51;
  n_points[2] = 31;

  QUESO::InterpolationSurrogateData<QUESO::GslVector, QUESO::GslMatrix>
    data(paramDomain,n_points);

  std::vector<double> values(n_points[0]*n_points[1]*n_points[2]);

  double spacing_x = (paramMaxs[0] - paramMins[0])/(n_points[0]-1);
  double spacing_y = (paramMaxs[1] - paramMins[1])/(n_points[1]-1);
  double spacing_z = (paramMaxs[2] - paramMins[2])/(n_points[2]-1);

  for( unsigned int i = 0; i < n_points[0]; i++ )
    {
      for( unsigned int j = 0; j < n_points[1]; j++ )
        {
          for( unsigned int k = 0; k < n_points[2]; k++ )
            {
              unsigned int n = i + j*n_points[0] + k*n_points[0]*n_points[1];

              double x = paramMins[0] + i*spacing_x;
              double y = paramMins[1] + j*spacing_y;
              double z = paramMins[2] + k*spacing_z;

              values[n] = three_d_fn(x,y,z);
            }
        }
    }

  data.set_values( values );

  QUESO::LinearLagrangeInterpolationSurrogate<QUESO::GslVector,QUESO::GslMatrix>
    three_d_surrogate( data );

  QUESO::GslVector domainVector(paramSpace.zeroVector());
  domainVector[0] = -0.4;
  domainVector[1] = 3.0;
  domainVector[2] = 1.5;

  double test_val = three_d_surrogate.evaluate(domainVector);

  double exact_val = three_d_fn(domainVector[0],domainVector[1],domainVector[2]);

  double tol = 2.0*std::numeric_limits<double>::epsilon();

  double rel_error = (test_val - exact_val)/exact_val;

  if( std::fabs(rel_error) > tol )
    {
      std::cerr << "ERROR: Tolerance exceeded for 3D Lagrange interpolation test."
                << std::endl
                << " test_val  = " << test_val << std::endl
                << " exact_val = " << exact_val << std::endl
                << " rel_error = " << rel_error << std::endl
                << " tol       = " << tol << std::endl;

      return_flag = 1;
    }

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif
  return return_flag;
}
Exemple #16
0
void infer_slope(const QUESO::FullEnvironment & env) {


// Statistical Inverse Problem: Compute posterior pdf for slope 'm' and y-intercept c

// Step 1: Instantiate the parameter space

	QUESO::VectorSpace<> paramSpace(env, "param_", 2, NULL); // 2 since we have a 2D problem
	
// Step 2: Parameter domain

	QUESO::GslVector paramMinValues(paramSpace.zeroVector());
	QUESO::GslVector paramMaxValues(paramSpace.zeroVector());

	paramMinValues[0] = 2.;
	paramMaxValues[0] = 5.;

	paramMinValues[1] = 3.;
	paramMaxValues[1] = 7.;
	
	QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMinValues, paramMaxValues);

// Step 3: Instantiate likelihood

	Likelihood<> lhood("like_", paramDomain);

// Step 4: Define the prior RV

	QUESO::UniformVectorRV<> priorRv("prior_", paramDomain);

// Step 5: Instantiate the inverse problem

	QUESO::GenericVectorRV<> postRv("post_", paramSpace);
	QUESO::StatisticalInverseProblem<> ip("", NULL, priorRv, lhood, postRv);

// Step 6: Solve the inverse problem

// Randomly sample for the initial state?
	QUESO::GslVector paramInitials(paramSpace.zeroVector());
	priorRv.realizer().realization(paramInitials);

// Initialize the Cov matrix:
	QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());
	proposalCovMatrix(0,0) = std::pow(std::abs(paramInitials[0]) / 20.0, 2.0);
	proposalCovMatrix(1,1) = std::pow(std::abs(paramInitials[1]) / 20.0, 2.0);

	ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

// Using the posterior pdfs for m and c, compute 'y' at a given 'x'
 
// Step 1: Instantiate the qoi space

	QUESO::VectorSpace<> qoiSpace(env, "qoi_", 1, NULL);

// Step 2: Instantiate the parameter domain

// Not necessary here because the posterior from SIP is used as the RV for SFP

// Step 3: Instantiate the qoi object to be used by QUESO

	Qoi<> qoi("qoi_", paramDomain, qoiSpace);

// Step 4: Define the input RV

// Not required because we use the posterior as RV

// Step 5: Instantiate the forward problem

	QUESO::GenericVectorRV<> qoiRv("qoi_", qoiSpace);
	
	QUESO::StatisticalForwardProblem<> fp("", NULL, postRv, qoi, qoiRv);

// Step 6: Solve the forward problem

	std::cout << "Solving the SFP with Monte Carlo" << std::endl << std::endl;
	fp.solveWithMonteCarlo(NULL);

	system("mv outputData/sfp_lineSlope_qoi_seq.txt outputData/sfp_lineSlope_qoi_seq_post.txt");

// SENSITIVITY ANALYSIS

// For m

	Qoi_m<> qoi_m("qoi_", paramDomain, qoiSpace);
		
// Step 4: Define the input RV

// Not required because we use the prior as RV for sensitivity analysis

// Step 5: Instantiate the forward problem

	QUESO::StatisticalForwardProblem<> fp_m("", NULL, priorRv, qoi_m, qoiRv);

// Step 6: Solve the forward problem

	fp_m.solveWithMonteCarlo(NULL);

	system("mv outputData/sfp_lineSlope_qoi_seq.txt outputData/sense_m.txt");

// For c

	Qoi_c<> qoi_c("qoi_", paramDomain, qoiSpace);
		
// Step 4: Define the input RV

// Not required because we use the prior as RV for sensitivity analysis

// Step 5: Instantiate the forward problem

	QUESO::StatisticalForwardProblem<> fp_c("", NULL, priorRv, qoi_c, qoiRv);

// Step 6: Solve the forward problem

	fp_c.solveWithMonteCarlo(NULL);

	system("mv outputData/sfp_lineSlope_qoi_seq.txt outputData/sense_c.txt");

// For both, m and c

	Qoi_mc<> qoi_mc("qoi_", paramDomain, qoiSpace);
		
// Step 4: Define the input RV

// Not required because we use the prior as RV for sensitivity analysis

// Step 5: Instantiate the forward problem

	QUESO::StatisticalForwardProblem<> fp_mc("", NULL, priorRv, qoi_mc, qoiRv);

// Step 6: Solve the forward problem

	fp_mc.solveWithMonteCarlo(NULL);

	system("mv outputData/sfp_lineSlope_qoi_seq.txt outputData/sense_mc.txt");
}
Exemple #17
0
int main(int argc, char ** argv) {
#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);
  QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL);
#else
  QUESO::FullEnvironment env(argv[1], "", NULL);
#endif

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", 1, NULL);

  double min_val = 0.0;
  double max_val = 1.0;

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(min_val);
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(max_val);

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_",
      paramDomain);

  // Set up observation space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> obsSpace(env,
      "obs_", 2, NULL);

  // Fill up observation vector
  QUESO::GslVector observations(obsSpace.zeroVector());
  observations[0] = 1.0;
  observations[1] = 1.0;

  // Pass in observations to Gaussian likelihood object
  Likelihood<QUESO::GslVector, QUESO::GslMatrix> lhood("llhd_", paramDomain,
      observations, 1.0);

  QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix>
    postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix>
    ip("", NULL, priorRv, lhood, postRv);

  QUESO::GslVector paramInitials(paramSpace.zeroVector());

  paramInitials[0] = 0.0;

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());

  for (unsigned int i = 0; i < 1; i++) {
    proposalCovMatrix(i, i) = 0.1;
  }

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
Exemple #18
0
void compute(const uqFullEnvironmentClass& env, bool useExperiments, bool useML)
{
  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "Entering compute()..."
                          << std::endl;
  }

  //***********************************************************************
  // Step 01 of 09: Instantiate parameter space, parameter domain, and prior Rv
  //***********************************************************************
  unsigned int paper_p_t = 1; // parameter dimension; 'p_t' in paper; drag coefficient 'C' in tower example
  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>
    paper_p_t_space(env, "param_", paper_p_t, NULL);

  uqGslVectorClass paramMins(paper_p_t_space.zeroVector());
  uqGslVectorClass paramMaxs(paper_p_t_space.zeroVector());
  paramMins[0] = 0.;
  paramMaxs[0] = 1.;

  uqBoxSubsetClass<uqGslVectorClass,uqGslMatrixClass>
    paramDomain("param_",paper_p_t_space,paramMins,paramMaxs);

  uqUniformVectorRVClass<uqGslVectorClass,uqGslMatrixClass>* paramPriorRvPtr = NULL;
//uqGaussianVectorRVClass<uqGslVectorClass,uqGslMatrixClass>* paramPriorRvPtr = NULL;

  //***********************************************************************
  // Step 02 of 09: Instantiate the 'scenario' and 'output' spaces
  //***********************************************************************
  unsigned int paper_p_x = 1; // scenario dimension; 'p_x' in paper; ball radius 'R' in tower example
  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>
    paper_p_x_space(env, "scenario_", paper_p_x, NULL);

  unsigned int paper_n_eta = 16; // simulation output dimension; 'n_eta' in paper; 16 in tower example
  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>
    paper_n_eta_space(env, "output_", paper_n_eta, NULL);

  //***********************************************************************
  // Step 03 of 09: Instantiate the simulation storage
  // Regarding simulation scenario input values, QUESO will standardize them so that
  //    they exist inside a hypercube: this will be done in the 'uqSimulationModelClass'
  //    constructor, step 04 of 09.
  // Regarding simulation output data, QUESO will transform it so that the mean is
  //    zero and the variance is one: this will be done in the 'uqSimulationModelClass'
  //    constructor, step 04 of 09.
  //***********************************************************************
  unsigned int paper_m = 25; // number of simulations; 'm' in paper; 25 in tower example
  uqSimulationStorageClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>
    simulationStorage(paper_p_x_space,paper_p_t_space,paper_n_eta_space,paper_m);

  // Add simulations: what if none?
  uqGslVectorClass extraSimulationGridVec(paper_n_eta_space.zeroVector());
  std::vector<uqGslVectorClass* > simulationScenarios(paper_m,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* > paramVecs          (paper_m,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* > outputVecs         (paper_m,(uqGslVectorClass*) NULL);

  for (unsigned int i = 0; i < paper_m; ++i) {
    simulationScenarios[i] = new uqGslVectorClass(paper_p_x_space.zeroVector());   // 'x_{i+1}^*' in paper
    paramVecs          [i] = new uqGslVectorClass(paper_p_t_space.zeroVector());   // 't_{i+1}^*' in paper
    outputVecs         [i] = new uqGslVectorClass(paper_n_eta_space.zeroVector()); // 'eta_{i+1}' in paper
  }

  // Populate all objects just instantiated
  std::set<unsigned int> tmpSetStep03;
  tmpSetStep03.insert(env.subId());

  extraSimulationGridVec.subReadContents("inputData/extraSimulHeights",
                                         "m",
                                         tmpSetStep03);

  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>
    paper_m_space(env, "simulation_", paper_m, NULL);
  uqGslVectorClass inputSimulScenarioVector(paper_m_space.zeroVector());
  inputSimulScenarioVector.subReadContents("inputData/allSimulScenarios",
                                           "m",
                                           tmpSetStep03);
  uqGslVectorClass inputSimulParameterVector(paper_m_space.zeroVector());
  inputSimulParameterVector.subReadContents("inputData/allSimulParameters",
                                            "m",
                                            tmpSetStep03);
  uqGslMatrixClass inputSimulOutputsMatrix(env,paper_n_eta_space.map(),paper_m);
  inputSimulOutputsMatrix.subReadContents("inputData/allSimulOutputs",
                                          "m",
                                          tmpSetStep03);

  for (unsigned int i = 0; i < paper_m; ++i) {
    (*(simulationScenarios[i]))[0] = inputSimulScenarioVector [i];
    (*(paramVecs          [i]))[0] = inputSimulParameterVector[i];
    inputSimulOutputsMatrix.getColumn(i,*(outputVecs[i]));
  }

  // Finally, add information to the simulation storage
  for (unsigned int i = 0; i < paper_m; ++i) {
    simulationStorage.addSimulation(*(simulationScenarios[i]),*(paramVecs[i]),*(outputVecs[i]));
  }

  //***********************************************************************
  // Step 04 of 09: Instantiate the simulation model
  //***********************************************************************
  uqSimulationModelClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>
    simulationModel("",   // prefix
                    NULL, // options values
                    simulationStorage);
  unsigned int paper_p_eta = simulationModel.numBasis(); // number of simulation basis; 'p_eta' in paper; 2 in tower example

  //***********************************************************************
  // Step 05 of 09: Instantiate the experiment storage
  // Regarding experimental scenario input values, QUESO will standardize them so that
  //    they exist inside a hypercube: this will be done in the 'uqExperimentModelClass'
  //    constructor, step 06 of 09.
  // Regarding experimental data, the user has to provide it already in transformed
  //    format, that is, with mean zero and standard deviation one.
  //***********************************************************************
  uqExperimentStorageClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>* experimentStoragePtr = NULL;
  uqExperimentModelClass  <uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>* experimentModelPtr   = NULL;

  unsigned int paper_n = 0;

  std::vector<uqGslVectorClass* >                                      experimentScenarios_original(paper_n,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* >                                      experimentScenarios_standard(paper_n,(uqGslVectorClass*) NULL);
  std::vector<unsigned int>                                            experimentDims              (paper_n,0);
  std::vector<uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>* > experimentSpaces            (paper_n,(uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>*) NULL);
  std::vector<uqGslVectorClass* >                                      extraExperimentGridVecs     (paper_n,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* >                                      experimentVecs_original     (paper_n,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* >                                      experimentVecs_auxMean      (paper_n,(uqGslVectorClass*) NULL);
  std::vector<uqGslVectorClass* >                                      experimentVecs_transformed  (paper_n,(uqGslVectorClass*) NULL);
  std::vector<uqGslMatrixClass* >                                      experimentMats_original     (paper_n,(uqGslMatrixClass*) NULL);
  std::vector<uqGslMatrixClass* >                                      experimentMats_transformed  (paper_n,(uqGslMatrixClass*) NULL);

  std::vector<uqGslMatrixClass* >                                      DobsMats                    (paper_n, (uqGslMatrixClass*) NULL);

  std::vector<uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>* > Kmats_interp_spaces         (paper_n, (uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>*) NULL);
  std::vector<uqGslMatrixClass*                                      > Kmats_interp                (paper_n, (uqGslMatrixClass*) NULL); // Interpolations of 'Kmat_eta' = 'K_i's' in paper

  if (useExperiments) {
    paper_n = 3; // number of experiments; 'n' in paper; 3 in tower example

    experimentStoragePtr = new uqExperimentStorageClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>(paper_p_x_space, paper_n);

    // Add experiments
    experimentScenarios_original.resize(paper_n,(uqGslVectorClass*) NULL);
    experimentScenarios_standard.resize(paper_n,(uqGslVectorClass*) NULL);
    experimentDims.resize              (paper_n,0);
    experimentSpaces.resize            (paper_n,(uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>*) NULL);
    extraExperimentGridVecs.resize     (paper_n,(uqGslVectorClass*) NULL);
    experimentVecs_original.resize     (paper_n,(uqGslVectorClass*) NULL);
    experimentVecs_auxMean.resize      (paper_n,(uqGslVectorClass*) NULL);
    experimentVecs_transformed.resize  (paper_n,(uqGslVectorClass*) NULL);
    experimentMats_original.resize     (paper_n,(uqGslMatrixClass*) NULL);
    experimentMats_transformed.resize  (paper_n,(uqGslMatrixClass*) NULL);

    experimentDims[0] = 4; // 'n_y_1' in paper; 4 in tower example
    experimentDims[1] = 4; // 'n_y_2' in paper; 4 in tower example
    experimentDims[2] = 3; // 'n_y_3' in paper; 3 in tower example

    for (unsigned int i = 0; i < paper_n; ++i) {
      experimentScenarios_original[i] = new uqGslVectorClass                                     (paper_p_x_space.zeroVector());               // 'x_{i+1}' in paper
      experimentScenarios_standard[i] = new uqGslVectorClass                                     (paper_p_x_space.zeroVector());               // 'x_{i+1}' in paper
      experimentSpaces            [i] = new uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>(env, "expSpace", experimentDims[i], NULL);
      extraExperimentGridVecs     [i] = new uqGslVectorClass                                     (experimentSpaces[i]->zeroVector());          //
      experimentVecs_original     [i] = new uqGslVectorClass                                     (experimentSpaces[i]->zeroVector());          //
      experimentVecs_auxMean      [i] = new uqGslVectorClass                                     (experimentSpaces[i]->zeroVector());          //
      experimentVecs_transformed  [i] = new uqGslVectorClass                                     (experimentSpaces[i]->zeroVector());          // 'y_{i+1}' in paper
      experimentMats_original     [i] = new uqGslMatrixClass                                     (experimentSpaces[i]->zeroVector());          //
      experimentMats_transformed  [i] = new uqGslMatrixClass                                     (experimentSpaces[i]->zeroVector());          // 'W_{i+1}' in paper
    }

    //***********************************************************************
    // Populate information regarding experiment '0'
    //***********************************************************************
    (*(experimentScenarios_original[0]))[0] = 0.1; // 'x_1' in paper; Radius in tower example
    *(experimentScenarios_standard[0])  = *(experimentScenarios_original[0]);
    *(experimentScenarios_standard[0]) -= simulationModel.xSeq_original_mins();
    for (unsigned int j = 0; j < paper_p_x; ++j) {
      (*(experimentScenarios_standard[0]))[j] /= simulationModel.xSeq_original_ranges()[j];
    }

    (*(extraExperimentGridVecs[0]))[0] = 5.;
    (*(extraExperimentGridVecs[0]))[1] = 10.;
    (*(extraExperimentGridVecs[0]))[2] = 15.;
    (*(extraExperimentGridVecs[0]))[3] = 20.;

    (*(experimentVecs_original[0]))[0] = 1.2180;
    (*(experimentVecs_original[0]))[1] = 2.0126;
    (*(experimentVecs_original[0]))[2] = 2.7942;
    (*(experimentVecs_original[0]))[3] = 3.5747;

    experimentVecs_auxMean[0]->matlabLinearInterpExtrap(extraSimulationGridVec,simulationModel.etaSeq_original_mean(),*(extraExperimentGridVecs[0]));
    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      *env.subDisplayFile() << "In compute(), step 05, experiment 0:"
                            << "\n  extraSimulationGridVec = "                 << extraSimulationGridVec
                            << "\n  simulationModel.etaSeq_original_mean() = " << simulationModel.etaSeq_original_mean()
                            << "\n  *(extraExperimentGridVecs[0]) = "          << *(extraExperimentGridVecs[0])
                            << "\n  *(experimentVecs_auxMean[0]) = "           << *(experimentVecs_auxMean[0])
                            << std::endl;
    }
    *(experimentVecs_transformed[0]) = (1./simulationModel.etaSeq_allStd()) * ( *(experimentVecs_original[0]) - *(experimentVecs_auxMean[0]) ); // 'y_1' in paper
    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      *env.subDisplayFile() << "In compute(), step 05, experiment 0:"
                            << "\n  *(experimentVecs_original[0]) = "    << *(experimentVecs_original[0])
                            << "\n  *(experimentVecs_auxMean[0]) = "     << *(experimentVecs_auxMean[0])
                            << "\n  simulationModel.etaSeq_allStd() = "  << simulationModel.etaSeq_allStd()
                            << "\n  *(experimentVecs_transformed[0]) = " << *(experimentVecs_transformed[0])
                            << std::endl;
    }

    (*(experimentMats_original[0]))(0,0) = 1.;
    (*(experimentMats_original[0]))(1,1) = 1.;
    (*(experimentMats_original[0]))(2,2) = 1.;
    (*(experimentMats_original[0]))(3,3) = 1.;

    *(experimentMats_transformed[0]) = *(experimentMats_original[0]);

    //***********************************************************************
    // Populate information regarding experiment '1'
    //***********************************************************************
    (*(experimentScenarios_original[1]))[0] = 0.2; // 'x_2' in paper; Radius in tower example
    *(experimentScenarios_standard[1])  = *(experimentScenarios_original[1]);
    *(experimentScenarios_standard[1]) -= simulationModel.xSeq_original_mins();
    for (unsigned int j = 0; j < paper_p_x; ++j) {
      (*(experimentScenarios_standard[1]))[j] /= simulationModel.xSeq_original_ranges()[j];
    }

    (*(extraExperimentGridVecs[1]))[0] = 5.;
    (*(extraExperimentGridVecs[1]))[1] = 10.;
    (*(extraExperimentGridVecs[1]))[2] = 15.;
    (*(extraExperimentGridVecs[1]))[3] = 20.;

    (*(experimentVecs_original[1]))[0] = 1.1129;
    (*(experimentVecs_original[1]))[1] = 1.7225;
    (*(experimentVecs_original[1]))[2] = 2.2898;
    (*(experimentVecs_original[1]))[3] = 2.8462;

    experimentVecs_auxMean[1]->matlabLinearInterpExtrap(extraSimulationGridVec,simulationModel.etaSeq_original_mean(),*(extraExperimentGridVecs[1]));
    *(experimentVecs_transformed[1]) = (1./simulationModel.etaSeq_allStd()) * ( *(experimentVecs_original[1]) - *(experimentVecs_auxMean[1]) ); // 'y_2' in paper

    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      *env.subDisplayFile() << "In compute(), step 05, experiment 1:"
                            << "\n  *(experimentVecs_original[1]) = "    << *(experimentVecs_original[1])
                            << "\n  *(experimentVecs_auxMean[1]) = "     << *(experimentVecs_auxMean[1])
                            << "\n  simulationModel.etaSeq_allStd() = "  << simulationModel.etaSeq_allStd()
                            << "\n  *(experimentVecs_transformed[1]) = " << *(experimentVecs_transformed[1])
                            << std::endl;
    }

    (*(experimentMats_original[1]))(0,0) = 1.;
    (*(experimentMats_original[1]))(1,1) = 1.;
    (*(experimentMats_original[1]))(2,2) = 1.;
    (*(experimentMats_original[1]))(3,3) = 1.;

    *(experimentMats_transformed[1]) = *(experimentMats_original[1]);

    //***********************************************************************
    // Populate information regarding experiment '2'
    //***********************************************************************
    (*(experimentScenarios_original[2]))[0] = 0.4; // 'x_3' in paper; Radius in tower example
    *(experimentScenarios_standard[2])  = *(experimentScenarios_original[2]);
    *(experimentScenarios_standard[2]) -= simulationModel.xSeq_original_mins();
    for (unsigned int j = 0; j < paper_p_x; ++j) {
      (*(experimentScenarios_standard[2]))[j] /= simulationModel.xSeq_original_ranges()[j];
    }

    (*(extraExperimentGridVecs[2]))[0] = 5.;
    (*(extraExperimentGridVecs[2]))[1] = 10.;
    (*(extraExperimentGridVecs[2]))[2] = 15.;

    (*(experimentVecs_original[2]))[0] = 1.0611;
    (*(experimentVecs_original[2]))[1] = 1.5740;
    (*(experimentVecs_original[2]))[2] = 2.0186;

    experimentVecs_auxMean[2]->matlabLinearInterpExtrap(extraSimulationGridVec,simulationModel.etaSeq_original_mean(),*(extraExperimentGridVecs[2]));
    *(experimentVecs_transformed[2]) = (1./simulationModel.etaSeq_allStd()) * ( *(experimentVecs_original[2]) - *(experimentVecs_auxMean[2]) ); // 'y_3' in paper

    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      *env.subDisplayFile() << "In compute(), step 05, experiment 2:"
                            << "\n  *(experimentVecs_original[2]) = "    << *(experimentVecs_original[2])
                            << "\n  *(experimentVecs_auxMean[2]) = "     << *(experimentVecs_auxMean[2])
                            << "\n  simulationModel.etaSeq_allStd() = "  << simulationModel.etaSeq_allStd()
                            << "\n  *(experimentVecs_transformed[2]) = " << *(experimentVecs_transformed[2])
                            << std::endl;
    }

    (*(experimentMats_original[2]))(0,0) = 1.;
    (*(experimentMats_original[2]))(1,1) = 1.;
    (*(experimentMats_original[2]))(2,2) = 1.;

    *(experimentMats_transformed[2]) = *(experimentMats_original[2]);

    //***********************************************************************
    // Finally, add information to the experiment storage
    //***********************************************************************
    for (unsigned int i = 0; i < paper_n; ++i) {
      if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
        *env.subDisplayFile() << "In compute(), step 05"
                              << ": calling experimentStoragePtr->addExperiment() for experiment of id '" << i << "'..."
                              << std::endl;
      }
      experimentStoragePtr->addExperiment(*(experimentScenarios_standard[i]),*(experimentVecs_transformed[i]),*(experimentMats_transformed[i]));
      if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
        *env.subDisplayFile() << "In compute(), step 05"
                              << ": returned from experimentStoragePtr->addExperiment() for experiment of id '" << i << "'"
                              << std::endl;
      }
    }


    //***********************************************************************
    // Step 06 of 09: Instantiate the experiment model
    // User has to provide 'D' matrices
    // User has to interpolate 'K_eta' matrix in order to form 'K_i' matrices
    // 'K_eta' is 'Ksim' in the GPMSA tower example document (page 9)
    // 'K_i' is 'Kobs' in the GPMSA tower example document (page 9)
    //***********************************************************************
    unsigned int paper_p_delta = 13; // number of experiment basis; 'p_delta' in paper; 13 in tower example

    //***********************************************************************
    // Form and compute 'DsimMat'
    // Not mentioned in the paper
    // 'Dsim' in the GPMSA tower example document (page 11)
    //***********************************************************************
    double kernelSigma = 2.;
    uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> paper_p_delta_space(env, "paper_p_delta_space", paper_p_delta, NULL);
    uqGslVectorClass kernelCenters(paper_p_delta_space.zeroVector());
    for (unsigned int i = 1; i < paper_p_delta; ++i) { // Yes, '1'
      kernelCenters[i] = kernelSigma*((double) i);
    }
    uqGslMatrixClass DsimMat(env,paper_n_eta_space.map(),paper_p_delta); // Important matrix (not mentioned on paper)
    uqGslVectorClass DsimCol(paper_n_eta_space.zeroVector());
    uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> oneDSpace(env, "oneDSpace", 1, NULL);
    uqGslVectorClass oneDVec(oneDSpace.zeroVector());
    uqGslMatrixClass oneDMat(oneDSpace.zeroVector());
    oneDMat(0,0) = kernelSigma*kernelSigma;
    for (unsigned int colId = 0; colId < DsimMat.numCols(); ++colId) {
      oneDVec[0] = kernelCenters[colId];
      uqGaussianJointPdfClass<uqGslVectorClass,uqGslMatrixClass> kernelPdf("",oneDSpace,oneDVec,oneDMat);
      for (unsigned int rowId = 0; rowId < paper_n_eta; ++rowId) {
        oneDVec[0] = extraSimulationGridVec[rowId];
        DsimCol[rowId] = kernelPdf.actualValue(oneDVec,NULL,NULL,NULL,NULL);
      }
      DsimMat.setColumn(colId,DsimCol);
    }

    //***********************************************************************
    // Populate information regarding experiment 'i'
    // 'D_{i+1}' in the paper
    // 'Dobs' in the GPMSA tower example document (page 11)
    //***********************************************************************
    DobsMats.resize(paper_n, (uqGslMatrixClass*) NULL); // Important matrices (D_i's on paper)
    for (unsigned int i = 0; i < paper_n; ++i) {
      DobsMats[i] = new uqGslMatrixClass(env,experimentSpaces[i]->map(),paper_p_delta); // 'D_{i+1}' in paper
      uqGslVectorClass DobsCol(experimentSpaces[i]->zeroVector());
      for (unsigned int colId = 0; colId < DobsMats[i]->numCols(); ++colId) {
        oneDVec[0] = kernelCenters[colId];
        uqGaussianJointPdfClass<uqGslVectorClass,uqGslMatrixClass> kernelPdf("",oneDSpace,oneDVec,oneDMat);
        for (unsigned int rowId = 0; rowId < DobsCol.sizeLocal(); ++rowId) {
          oneDVec[0] = (*(extraExperimentGridVecs[1]))[rowId];
          DobsCol[rowId] = kernelPdf.actualValue(oneDVec,NULL,NULL,NULL,NULL);
        }
        DobsMats[i]->setColumn(colId,DobsCol);
      }
    }
  
    //***********************************************************************
    // Normalize 'DsimMat' and all 'DobsMats'
    //***********************************************************************
    uqGslMatrixClass DsimMatTranspose(env,paper_p_delta_space.map(),paper_n_eta);
    DsimMatTranspose.fillWithTranspose(0,0,DsimMat,true,true);
    double Dmax = (DsimMat * DsimMatTranspose).max();
    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      *env.subDisplayFile() << "In compute()"
                            << ": Dmax = " << Dmax
                            << std::endl;
    }
    DsimMat /= std::sqrt(Dmax);

    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
      DsimMat.setPrintHorizontally(false);
      *env.subDisplayFile() << "In compute()"
                            << ": 'DsimMat'"
                            << ", nRows = "      << DsimMat.numRowsLocal()
                            << ", nCols = "      << DsimMat.numCols()
                            << ", contents =\n " << DsimMat
                            << std::endl;
    }
    for (unsigned int i = 0; i < paper_n; ++i) {
      *(DobsMats[i]) /= std::sqrt(Dmax);
      DobsMats[i]->setPrintHorizontally(false);
      if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
        *env.subDisplayFile() << "In compute()"
                              << ": 'DobsMats', i = " << i
                              << ", nRows = "         << DobsMats[i]->numRowsLocal()
                              << ", nCols = "         << DobsMats[i]->numCols()
                              << ", contents =\n"     << *(DobsMats[i])
                              << std::endl;
      }
    }

    //***********************************************************************
    // Compute 'K_i' matrices
    // 'Kobs' in the GPMSA tower example document (page 9)
    //***********************************************************************
    Kmats_interp_spaces.resize(paper_n, (uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>*) NULL);
    Kmats_interp.resize       (paper_n, (uqGslMatrixClass*) NULL); // Important matrices (K_i's on paper)
    for (unsigned int i = 0; i < paper_n; ++i) {
      Kmats_interp_spaces[i] = new uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass>(env,"Kmats_interp_spaces_",experimentStoragePtr->n_ys_transformed()[i],NULL);
      Kmats_interp       [i] = new uqGslMatrixClass(env,Kmats_interp_spaces[i]->map(),paper_p_eta);
      Kmats_interp       [i]->matlabLinearInterpExtrap(extraSimulationGridVec,simulationModel.Kmat_eta(),*(extraExperimentGridVecs[i])); // Important matrix (K_eta on paper) 
      Kmats_interp[i]->setPrintHorizontally(false);
      if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
        *env.subDisplayFile() << "In compute()"
                              << ": 'Kmats_interp', i = " << i
                              << ", nRows = "             << Kmats_interp[i]->numRowsLocal()
                              << ", nCols = "             << Kmats_interp[i]->numCols()
                              << ", contents =\n"         << *(Kmats_interp[i])
                              << std::endl;
      }
    }

    if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
      *env.subDisplayFile() << "In compute()"
                            << ": finished computing 'K_i' matrices"
                            << std::endl;
    }

    //***********************************************************************
    // The constructor below will read from the options file:
    // --> the 'G' values (a total of 'F' of them); 'Gs' in paper; G[0] = 13 in tower example
    // --> 'F' in paper = number of groups of experiment basis; 1 in tower example
    //***********************************************************************
    experimentModelPtr = new uqExperimentModelClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>("",   // prefix
                                                                                                                         NULL, // options values
                                                                                                                         *experimentStoragePtr,
                                                                                                                         DobsMats,
                                                                                                                         Kmats_interp);

    paramPriorRvPtr = new uqUniformVectorRVClass<uqGslVectorClass,uqGslMatrixClass>("prior_",paramDomain);
  //uqGslVectorClass meanVec(paper_p_t_space.zeroVector());
  //meanVec[0] = 0.5;
  //uqGslMatrixClass covaMat(paper_p_t_space.zeroVector());
  //covaMat(0,0) = 100.;
  //paramPriorRvPtr = new uqGaussianVectorRVClass<uqGslVectorClass,uqGslMatrixClass>("prior_",paramDomain/*paper_p_t_space*/,meanVec,covaMat);
  } // if (useExperiments)

  //***********************************************************************
  // Step 07 of 09: Instantiate the GPMSA computer model
  //***********************************************************************
  uqGpmsaComputerModelClass<uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass,uqGslVectorClass,uqGslMatrixClass>* gcm;
  gcm = new uqGpmsaComputerModelClass<uqGslVectorClass,uqGslMatrixClass,
                                      uqGslVectorClass,uqGslMatrixClass,
                                      uqGslVectorClass,uqGslMatrixClass,
                                      uqGslVectorClass,uqGslMatrixClass>
          ("",
           NULL,
           simulationStorage,
           simulationModel,
           experimentStoragePtr, // pass "NULL" if there is no experimental data available
           experimentModelPtr,   // pass "NULL" if there is no experimental data available
           paramPriorRvPtr);     // pass "NULL" if there is no experimental data available

  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "In compute()"
                          << ": finished instantiating 'gcm'"
                          << ", gcm->totalSpace().dimLocal() = " << gcm->totalSpace().dimLocal()
                          << std::endl;
  }

  //***********************************************************************
  // Step 08 of 09: Calibrate the computer model
  //***********************************************************************
  uqGslVectorClass totalInitialVec(gcm->totalSpace().zeroVector());
  gcm->totalPriorRv().realizer().realization(totalInitialVec); // todo_r

  uqGslVectorClass diagVec(gcm->totalSpace().zeroVector());
  diagVec.cwSet(0.25);

  if (useExperiments) {
#if 1
    // Use same initial values as matlab code, for debug
    totalInitialVec[ 0] = 2.9701e+04;          // lambda_eta = lamWOs
    totalInitialVec[ 1] = 1.;                  // lambda_w_1 = lamUz
    totalInitialVec[ 2] = 1.;                  // lambda_w_2 =
    totalInitialVec[ 3] = std::exp(-0.1*0.25); // rho_w_1_1  = exp(-model.betaU.*(0.5^2));
    totalInitialVec[ 4] = std::exp(-0.1*0.25); // rho_w_1_2  =
    totalInitialVec[ 5] = std::exp(-0.1*0.25); // rho_w_2_1  =
    totalInitialVec[ 6] = std::exp(-0.1*0.25); // rho_w_2_2  =
    totalInitialVec[ 7] = 1000.;               // lambda_s_1 = lamWs
    totalInitialVec[ 8] = 1000.;               // lambda_s_2 =
    totalInitialVec[ 9] = 999.999;             // lambda_y   = lamOs
    totalInitialVec[10] = 20.;                 // lambda_v_1 = lamVz
    totalInitialVec[11] = std::exp(-0.1*0.25); // rho_v_1_1  = betaV
    totalInitialVec[12] = 0.5;                 // theta_1    = theta
#endif

    diagVec[ 0] = 2500.; // lambda_eta = lamWOs
    diagVec[ 1] = 0.09;  // lambda_w_1 = lamUz
    diagVec[ 2] = 0.09;  // lambda_w_2 =
    diagVec[ 3] = 0.01;  // rho_w_1_1  = betaU
    diagVec[ 4] = 0.01;  // rho_w_1_2  =
    diagVec[ 5] = 0.01;  // rho_w_2_1  =
    diagVec[ 6] = 0.01;  // rho_w_2_2  =
    diagVec[ 7] = 2500.; // lambda_s_1 = lamWs
    diagVec[ 8] = 2500;  // lambda_s_2 = 
    diagVec[ 9] = 2500;  // lambda_y   = lamOs
    diagVec[10] = 2500;  // lambda_v_1 = lamVz
    diagVec[11] = 0.01;  // rho_v_1_1  = betaV
    diagVec[12] = 100.;  // theta_1    = theta
  }
  else {
#if 1
    // Use same initial values as matlab code, for debug
    totalInitialVec[ 0] = 2.9701e+04;          // lambda_eta = lamWOs
    totalInitialVec[ 1] = 1.;                  // lambda_w_1 = lamUz
    totalInitialVec[ 2] = 1.;                  // lambda_w_2 =
    totalInitialVec[ 3] = std::exp(-0.1*0.25); // rho_w_1_1  = exp(-model.betaU.*(0.5^2));
    totalInitialVec[ 4] = std::exp(-0.1*0.25); // rho_w_1_2  =
    totalInitialVec[ 5] = std::exp(-0.1*0.25); // rho_w_2_1  =
    totalInitialVec[ 6] = std::exp(-0.1*0.25); // rho_w_2_2  =
    totalInitialVec[ 7] = 1000.;               // lambda_s_1 = lamWs
    totalInitialVec[ 8] = 1000.;               // lambda_s_2 =
#endif

    diagVec[ 0] = 2500.; // lambda_eta = lamWOs
    diagVec[ 1] = 0.09;  // lambda_w_1 = lamUz
    diagVec[ 2] = 0.09;  // lambda_w_2 =
    diagVec[ 3] = 0.01;  // rho_w_1_1  = betaU
    diagVec[ 4] = 0.01;  // rho_w_1_2  =
    diagVec[ 5] = 0.01;  // rho_w_2_1  =
    diagVec[ 6] = 0.01;  // rho_w_2_2  =
    diagVec[ 7] = 2500.; // lambda_s_1 = lamWs
    diagVec[ 8] = 2500;  // lambda_s_2 = 
  }

  uqGslMatrixClass totalInitialProposalCovMatrix(diagVec); // todo_r

  if (useML) {
    gcm->calibrateWithBayesMLSampling();
  }
  else {
    gcm->calibrateWithBayesMetropolisHastings(NULL,totalInitialVec,&totalInitialProposalCovMatrix);
  }

  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "In compute()"
                          << ": finished calibrating 'gcm'"
                          << std::endl;
  }

  //***********************************************************************
  // Step 09 of 09: Make predictions with the calibrated computer model
  // Substep 09a: predict 'v' and 'u' weights
  // Substep 09b: predict 'w' weights
  // Substep 09c: predict new experiment results
  // Substep 09d: predict new simulation outputs
  //***********************************************************************
  unsigned int dim1 = 16;
  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> predictionGrid1Space(env, "predictionGrid1_", dim1, NULL);
  uqGslVectorClass predictionGrid1Vec(predictionGrid1Space.zeroVector());
  for (unsigned int i = 0; i < dim1; ++i) {
    predictionGrid1Vec[i] = ((double) i)/((double) (dim1-1));
  }
  
  unsigned int dim2 = 16;
  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> predictionGrid2Space(env, "predictionGrid2_", dim2, NULL);
  uqGslVectorClass predictionGrid2Vec(predictionGrid2Space.zeroVector());
  for (unsigned int j = 0; j < dim2; ++j) {
    predictionGrid2Vec[j] = ((double) j)/((double) (dim2-1));
  }

  if (env.fullRank() == 0) { // Yes, only one processor in all 'full' communicator
    std::set<unsigned int> tmpSet;
    tmpSet.insert(0);

    predictionGrid1Vec.subWriteContents("towerPredictionGrid1", // varNamePrefix,
                                        "predictionGrid1",
                                        "m",
                                        tmpSet); // allowedSubEnvIds
    predictionGrid2Vec.subWriteContents("towerPredictionGrid2", // varNamePrefix,
                                        "predictionGrid2",
                                        "m",
                                        tmpSet); // allowedSubEnvIds
  }

  uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> paper_p_eta_space(env, "paper_p_eta_", paper_p_eta, NULL); // = gcm->unique_u_space() or gcm->unique_w_space()

  if (useExperiments) {
#if 1 // Might put '0' while code is not finished
    //***********************************************************************
    // Substep 09a of 09: Predict 'v' and 'u' weights
    //***********************************************************************
    uqGslVectorClass tmpExperimentScenarioVec (paper_p_x_space.zeroVector());
    uqGslVectorClass tmpSimulationParameterVec(paper_p_t_space.zeroVector());

    unsigned int paper_p_delta = 13; // todo_rr: repeated
    uqVectorSpaceClass<uqGslVectorClass,uqGslMatrixClass> paper_p_delta_space(env, "paper_p_delta_space", paper_p_delta, NULL); // todo_rr: repeated // = gcm_unique_v_space()

    std::vector<uqGslMatrixClass* > predictionGridVMats(paper_p_delta,NULL);
    for (unsigned int k = 0; k < paper_p_delta; ++k) {
      predictionGridVMats[k] = new uqGslMatrixClass(predictionGrid1Space.zeroVector());
    }
    std::vector<uqGslMatrixClass* > predictionGridUMats(paper_p_eta,NULL);
    for (unsigned int k = 0; k < paper_p_eta; ++k) {
      predictionGridUMats[k] = new uqGslMatrixClass(predictionGrid1Space.zeroVector());
    }

    uqGslVectorClass vuMeanVec  (gcm->unique_vu_space().zeroVector());
    uqGslMatrixClass vuCovMatrix(gcm->unique_vu_space().zeroVector());
    uqGslVectorClass vMeanVec   (paper_p_delta_space.zeroVector());
    uqGslMatrixClass vCovMatrix (paper_p_delta_space.zeroVector());
    uqGslVectorClass uMeanVec   (paper_p_eta_space.zeroVector());
    uqGslMatrixClass uCovMatrix (paper_p_eta_space.zeroVector());
    for (unsigned int i = 0; i < dim1; ++i) {
      tmpExperimentScenarioVec[0] = predictionGrid1Vec[i];
      for (unsigned int j = 0; j < dim2; ++j) {
        tmpSimulationParameterVec[0] = predictionGrid2Vec[j];
#if 1
        gcm->predictVUsAtGridPoint(tmpExperimentScenarioVec,
                                   tmpSimulationParameterVec,
                                   vuMeanVec,
                                   vuCovMatrix,
                                   vMeanVec,
                                   vCovMatrix,
                                   uMeanVec,
                                   uCovMatrix);
#endif
        for (unsigned int k = 0; k < paper_p_delta; ++k) {
          (*predictionGridVMats[k])(i,j) = vMeanVec[k];
        }

        for (unsigned int k = 0; k < paper_p_eta; ++k) {
          (*predictionGridUMats[k])(i,j) = uMeanVec[k];
        }
      }
    }

    if (env.fullRank() == 0) { // Yes, only one processor in all 'full' communicator
      std::set<unsigned int> tmpSet;
      tmpSet.insert(0);

      char varNamePrefix[32+1];
      char fileName     [32+1];

      for (unsigned int i = 0; i < paper_p_delta; ++i) {
        sprintf(varNamePrefix,"towerV%dmat",i+1);
        sprintf(fileName,     "v%dmat",     i+1);
        predictionGridVMats[i]->subWriteContents(varNamePrefix,
                                                 fileName,
                                                 "m",
                                                 tmpSet); // allowedSubEnvIds
      }

      for (unsigned int i = 0; i < paper_p_eta; ++i) {
        sprintf(varNamePrefix,"towerU%dmat",i+1);
        sprintf(fileName,     "u%dmat",     i+1);
        predictionGridUMats[i]->subWriteContents(varNamePrefix,
                                                 fileName,
                                                 "m",
                                                 tmpSet); // allowedSubEnvIds
      }
    }

    for (unsigned int i = 0; i < paper_p_eta; ++i) {
      delete predictionGridUMats[i];
    }
    for (unsigned int i = 0; i < paper_p_delta; ++i) {
      delete predictionGridVMats[i];
    }
#endif // Might put '0'
  } // if (useExperiments)

#if 1 // Might put '0' while code is not finished
  //***********************************************************************
  // Substep 09b of 09: Predict 'w' weights
  //***********************************************************************
  uqGslVectorClass tmpSimulationScenarioVec (paper_p_x_space.zeroVector());
  uqGslVectorClass tmpSimulationParameterVec(paper_p_t_space.zeroVector());
  uqGslVectorClass wMeanVec  (paper_p_eta_space.zeroVector());
  uqGslMatrixClass wCovMatrix(paper_p_eta_space.zeroVector());

#if 0 // For debug only
  tmpSimulationScenarioVec [0] = 0.4;
  tmpSimulationParameterVec[0] = 0.4;

  uqGslVectorClass forcingSampleVecForDebug(gcm->totalSpace().zeroVector());
  forcingSampleVecForDebug[ 0] = 2.9700e+04;             // lambda_eta = lamWOs
  forcingSampleVecForDebug[ 1] = 1.0000;                 // lambda_w_1 = lamUz
  forcingSampleVecForDebug[ 2] = 1.0083;                 // lambda_w_2 =
  forcingSampleVecForDebug[ 3] = std::exp(-0.1004*0.25); // rho_w_1_1  = exp(-model.betaU.*(0.5^2));
  forcingSampleVecForDebug[ 4] = std::exp(-0.1022*0.25); // rho_w_1_2  =
  forcingSampleVecForDebug[ 5] = std::exp(-0.1013*0.25); // rho_w_2_1  =
  forcingSampleVecForDebug[ 6] = std::exp(-0.1011*0.25); // rho_w_2_2  =
  forcingSampleVecForDebug[ 7] = 999.5113;               // lambda_s_1 = lamWs
  forcingSampleVecForDebug[ 8] = 999.3138;               // lambda_s_2 =
  forcingSampleVecForDebug[ 9] = 996.6176;               // lambda_y   = lamOs
  forcingSampleVecForDebug[10] = 20.0194;                // lambda_v_1 = lamVz
  forcingSampleVecForDebug[11] = std::exp(-0.1020*0.25); // rho_v_1_1  = betaV
  forcingSampleVecForDebug[12] = 0.5000;                 // theta_1    = theta

  gcm->predictWsAtGridPoint(tmpSimulationScenarioVec,
                            tmpSimulationParameterVec,
                            &forcingSampleVecForDebug,
                            wMeanVec,
                            wCovMatrix);
  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "In compute()"
                          << ": for scenario = " << tmpSimulationScenarioVec [0]
                          << " and parameter = " << tmpSimulationParameterVec[0]
                          << ", wMeanVec = "     << wMeanVec
                          << ", wCovMatrix = "   << wCovMatrix
                          << std::endl;
  }
  env.fullComm().Barrier();
  sleep(1);
  exit(1);
#endif

  std::vector<uqGslMatrixClass* > predictionGridWMats(paper_p_eta,NULL);
  for (unsigned int k = 0; k < paper_p_eta; ++k) {
    predictionGridWMats[k] = new uqGslMatrixClass(env,predictionGrid1Space.map(),dim2);
  }

  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "In compute()"
                          << ": beginning loop on predictions"
                          << ", dim1 = " << dim1
                          << ", dim2 = " << dim2
                          << std::endl;
  }

  for (unsigned int i = 0; i < dim1; ++i) {
    tmpSimulationScenarioVec[0] = predictionGrid1Vec[i];
    for (unsigned int j = 0; j < dim2; ++j) {
      tmpSimulationParameterVec[0] = predictionGrid2Vec[j];

      struct timeval timevalBeforePredict;
      int iRC = gettimeofday(&timevalBeforePredict, NULL);
      if (iRC) {}; // just to remove compiler warning

      gcm->predictWsAtGridPoint(tmpSimulationScenarioVec,
                                tmpSimulationParameterVec,
                                NULL,
                                wMeanVec,
                                wCovMatrix);

      double predictTime = uqMiscGetEllapsedSeconds(&timevalBeforePredict);
      if ((env.subDisplayFile()) && (env.displayVerbosity() >= 3)) {
        *env.subDisplayFile() << "In compute()"
                              << ": looping on predictions"
                              << ", i = " << i << " < " << dim1
                              << ", j = " << j << " < " << dim2
                              << ", returned from 'gcm->predictWsAtGridPoint()' after " << predictTime << " seconds"
                              << std::endl;
      }

      for (unsigned int k = 0; k < paper_p_eta; ++k) {
        (*predictionGridWMats[k])(i,j) = wMeanVec[k];
      }
    }
  }

  if (env.fullRank() == 0) { // Yes, only one processor in all 'full' communicator
    std::set<unsigned int> tmpSet;
    tmpSet.insert(0);

    char varNamePrefix[32+1];
    char fileName     [32+1];
    for (unsigned int i = 0; i < paper_p_eta; ++i) {
      sprintf(varNamePrefix,"towerW%dmat",i+1);
      sprintf(fileName,     "w%dmat",     i+1);
      predictionGridWMats[i]->subWriteContents(varNamePrefix,
                                               fileName,
                                               "m",
                                               tmpSet); // allowedSubEnvIds
    }
  }

  for (unsigned int i = 0; i < paper_p_eta; ++i) {
    delete predictionGridWMats[i];
  }

  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "In compute()"
                          << ": finished making predictions"
                          << std::endl;
  }
#endif // Might put '0'

#if 0 // Might put '0' while code is not finished
  //***********************************************************************
  // Substep 09c of 09: Predict new experiment results
  //***********************************************************************
  uqGslVectorClass newExperimentScenarioVec(paper_p_x_space.zeroVector());              // todo_rr
  uqGslMatrixClass newKmat_interp          (env,paper_n_eta_space.map(),paper_p_eta);   // todo_rr
  uqGslMatrixClass newDmat                 (env,paper_n_eta_space.map(),paper_p_delta); // todo_rr
  uqGslVectorClass simulationOutputMeanVec (paper_n_eta_space.zeroVector()); // Yes, size of simulation, since it is a prediction using the emulator
  uqGslVectorClass discrepancyMeanVec      (paper_n_eta_space.zeroVector());
  gcm->predictExperimentResults(newExperimentScenarioVec,newKmat_interp,newDmat,simulationOutputMeanVec,discrepancyMeanVec);

  //***********************************************************************
  // Substep 09d of 09: Predict new simulation outputs
  //***********************************************************************
  uqGslVectorClass newSimulationScenarioVec (paper_p_x_space.zeroVector  ()); // todo_rr
  uqGslVectorClass newSimulationParameterVec(paper_p_t_space.zeroVector  ()); // todo_rr
  uqGslVectorClass simulationOutputMeanVec2 (paper_n_eta_space.zeroVector());
  gcm->predictSimulationOutputs(newSimulationScenarioVec,newSimulationParameterVec,simulationOutputMeanVec2);
#endif // Might put '0'

  //***********************************************************************
  // Clean memory
  //***********************************************************************
  env.fullComm().Barrier();
  delete paramPriorRvPtr;
  delete experimentModelPtr;
  delete experimentStoragePtr;
  for (unsigned int i = 0; i < paper_n; ++i) {
    delete Kmats_interp       [i];
    delete Kmats_interp_spaces[i];
  }
  for (unsigned int i = 0; i < paper_m; ++i) {
    delete outputVecs         [i];
    delete paramVecs          [i];
    delete simulationScenarios[i];
  }
  for (unsigned int i = 0; i < paper_n; ++i) {
    delete experimentMats_transformed  [i];
    delete experimentMats_original     [i];
    delete experimentVecs_transformed  [i];
    delete experimentVecs_original     [i];
    delete experimentSpaces            [i];
    delete experimentScenarios_standard[i];
    delete experimentScenarios_original[i];
  }
  delete gcm;

  if ((env.subDisplayFile()) && (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "Leaving compute()"
                          << std::endl;
  }

  return;
}
int main(int argc, char ** argv)
{
#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "", "", NULL);
#else
  QUESO::FullEnvironment env("", "", NULL);
#endif

  unsigned int dim = 3;
  QUESO::VectorSpace<> paramSpace(env, "param_", dim, NULL);

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins.cwSet(-INFINITY);

  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs.cwSet(INFINITY);

  QUESO::BoxSubset<> paramDomain("param_", paramSpace, paramMins, paramMaxs);

  QUESO::GslVector mean(paramSpace.zeroVector());
  QUESO::GslMatrix var(paramSpace.zeroVector());
  mean[0] = 2.0;
  mean[1] = 3.0;
  mean[2] = 4.0;
  var(0,0) = 5.0;
  var(1,1) = 6.0;
  var(2,2) = 7.0;

  // Construct a Gaussian PDF
  QUESO::GaussianJointPdf<> pdf("", paramDomain, mean, var);

  // Vectors to store gradient calculations
  QUESO::GslVector lnGradVector(paramSpace.zeroVector());
  QUESO::GslVector gradVector(paramSpace.zeroVector());

  // Where to evaluate the gradient.  Evaluating at the mean (the mode for a
  // Gaussian) should give a gradient consisting of a vector of zeros.
  QUESO::GslVector point(mean);

  // We are testing that the gradient of log of the pdf is all zeros
  pdf.lnValue(point, NULL, &lnGradVector, NULL, NULL);
  queso_require_less_equal_msg(std::abs(lnGradVector[0]), TOL, "grad log gaussian pdf values are incorrect");
  queso_require_less_equal_msg(std::abs(lnGradVector[1]), TOL, "grad log gaussian pdf values are incorrect");
  queso_require_less_equal_msg(std::abs(lnGradVector[2]), TOL, "grad log gaussian pdf values are incorrect");

  // We are testing that the of the pdf is all zeros
  pdf.actualValue(point, NULL, &gradVector, NULL, NULL);
  queso_require_less_equal_msg(std::abs(gradVector[0]), TOL, "grad guassian pdf values are incorrect");
  queso_require_less_equal_msg(std::abs(gradVector[1]), TOL, "grad guassian pdf values are incorrect");
  queso_require_less_equal_msg(std::abs(gradVector[2]), TOL, "grad guassian pdf values are incorrect");


  // Now construct another Gaussian.  This time we're constructing a Gaussian
  // that we know will have a gradient consisting entirely of ones (in log
  // space).
  mean[0] = 0.0;
  mean[1] = 0.0;
  mean[2] = 0.0;

  var(0,0) = 1.0;
  var(0,1) = 0.8;
  var(0,2) = 0.7;
  var(1,0) = 0.8;
  var(1,1) = 2.0;
  var(1,2) = 0.6;
  var(2,0) = 0.7;
  var(2,1) = 0.6;
  var(2,2) = 3.0;

  point[0] = -2.5;
  point[1] = -3.4;
  point[2] = -4.3;

  QUESO::GaussianJointPdf<> pdf2("", paramDomain, mean, var);

  pdf2.lnValue(point, NULL, &lnGradVector, NULL, NULL);

  queso_require_less_equal_msg(std::abs(lnGradVector[0] - 1.0), TOL, "grad log gaussian pdf2 values are incorrect");
  queso_require_less_equal_msg(std::abs(lnGradVector[1] - 1.0), TOL, "grad log gaussian pdf2 values are incorrect");
  queso_require_less_equal_msg(std::abs(lnGradVector[2] - 1.0), TOL, "grad log gaussian pdf2 values are incorrect");

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}
Exemple #20
0
void compute(const QUESO::FullEnvironment& env, unsigned int numModes) {
  ////////////////////////////////////////////////////////
  // Step 1 of 5: Instantiate the parameter space
  ////////////////////////////////////////////////////////


#ifdef APPLS_MODAL_USES_CONCATENATION
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix>
    paramSpaceA(env, "paramA_", 2, NULL);
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix>
    paramSpaceB(env, "paramB_", 1, NULL);
#endif
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix>
    paramSpace(env, "param_", 3, NULL);

  ////////////////////////////////////////////////////////
  // Step 2 of 5: Instantiate the parameter domain
  ////////////////////////////////////////////////////////
#ifdef APPLS_MODAL_USES_CONCATENATION
  QUESO::GslVector paramMinsA(paramSpaceA.zeroVector());
  paramMinsA[0] = 0.;
  paramMinsA[1] = 0.;
  QUESO::GslVector paramMaxsA(paramSpaceA.zeroVector());
  paramMaxsA[0] = 3.;
  paramMaxsA[1] = 3.;
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
  
  paramDomainA("paramA_",paramSpaceA,paramMinsA,paramMaxsA);

  QUESO::GslVector paramMinsB(paramSpaceB.zeroVector());
  paramMinsB[0] = 0.;
  QUESO::GslVector paramMaxsB(paramSpaceB.zeroVector());
  paramMaxsB[0] = INFINITY;
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomainB("paramB_",paramSpaceB,paramMinsB,paramMaxsB);

  QUESO::ConcatenationSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("",paramSpace,paramDomainA,paramDomainB);
#else
  QUESO::GslVector paramMins(paramSpace.zeroVector());
  paramMins[0] = 0.;
  paramMins[1] = 0.;
  paramMins[2] = 0.;
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());
  paramMaxs[0] = 3.;
  paramMaxs[1] = 3.;
  paramMaxs[2] = .3;
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("param_",paramSpace,paramMins,paramMaxs);
#endif

  ////////////////////////////////////////////////////////
  // Step 3 of 5: Instantiate the likelihood function object
  ////////////////////////////////////////////////////////
  likelihoodRoutine_DataType likelihoodRoutine_Data;
 
  likelihoodRoutine_Data.numModes = numModes;
  QUESO::GenericScalarFunction<QUESO::GslVector,QUESO::GslMatrix>
    likelihoodFunctionObj("like_",
                          paramDomain,
                          likelihoodRoutine,
                          (void *) &likelihoodRoutine_Data,
                          true); // routine computes [-2.*ln(function)]
  
    ////////////////////////////////////////////////////////
  // Step 4 of 5: Instantiate the inverse problem
  ////////////////////////////////////////////////////////
#ifdef APPLS_MODAL_USES_CONCATENATION
  QUESO::UniformVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    priorRvA("priorA_", paramDomainA);
 
  QUESO::GslVector alpha(paramSpaceB.zeroVector());
  alpha[0] = 3.;
  QUESO::GslVector beta(paramSpaceB.zeroVector());
  if (numModes == 1) {
    beta[0] = 0.09709133373799;
  }
  else {
    beta[0] = 0.08335837191688;
  }
  QUESO::InverseGammaVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    priorRvB("priorB_", paramDomainB,alpha,beta);

  QUESO::ConcatenatedVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    priorRv("prior_", priorRvA, priorRvB, paramDomain);
#else
  QUESO::UniformVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    priorRv("prior_", paramDomain);
#endif

  QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<QUESO::GslVector,QUESO::GslMatrix>
    ip("", NULL, priorRv, likelihoodFunctionObj, postRv);

  ////////////////////////////////////////////////////////
  // Step 5 of 5: Solve the inverse problem
  ////////////////////////////////////////////////////////
  ip.solveWithBayesMLSampling();

  ////////////////////////////////////////////////////////
  // Print some statistics
  ////////////////////////////////////////////////////////
  unsigned int numPosTotal = postRv.realizer().subPeriod();
  if (env.subDisplayFile()) {
    *env.subDisplayFile() << "numPosTotal = " << numPosTotal
                          << std::endl;
  }

  QUESO::GslVector auxVec(paramSpace.zeroVector());
  unsigned int numPosTheta1SmallerThan1dot5 = 0;
  for (unsigned int i = 0; i < numPosTotal; ++i) {
    postRv.realizer().realization(auxVec);
    if (auxVec[0] < 1.5) numPosTheta1SmallerThan1dot5++;
  }

  if (env.subDisplayFile()) {
    *env.subDisplayFile() << "numPosTheta1SmallerThan1dot5 = " << numPosTheta1SmallerThan1dot5
                          << ", ratio = " << ((double) numPosTheta1SmallerThan1dot5)/((double) numPosTotal)
                          << std::endl;
  }

  return;
}
Exemple #21
0
void computeGravityAndTraveledDistance(const QUESO::FullEnvironment& env) {
  struct timeval timevalNow;
  
  gettimeofday(&timevalNow, NULL);
  if (env.fullRank() == 0) {
    std::cout << "\nBeginning run of 'Gravity + Projectile motion' example at "
              << ctime(&timevalNow.tv_sec)
              << "\n my fullRank = "         << env.fullRank()
              << "\n my subEnvironmentId = " << env.subId()
              << "\n my subRank = "          << env.subRank()
              << "\n my interRank = "        << env.inter0Rank()
               << std::endl << std::endl;
  }

  // Just examples of possible calls
  if ((env.subDisplayFile()       ) && 
      (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "Beginning run of 'Gravity + Projectile motion' example at "
                          << ctime(&timevalNow.tv_sec)
                          << std::endl;
  }
  env.fullComm().Barrier();
  env.subComm().Barrier();  // Just an example of a possible call
  
  //================================================================
  // Statistical inverse problem (SIP): find posterior PDF for 'g'
  //================================================================
  gettimeofday(&timevalNow, NULL);
  if (env.fullRank() == 0) {
    std::cout << "Beginning 'SIP -> Gravity estimation' at "
              << ctime(&timevalNow.tv_sec)
              << std::endl;
  }

  //------------------------------------------------------
  // SIP Step 1 of 6: Instantiate the parameter space
  //------------------------------------------------------
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix> paramSpace(env, "param_", 1, NULL);

  //------------------------------------------------------
  // SIP Step 2 of 6: Instantiate the parameter domain
  //------------------------------------------------------
  QUESO::GslVector paramMinValues(paramSpace.zeroVector());
  QUESO::GslVector paramMaxValues(paramSpace.zeroVector());
  
  paramMinValues[0] = 8.;
  paramMaxValues[0] = 11.;
  
  QUESO::BoxSubset<QUESO::GslVector,QUESO::GslMatrix>
    paramDomain("param_",
      paramSpace,
      paramMinValues,
      paramMaxValues);
  
  //------------------------------------------------------
  // SIP Step 3 of 6: Instantiate the likelihood function 
  // object to be used by QUESO.
  //------------------------------------------------------
  likelihoodRoutine_Data likelihoodRoutine_Data(env);
  QUESO::GenericScalarFunction<QUESO::GslVector,QUESO::GslMatrix>
    likelihoodFunctionObj("like_",
			  paramDomain,
			  likelihoodRoutine,
			  (void *) &likelihoodRoutine_Data,
			  true); // the routine computes [ln(function)]
    
  //------------------------------------------------------
  // SIP Step 4 of 6: Define the prior RV
  //------------------------------------------------------
  
#ifdef PRIOR_IS_GAUSSIAN
  QUESO::GslVector meanVector( paramSpace.zeroVector() );
  meanVector[0] = 9;
 
  QUESO::GslMatrix covMatrix = QUESO::GslMatrix(paramSpace.zeroVector());
  covMatrix(0,0) = 1.; 
  
  // Create a Gaussian prior RV
  QUESO::GaussianVectorRV<QUESO::GslVector,QUESO::GslMatrix> priorRv("prior_",paramDomain,meanVector,covMatrix);
  
#else
  // Create an uniform prior RV
  QUESO::UniformVectorRV<QUESO::GslVector,QUESO::GslMatrix> priorRv("prior_",paramDomain);
  
#endif
  
  //------------------------------------------------------
  // SIP Step 5 of 6: Instantiate the inverse problem
  //------------------------------------------------------
  QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix>
    postRv("post_",  // Extra prefix before the default "rv_" prefix
           paramSpace);
        
  QUESO::StatisticalInverseProblem<QUESO::GslVector,QUESO::GslMatrix>
    ip("",          // No extra prefix before the default "ip_" prefix
       NULL, 
       priorRv, 
       likelihoodFunctionObj, 
       postRv); 

  //------------------------------------------------------
  // SIP Step 6 of 6: Solve the inverse problem, that is,
  // set the 'pdf' and the 'realizer' of the posterior RV
  //------------------------------------------------------
  std::cout << "Solving the SIP with Metropolis Hastings" 
	    << std::endl << std::endl;  

  QUESO::GslVector paramInitials(paramSpace.zeroVector());
  priorRv.realizer().realization(paramInitials);

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());
  proposalCovMatrix(0,0) = std::pow( fabs(paramInitials[0])/20. , 2. );

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

  //================================================================
  // Statistical forward problem (SFP): find the max distance 
  // traveled by an object in projectile motion; input pdf for 'g' 
  // is the solution of the SIP above.
  //================================================================
  gettimeofday(&timevalNow, NULL);
  std::cout << "Beginning 'SFP -> Projectile motion' at " 
            << ctime(&timevalNow.tv_sec)
            << std::endl;
	    
  //------------------------------------------------------
  // SFP Step 1 of 6: Instantiate the parameter *and* qoi spaces. 
  // SFP input RV = FIP posterior RV, so SFP parameter space
  // has been already defined.
  //------------------------------------------------------
  QUESO::VectorSpace<QUESO::GslVector,QUESO::GslMatrix> qoiSpace(env, "qoi_", 1, NULL);
  
  //------------------------------------------------------
  // SFP Step 2 of 6: Instantiate the parameter domain 
  //------------------------------------------------------
  
  // Not necessary because input RV of the SFP = output RV of SIP. 
  // Thus, the parameter domain has been already defined.
  
  //------------------------------------------------------ 
  // SFP Step 3 of 6: Instantiate the qoi function object 
  // to be used by QUESO.
  //------------------------------------------------------
  qoiRoutine_Data qoiRoutine_Data;
  qoiRoutine_Data.m_angle          = M_PI/4.0; //45 degrees (radians)
  qoiRoutine_Data.m_initialVelocity= 5.;      //initial speed (m/s) 
  qoiRoutine_Data.m_initialHeight  = 0.;       //initial height (m)
  
  QUESO::GenericVectorFunction<QUESO::GslVector,QUESO::GslMatrix,QUESO::GslVector,QUESO::GslMatrix>
    qoiFunctionObj("qoi_",
                   paramDomain,
                   qoiSpace,
                   qoiRoutine,
                   (void *) &qoiRoutine_Data);
      
  //------------------------------------------------------
  // SFP Step 4 of 6: Define the input RV
  //------------------------------------------------------
  
  // Not necessary because input RV of SFP = output RV of SIP 
  // (postRv).
      
  //------------------------------------------------------
  // SFP Step 5 of 6: Instantiate the forward problem
  //------------------------------------------------------
  QUESO::GenericVectorRV<QUESO::GslVector,QUESO::GslMatrix> qoiRv("qoi_", qoiSpace);
  
  QUESO::StatisticalForwardProblem<QUESO::GslVector,QUESO::GslMatrix,QUESO::GslVector,QUESO::GslMatrix>
    fp("",
       NULL,
       postRv,
       qoiFunctionObj,
       qoiRv);

  //------------------------------------------------------
  // SFP Step 6 of 6: Solve the forward problem
  //------------------------------------------------------
  std::cout << "Solving the SFP with Monte Carlo" 
            << std::endl << std::endl;  
  fp.solveWithMonteCarlo(NULL);

  //------------------------------------------------------
  gettimeofday(&timevalNow, NULL);
  if ((env.subDisplayFile()       ) && 
      (env.displayVerbosity() >= 2)) {
    *env.subDisplayFile() << "Ending run of 'Gravity + Projectile motion' example at "
                          << ctime(&timevalNow.tv_sec)
                          << std::endl;
  }
  if (env.fullRank() == 0) {
    std::cout << "Ending run of 'Gravity + Projectile motion' example at "
              << ctime(&timevalNow.tv_sec)
              << std::endl;
  }

  return;
}
void GaussianMean1DRegressionCompute(const QUESO::BaseEnvironment& env,
    double priorMean, double priorVar, const likelihoodData& dat)
{
  // parameter space: 1-D on (-infinity, infinity)
  QUESO::VectorSpace<P_V, P_M> paramSpace(
					 env,       // queso environment
					 "param_",  // name prefix
					 1,         // dimensions
					 NULL);     // names

  P_V paramMin(paramSpace.zeroVector());
  P_V paramMax(paramSpace.zeroVector());
  paramMin[0] = -INFINITY;
  paramMax[0] = INFINITY;
  QUESO::BoxSubset<P_V, P_M> paramDomain(
					"paramBox_",  // name prefix
					paramSpace,   // vector space
					paramMin,     // min values
					paramMax);    // max values

  // gaussian prior with user supplied mean and variance
  P_V priorMeanVec(paramSpace.zeroVector());
  P_V priorVarVec(paramSpace.zeroVector());
  priorMeanVec[0] = priorMean;
  priorVarVec[0] = priorVar;
  QUESO::GaussianVectorRV<P_V, P_M> priorRv("prior_", paramDomain, priorMeanVec,
      priorVarVec);

  // likelihood is important
  QUESO::GenericScalarFunction<P_V, P_M> likelihoodFunctionObj(
							      "like_",                   // name prefix
							      paramDomain,               // image set
							      LikelihoodFunc<P_V, P_M>,  // routine
							      (void *) &dat,             // routine data ptr
							      true);                     // routineIsForLn

  QUESO::GenericVectorRV<P_V, P_M> postRv(
      "post_",       // name prefix
       paramSpace);  // image set


  // Initialize and solve the Inverse Problem with Bayes multi-level sampling
  QUESO::StatisticalInverseProblem<P_V, P_M> invProb(
      "",                     // name prefix
      NULL,                   // alt options
      priorRv,                // prior RV
      likelihoodFunctionObj,  // likelihood fcn
      postRv);                // posterior RV

  invProb.solveWithBayesMLSampling();

  // compute mean and second moment of samples on each proc via Knuth online mean/variance algorithm
  int N = invProb.postRv().realizer().subPeriod();
  double subMean = 0.0;
  double subM2 = 0.0;
  double delta;
  P_V sample(paramSpace.zeroVector());
  for (int n = 1; n <= N; n++) {
    invProb.postRv().realizer().realization(sample);
    delta = sample[0] - subMean;
    subMean += delta / n;
    subM2 += delta * (sample[0] - subMean);
  }

  // gather all Ns, means, and M2s to proc 0
  std::vector<int> unifiedNs(env.inter0Comm().NumProc());
  std::vector<double> unifiedMeans(env.inter0Comm().NumProc());
  std::vector<double> unifiedM2s(env.inter0Comm().NumProc());
  MPI_Gather(&N, 1, MPI_INT, &(unifiedNs[0]), 1, MPI_INT, 0,
      env.inter0Comm().Comm());
  MPI_Gather(&subMean, 1, MPI_DOUBLE, &(unifiedMeans[0]), 1, MPI_DOUBLE, 0,
      env.inter0Comm().Comm());
  MPI_Gather(&subM2, 1, MPI_DOUBLE, &(unifiedM2s[0]), 1, MPI_DOUBLE, 0,
      env.inter0Comm().Comm());

  // get the total number of likelihood calls at proc 0
  unsigned long totalLikelihoodCalls = 0;
  MPI_Reduce(&likelihoodCalls, &totalLikelihoodCalls, 1, MPI_UNSIGNED_LONG,
      MPI_SUM, 0, env.inter0Comm().Comm());

  // compute global posterior mean and std via Chan algorithm, output results on proc 0
  if (env.inter0Rank() == 0) {
    int postN = unifiedNs[0];
    double postMean = unifiedMeans[0];
    double postVar = unifiedM2s[0];
    for (unsigned int i = 1; i < unifiedNs.size(); i++) {
      delta = unifiedMeans[i] - postMean;
      postMean = (postN * postMean + unifiedNs[i] * unifiedMeans[i]) /
        (postN + unifiedNs[i]);
      postVar += unifiedM2s[i] + delta * delta *
        (((double)postN * unifiedNs[i]) / (postN + unifiedNs[i]));
      postN += unifiedNs[i];
    }
    postVar /= postN;

    //compute exact answer - available in this case since the exact posterior is a gaussian
    N = dat.dataSet.size();
    double dataSum = 0.0;
    for (int i = 0; i < N; i++)
      dataSum += dat.dataSet[i];
    double datMean = dataSum / N;
    double postMeanExact = (N * priorVar / (N * priorVar + dat.samplingVar)) *
      datMean + (dat.samplingVar / (N * priorVar + dat.samplingVar)) * priorMean;
    double postVarExact = 1.0 / (N / dat.samplingVar + 1.0 / priorVar);

    std::cout << "Number of posterior samples: " << postN << std::endl;
    std::cout << "Estimated posterior mean: " << postMean << " +/- "
      << std::sqrt(postVar) << std::endl;
    std::cout << "Likelihood function calls: " << totalLikelihoodCalls
      << std::endl;
    std::cout << "\nExact posterior: Gaussian with mean " << postMeanExact
      << ", standard deviation " << std::sqrt(postVarExact) << std::endl;
  }
}
int main(int argc, char ** argv) {
  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL);

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", 2, NULL);

  double min_val = 0.0;
  double max_val = 1.0;

  QUESO::GslVector paramMins(paramSpace.zeroVector());
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());

  // Model parameter between 0 and 1
  paramMins[0] = 0.0;
  paramMaxs[0] = 1.0;

  // Hyperparameter (multiplicative coefficient of observational error
  // covariance matrix) between 0.0 and \infty
  paramMins[1] = 0.0;
  paramMaxs[1] = INFINITY;

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_",
      paramDomain);

  // Set up observation space
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> obsSpace(env,
      "obs_", 2, NULL);

  // Fill up observation vector
  QUESO::GslVector observations(obsSpace.zeroVector());
  observations[0] = 1.0;
  observations[1] = 1.0;

  // Fill up covariance 'matrix'
  QUESO::GslMatrix covariance(obsSpace.zeroVector());
  covariance(0, 0) = 1.0;
  covariance(0, 1) = 0.0;
  covariance(1, 0) = 0.0;
  covariance(1, 1) = 1.0;

  // Pass in observations to Gaussian likelihood object
  Likelihood<QUESO::GslVector, QUESO::GslMatrix> lhood("llhd_", paramDomain,
      observations, covariance);

  QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix>
    postRv("post_", paramSpace);

  QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix>
    ip("", NULL, priorRv, lhood, postRv);

  QUESO::GslVector paramInitials(paramSpace.zeroVector());

  paramInitials[0] = 0.0;

  QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector());

  for (unsigned int i = 0; i < 1; i++) {
    proposalCovMatrix(i, i) = 0.1;
  }

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

  MPI_Finalize();

  return 0;
}
Exemple #24
0
int main(int argc, char ** argv) {
  // Step 0: Set up some variables
  unsigned int numExperiments = 10;  // Number of experiments
  unsigned int numUncertainVars = 5;  // Number of things to calibrate
  unsigned int numSimulations = 50;  // Number of simulations
  unsigned int numConfigVars = 1;  // Dimension of configuration space
  unsigned int numEta = 1;  // Number of responses the model is returning
  unsigned int experimentSize = 1;  // Size of each experiment

#ifdef QUESO_HAS_MPI
  MPI_Init(&argc, &argv);

  // Step 1: Set up QUESO environment
  QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL);
#else
  QUESO::FullEnvironment env(argv[1], "", NULL);
#endif

  // Step 2: Set up prior for calibration parameters
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env,
      "param_", numUncertainVars, NULL);

  // Parameter (theta) bounds:
  //   descriptors   'k_tmasl' 'k_xkle' 'k_xkwew' 'k_xkwlx' 'k_cd'
  //   upper_bounds   1.05      1.1      1.1       1.1       1.1
  //   lower_bounds   0.95      0.9      0.9       0.9       0.9
  //
  // These bounds are dealt with when reading in the data
  QUESO::GslVector paramMins(paramSpace.zeroVector());
  QUESO::GslVector paramMaxs(paramSpace.zeroVector());

  paramMins.cwSet(0.0);
  paramMaxs.cwSet(1.0);

  QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_",
      paramSpace, paramMins, paramMaxs);

  QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_",
      paramDomain);

  // Step 3: Instantiate the 'scenario' and 'output' spaces for simulation
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> configSpace(env,
      "scenario_", numConfigVars, NULL);

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> nEtaSpace(env,
      "output_", numEta, NULL);

  // Step 4: Instantiate the 'output' space for the experiments
  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> experimentSpace(env,
      "experimentspace_", experimentSize, NULL);

  QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> totalExperimentSpace(env,
      "experimentspace_", experimentSize * numExperiments, NULL);

  // Step 5: Instantiate the Gaussian process emulator object
  //
  // Regarding simulation scenario input values, the user should standardise
  // them so that they exist inside a hypercube.
  //
  // Regarding simulation output data, the user should transform it so that the
  // mean is zero and the variance is one.
  //
  // Regarding experimental scenario input values, the user should standardize
  // them so that they exist inside a hypercube.
  //
  // Regarding experimental data, the user should transformed it so that it has
  // zero mean and variance one.

  // GPMSA stores all the information about our simulation
  // data and experimental data.  It also stores default information about the
  // hyperparameter distributions.
  QUESO::GPMSAFactory<QUESO::GslVector, QUESO::GslMatrix>
    gpmsaFactory(env,
                 NULL,
                 priorRv,
                 configSpace,
                 paramSpace,
                 nEtaSpace,
                 experimentSpace,
                 numSimulations,
                 numExperiments);

  // std::vector containing all the points in scenario space where we have
  // simulations
  std::vector<QUESO::GslVector *> simulationScenarios(numSimulations,
      (QUESO::GslVector *) NULL);

  // std::vector containing all the points in parameter space where we have
  // simulations
  std::vector<QUESO::GslVector *> paramVecs(numSimulations,
      (QUESO::GslVector *) NULL);

  // std::vector containing all the simulation output data
  std::vector<QUESO::GslVector *> outputVecs(numSimulations,
      (QUESO::GslVector *) NULL);

  // std::vector containing all the points in scenario space where we have
  // experiments
  std::vector<QUESO::GslVector *> experimentScenarios(numExperiments,
      (QUESO::GslVector *) NULL);

  // std::vector containing all the experimental output data
  std::vector<QUESO::GslVector *> experimentVecs(numExperiments,
      (QUESO::GslVector *) NULL);

  // The experimental output data observation error covariance matrix
  QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector());

  // Instantiate each of the simulation points/outputs
  for (unsigned int i = 0; i < numSimulations; i++) {
    simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector());  // 'x_{i+1}^*' in paper
    paramVecs          [i] = new QUESO::GslVector(paramSpace.zeroVector());  // 't_{i+1}^*' in paper
    outputVecs         [i] = new QUESO::GslVector(nEtaSpace.zeroVector());  // 'eta_{i+1}' in paper
  }

  for (unsigned int i = 0; i < numExperiments; i++) {
    experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}' in paper
    experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector());
  }

  // Read in data and store the standard deviation of the simulation data.  We
  // will need the standard deviation when we pass the experiment error
  // covariance matrix to QUESO.
  double stdsim = readData(simulationScenarios,
                           paramVecs,
                           outputVecs,
                           experimentScenarios,
                           experimentVecs);

  for (unsigned int i = 0; i < numExperiments; i++) {
    // Passing in error of experiments (standardised).
    experimentMat(i, i) = (0.025 / stdsim) * (0.025 / stdsim);
  }

  // Add simulation and experimental data
  gpmsaFactory.addSimulations(simulationScenarios, paramVecs, outputVecs);
  gpmsaFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat);

  QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> postRv(
      "post_",
      gpmsaFactory.prior().imageSet().vectorSpace());
  QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("",
      NULL, gpmsaFactory, postRv);

  QUESO::GslVector paramInitials(
      gpmsaFactory.prior().imageSet().vectorSpace().zeroVector());

  // Initial condition of the chain
  // Have to set each of these by hand, *and* the sampler is sensitive to these
  // values
  paramInitials[0] = 0.5; // param 1
  paramInitials[1] = 0.5; // param 2
  paramInitials[2] = 0.5; // param 3
  paramInitials[3] = 0.5; // param 4
  paramInitials[4] = 0.5; // param 5
  paramInitials[5]  = 0.4;  // not used.  emulator mean
  paramInitials[6]  = 0.4; // emulator precision
  paramInitials[7]  = 0.97; // emulator corr str
  paramInitials[8]  = 0.97; // emulator corr str
  paramInitials[9]  = 0.97; // emulator corr str
  paramInitials[10]  = 0.97; // emulator corr str
  paramInitials[11]  = 0.20; // emulator corr str
  paramInitials[12]  = 0.80; // emulator corr str
  paramInitials[13]  = 10.0; // discrepancy precision
  paramInitials[14]  = 0.97; // discrepancy corr str
  paramInitials[15]  = 8000.0; // emulator data precision

  QUESO::GslMatrix proposalCovMatrix(
      gpmsaFactory.prior().imageSet().vectorSpace().zeroVector());

  // Setting the proposal covariance matrix by hand.  This requires great
  // forethough, and can generally be referred to as a massive hack.  These
  // values were taken from the gpmsa matlab code and fiddled with.
  double scale = 600.0;
  proposalCovMatrix(0, 0)   = 3.1646 / 10.0;  // param 1
  proposalCovMatrix(1, 1)   = 3.1341 / 10.0;  // param 2
  proposalCovMatrix(2, 2)   = 3.1508 / 10.0;  // param 3
  proposalCovMatrix(3, 3)   = 0.3757 / 10.0;  // param 4
  proposalCovMatrix(4, 4)   = 0.6719 / 10.0;  // param 5
  proposalCovMatrix(5, 5)   = 0.1 / scale;  // not used.  emulator mean
  proposalCovMatrix(6, 6)   = 0.4953 / scale;  // emulator precision
  proposalCovMatrix(7, 7)   = 0.6058 / scale;  // emulator corr str
  proposalCovMatrix(8, 8)   = 7.6032e-04 / scale;  // emulator corr str
  proposalCovMatrix(9, 9)   = 8.3815e-04 / scale;  // emulator corr str
  proposalCovMatrix(10, 10) = 7.5412e-04 / scale;  // emulator corr str
  proposalCovMatrix(11, 11) = 0.2682 / scale;  // emulator corr str
  proposalCovMatrix(12, 12) = 0.0572 / scale;  // emulator corr str
  proposalCovMatrix(13, 13) = 1.3417 / scale;  // discrepancy precision
  proposalCovMatrix(14, 14) = 0.3461 / scale;  // discrepancy corr str
  proposalCovMatrix(15, 15) = 495.3 / scale;  // emulator data precision

  // Square to get variances
  for (unsigned int i = 0; i < 16; i++) {
    proposalCovMatrix(i, i) = proposalCovMatrix(i, i) * proposalCovMatrix(i, i);
  }

  ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix);

#ifdef QUESO_HAS_MPI
  MPI_Finalize();
#endif

  return 0;
}