예제 #1
0
 //! Constructor
 Rosenbrock() : 
   initialGuess(2),
   solution(2)
 {
   initialGuess(0) = -1.2;
   initialGuess(1) = 1;
   solution(0) = 1;
   solution(1) = 1;
 };
예제 #2
0
void
ChanProblemInterface::init() {

  for (int i=0; i<n; i++) 
    initialGuess(i) = 
      i*(n-1-i)*source_param(alpha, scale)/((n-1)*(n-1)) + 0.001;
}
예제 #3
0
// Generate the rational approximation x^(pnum/pden)
void AlgRemez::generateApprox()
{
  char *fname = "generateApprox()";

  Float time = -dclock();
  iter = 0;
  spread = 1.0e37;

  if (approx_type == RATIONAL_APPROX_ZERO_POLE) {
    n--;
    neq--;
  }

  initialGuess();
  stpini(step);

  while (spread > tolerance) { //iterate until convergance

    if (iter++%100==0) 
      VRB.Result(cname,fname,"Iteration %d, spread %e delta %e\n", iter-1,(Float)spread,(Float)delta);
    equations();
    if (delta < tolerance)
      ERR.General(cname, fname,"Delta too small, try increasing precision\n");

    search(step);

  }

  int sign;
  Float error = (Float)getErr(mm[0],&sign);
  VRB.Result(cname,fname,"Converged at %d iterations, error = %e\n",
	     iter,error);

  //!< Once the approximation has been generated, calculate the roots
  if(!root()) ERR.General(cname,fname,"Root finding failed\n");
  
  if (approx_type == RATIONAL_APPROX_ZERO_POLE) {
    roots[n] = (bigfloat)0.0;
    n++;
    neq++;
  }

  //!< Now find the partial fraction expansions
  if (remez_arg->field_type == BOSON) {
    getPFE(remez_arg->residue, remez_arg->pole, &(remez_arg->norm));
    getIPFE(remez_arg->residue_inv, remez_arg->pole_inv, &(remez_arg->norm_inv));
  } else {
    getIPFE(remez_arg->residue, remez_arg->pole, &(remez_arg->norm));
    getPFE(remez_arg->residue_inv, remez_arg->pole_inv, &(remez_arg->norm_inv));
  }

  remez_arg->error = error;
  time += dclock();
  print_time(cname,fname,time);

}
예제 #4
0
PitchforkProblemInterface::PitchforkProblemInterface(int N, double a, 
						     double b, double l)  : 
  initialGuess(N),
  alpha(a),
  beta(b),
  lambda(l),
  n(N)
{
  for (int i=0; i<n; i++) 
    initialGuess(i) = lambda/alpha + 0.01;
}
예제 #5
0
  //! Constructor
  Broyden(int m, double lambdaVal=0) : 
    initialGuess(m),
    solution(m)
  {
    n = m;
    lambda = lambdaVal;

    cout << "Broyden ill-conditioning: lambda = " << lambda << "\n"; 
    
    for (int i=0; i<n; i++) {
      // initialGuess(i) = -100;   // Case for lambdaBar != 1.0
      initialGuess(i) = 0;      // General testing
      // initialGuess(i) = -1;     // Standard
      solution(i) = 1;
    }
    fevals = 0;
  };
예제 #6
0
  void NICPAlignerGuiMainWindow::correspondences() {
    if(viewer->drawableList().size() < 2) { return; }
    initialGuess();
    _selectProjector();
    nicp::Cloud *referenceCloud = _clouds[_clouds.size() - 2];
    nicp::Cloud *currentCloud = _clouds.back();

    // Projective Correspondence Finder
    _projector->setTransform(_sensorOffset);
    _projector->project(_correspondenceFinderProjective->currentIndexImage(),
    			_correspondenceFinderProjective->currentDepthImage(),
    			currentCloud->points());
    _projector->setTransform(_sensorOffset);
    _projector->project(_correspondenceFinderProjective->referenceIndexImage(),
    			_correspondenceFinderProjective->referenceDepthImage(),
    			referenceCloud->points());
    _correspondenceFinder->compute(*referenceCloud, *currentCloud, (_poses[_poses.size() - 2].inverse() * _poses.back()).inverse());

    // NN Correspondence Finder
    // _correspondenceFinderNN->init(*referenceCloud, *currentCloud);
    // _correspondenceFinder->compute(*referenceCloud, *currentCloud, (_poses[_poses.size() - 2].inverse() * _poses.back()).inverse());

    nicp_viewer::Drawable *d = viewer->drawableList().back();
    nicp_viewer::DrawableCloud *dCloud = dynamic_cast<nicp_viewer::DrawableCloud*>(d);
    if(dCloud) {
      dCloud->setTransformation(_poses.back());
      dCloud->clearDrawableObjects();
      dCloud->constructDrawableObjects();
      dCloud->drawableCorrespondences()->setReferencePointsTransformation((_poses[_poses.size() - 2].inverse() * _poses.back()).inverse());
      dCloud->drawableCorrespondences()->setReferencePoints(&referenceCloud->points());
      dCloud->drawableCorrespondences()->setCurrentPoints(&currentCloud->points());
      dCloud->drawableCorrespondences()->setCorrespondences(&_correspondenceFinder->correspondences());
      dCloud->drawableCorrespondences()->setNumCorrespondences(_correspondenceFinder->numCorrespondences());
      dCloud->drawableCorrespondences()->parameter()->setShow(true);
      std::cout << "[STATUS] " << _correspondenceFinder->numCorrespondences() << " correspondences computed" << std::endl;
    }
    visualizationUpdate();
    viewer->updateGL();
  }
예제 #7
0
FGSimplexTrim::FGSimplexTrim(FGFDMExec * fdm, TrimMode mode)
{
    std::clock_t time_start=clock(), time_trimDone;

    // variables
    FGTrimmer::Constraints constraints;

    if (fdm->GetDebugLevel() > 0) {
        std::cout << "\n-----Performing Simplex Based Trim --------------\n" << std::endl;
    }

    // defaults
    std::string aircraftName = fdm->GetAircraft()->GetAircraftName();
    FGPropertyNode* node = fdm->GetPropertyManager()->GetNode();
    double rtol = node->GetDouble("trim/solver/rtol");
    double abstol = node->GetDouble("trim/solver/abstol");
    double speed = node->GetDouble("trim/solver/speed"); // must be > 1, 2 typical
    double random = node->GetDouble("trim/solver/random");
    int iterMax = int(node->GetDouble("trim/solver/iterMax"));
    bool showConvergence = node->GetBool("trim/solver/showConvergence");
    bool pause = node->GetBool("trim/solver/pause");
    bool showSimplex = node->GetBool("trim/solver/showSimplex");

    // flight conditions
    double phi = fdm->GetIC()->GetPhiRadIC();
    double theta = fdm->GetIC()->GetThetaRadIC();
    double gd = fdm->GetInertial()->gravity();

    constraints.velocity = fdm->GetIC()->GetVtrueFpsIC();
    constraints.altitude = fdm->GetIC()->GetAltitudeASLFtIC();
    constraints.gamma = fdm->GetIC()->GetFlightPathAngleRadIC();
    constraints.rollRate = 0;
    constraints.pitchRate = 0;
    constraints.yawRate = tan(phi)*gd*cos(theta)/constraints.velocity;

    constraints.stabAxisRoll = true; // FIXME, make this an option

    // initial solver state
    int n = 6;
    std::vector<double> initialGuess(n), lowerBound(n), upperBound(n), initialStepSize(n);

    lowerBound[0] = node->GetDouble("trim/solver/throttleMin");
    lowerBound[1] = node->GetDouble("trim/solver/elevatorMin");
    lowerBound[2] = node->GetDouble("trim/solver/alphaMin");
    lowerBound[3] = node->GetDouble("trim/solver/aileronMin");
    lowerBound[4] = node->GetDouble("trim/solver/rudderMin");
    lowerBound[5] = node->GetDouble("trim/solver/betaMin");

    upperBound[0] = node->GetDouble("trim/solver/throttleMax");
    upperBound[1] = node->GetDouble("trim/solver/elevatorMax");
    upperBound[2] = node->GetDouble("trim/solver/alphaMax");
    upperBound[3] = node->GetDouble("trim/solver/aileronMax");
    upperBound[4] = node->GetDouble("trim/solver/rudderMax");
    upperBound[5] = node->GetDouble("trim/solver/betaMax");

    initialStepSize[0] = node->GetDouble("trim/solver/throttleStep");
    initialStepSize[1] = node->GetDouble("trim/solver/elevatorStep");
    initialStepSize[2] = node->GetDouble("trim/solver/alphaStep");
    initialStepSize[3] = node->GetDouble("trim/solver/aileronStep");
    initialStepSize[4] = node->GetDouble("trim/solver/rudderStep");
    initialStepSize[5] = node->GetDouble("trim/solver/betaStep");

    initialGuess[0] = node->GetDouble("trim/solver/throttleGuess");
    initialGuess[1] = node->GetDouble("trim/solver/elevatorGuess");
    initialGuess[2] = node->GetDouble("trim/solver/alphaGuess");
    initialGuess[3] = node->GetDouble("trim/solver/aileronGuess");
    initialGuess[4] = node->GetDouble("trim/solver/rudderGuess");
    initialGuess[5] = node->GetDouble("trim/solver/betaGuess");

    // solve
    FGTrimmer * trimmer = new FGTrimmer(fdm, &constraints);
    Callback callback(aircraftName, trimmer);
    FGNelderMead * solver = NULL;

    solver = new FGNelderMead(trimmer,initialGuess,
        lowerBound, upperBound, initialStepSize,iterMax,rtol,
        abstol,speed,random,showConvergence,showSimplex,pause,&callback);
    while(solver->status()==1) solver->update();
    time_trimDone = std::clock();

    // output
    if (fdm->GetDebugLevel() > 0) {
        trimmer->printSolution(std::cout,solver->getSolution());
        std::cout << "\nfinal cost: " << std::scientific << std::setw(10) << trimmer->eval(solver->getSolution()) << std::endl;
        std::cout << "\ntrim computation time: " << (time_trimDone - time_start)/double(CLOCKS_PER_SEC) << "s \n" << std::endl;
    }

    delete solver;
    delete trimmer;
}
    Disposable<std::vector<boost::shared_ptr<CalibrationHelper> > >
    BasketGeneratingEngine::calibrationBasket(
        const boost::shared_ptr<Exercise> &exercise,
        boost::shared_ptr<SwapIndex> standardSwapBase,
        boost::shared_ptr<SwaptionVolatilityStructure> swaptionVolatility,
        const CalibrationBasketType basketType) const {

        QL_REQUIRE(
            !standardSwapBase->forwardingTermStructure().empty(),
            "standard swap base forwarding term structure must not be empty.");
        QL_REQUIRE(
            !standardSwapBase->exogenousDiscount() ||
                !standardSwapBase->discountingTermStructure().empty(),
            "standard swap base discounting term structure must not be empty.");

        std::vector<boost::shared_ptr<CalibrationHelper> > result;

        int minIdxAlive =
            std::upper_bound(exercise->dates().begin(), exercise->dates().end(),
                             Settings::instance().evaluationDate()) -
            exercise->dates().begin();

        boost::shared_ptr<RebatedExercise> rebEx =
            boost::dynamic_pointer_cast<RebatedExercise>(exercise);

        for (Size i = minIdxAlive; i < exercise->dates().size(); i++) {

            Date expiry = exercise->date(i);
            Real rebate = 0.0;
            Date rebateDate = expiry;
            if (rebEx != NULL) {
                rebate = rebEx->rebate(i);
                rebateDate = rebEx->rebatePaymentDate(i);
            }

            boost::shared_ptr<SwaptionHelper> helper;

            switch (basketType) {

            case Naive: {
                Real swapLength = swaptionVolatility->dayCounter().yearFraction(
                    standardSwapBase->valueDate(expiry), underlyingLastDate());
                boost::shared_ptr<SmileSection> sec =
                    swaptionVolatility->smileSection(
                        expiry,
                        static_cast<Size>(swapLength * 12.0 + 0.5) * Months,
                        true);
                Real atmStrike = sec->atmLevel();
                Real atmVol;
                if (atmStrike == Null<Real>())
                    atmVol = sec->volatility(0.03);
                else
                    atmVol = sec->volatility(atmStrike);

                helper = boost::shared_ptr<SwaptionHelper>(new SwaptionHelper(
                    expiry, underlyingLastDate(),
                    Handle<Quote>(boost::make_shared<SimpleQuote>(atmVol)),
                    standardSwapBase->iborIndex(),
                    standardSwapBase->fixedLegTenor(),
                    standardSwapBase->dayCounter(),
                    standardSwapBase->iborIndex()->dayCounter(),
                    standardSwapBase->exogenousDiscount()
                        ? standardSwapBase->discountingTermStructure()
                        : standardSwapBase->forwardingTermStructure(),
                    CalibrationHelper::RelativePriceError, Null<Real>(), 1.0));

                break;
            }

            case MaturityStrikeByDeltaGamma: {

                // determine the npv, first and second order derivatives at
                // $y=0$ of the underlying swap

                const Real h = 0.0001; // finite difference step in $y$, make
                                       // this a parameter of the engine ?
                Real zSpreadDsc =
                    oas_.empty() ? 1.0
                                 : exp(-oas_->value() *
                                       onefactormodel_->termStructure()
                                           ->dayCounter()
                                           .yearFraction(expiry, rebateDate));

                Real npvm = underlyingNpv(expiry, -h) +
                            rebate *
                                onefactormodel_->zerobond(rebateDate, expiry,
                                                          -h, discountCurve_) *
                                zSpreadDsc;
                Real npv = underlyingNpv(expiry, 0.0) +
                           rebate * onefactormodel_->zerobond(
                                        rebateDate, expiry, 0, discountCurve_) *
                               zSpreadDsc;
                Real npvp = underlyingNpv(expiry, h) +
                            rebate *
                                onefactormodel_->zerobond(rebateDate, expiry, h,
                                                          discountCurve_) *
                                zSpreadDsc;

                Real delta = (npvp - npvm) / (2.0 * h);
                Real gamma = (npvp - 2.0 * npv + npvm) / (h * h);

                QL_REQUIRE(npv * npv + delta * delta + gamma * gamma > 0.0,
                           "(npv,delta,gamma) must have a positive norm");

                // debug output
                // std::cout << "EXOTIC npv " << npv << " delta " << delta
                //           << " gamma " << gamma << std::endl;
                // Real xtmp = -5.0;
                // std::cout
                //     << "********************************************EXERCISE "
                //     << expiry << " ******************" << std::endl;
                // std::cout << "globalExoticNpv;";
                // while (xtmp <= 5.0 + QL_EPSILON) {
                //     std::cout << underlyingNpv(expiry, xtmp) << ";";
                //     xtmp += 0.1;
                // }
                // std::cout << std::endl;
                // end debug output

                // play safe, we restrict the maximum maturity so to easily fit
                // in the date class restriction
                Real maxMaturity =
                    swaptionVolatility->dayCounter().yearFraction(
                        expiry, Date::maxDate() - 365);

                boost::shared_ptr<MatchHelper> matchHelper_;
                matchHelper_ = boost::shared_ptr<MatchHelper>(new MatchHelper(
                    underlyingType(), npv, delta, gamma, onefactormodel_,
                    standardSwapBase, expiry, maxMaturity, h));

                // Optimize
                Array initial = initialGuess(expiry);
                QL_REQUIRE(initial.size() == 3,
                           "initial guess must have size 3 (but is "
                               << initial.size() << ")");

                EndCriteria ec(1000, 200, 1E-8, 1E-8, 1E-8); // make these
                                                             // criteria and the
                                                             // optimizer itself
                                                             // parameters of
                                                             // the method ?
                Constraint constraint = NoConstraint();
                Problem p(*matchHelper_, constraint, initial);
                LevenbergMarquardt lm;

                EndCriteria::Type ret = lm.minimize(p, ec);
                QL_REQUIRE(ret != EndCriteria::None &&
                               ret != EndCriteria::Unknown &&
                               ret != EndCriteria::MaxIterations,
                           "optimizer returns error (" << ret << ")");
                Array solution = p.currentValue();

                Real maturity = fabs(solution[1]);

                Size years = (Size)std::floor(maturity);
                maturity -= (Real)years;
                maturity *= 12.0;
                Size months = (Size)std::floor(maturity + 0.5);
                if (years == 0 && months == 0)
                    months = 1; // ensure a maturity of at least one months
                // maturity -= (Real)months; maturity *= 365.25;
                // Size days = (Size)std::floor(maturity);

                Period matPeriod =
                    years * Years + months * Months; //+days*Days;

                // we have to floor the strike of the calibration instrument,
                // see warning in the header
                solution[2] = std::max(solution[2], 0.00001); // floor at 0.1bp

                // also the calibrated nominal may be zero, so we floor it, too
                solution[0] =
                    std::max(solution[0], 0.000001); // float at 0.01bp

                helper = boost::shared_ptr<SwaptionHelper>(new SwaptionHelper(
                    expiry, matPeriod,
                    Handle<Quote>(boost::make_shared<SimpleQuote>(
                        swaptionVolatility->volatility(
                            expiry, matPeriod, solution[2], true))),
                    standardSwapBase->iborIndex(),
                    standardSwapBase->fixedLegTenor(),
                    standardSwapBase->dayCounter(),
                    standardSwapBase->iborIndex()->dayCounter(),
                    standardSwapBase->exogenousDiscount()
                        ? standardSwapBase->discountingTermStructure()
                        : standardSwapBase->forwardingTermStructure(),
                    CalibrationHelper::RelativePriceError, solution[2],
                    fabs(solution[0])));
                break;
            }

            default:
                QL_FAIL("Calibration basket type not known (" << basketType
                                                              << ")");
            }

            result.push_back(helper);
        }

        return result;
    }
예제 #9
0
// Generate the rational approximation x^(pnum/pden)
double AlgRemez::generateApprox(int num_degree, int den_degree, 
				unsigned long pnum, unsigned long pden,
				int a_len, double *a_param, int *a_pow)
{
  char *fname = "generateApprox(int, unsigned long, unsigned long)";

  printf("Degree of the approximation is (%d,%d)\n", num_degree, den_degree);
  printf("Approximating the function x^(%d/%d)\n", pnum, pden);

  // Reallocate arrays, since degree has changed
  if (num_degree != n || den_degree != d) allocate(num_degree,den_degree);

  if (a_len > SUM_MAX) {
    printf("Error: a_length > SUM_MAX");
    exit(0);
  }

  step = new bigfloat[num_degree+den_degree+2];

  a_length = a_len;
  for (int j=0; j<a_len; j++) {
    a[j]= a_param[j];
    a_power[j] = a_pow[j];
  }

  power_num = pnum;
  power_den = pden;
  spread = 1.0e37;
  iter = 0;

  n = num_degree;
  d = den_degree;
  neq = n + d + 1;

  initialGuess();
  stpini(step);

  while (spread > tolerance) { //iterate until convergance

    if (iter++%100==0) 
      printf("Iteration %d, spread %e delta %e\n", 
	     iter-1,(double)spread,(double)delta);

    equations();
    if (delta < tolerance) {
      printf("Delta too small, try increasing precision\n");
      exit(0);
    }

    search(step);

  }

  int sign;
  double error = (double)getErr(mm[0],&sign);
  printf("Converged at %d iterations, error = %e\n",iter,error);

  // Once the approximation has been generated, calculate the roots
  if(!root()) {
    printf("Root finding failed\n");
  } else {
    foundRoots = 1;
  }
  
  delete [] step;

  // Return the maximum error in the approximation
  return error;
}
예제 #10
0
int main(int argc, char *argv[])
{
  int ierr = 0;
  int MyPID = 0;
  double alpha = 0.25;
  double beta = 1.5;
  double D1 = 1.0/40.0;
  double D2 = 1.0/40.0;
  int maxNewtonIters = 10;

  try {

    // Initialize MPI
#ifdef HAVE_MPI
    MPI_Init(&argc,&argv);
#endif

    // Create a communicator for Epetra objects
#ifdef HAVE_MPI
    Epetra_MpiComm Comm( MPI_COMM_WORLD );
#else
    Epetra_SerialComm Comm;
#endif

    // Get the process ID and the total number of processors
    MyPID = Comm.MyPID();
    int NumProc = Comm.NumProc();

    // Check for verbose output
    bool verbose = false;
    if (argc>1) 
      if (argv[1][0]=='-' && argv[1][1]=='v') 
	verbose = true;

    // Get the number of elements from the command line
    int NumGlobalNodes = 0;
    if ((argc > 2) && (verbose))
      NumGlobalNodes = atoi(argv[2]) + 1;
    else if ((argc > 1) && (!verbose))
      NumGlobalNodes = atoi(argv[1]) + 1;
    else 
      NumGlobalNodes = 101;

    // The number of unknowns must be at least equal to the 
    // number of processors.
    if (NumGlobalNodes < NumProc) {
      std::cout << "numGlobalNodes = " << NumGlobalNodes 
		<< " cannot be < number of processors = " << NumProc 
		<< std::endl;
      exit(1);
    }

    // Create the Brusselator problem class.  This creates all required
    // Epetra objects for the problem and allows calls to the 
    // function (F) and Jacobian evaluation routines.
    Brusselator Problem(NumGlobalNodes, Comm);

    // Get the vector from the Problem
    Epetra_Vector& soln = Problem.getSolution();

    // Begin LOCA Solver ************************************

    // Create the top level parameter list

    Teuchos::RCP<Teuchos::ParameterList> paramList =
      Teuchos::rcp(new Teuchos::ParameterList);

    // Create LOCA sublist
    Teuchos::ParameterList& locaParamsList = paramList->sublist("LOCA");

    // Create the stepper sublist and set the stepper parameters
    Teuchos::ParameterList& stepperList = locaParamsList.sublist("Stepper");
    stepperList.set("Bordered Solver Method", "Householder");
    stepperList.set("Continuation Parameter", "beta");
    stepperList.set("Initial Value", beta);
    stepperList.set("Max Value", 1.6);
    stepperList.set("Min Value", 0.0);
    stepperList.set("Max Steps", 100);
    stepperList.set("Max Nonlinear Iterations", maxNewtonIters);

#ifdef HAVE_LOCA_ANASAZI
    // Create Anasazi Eigensolver sublist (needs --with-loca-anasazi)
    stepperList.set("Compute Eigenvalues",true);
    Teuchos::ParameterList& aList = stepperList.sublist("Eigensolver");
    aList.set("Method", "Anasazi");
    if (!verbose)
      aList.set("Verbosity", Anasazi::Errors);
    aList.set("Block Size", 1);        // Size of blocks
    aList.set("Num Blocks", 50);       // Size of Arnoldi factorization
    aList.set("Num Eigenvalues", 3);   // Number of eigenvalues
    aList.set("Convergence Tolerance", 1.0e-7);          // Tolerance
    aList.set("Step Size", 1);         // How often to check convergence
    aList.set("Maximum Restarts",1);   // Maximum number of restarts
    aList.set("Operator", "Cayley");
    aList.set("Cayley Pole", 0.1);
    aList.set("Cayley Zero", -0.1);
    aList.set("Sorting Order", "CA");
#else
    stepperList.set("Compute Eigenvalues",false);
#endif

    // Create predictor sublist
    Teuchos::ParameterList& predictorList = 
      locaParamsList.sublist("Predictor");
    predictorList.set("Method", "Constant");

    // Create step size sublist
    Teuchos::ParameterList& stepSizeList = locaParamsList.sublist("Step Size");
    stepSizeList.set("Initial Step Size", 0.01);
    stepSizeList.set("Min Step Size", 1.0e-3);
    stepSizeList.set("Max Step Size", 0.01);
    stepSizeList.set("Aggressiveness", 0.1);

    // Create the "Solver" parameters sublist to be used with NOX Solvers
    Teuchos::ParameterList& nlParams = paramList->sublist("NOX");

    // Set the printing parameters in the "Printing" sublist
    Teuchos::ParameterList& printParams = nlParams.sublist("Printing");
    printParams.set("MyPID", MyPID); 
    printParams.set("Output Precision", 3);
    printParams.set("Output Processor", 0);
     if (verbose)
      printParams.set("Output Information", 
		      NOX::Utils::OuterIteration + 
		      NOX::Utils::OuterIterationStatusTest + 
		      NOX::Utils::InnerIteration +
		      NOX::Utils::Details + 
		      NOX::Utils::Warning +
		      NOX::Utils::TestDetails + 
		      NOX::Utils::Error + 
		      NOX::Utils::StepperIteration +
		      NOX::Utils::StepperDetails +
		      NOX::Utils::StepperParameters);
     else
       printParams.set("Output Information", NOX::Utils::Error);

    // Sublist for "Linear Solver"
    Teuchos::ParameterList& dirParams = nlParams.sublist("Direction");
    Teuchos::ParameterList& newtonParams = dirParams.sublist("Newton");
    Teuchos::ParameterList& lsParams = newtonParams.sublist("Linear Solver");
    lsParams.set("Aztec Solver", "GMRES");  
    lsParams.set("Max Iterations", 800);  
    lsParams.set("Tolerance", 1e-6);
    lsParams.set("Output Frequency", 50);    
    lsParams.set("Preconditioner", "Ifpack"); 

    // Create the interface between the test problem and the nonlinear solver
    Teuchos::RCP<Problem_Interface> interface = 
      Teuchos::rcp(new Problem_Interface(Problem));

    // Create the Epetra_RowMatrixfor the Jacobian/Preconditioner
    Teuchos::RCP<Epetra_RowMatrix> A = 
      Teuchos::rcp(&Problem.getJacobian(),false);


    // Use an Epetra Scaling object if desired
    Teuchos::RCP<Epetra_Vector> scaleVec = 
      Teuchos::rcp(new Epetra_Vector(soln));
    NOX::Epetra::Scaling scaling;
    scaling.addRowSumScaling(NOX::Epetra::Scaling::Left, scaleVec);

    Teuchos::RCP<LOCA::Epetra::Interface::Required> iReq = interface;

    // Create the Linear System
    Teuchos::RCP<NOX::Epetra::Interface::Jacobian> iJac = interface;
    Teuchos::RCP<NOX::Epetra::LinearSystemAztecOO> linSys = 
      Teuchos::rcp(new NOX::Epetra::LinearSystemAztecOO(printParams, lsParams,
							iReq, iJac, A, soln));
                                                        //&scaling);
    Teuchos::RCP<NOX::Epetra::LinearSystemAztecOO> shiftedLinSys = 
      Teuchos::rcp(new NOX::Epetra::LinearSystemAztecOO(printParams, lsParams,
							iReq, iJac, A, soln));

    // Create initial guess
    NOX::Epetra::Vector initialGuess(Teuchos::rcp(&soln,false), 
				     NOX::Epetra::Vector::CreateView,
				     NOX::DeepCopy);

    // Create and initialize the parameter vector
    LOCA::ParameterVector pVector;
    pVector.addParameter("alpha",alpha);
    pVector.addParameter("beta",beta);
    pVector.addParameter("D1",D1);
    pVector.addParameter("D2",D2);

    // Create Epetra factory
    Teuchos::RCP<LOCA::Abstract::Factory> epetraFactory =
      Teuchos::rcp(new LOCA::Epetra::Factory);

    // Create global data object
    Teuchos::RCP<LOCA::GlobalData> globalData = 
      LOCA::createGlobalData(paramList, epetraFactory);

    // Create the Group
    Teuchos::RCP<LOCA::Epetra::Interface::TimeDependent> iTime = interface;
    Teuchos::RCP<LOCA::Epetra::Group> grp =
      Teuchos::rcp(new LOCA::Epetra::Group(globalData, printParams,
					   iTime, initialGuess, linSys, 
					   shiftedLinSys, pVector));

    grp->computeF();

    // Create the convergence tests
    Teuchos::RCP<NOX::StatusTest::NormF> absresid = 
      Teuchos::rcp(new NOX::StatusTest::NormF(1.0e-8, 
					   NOX::StatusTest::NormF::Unscaled));
    Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters = 
      Teuchos::rcp(new NOX::StatusTest::MaxIters(maxNewtonIters));
    Teuchos::RCP<NOX::StatusTest::Combo> combo =
      Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR));
    combo->addStatusTest(absresid);
    combo->addStatusTest(maxiters);

    // Create stepper
    LOCA::Stepper stepper(globalData, grp, combo, paramList);

    LOCA::Abstract::Iterator::IteratorStatus status = stepper.run();

    if (status != LOCA::Abstract::Iterator::Finished) {
      ierr = 1;
      if (globalData->locaUtils->isPrintType(NOX::Utils::Error))
	globalData->locaUtils->out() 
	  << "Stepper failed to converge!" << std::endl;
    }

    // Get the final solution from the stepper
    Teuchos::RCP<const LOCA::Epetra::Group> finalGroup = 
      Teuchos::rcp_dynamic_cast<const LOCA::Epetra::Group>(stepper.getSolutionGroup());
    const NOX::Epetra::Vector& finalSolution = 
      dynamic_cast<const NOX::Epetra::Vector&>(finalGroup->getX());

    // Output the parameter list
    if (globalData->locaUtils->isPrintType(NOX::Utils::StepperParameters)) {
      globalData->locaUtils->out() 
	<< std::endl << "Final Parameters" << std::endl
	<< "****************" << std::endl;
      stepper.getList()->print(globalData->locaUtils->out());
      globalData->locaUtils->out() << std::endl;
    }

    // Check some statistics on the solution
    NOX::TestCompare testCompare(globalData->locaUtils->out(), 
				 *(globalData->locaUtils));
  
    if (globalData->locaUtils->isPrintType(NOX::Utils::TestDetails))
      globalData->locaUtils->out() 
	<< std::endl 
	<< "***** Checking solution statistics *****" 
	<< std::endl;

    // Check number of continuation steps
    int numSteps = stepper.getStepNumber();
    int numSteps_expected = 11;
    ierr += testCompare.testValue(numSteps, numSteps_expected, 0.0,
				  "number of continuation steps",
				  NOX::TestCompare::Absolute);

    // Check number of failed steps
    int numFailedSteps = stepper.getNumFailedSteps();
    int numFailedSteps_expected = 0;
    ierr += testCompare.testValue(numFailedSteps, numFailedSteps_expected, 0.0,
				  "number of failed continuation steps",
				  NOX::TestCompare::Absolute);

    // Check final value of continuation parameter
    double beta_final = finalGroup->getParam("beta");
    double beta_expected = 1.6;
    ierr += testCompare.testValue(beta_final, beta_expected, 1.0e-14,
				  "final value of continuation parameter", 
				  NOX::TestCompare::Relative);

    // Check final of solution
    NOX::Epetra::Vector final_x_expected(finalSolution);
    int n = final_x_expected.getEpetraVector().MyLength()/2;
    for (int i=0; i<n; i++) {
      final_x_expected.getEpetraVector()[2*i] = alpha;
      final_x_expected.getEpetraVector()[2*i+1] = beta_final/alpha;
    }
    ierr += testCompare.testVector(finalSolution, final_x_expected, 
				   1.0e-6, 1.0e-6,
				   "value of final solution");

    LOCA::destroyGlobalData(globalData);
  }
  catch (std::exception& e) {
    std::cout << e.what() << std::endl;
    ierr = 1;
  }
  catch (const char *s) {
    std::cout << s << std::endl;
    ierr = 1;
  }
  catch (...) {
    std::cout << "Caught unknown exception!" << std::endl;
    ierr = 1;
  }

  if (MyPID == 0) {
    if (ierr == 0)
      std::cout << "All tests passed!" << std::endl;
    else
      std::cout << ierr << " test(s) failed!" << std::endl;
  }

#ifdef HAVE_MPI
  MPI_Finalize() ;
#endif

return ierr;
}
RadialCorrection RadialCorrection::invertCorrection(int h, int w, int step)
{
    LensDistortionModelParameters input = this->mParams;
    LensDistortionModelParameters result;

    /* make initial guess */

    result.setPrincipalX(input.principalX());
    result.setPrincipalY(input.principalY());
    result.setNormalizingFocal(input.normalizingFocal());

    result.setTangentialX(-input.tangentialX());
    result.setTangentialY(-input.tangentialY());

    result.setScale(1.0 / input.scale());

    result.setAspect(1.0 / input.scale()); /*< bad guess I believe */

    result.mKoeff.resize(RadialCorrectionInversionCostFunction::MODEL_POWER);
    for (unsigned i = 0; i < RadialCorrectionInversionCostFunction::MODEL_POWER; i++)
    {
        if (i < input.mKoeff.size()) {
            result.mKoeff[i] = -input.mKoeff[i];
        } else {
            result.mKoeff[i] = 0.0;
        }
    }

    /* Pack the guess and launch optimization */
    RadialCorrection guess(result);
    RadialCorrectionInversionCostFunction cost(*this, guess, step, h, w);

    LevenbergMarquardt lmFit;
    lmFit.maxIterations = 101;
    lmFit.maxLambda = 10e8;
    lmFit.lambdaFactor = 8;
    lmFit.f = &cost;
    lmFit.traceCrucial  = true;
    lmFit.traceProgress = true;
    lmFit.traceMatrix   = true;

    vector<double> initialGuess(cost.inputs);
    RadialCorrectionInversionCostFunction::fillWithRadial(guess, &(initialGuess[0]));
    cout << guess.mParams << endl;

    EllipticalApproximation1d stats;
    stats = cost.aggregatedCost(&(initialGuess[0]));
    SYNC_PRINT(("Start Mean Error: %f px\n", stats.getRadiusAround0()));
    SYNC_PRINT(("Start Max  Error: %f px\n", stats.getMax()));

    vector<double> target(cost.outputs, 0.0);
    vector<double> optimal = lmFit.fit(initialGuess, target);

    guess = RadialCorrectionInversionCostFunction::updateWithModel(guess, &(optimal[0]));

    /* Cost */

    cout << guess.mParams << endl;
    stats = cost.aggregatedCost(&(optimal[0]));
    SYNC_PRINT(("Final Mean Error: %f px\n", stats.getRadiusAround0()));
    SYNC_PRINT(("Final Max  Error: %f px\n", stats.getMax()));


    return guess;
}
예제 #12
0
/********************
 * remez
 *=======
 * Calculates the optimal (in the Chebyshev/minimax sense)
 * FIR filter impulse response given a set of band edges,
 * the desired reponse on those bands, and the weight given to
 * the error in those bands.
 *
 * INPUT:
 * ------
 * int      numtaps - Number of filter coefficients
 * int      numband - Number of bands in filter specification
 * double[] bands   - User-specified band edges [2 * numband]
 * double[] des     - User-specified band responses [numband]
 * double[] weight  - User-specified error weights [numband]
 * int      type    - Type of filter
 *
 * OUTPUT:
 * -------
 * double[] h       - Impulse response of final filter [numtaps]
 **************************************************************************
 *  Converted to C++ by Tony Kirke July 2001
 **************************************************************************
 *  Copyright (C) 1995  Jake Janovetz ([email protected])
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * Converted to Java by Iain A Robin, June 1998 
 *************************************************************************/
double* remez_fir::remez(int numtaps, int numband,
						 double bands[], double des[], double weight[], int type) {

  double c;
  int i;
  int symmetry = (type == BANDPASS)? POSITIVE : NEGATIVE;
  int r = numtaps/2;   // number of extrema
  if ((numtaps%2 != 0) && (symmetry == POSITIVE)) r++;
  
  // Predict dense grid size in advance for array sizes
  int gridSize = 0;
  for (i=0; i<numband; i++) {
	gridSize += (int)floor(0.5+2*r*GRIDDENSITY*(bands[2*i+1] - bands[2*i]));
  }
  if (symmetry == NEGATIVE) gridSize--;
  
  double* grid = new double[gridSize];
  double* d    = new double[gridSize];
  double* w    = new double[gridSize];
  double* e    = new double[gridSize];
  double* x    = new double[r+1];
  double* y    = new double[r+1];
  double* ad   = new double[r+1];
  double* taps = new double[r+1];
  int*    ext  = new int[r+1];
  
  // Create dense frequency grid
  createDenseGrid(r, numtaps, numband, bands, des, weight,
				  gridSize, grid, d, w, symmetry);
  initialGuess(r, ext, gridSize);
  
  // For Differentiator: (fix grid)
  if (type == DIFFERENTIATOR) {
	for (i=0; i<gridSize; i++) {
	  if (d[i] > 0.0001) w[i] /= grid[i];
	}
  }
  
  // For odd or Negative symmetry filters, alter the
  // d[] and w[] according to Parks McClellan
  if (symmetry == POSITIVE) {
	if (numtaps % 2 == 0) {
	  for (i=0; i<gridSize; i++) {
		c = cos(PI * grid[i]);
		d[i] /= c;
		w[i] *= c;
	  }
	}
  }
  else {
	if (numtaps % 2 != 0) {
	  for (i=0; i<gridSize; i++) {
		c = sin(TWOPI * grid[i]);
		d[i] /= c;
		w[i] *= c;
	  }
	}
	else {
	  for (i=0; i<gridSize; i++) {
		c = sin(PI * grid[i]);
		d[i] /= c;
		w[i] *= c;
	  }
	}
  }

  // Perform the Remez Exchange algorithm
  int iter;
  for (iter=0; iter<MAXITERATIONS; iter++) {
	calcParms(r, ext, grid, d, w, ad, x, y);
	calcError(r, ad, x, y, gridSize, grid, d, w, e);
	search(r, ext, gridSize, e);
	if (isDone(r, ext, e)) break;
  }
  if (iter == MAXITERATIONS) {
	cout << "Reached maximum iteration count.\n";
	cout << "Results may be bad\n";
  }
  
  calcParms(r, ext, grid, d, w, ad, x, y);
  
  // Find the 'taps' of the filter for use with Frequency
  // Sampling.  If odd or Negative symmetry, fix the taps
  // according to Parks McClellan
  for (i=0; i<=numtaps/2; i++) {
	if (symmetry == POSITIVE) {
	  if (numtaps%2 != 0) c = 1;
	  else c = cos(PI * (double)i/numtaps);
	}
	else {
	  if (numtaps%2 != 0) c = sin(TWOPI * (double)i/numtaps);
	  else c = sin(PI * (double)i/numtaps);
	}
	taps[i] = computeA((double)i/numtaps, r, ad, x, y)*c;
  }
  // Frequency sampling design with calculated taps
  return freqSample(taps, numtaps, symmetry);
}