Exemplo n.º 1
0
EnumerationConstraint* ModelEnumerator::doInit(SharedContext& ctx, MinimizeConstraint* min, int numModels) {
	delete queue_;
	queue_ = 0;
	initProjection(ctx); 
	uint32 st = strategy();
	if (detectStrategy() || (ctx.concurrency() > 1 && !ModelEnumerator::supportsParallel())) {
		st = 0;
	}
	bool optOne  = minimizer() && minimizer()->mode() == MinimizeMode_t::optimize;
	bool trivial = optOne || std::abs(numModels) == 1;
	if (optOne && project_) {
		const SharedMinimizeData* min = minimizer();
		for (const WeightLiteral* it = min->lits; !isSentinel(it->first) && trivial; ++it) {
			trivial = ctx.varInfo(it->first.var()).project();
		}
		if (!trivial) { ctx.report(warning(Event::subsystem_prepare, "Projection: Optimization may depend on enumeration order.")); }
	}
	if (st == strategy_auto) { st  = trivial || (project_ && ctx.concurrency() > 1) ? strategy_record : strategy_backtrack; }
	if (trivial)             { st |= trivial_flag; }
	if (ctx.concurrency() > 1 && !trivial && st != strategy_backtrack) {
		queue_ = new SolutionQueue(ctx.concurrency()); 
		queue_->reserve(ctx.concurrency() + 1);
	}
	options_ &= ~uint32(strategy_opts_mask);
	options_ |= st;
	Solver& s = *ctx.master();
	EnumerationConstraint* c = st == strategy_backtrack 
	  ? static_cast<ConPtr>(new BacktrackFinder(s, min, project_, projectOpts()))
	  : static_cast<ConPtr>(new RecordFinder(s, min, project_, queue_));
	if (projectionEnabled()) { setIgnoreSymmetric(true); }
	return c;
}
Exemplo n.º 2
0
EnumerationConstraint* ModelEnumerator::doInit(SharedContext& ctx, SharedMinimizeData* opt, int numModels) {
	initProjection(ctx);
	uint32 st = strategy();
	if (detectStrategy() || (ctx.concurrency() > 1 && !ModelEnumerator::supportsParallel())) {
		st = 0;
	}
	bool optOne  = opt && opt->mode() == MinimizeMode_t::optimize;
	bool trivial = optOne || std::abs(numModels) == 1;
	if (optOne && projectionEnabled()) {
		for (const WeightLiteral* it =  minimizer()->lits; !isSentinel(it->first) && trivial; ++it) {
			trivial = ctx.varInfo(it->first.var()).project();
		}
		if (!trivial) { ctx.report(warning(Event::subsystem_prepare, "Projection: Optimization may depend on enumeration order.")); }
	}
	if (st == strategy_auto) { st  = trivial || (projectionEnabled() && ctx.concurrency() > 1) ? strategy_record : strategy_backtrack; }
	if (trivial)             { st |= trivial_flag; }
	options_ &= ~uint32(strategy_opts_mask);
	options_ |= st;
	const LitVec* dom = (projectOpts() & project_dom_lits) != 0 ? (ctx.heuristic.domRec = &domRec_) : 0;
	EnumerationConstraint* c = st == strategy_backtrack
	  ? static_cast<ConPtr>(new BacktrackFinder(projectOpts()))
	  : static_cast<ConPtr>(new RecordFinder(dom));
	if (projectionEnabled()) { setIgnoreSymmetric(true); }
	return c;
}
Exemplo n.º 3
0
  long NormalModeRelax::run(const long numTimesteps) {
    if( numTimesteps < 1 ) return 0;

    //check valid eigenvectors
    if(*Q == NULL)
        report << error << "No Eigenvectors for NormalMode integrator."<<endr;
    //
    //do minimization with local forces, max loop 100, set subSpace minimization true
    itrs = minimizer(minLim, 100, simpleMin, reDiag, true, &forceCalc, &lastLambda, &app->energies, &app->positions, app->topology);
    Real minPotEnergy = app->energies.potentialEnergy();				//save potential energy before random
    //constraints?
    app->energies.clear();
    //run brownian if any remaining modes
    if(testRemainingModes()) myNextIntegrator->run(myCycleLength);	//cyclelength 
    (app->energies)[ScalarStructure::OTHER] = minPotEnergy;			//store minimum potential energy
    if(*Q == NULL){	//rediagonalize?
        if(myPreviousIntegrator == NULL) 
            report << error << "[NormalModeRelax::Run] Re-diagonalization forced with NormalModeRelax as outermost Integrator. Aborting."<<endr;
        return numTimesteps;
    }
    //
    postStepModify();
    
    return numTimesteps;
  }  
Exemplo n.º 4
0
gp_Circ LeastSquaresFitting::fitLeastSquaresCircleToPoints(const Handle_TColgp_HArray1OfPnt& points)
{
	//Get initial guess for least squares fit
	InitialGuessForLeastSquaresFitting initialGuess = findInitialGuess(points);

	math_Vector startingPointForBFGS(1,3);
	startingPointForBFGS(1) = initialGuess.myCenterPoint.X();
	startingPointForBFGS(2) = initialGuess.myCenterPoint.Y();
	startingPointForBFGS(3) = initialGuess.myRadius;

	CircleFitCostFunction costFunction(points);

	math_BFGS minimizer(costFunction,startingPointForBFGS);

	math_Vector minimum(1,3);

	if (minimizer.IsDone()) 
	{
		std::cout << "Minimizer is done, result is:" << std::endl;
		minimizer.Location(minimum);
		std::cout << minimum(1) << " " << minimum(2) << " " << minimum(3) << std::endl;
		
	} else 
	{
		std::cout << "Error: minimizer failed!" << std::endl;		
	}

	gp_Ax2 axis = gp::XOY();
	axis.SetLocation(gp_Pnt(minimum(1),minimum(2),0.0));
	gp_Circ result(axis,minimum(3));

	return result;

}
Exemplo n.º 5
0
EllipseFit2<Real>::EllipseFit2 (int numPoints, const Vector2<Real>* points,
    Vector2<Real>& center, Matrix2<Real>& rotate, Real diag[2],
    Real& error)
    :
    mNumPoints(numPoints),
    mPoints(points)
{
    // Energy function is E : R^5 -> R where
    // V = (V0, V1, V2, V3, V4)
    //   = (D[0], D[1], U.X(), U.Y(), atan2(R[1][0],R[1][1])).

    mTemp = new1<Vector2<Real> >(numPoints);

    MinimizeN<Real> minimizer(5, Energy, 8, 8, 32, this);

    InitialGuess(numPoints, mPoints, center, rotate, diag);
    Real angle = Math<Real>::ACos(rotate[0][0]);
    Real e0 = diag[0]*Math<Real>::FAbs(rotate[0][0]) + 
        diag[1]*Math<Real>::FAbs(rotate[0][1]);
    Real e1 = diag[0]*Math<Real>::FAbs(rotate[1][0]) +
        diag[1]*Math<Real>::FAbs(rotate[1][1]);

    Real v0[5] =
    {
        ((Real)0.5)*diag[0],
        ((Real)0.5)*diag[1],
        center.X() - e0,
        center.Y() - e1,
        (Real)0
    };

    Real v1[5] =
    {
        ((Real)2)*diag[0],
        ((Real)2)*diag[1],
        center.X() + e0,
        center.Y() + e1,
        Math<Real>::PI
    };

    Real vInitial[5] =
    {
        diag[0],
        diag[1],
        center.X(),
        center.Y(),
        angle
    };

    Real vMin[5];
    minimizer.GetMinimum(v0, v1, vInitial, vMin, error);

    diag[0] = vMin[0];
    diag[1] = vMin[1];
    center.X() = vMin[2];
    center.Y() = vMin[3];
    rotate.MakeRotation(vMin[4]);

    delete1(mTemp);
}
Exemplo n.º 6
0
int RigidRegistration::StartRegistration(vnl_vector<double>& params) {
  vnl_lbfgsb minimizer(*func_);
  SetRigidTransformBound(this->d_, &minimizer);
  //double fxval;
  func_->SetBase(this);
  for (unsigned int k = 0; k < this->level_; ++k) {
    func_->SetScale(this->v_scale_[k]);
    SetParam(params);
    minimizer.set_max_function_evals(this->v_func_evals_[k]);
    // For more options, see
    // http://public.kitware.com/vxl/doc/release/core/vnl/html/vnl__nonlinear__minimizer_8h-source.html
    minimizer.minimize(params);
    if (minimizer.get_failure_code() < 0) {
      /*
      fxval = func->f( params );
      vcl_cout << "break Minimized to " << fxval << vcl_endl
        << "Iterations: " << minimizer.get_num_iterations() << "; "
        << "Evaluations: " << minimizer.get_num_evaluations() << vcl_endl;
      vcl_cout << params << vcl_endl;
      */
      return -1;
    }
    /*
    fxval = func->f( params );
    vcl_cout << "Minimized to " << fxval << vcl_endl
             << "Iterations: " << minimizer.get_num_iterations() << "; "
             << "Evaluations: " << minimizer.get_num_evaluations() << vcl_endl;
    */
  }
  vcl_cout << "Solution: " << params << vcl_endl;

  return 0;
}
Exemplo n.º 7
0
  // Finds parameters b, n in the confidence region induced by confidence
  // which maximize wblinv(c, b, n)
	WeibullEstimates 
  estimate_weibull_upper_bounds(std::map<double,double> distribution,
                                const WeibullEstimates& best_params,
                                double confidence,
                                double c)
  {
    if (has_key(distribution, 0))
      distribution[0.0001] += distribution[0];
    distribution.erase(0);
	  if (distribution.size() < 5)
      return best_params;
  	weibull_upper_bounds_function f(distribution, best_params, confidence, c);
    // vnl_lbfgs minimizer(f);
    vnl_powell minimizer(&f);
    // vnl_conjugate_gradient minimizer(f);
    vnl_vector<double> estimate(2);
    estimate[0] = best_params.beta;
    estimate[1] = best_params.etha;
    ntk_assert(minimizer.minimize(estimate), "");
    if (std::abs(estimate[0]-best_params.beta) > (best_params.beta*0.8)
        || std::abs(estimate[1]-best_params.etha) > (best_params.etha*0.8))
    {
      std::cerr << "Warning: algorithm did not converge." << std::endl;
      return best_params;
    }
    WeibullEstimates estimates;
    estimates.beta = estimate[0];
    estimates.etha = estimate[1];
    estimates.gamma = best_params.gamma;
    estimates.logl = 0;
    return estimates;
  }
Exemplo n.º 8
0
FunctionMinimum MnApplication::operator()(unsigned int maxfcn, double toler) {

  assert(theState.isValid());
  unsigned int npar = variableParameters();
//   assert(npar > 0);
  if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar;
  FunctionMinimum min = minimizer().minimize( fcnbase(), theState, theStrategy, maxfcn, toler);
  theNumCall += min.nfcn();
  theState = min.userState();
  return min;
}
Exemplo n.º 9
0
void itk::BiExpFitFunctor::operator()(vnl_matrix<double> & newSignal,const vnl_matrix<double> & SignalMatrix, const double & S0)
{

  vnl_vector<double> initalGuess(3);
  // initialize Least Squres Function
  // SignalMatrix.cols() defines the number of shells points
  lestSquaresFunction model(SignalMatrix.cols());
  model.set_bvalues(m_BValueList);// set BValue Vector e.g.: [1000, 2000, 3000] <- shell b Values

  // initialize Levenberg Marquardt
  vnl_levenberg_marquardt minimizer(model);
  minimizer.set_max_function_evals(1000);   // Iterations
  minimizer.set_f_tolerance(1e-10);        // Function tolerance

  // for each Direction calculate LSF Coeffs ADC & AKC
  for(unsigned int i = 0 ; i < SignalMatrix.rows(); i++)
  {
    model.set_measurements(SignalMatrix.get_row(i));
    model.set_reference_measurement(S0);

    initalGuess.put(0, 0.f); // ADC_slow
    initalGuess.put(1, 0.009f); // ADC_fast
    initalGuess.put(2, 0.7f); // lambda

    // start Levenberg-Marquardt
    minimizer.minimize_without_gradient(initalGuess);

    const double & ADC_slow = initalGuess.get(0);
    const double & ADC_fast = initalGuess.get(1);
    const double & lambda = initalGuess(2);

    newSignal.put(i, 0, S0 * (lambda * std::exp(-m_TargetBvalue * ADC_slow) + (1-lambda)* std::exp(-m_TargetBvalue * ADC_fast)));
    newSignal.put(i, 1, minimizer.get_end_error()); // RMS Error

    //OUTPUT FOR EVALUATION
    /*std::cout << std::scientific << std::setprecision(5)
              << ADC_slow   << ","                        // lambda
              << ADC_fast   << ","                        // alpha
              << lambda     << ","                        // lambda
              << S0         << ","                        // S0 value
              << minimizer.get_end_error() << ",";      // End error
    for(unsigned int j = 0; j < SignalMatrix.get_row(i).size(); j++ ){
      std::cout << std::scientific << std::setprecision(5) << SignalMatrix.get_row(i)[j];    // S_n Values corresponding to shell 1 to shell n
      if(j != SignalMatrix.get_row(i).size()-1) std::cout << ",";
    }
    std::cout << std::endl;*/
  }

}
Exemplo n.º 10
0
 void estimate_weibull3(std::map<double,double> distribution, 
                        WeibullEstimates& e)
 {
   if (has_key(distribution, 0))
     distribution[0.0001] += distribution[0];
   distribution.erase(0);
   weibull3_likelihood_function f(distribution, e);
   // vnl_lbfgs minimizer(f);
   // vnl_powell minimizer(&f);
   vnl_amoeba minimizer(f);
   vnl_vector<double> estimate(1);
   estimate[0] = e.gamma;
   minimizer.minimize(estimate);
   ntk_assert(flt_eq(e.gamma, estimate[0]), "");
 }
Exemplo n.º 11
0
int main() {

    double q = 2.0;
    double g0 = 2.0;

    for(int i = 1, j = 0; i <= N; i = 2*(++j) + 1) { /* i in {2k+1} */

        std::cout<<"#Gaussian: "<<i<<" Result:       ";
        GMinimizer minimizer(i);                  /*minimizer*/
        const gsl_vector  *result =  &minimizer.solve(q, g0, 1.0e-6);

        q = gsl_vector_get(result,0);
        g0 =gsl_vector_get(result, 1);

        std::cout<<"q = "<<q<< " g_0 = "<<g0<<" E_0 = "<<gsl_vector_get(result, 2)<<std::endl;
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 12
0
void TpsRegistration::StartRegistration(vnl_vector<double>& params) {
  vnl_lbfgs minimizer(*func_);
  func_->SetBase(this);
  for (unsigned int k = 0; k < level_; ++k) {
    func_->SetScale(v_scale_[k]);
    func_->SetLambda(v_lambda_[k]);
    bool b_fix_affine = (v_affine_[k] == 1);
    func_->SetFixAffine(b_fix_affine);
    func_->PrepareParamGradient();
    SetParam(params);
    int n_max_func_evals = v_func_evals_[k];
    minimizer.set_max_function_evals(n_max_func_evals);
    // For more options, see
    // http://public.kitware.com/vxl/doc/release/core/vnl/html/vnl__nonlinear__minimizer_8h-source.html
    minimizer.minimize(params);
    if (minimizer.get_failure_code() < 0) {
      break;
    }
  }
  vcl_cout << "registration done" << vcl_endl;
}
Exemplo n.º 13
0
 void estimate_weibull(std::map<double,double> distribution, 
                       WeibullEstimates& e)
 {	
   if (has_key(distribution, 0))
     distribution[0.0001] += distribution[0];
   distribution.erase(0);
 	weibull_likelihood_function f(distribution, e.gamma);
   // vnl_lbfgs minimizer(f);
   // vnl_powell minimizer(&f);
   vnl_amoeba minimizer(f);
   vnl_vector<double> estimate(2);
   estimate[0] = e.beta;
   estimate[1] = e.etha;
   // Q_ASSERT(minimizer.minimize(estimate));
   minimizer.minimize(estimate);
   WeibullEstimates estimates;
   e.beta = estimate[0];
   e.etha = estimate[1];
   WeibullDistrib m (e.beta, e.etha, e.gamma);
   e.logl = model_log_likelihood(distribution, 
                                 distrib_size(distribution),
                                 m);
 }
Exemplo n.º 14
0
bool CamAugmentation::OptimizeCurrentView( int iter, double eps ){

  // Get number parameters and observations:
  int parameter_number   = 6;
  int observation_number = GetObservationNumber();

  ls_minimizer2 minimizer(parameter_number);
  minimizer.set_user_data(0, this);
  minimizer.set_state_change_callback(updateCB);
  minimizer.lm_set_max_iterations(iter);

  // Feed with initial parameters:
  GetParameterSet();
  //FillLsqParams( lsqData, &v_opt_param[0], 0, 0 );

  // Add the observations for ...
  int test = 0;
  for( int c = 0; c < (int)v_homography.size(); c++ )   // ... cameras
    if( v_homography[c]->m_homography ){                   
      int points = (int)v_homography[c]->v_point.size();
      for( int point = 0; point < points; point++ ){ // ... points 
        PoseObs *o = new PoseObs();
        o->cam = c;
        o->point = point;
        o->target[0] = v_homography[c]->v_point[point].u;
        o->target[1] = v_homography[c]->v_point[point].v;
        minimizer.add_observation(o, true, false);
      }
    }

    minimizer.minimize_using_levenberg_marquardt_from(&v_opt_param[0]);

    void *ptr = this;
    updateCB(minimizer.state, &ptr);

    return true;
}
Exemplo n.º 15
0
  void NormalModeMinimizer::run(int numTimesteps) {
    if( numTimesteps < 1 )
        return;

    //check valid eigenvectors
    if(*Q == NULL)
        report << error << "No Eigenvectors for NormalMode integrator."<<endr;
    //
    preStepModify();
    //remove last random pertubation
    if(randforce) app->positions.intoSubtract(gaussRandCoord1);
    //(*myPositions).intoWeightedAdd(-randStp,gaussRandCoord1);
    //do minimization with local forces, max loop rediagOnMaxMinSteps, set subSpace minimization true
    itrs = minimizer(minLim, rediagOnMaxMinSteps>0 ? rediagOnMaxMinSteps : 100 , simpleMin, reDiag, true, &forceCalc, &lastLambda, &app->energies, &app->positions, app->topology);

    //flag excessive minimizations
    if(itrs > 10) report << debug(1) << "[NormalModeMinimizer::run] iterations = " << itrs << "." << endr;
    else report << debug(3) << "[NormalModeMinimizer::run] iterations = " << itrs << "." << endr;

    avItrs += itrs;

    //rediagonalize if minimization steps exceeds 'rediagOnMaxMinSteps'
    if(reDiag && rediagOnMaxMinSteps > 0 && itrs >= rediagOnMaxMinSteps){
      report << debug(1) << "[NormalModeMinimizer::run] Minimization steps (" 
              << itrs << ") exceeded maximum (" << rediagOnMaxMinSteps << "), forcing re-diagonalize." << endr;
      itrs = -1;  //force re-diag
    }

    numSteps++;
    avMinForceCalc += forceCalc;
    report <<debug(5)<<"[NormalModeMinimizer::run] iterations = "<<itrs<<" average = "<<
                (float)avItrs/(float)numSteps<<" force calcs = "<<forceCalc<<" average = "<<(float)avMinForceCalc/(float)numSteps<<endl;
    if(randforce && itrs != -1 && lastLambda > 0){	//add random force, but not if rediagonalizing

      //add random force
      if(myPreviousNormalMode->genCompNoise) gaussRandCoord1 = myPreviousNormalMode->tempV3DBlk;
      else genProjGauss(&gaussRandCoord1, app->topology);
      //lambda = eUFactor / *eigValP;	//user factor
      randStp = sqrt(2 * Constant::BOLTZMANN * myTemp * lastLambda);	//step length
      //(*myPositions).intoWeightedAdd(randStp,gaussRandCoord1);
      gaussRandCoord1.intoWeighted(randStp,gaussRandCoord1);
      app->positions.intoAdd(gaussRandCoord1);

      //additional random steps?
      if(randforce > 1){
        eUFactor = 0.5;
        Real lambda;
        for(int i=1;i<randforce;i++){
          utilityCalculateForces();
          nonSubspaceForce(myForces, myForces);
          for(int j=0;j<_N;j++) (*myForces)[j] /= app->topology->atoms[j].scaledMass;
          lambda = eUFactor / *eigValP;	//user factor
          //update positions
          app->positions.intoWeightedAdd(lambda,*myForces);
          gaussRandCoord1.intoWeightedAdd(lambda,*myForces); //add to grc1 so can be removed at the next step
          //random force
          genProjGauss(&gaussRandCoord2, app->topology);
          randStp = sqrt(2 * Constant::BOLTZMANN * myTemp * lambda);
          app->positions.intoWeightedAdd(randStp,gaussRandCoord2);
          //add to grc1 so can be removed at the next step
          gaussRandCoord1.intoWeightedAdd(randStp,gaussRandCoord2); 
        }
      }

    }else{
        gaussRandCoord1.zero(-1);

        //flag re-diagonalize if detected
        if(itrs == -1) app->eigenInfo.reDiagonalize = true;
    }

    //
    postStepModify();
  }