コード例 #1
0
ファイル: nloptTest.cpp プロジェクト: qanny/tools
int main() {
	double lb[2] = { -HUGE_VAL, 0 }; /* lower bounds */
	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LD_MMA, 2); /* algorithm and dimensionality */
	nlopt_set_lower_bounds(opt, lb);
	nlopt_set_min_objective(opt, myfunc, NULL);
	my_constraint_data data[2] = { { 2, 0 }, { -1, 1 } };

	nlopt_add_inequality_constraint(opt, myconstraint, &data[0], 1e-8);
	nlopt_add_inequality_constraint(opt, myconstraint, &data[1], 1e-8);

	nlopt_set_xtol_rel(opt, 1e-4);

	double x[2] = { 1.234, 5.678 };  /* some initial guess */
	double minf; /* the minimum objective value, upon return */

	if (nlopt_optimize(opt, x, &minf) < 0) {
		printf("nlopt failed!\n");
	}
	else {
		printf("found minimum at f(%g,%g) = %0.10g\n", x[0], x[1], minf);
	}

	nlopt_destroy(opt);
}
コード例 #2
0
nlopt_result nlopt_optimize_limited(nlopt_opt opt, double *x, double *minf,
				    int maxeval, double maxtime)
{
     int save_maxeval;
     double save_maxtime;
     nlopt_result ret;

     if (!opt) return NLOPT_INVALID_ARGS;

     save_maxeval = nlopt_get_maxeval(opt);
     save_maxtime = nlopt_get_maxtime(opt);
     
     /* override opt limits if maxeval and/or maxtime are more stringent */
     if (save_maxeval <= 0 || (maxeval > 0 && maxeval < save_maxeval))
	  nlopt_set_maxeval(opt, maxeval);
     if (save_maxtime <= 0 || (maxtime > 0 && maxtime < save_maxtime))
	  nlopt_set_maxtime(opt, maxtime);

     ret = nlopt_optimize(opt, x, minf);

     nlopt_set_maxeval(opt, save_maxeval);
     nlopt_set_maxtime(opt, save_maxtime);

     return ret;
}
コード例 #3
0
ファイル: phyanimal.c プロジェクト: igococha/codesamples
static void phyanimal_fit_lambda(PhyAnimal model) {
  nlopt_opt opt;
  double lb, ub, lambda, loglh;

  
  opt = nlopt_create(NLOPT_LN_NELDERMEAD, 1); /* one dimension */
  lb = 0.0;
  ub = 1.0;
  nlopt_set_lower_bounds(opt,&lb);
  nlopt_set_upper_bounds(opt,&ub);
  /* No inequality constraints */
  nlopt_set_max_objective(opt, loglh_worker, model);
  nlopt_set_xtol_rel(opt, 1e-4);
  lambda = 0.1;
  if (nlopt_optimize(opt, &lambda, &loglh)<0) {
    printf("NLOPT failed\n");
  } else {
    printf("Maximum lh %f at lambda %f\n",loglh,lambda);
    printf("Sigma = %f\n",model->sigma);
    printf("Sigma_b = %f\nSigma_e = %f\n",model->sigma*lambda,model->sigma*(1-lambda));
  }
  model->loglh = loglh;
  model->lambda = lambda;
  nlopt_destroy(opt);
  return;
}
コード例 #4
0
Eigen::VectorXd TargetTrackingController::getControl(const EKF *ekf, const MultiAgentMotionModel *motionModel, const std::vector<const SensorModel*> &sensorModel, double *f) const {
  Evaluator evaluator(ekf, motionModel, sensorModel, params);

  Eigen::VectorXd p = Eigen::VectorXd::Zero(motionModel->getControlDim());
  Eigen::VectorXd lowerBound = Eigen::VectorXd::Constant(motionModel->getControlDim(), params("multi_rotor_control/controlMin").toDouble());
  Eigen::VectorXd upperBound = Eigen::VectorXd::Constant(motionModel->getControlDim(), params("multi_rotor_control/controlMax").toDouble());

  nlopt_opt opt = nlopt_create(NLOPT_LN_COBYLA, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LN_BOBYQA, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LN_NEWUOA_BOUND, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LN_PRAXIS, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LN_NELDERMEAD, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LN_SBPLX, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_GN_ORIG_DIRECT, p.size()); // failed
//  nlopt_opt opt = nlopt_create(NLOPT_GN_ORIG_DIRECT_L, p.size()); // very good: p    0.0118546 -6.27225e-05  6.27225e-05 -2.09075e-05  2.09075e-05 -8.51788e-06 -2.09075e-05           10
//  nlopt_opt opt = nlopt_create(NLOPT_GN_ISRES, p.size()); // rather bad
//  nlopt_opt opt = nlopt_create(NLOPT_GN_CRS2_LM, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LD_MMA, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LD_CCSAQ, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LD_SLSQP, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LD_LBFGS, p.size());
//  nlopt_opt opt = nlopt_create(NLOPT_LD_TNEWTON_PRECOND, p.size()); // bad
//  nlopt_opt opt = nlopt_create(NLOPT_LD_TNEWTON_PRECOND_RESTART, p.size()); // bad
//  nlopt_opt opt = nlopt_create(NLOPT_LD_VAR2, p.size());

  nlopt_set_min_objective(opt, f_evaluate, &evaluator);
  nlopt_set_lower_bounds(opt, lowerBound.data());
  nlopt_set_upper_bounds(opt, upperBound.data());
  nlopt_set_ftol_abs(opt, 1E-6);
  nlopt_set_xtol_rel(opt, 1E-3);
  nlopt_set_maxeval(opt, 1E8);
  nlopt_set_maxtime(opt, 7200);
  double pa[p.size()];
  memcpy(pa, p.data(), p.size()*sizeof(double));
  double cost = 0;
//  std::string tmp; std::cerr << "Press enter to start optimization\n"; std::getline(std::cin, tmp);
  nlopt_result ret = nlopt_optimize(opt, pa, &cost);
  Eigen::VectorXd p_res = Eigen::Map<Eigen::VectorXd>(pa, p.size());
  if (f)
    *f = cost;

  std::cerr << "\nInitial guess:\n";
  std::cerr << "  p " << p.transpose() << "\n";
  std::cerr << "  value " << evaluator.evaluate(p) << "\n";

  std::cerr << "Optimization result (return code " << ret << "):\n";
  std::cerr << "  p " << p_res.transpose() << "\n";
  std::cerr << "  value " << evaluator.evaluate(p_res) << "\n";
  nlopt_destroy(opt);
  return p_res;
}
コード例 #5
0
ファイル: 1d-org.cpp プロジェクト: mj-harvey/gaamp-local
double Optimize_Torsion_Parameters(int Idx_Soft_Tor)
{
	double lb[N_TOR_PARA] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -100.0 }; /* lower bounds */
	double ub[N_TOR_PARA] = { 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0,  100.0 }; /* lower bounds */
	double Phase[32][5]={{0, 0, 0, 0, 0}, {0, 0, 0, 0, PI}, {0, 0, 0, PI, 0}, {0, 0, 0, PI, PI}, {0, 0, PI, 0, 0}, {0, 0, PI, 0, PI}, {0, 0, PI, PI, 0}, {0, 0, PI, PI, PI}, {0, PI, 0, 0, 0}, {0, PI, 0, 0, PI}, 
						{0, PI, 0, PI, 0}, {0, PI, 0, PI, PI}, {0, PI, PI, 0, 0}, {0, PI, PI, 0, PI}, {0, PI, PI, PI, 0}, {0, PI, PI, PI, PI}, {PI, 0, 0, 0, 0}, {PI, 0, 0, 0, PI}, {PI, 0, 0, PI, 0}, {PI, 0, 0, PI, PI},
						{PI, 0, PI, 0, 0}, {PI, 0, PI, 0, PI}, {PI, 0, PI, PI, 0}, {PI, 0, PI, PI, PI}, {PI, PI, 0, 0, 0}, {PI, PI, 0, 0, PI}, {PI, PI, 0, PI, 0}, {PI, PI, 0, PI, PI}, {PI, PI, PI, 0, 0}, {PI, PI, PI, 0, PI}, 
						{PI, PI, PI, PI, 0}, {PI, PI, PI, PI, PI}};
	nlopt_opt opt;
	double Chi_SQ;
	int i, j, Idx_Phi;

	Chi_SQ_Min = 1.0E100;
	opt = nlopt_create(NLOPT_LD_LBFGS, N_TOR_PARA);

	nlopt_set_lower_bounds(opt, lb);
	nlopt_set_upper_bounds(opt, ub);
	nlopt_set_min_objective(opt, Callback_Eval_Gradient, NULL);
	nlopt_set_xtol_rel(opt, 1e-8);

	iseed = time(NULL);
	
	ActiveRun = 0;
	Chi_SQ_Min_Local[0] = 1.0E200;
	FailCount = Iteration = 0;

	Idx_Phi = IdxDihSelect[Idx_Soft_Tor];
	
	Para_Tor[10] = 0.0;
	
	for(i=0; i<N_TOR_PARA; i++)	{
		IsPara_Fixed[i] = 1;
	}
	IsPara_Fixed[N_TOR_PARA-1] = 0;	// only optimize the last parameter

	if (nlopt_optimize(opt, Para_Tor, &Chi_SQ) < 0) {
		printf("nlopt failed!\n");
	}
	else {
		printf("Chi_SQ_min = %lf  Chi_SQ = %lf\n", Chi_SQ_Min, Chi_SQ);
	}

	memcpy(Para_Tor, Para_Best, sizeof(double)*N_TOR_PARA);
	CalObjectiveFunction_Tor(Para_Tor);


	nlopt_destroy(opt);

	return Chi_SQ_Min;
}
コード例 #6
0
ファイル: nlopt_c.c プロジェクト: benb/EvoHaskell
int call_nlopt(nlopt_algorithm alg, double ftol, double *step_size, double *params, unsigned np, double (*func) (unsigned,const double*,double*,void*),double *lower, double *upper) {
    nlopt_opt opt;
    double minf; /* the minimum objective value, upon return */
    int retval;
    int i;
    opt = nlopt_create(alg,np);
    nlopt_set_lower_bounds(opt,lower);
    nlopt_set_upper_bounds(opt,upper);
    nlopt_set_min_objective(opt,func,NULL);
    nlopt_set_ftol_abs(opt,ftol);
    nlopt_set_initial_step(opt,step_size);
    retval = nlopt_optimize(opt, params, &minf) ;
    nlopt_destroy(opt);
    return retval;
}
コード例 #7
0
ファイル: shredder.cpp プロジェクト: dcjones/isolator
double Shredder::optimize(double x0)
{
    // bounds may have changed
    nlopt_set_lower_bounds(opt, &lower_limit);
    nlopt_set_upper_bounds(opt, &upper_limit);

    x0 = std::max<double>(std::min<double>(x0, upper_limit), lower_limit);
    //x0 = (lower_limit + upper_limit) / 2;
    double maxf;
    nlopt_result result = nlopt_optimize(opt, &x0, &maxf);

    if (result < 0 && result != NLOPT_ROUNDOFF_LIMITED) {
        Logger::warn("Optimization failed with code %d", (int) result);
    }

    return std::max<double>(std::min<double>(x0, upper_limit), lower_limit);
}
コード例 #8
0
ファイル: 1d_rotamer_fitting.cpp プロジェクト: salotz/htmd
double Do_Geometry_Optimization(CMol *pMol)
{
	int i, nAtom, nDim, iPos, Return_Opt;
	double x[MAX_NUM_ATOM*3], x_Ini[MAX_NUM_ATOM], y_Ini[MAX_NUM_ATOM], z_Ini[MAX_NUM_ATOM], E_min=1.0E100;

//	pMol->Restrain_All_Torsions(1);

	nAtom = pMol->nAtom;
	nDim = 3*nAtom;

	// for a large molecule with many soft dihedrals, we prefer the optimizer in nlopt since it is around 8 times faster
	memcpy(x_Ini, pMol->x, sizeof(double)*nAtom);	// backup the structure
	memcpy(y_Ini, pMol->y, sizeof(double)*nAtom);
	memcpy(z_Ini, pMol->z, sizeof(double)*nAtom);

	opt_Geo = nlopt_create(NLOPT_LD_LBFGS, nDim);	// fast for non-polarizable model. Not applicable for drude model
	nlopt_set_min_objective(opt_Geo, func_Geo_Optimization, pMol);
	nlopt_set_ftol_rel(opt_Geo, 5E-12);

	for(i=0; i<nAtom; i++)	{	// to set up the initial parameters
		iPos = 3*i;
		x[iPos  ] = pMol->x[i];
		x[iPos+1] = pMol->y[i];
		x[iPos+2] = pMol->z[i];
	}
	Iter_Geo_Opt = 0;
	Return_Opt = nlopt_optimize(opt_Geo, x, &E_min);
	nlopt_destroy(opt_Geo);

	if( (Return_Opt == NLOPT_FTOL_REACHED) || (Return_Opt == NLOPT_SUCCESS) )	{	// success in optimization
		pMol->Restrain_All_Torsions(0);
		return (pMol->Cal_E(0));
	}
	else	{	// try FullGeometryOptimization_LBFGS()
		memcpy(pMol->x, x_Ini, sizeof(double)*nAtom);	// restore the structure
		memcpy(pMol->y, y_Ini, sizeof(double)*nAtom);
		memcpy(pMol->z, z_Ini, sizeof(double)*nAtom);
		
		pMol->FullGeometryOptimization_LBFGS_step(0);
		pMol->Restrain_All_Torsions(0);
		E_min = pMol->Cal_E(0);
		return E_min;
	}
}
コード例 #9
0
/*
 * NLOPT optimization routine for table tennis traj gen
 *
 */
void nlopt_optim_poly_run(double *x, double *params) {

	static double tol[EQ_CONSTR_DIM];
	static double lb[OPTIM_DIM]; /* lower bounds */
	static double ub[OPTIM_DIM]; /* upper bounds */

	set_bounds(lb,ub);
	const_vec(EQ_CONSTR_DIM,1e-2,tol); /* set tolerances equal to second argument */

	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LN_COBYLA, OPTIM_DIM); /* LN = does not require gradients */
	//nlopt_set_xtol_rel(opt, 1e-2);
	//opt = nlopt_create(NLOPT_AUGLAG, OPTIM_DIM); /* algorithm and dimensionality */
	//nlopt_set_local_optimizer(opt, opt);
	nlopt_set_lower_bounds(opt, lb);
	nlopt_set_upper_bounds(opt, ub);
	nlopt_set_min_objective(opt, costfunc, params);
	nlopt_add_inequality_mconstraint(opt, INEQ_CONSTR_DIM, joint_limits_ineq_constr, params, tol);
	nlopt_add_equality_mconstraint(opt, EQ_CONSTR_DIM, kinematics_eq_constr, params, tol);
	nlopt_set_xtol_rel(opt, 1e-2);

	//int maxeval = 20000;
	//nlopt_set_maxeval(opt, maxeval);

	//double maxtime = 0.001;
	//nlopt_set_maxtime(opt, maxtime);

	//init_soln_to_rest_posture(x,params); //parameters are the initial joint positions q0
	double initTime = get_time();
	double minf; /* the minimum objective value, upon return */

	if (nlopt_optimize(opt, x, &minf) < 0) {
	    printf("NLOPT failed!\n");
	}
	else {
		//nlopt_example_run();
		printf("NLOPT took %f ms\n", (get_time() - initTime)/1e3);
	    printf("Found minimum at f = %0.10g\n", minf);
	    test_optim(x,params);
	}
	nlopt_destroy(opt);
}
コード例 #10
0
ファイル: NLfit.cpp プロジェクト: JonathanWatkins/fityk
double NLfit::run_method(vector<realt>* best_a)
{
    if (opt_ != NULL && na_ != (int) nlopt_get_dimension(opt_)) {
        nlopt_destroy(opt_);
        opt_ = NULL;
    }

    if (opt_ == NULL) {
        opt_ = nlopt_create(algorithm_, na_);
        nlopt_set_min_objective(opt_, calculate_for_nlopt, this);
    }

    // this is also handled in Fit::common_termination_criteria()
    nlopt_set_maxtime(opt_, F_->get_settings()->max_fitting_time);
    nlopt_set_maxeval(opt_, max_eval() - 1); // save 1 eval for final calc.
    nlopt_set_ftol_rel(opt_, F_->get_settings()->ftol_rel);
    nlopt_set_xtol_rel(opt_, F_->get_settings()->xtol_rel);

    double *lb = new double[na_];
    double *ub = new double[na_];
    for (int i = 0; i < na_; ++i) {
        const RealRange& d = F_->mgr.get_variable(i)->domain;
        lb[i] = d.lo;
        ub[i] = d.hi;
    }
    nlopt_set_lower_bounds(opt_, lb);
    nlopt_set_upper_bounds(opt_, ub);
    delete [] lb;
    delete [] ub;

    double opt_f;
    double *a = new double[na_];
    for (int i = 0; i < na_; ++i)
        a[i] = a_orig_[i];
    nlopt_result r = nlopt_optimize(opt_, a, &opt_f);
    F_->msg("NLopt says: " + S(nlresult_to_string(r)));
    best_a->assign(a, a+na_);
    delete [] a;
    return opt_f;
}
コード例 #11
0
ファイル: LMM.cpp プロジェクト: gpcr/rvtests
  void calculateSigma2() {
    // use non linear optimization to calculate sigma2
    nlopt_opt opt;
    const int nParam = sigma2.size();
    std::vector<double> lb(nParam, 1e-10);
    
    opt = nlopt_create(NLOPT_LN_COBYLA, nParam);
    nlopt_set_lower_bounds(opt, lb.data());
    nlopt_set_min_objective(opt, goalFunction, this);
    nlopt_set_xtol_rel(opt, 1e-4);

    double minf; /* the minimum objective value, upon return */
    int retCode = nlopt_optimize(opt, sigma2.data(), &minf);
    if (retCode < 0) {
#ifdef DEBUG              
      printf("nlopt failed [ %d ]!\n", retCode);
#endif
    } else {
#ifdef DEBUG              
      printf("found minimum at %g\n", minf);
#endif
    }
    nlopt_destroy(opt);
  }
コード例 #12
0
void
FitOrientation(
    const int NrOfFiles,
    const int nLayers,
    const double ExcludePoleAngle,
    double Lsd[nLayers],
    const long long int SizeObsSpots,
    const double XGrain[3],
    const double YGrain[3],
    double TiltsOrig[3],
    const double OmegaStart,
    const double OmegaStep,
    const double px,
    double ybc[nLayers],
    double zbc[nLayers],
    const double gs,
    double OmegaRanges[MAX_N_OMEGA_RANGES][2],
    const int NoOfOmegaRanges,
    double BoxSizes[MAX_N_OMEGA_RANGES][4],
    double P0[nLayers][3],
    const int NrPixelsGrid,
    int *ObsSpotsInfo,
    double EulerIn[3],
    double tol,
    double *EulerOutA,
    double *EulerOutB,
    double *EulerOutC,
    double *ResultFracOverlap,
    double hkls[5000][4],
    double Thetas[5000],
    int n_hkls,
    double *LsdFit,
    double *TiltsFit,
    double **BCsFit,
    double tolLsd,
    double tolLsdRel,
    double tolTilts,
    double tolBCsa,
    double tolBCsb)
{
    unsigned n;
    long int i,j;
    n  = 6+(nLayers*3);
    double x[n],xl[n],xu[n];
    for (i=0;i<n;i++){
        x[i] = 0;
        xl[i] = 0;
        xu[i] = 0;
    }
    for( i=0; i<3; i++)
    {
        x[i] = EulerIn[i];
        xl[i] = x[i] - (tol*M_PI/180);
        xu[i] = x[i] + (tol*M_PI/180);
    }
    int count = 0;
    for (i=3;i<6;i++)
    {
        x[i] = TiltsOrig[count];
        xl[i] = x[i] - tolTilts;
        xu[i] = x[i] + tolTilts;
        count++;
    }
    count = 0;
    x[6] = Lsd[0];
    xl[6] = x[6] - tolLsd;
    xu[6] = x[6] + tolLsd;
    count++;
    for (i=7;i<nLayers+6;i++)
    {
        x[i] = Lsd[count] - Lsd[count-1];
        xl[i] = x[i] - tolLsdRel;
        xu[i] = x[i] + tolLsdRel;
        count++;
    }
    count = 0;
    for (i=6+nLayers;i<6+(nLayers*2);i++)
    {
        x[i] = ybc[count];
        x[i+nLayers] = zbc[count];
        xl[i] = x[i] - tolBCsa;
        xl[i+nLayers] = x[i+nLayers] - tolBCsb;
        xu[i] = x[i] + tolBCsa;
        xu[i+nLayers] = x[i+nLayers] + tolBCsb;
        count++;
    }
	struct my_func_data f_data;
	f_data.NrOfFiles = NrOfFiles;
	f_data.nLayers = nLayers;
	f_data.n_hkls = n_hkls;
	for (i=0;i<5000;i++){
		f_data.hkls[i][0] = hkls[i][0];
		f_data.hkls[i][1] = hkls[i][1];
		f_data.hkls[i][2] = hkls[i][2];
		f_data.hkls[i][3] = hkls[i][3];
		f_data.Thetas[i] = Thetas[i];
	}
	f_data.ExcludePoleAngle = ExcludePoleAngle;
	f_data.SizeObsSpots = SizeObsSpots;
	f_data.P0 = allocMatrixF(nLayers,3);
	for (i=0;i<3;i++){
		f_data.XGrain[i] = XGrain[i];
		f_data.YGrain[i] = YGrain[i];
		for (j=0;j<nLayers;j++){
			f_data.P0[j][i] = P0[j][i];
		}
	}
	for (i=0;i<MAX_N_OMEGA_RANGES;i++){
		for (j=0;j<2;j++){
			f_data.OmegaRanges[i][j] = OmegaRanges[i][j];
		}
		for (j=0;j<4;j++){
			f_data.BoxSizes[i][j] = BoxSizes[i][j];
		}
	}
	f_data.ObsSpotsInfo = &ObsSpotsInfo[0];
	f_data.OmegaStart = OmegaStart;
	f_data.OmegaStep = OmegaStep;
	f_data.px = px;
	f_data.gs = gs;
	f_data.NoOfOmegaRanges = NoOfOmegaRanges;
	f_data.NrPixelsGrid = NrPixelsGrid;
	struct my_func_data *f_datat;
	f_datat = &f_data;
	void* trp = (struct my_func_data *) f_datat;
	double tole = 1e-3;
	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LN_NELDERMEAD, n);
	nlopt_set_lower_bounds(opt, xl);
	nlopt_set_upper_bounds(opt, xu);
	nlopt_set_min_objective(opt, problem_function, trp);
	double minf=1;
	nlopt_optimize(opt, x, &minf);
	nlopt_destroy(opt);
    *ResultFracOverlap = minf;
    *EulerOutA = x[0];
    *EulerOutB = x[1];
    *EulerOutC = x[2];
    TiltsFit[0] = x[3];
    TiltsFit[1] = x[4];
    TiltsFit[2] = x[5];
    LsdFit[0] = x[6];
    for (i=1;i<nLayers;i++){
        LsdFit[i] = LsdFit[i-1] + x[6+i];
    }
    for (i=0;i<nLayers;i++){
        BCsFit[i][0] = x[6+nLayers+i];
        BCsFit[i][1] = x[6+nLayers+nLayers+i];
    }
}
コード例 #13
0
ファイル: mldosshg.c プロジェクト: epscodes/MLDOS
int main(int argc, char **argv)
{
  /* -------Initialize and Get the parameters from command line ------*/
  PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
  PetscPrintf(PETSC_COMM_WORLD,"--------Initializing------ \n");
  PetscErrorCode ierr;

  PetscBool flg;

  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
  if(myrank==0) 
    mma_verbose=1;
    
  /*-------------------------------------------------*/
  int Mx,My,Mz,Mzslab, Npmlx,Npmly,Npmlz,DegFree, anisotropic;

  PetscOptionsGetInt(PETSC_NULL,"-Nx",&Nx,&flg);  MyCheckAndOutputInt(flg,Nx,"Nx","Nx");
  PetscOptionsGetInt(PETSC_NULL,"-Ny",&Ny,&flg);  MyCheckAndOutputInt(flg,Ny,"Ny","Nx");
  PetscOptionsGetInt(PETSC_NULL,"-Nz",&Nz,&flg);  MyCheckAndOutputInt(flg,Nz,"Nz","Nz");
  PetscOptionsGetInt(PETSC_NULL,"-Mx",&Mx,&flg);  MyCheckAndOutputInt(flg,Mx,"Mx","Mx");
  PetscOptionsGetInt(PETSC_NULL,"-My",&My,&flg);  MyCheckAndOutputInt(flg,My,"My","My");
  PetscOptionsGetInt(PETSC_NULL,"-Mz",&Mz,&flg);  MyCheckAndOutputInt(flg,Mz,"Mz","Mz");
  PetscOptionsGetInt(PETSC_NULL,"-Mzslab",&Mzslab,&flg);  MyCheckAndOutputInt(flg,Mzslab,"Mzslab","Mzslab");
  PetscOptionsGetInt(PETSC_NULL,"-Npmlx",&Npmlx,&flg);  MyCheckAndOutputInt(flg,Npmlx,"Npmlx","Npmlx");
  PetscOptionsGetInt(PETSC_NULL,"-Npmly",&Npmly,&flg);  MyCheckAndOutputInt(flg,Npmly,"Npmly","Npmly");
  PetscOptionsGetInt(PETSC_NULL,"-Npmlz",&Npmlz,&flg);  MyCheckAndOutputInt(flg,Npmlz,"Npmlz","Npmlz");

  Nxyz = Nx*Ny*Nz;

  // if anisotropic !=0, Degree of Freedom = 3*Mx*My*Mz; else DegFree = Mx*My*Mz;
  PetscOptionsGetInt(PETSC_NULL,"-anisotropic",&anisotropic,&flg);
  if(!flg) anisotropic = 0; // by default, it is isotropc.
  DegFree = (anisotropic ? 3 : 1 )*Mx*My*((Mzslab==0)?Mz:1); 
  PetscPrintf(PETSC_COMM_WORLD," the Degree of Freedoms is %d \n ", DegFree);
  
  int DegFreeAll=DegFree+1;
  PetscPrintf(PETSC_COMM_WORLD," the Degree of Freedoms ALL is %d \n ", DegFreeAll);

  int BCPeriod, Jdirection, Jdirectiontwo, LowerPML;
  int bx[2], by[2], bz[2];
  PetscOptionsGetInt(PETSC_NULL,"-BCPeriod",&BCPeriod,&flg);  MyCheckAndOutputInt(flg,BCPeriod,"BCPeriod","BCPeriod given");
  PetscOptionsGetInt(PETSC_NULL,"-Jdirection",&Jdirection,&flg);  MyCheckAndOutputInt(flg,Jdirection,"Jdirection","Diapole current direction");
  PetscOptionsGetInt(PETSC_NULL,"-Jdirectiontwo",&Jdirectiontwo,&flg);  MyCheckAndOutputInt(flg,Jdirectiontwo,"Jdirectiontwo","Diapole current direction for source two");
  PetscOptionsGetInt(PETSC_NULL,"-LowerPML",&LowerPML,&flg);  MyCheckAndOutputInt(flg,LowerPML,"LowerPML","PML in the lower xyz boundary");
  PetscOptionsGetInt(PETSC_NULL,"-bxl",bx,&flg);  MyCheckAndOutputInt(flg,bx[0],"bxl","BC at x lower");
  PetscOptionsGetInt(PETSC_NULL,"-bxu",bx+1,&flg);  MyCheckAndOutputInt(flg,bx[1],"bxu","BC at x upper");
  PetscOptionsGetInt(PETSC_NULL,"-byl",by,&flg);  MyCheckAndOutputInt(flg,by[0],"byl","BC at y lower");
  PetscOptionsGetInt(PETSC_NULL,"-byu",by+1,&flg);  MyCheckAndOutputInt(flg,by[1],"byu","BC at y upper");
  PetscOptionsGetInt(PETSC_NULL,"-bzl",bz,&flg);  MyCheckAndOutputInt(flg,bz[0],"bzl","BC at z lower");
  PetscOptionsGetInt(PETSC_NULL,"-bzu",bz+1,&flg);  MyCheckAndOutputInt(flg,bz[1],"bzu","BC at z upper");


  double  epssub, RRT, sigmax, sigmay, sigmaz ;
   
  PetscOptionsGetReal(PETSC_NULL,"-hx",&hx,&flg);  MyCheckAndOutputDouble(flg,hx,"hx","hx");
  hy = hx;
  hz = hx;
  hxyz = (Nz==1)*hx*hy + (Nz>1)*hx*hy*hz;  

  double omega, omegaone, omegatwo, wratio;
  PetscOptionsGetReal(PETSC_NULL,"-omega",&omega,&flg);  MyCheckAndOutputDouble(flg,omega,"omega","omega");
   PetscOptionsGetReal(PETSC_NULL,"-wratio",&wratio,&flg);  MyCheckAndOutputDouble(flg,wratio,"wratio","wratio");
  omegaone=omega;
  omegatwo=wratio*omega;
  PetscPrintf(PETSC_COMM_WORLD,"---omegaone is %.16e and omegatwo is %.16e ---\n",omegaone, omegatwo);

  PetscOptionsGetReal(PETSC_NULL,"-Qabs",&Qabs,&flg); 
  if (flg && Qabs>1e+15)
    Qabs=1.0/0.0;
  MyCheckAndOutputDouble(flg,Qabs,"Qabs","Qabs");
  PetscOptionsGetReal(PETSC_NULL,"-epsair",&epsair,&flg);  MyCheckAndOutputDouble(flg,epsair,"epsair","epsair");
  PetscOptionsGetReal(PETSC_NULL,"-epssub",&epssub,&flg);  MyCheckAndOutputDouble(flg,epssub,"epssub","epssub");
  PetscOptionsGetReal(PETSC_NULL,"-RRT",&RRT,&flg);  MyCheckAndOutputDouble(flg,RRT,"RRT","RRT given");
  sigmax = pmlsigma(RRT,Npmlx*hx);
  sigmay = pmlsigma(RRT,Npmly*hy);
  sigmaz = pmlsigma(RRT,Npmlz*hz);  
  PetscPrintf(PETSC_COMM_WORLD,"----sigmax is %.12e \n",sigmax);
  PetscPrintf(PETSC_COMM_WORLD,"----sigmay is %.12e \n",sigmay);
  PetscPrintf(PETSC_COMM_WORLD,"----sigmaz is %.12e \n",sigmaz);

  char initialdata[PETSC_MAX_PATH_LEN]; //filenameComm[PETSC_MAX_PATH_LEN];
  PetscOptionsGetString(PETSC_NULL,"-initialdata",initialdata,PETSC_MAX_PATH_LEN,&flg); MyCheckAndOutputChar(flg,initialdata,"initialdata","Inputdata file");
  PetscOptionsGetString(PETSC_NULL,"-filenameComm",filenameComm,PETSC_MAX_PATH_LEN,&flg); MyCheckAndOutputChar(flg,filenameComm,"filenameComm","Output filenameComm");


  // add cx, cy, cz to indicate where the diapole current is;

  int cx, cy, cz;
  PetscOptionsGetInt(PETSC_NULL,"-cx",&cx,&flg); 
  if (!flg)
    {cx=(LowerPML)*floor(Nx/2); PetscPrintf(PETSC_COMM_WORLD,"cx is %d by default \n",cx);}
  else
    {PetscPrintf(PETSC_COMM_WORLD,"the current poisiont cx is %d \n",cx);}
  

  PetscOptionsGetInt(PETSC_NULL,"-cy",&cy,&flg); 
  if (!flg)
    {cy=(LowerPML)*floor(Ny/2); PetscPrintf(PETSC_COMM_WORLD,"cy is %d by default \n",cy);}
 else
    {PetscPrintf(PETSC_COMM_WORLD,"the current poisiont cy is %d \n",cy);}
  

  PetscOptionsGetInt(PETSC_NULL,"-cz",&cz,&flg); 
  if (!flg)
    {cz=(LowerPML)*floor(Nz/2); PetscPrintf(PETSC_COMM_WORLD,"cz is %d by default \n",cz);}
  else
    {PetscPrintf(PETSC_COMM_WORLD,"the current poisiont cz is %d \n",cz);}
    
  posj = (cx*Ny+ cy)*Nz + cz;
  PetscPrintf(PETSC_COMM_WORLD,"the posj is %d \n. ", posj);

  int fixpteps;
  PetscOptionsGetInt(PETSC_NULL,"-fixpteps",&fixpteps,&flg);  MyCheckAndOutputInt(flg,fixpteps,"fixpteps","fixpteps");

  // Get minapproach;
  PetscOptionsGetInt(PETSC_NULL,"-minapproach",&minapproach,&flg);  MyCheckAndOutputInt(flg,minapproach,"minapproach","minapproach");
   
  // Get withepsinldos;
  PetscOptionsGetInt(PETSC_NULL,"-withepsinldos",&withepsinldos,&flg);  MyCheckAndOutputInt(flg,withepsinldos,"withepsinldos","withepsinldos");
  
  // Get outputbase;
  PetscOptionsGetInt(PETSC_NULL,"-outputbase",&outputbase,&flg);  MyCheckAndOutputInt(flg,outputbase,"outputbase","outputbase");
  // Get cavityverbose;
  PetscOptionsGetInt(PETSC_NULL,"-cavityverbose",&cavityverbose,&flg);
  if(!flg) cavityverbose=0;
  PetscPrintf(PETSC_COMM_WORLD,"the cavity verbose is set as %d \n", cavityverbose); 
  // Get refinedldos;
  PetscOptionsGetInt(PETSC_NULL,"-refinedldos",&refinedldos,&flg);
  if(!flg) refinedldos=0;
  PetscPrintf(PETSC_COMM_WORLD,"the refinedldos is set as %d \n", refinedldos);
  // Get cmpwrhs;
  int cmpwrhs;
   PetscOptionsGetInt(PETSC_NULL,"-cmpwrhs",&cmpwrhs,&flg);
  if(!flg) cmpwrhs=0;
  PetscPrintf(PETSC_COMM_WORLD,"the cmpwrhs is set as %d \n", cmpwrhs);
  // Get lrzsqr;
   PetscOptionsGetInt(PETSC_NULL,"-lrzsqr",&lrzsqr,&flg);
  if(!flg) lrzsqr=0;
  PetscPrintf(PETSC_COMM_WORLD,"the lrzsqr is set as %d \n", lrzsqr);
  // Get newQdef;
   PetscOptionsGetInt(PETSC_NULL,"-newQdef",&newQdef,&flg);
  if(!flg) newQdef=0;
  PetscPrintf(PETSC_COMM_WORLD,"the newQdef is set as %d \n", newQdef);
  /*--------------------------------------------------------*/

  /*--------------------------------------------------------*/


  /*---------- Set the current source---------*/
  //Mat D; //ImaginaryIMatrix;
  ImagIMat(PETSC_COMM_WORLD, &D,6*Nxyz);

  Vec J;
  ierr = VecCreateMPI(PETSC_COMM_WORLD, PETSC_DECIDE, 6*Nxyz, &J);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) J, "Source");CHKERRQ(ierr);
  VecSet(J,0.0); //initialization;

  if (Jdirection == 1)
    SourceSingleSetX(PETSC_COMM_WORLD, J, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else if (Jdirection ==2)
    SourceSingleSetY(PETSC_COMM_WORLD, J, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else if (Jdirection == 3)
    SourceSingleSetZ(PETSC_COMM_WORLD, J, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else
    PetscPrintf(PETSC_COMM_WORLD," Please specify correct direction of current: x (1) , y (2) or z (3)\n "); 

  Vec Jtwo;
  ierr = VecDuplicate(J, &Jtwo);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) Jtwo, "Sourcetwo");CHKERRQ(ierr);
  VecSet(Jtwo,0.0); //initialization;

  if (Jdirectiontwo == 1)
    SourceSingleSetX(PETSC_COMM_WORLD, Jtwo, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else if (Jdirectiontwo ==2)
    SourceSingleSetY(PETSC_COMM_WORLD, Jtwo, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else if (Jdirectiontwo == 3)
    SourceSingleSetZ(PETSC_COMM_WORLD, Jtwo, Nx, Ny, Nz, cx, cy, cz,1.0/hxyz);
  else
    PetscPrintf(PETSC_COMM_WORLD," Please specify correct direction of current two: x (1) , y (2) or z (3)\n "); 


  //Vec b; // b= i*omega*J;
  Vec bone, btwo;

  ierr = VecDuplicate(J,&b);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) b, "rhsone");CHKERRQ(ierr);

  ierr = VecDuplicate(J,&bone);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) bone, "rhsone");CHKERRQ(ierr);

  ierr = VecDuplicate(Jtwo,&btwo);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) btwo, "rhstwo");CHKERRQ(ierr);

  if (cmpwrhs==0)
    {
      ierr = MatMult(D,J,b);CHKERRQ(ierr);
      ierr = MatMult(D,Jtwo,btwo);CHKERRQ(ierr);
      
      VecCopy(b,bone);
      VecScale(bone,omegaone);

      VecScale(btwo,omegatwo);

      VecScale(b,omega);      
    }
  else
    {
      double complex cmpiomega;
      cmpiomega = cpow(1+I/Qabs,newQdef+1);
      double sqrtiomegaR = -omega*cimag(csqrt(cmpiomega));
      double sqrtiomegaI = omega*creal(csqrt(cmpiomega));
      PetscPrintf(PETSC_COMM_WORLD,"the real part of sqrt cmpomega is %g and imag sqrt is % g ", sqrtiomegaR, sqrtiomegaI);
      Vec tmpi;
      ierr = VecDuplicate(J,&tmpi);
      VecSet(b,0.0);
      VecSet(tmpi,0.0);
      CmpVecScale(J,b,sqrtiomegaR,sqrtiomegaI,D,tmpi);
      VecDestroy(&tmpi);
    }

  /*-------Get the weight vector ------------------*/
  //Vec weight;
  ierr = VecDuplicate(J,&weight); CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) weight, "weight");CHKERRQ(ierr);

  if(LowerPML==0)
    GetWeightVec(weight, Nx, Ny,Nz); // new code handles both 3D and 2D;
  else
    VecSet(weight,1.0);

  Vec weightedJ;
  ierr = VecDuplicate(J,&weightedJ); CHKERRQ(ierr);
  ierr = VecPointwiseMult(weightedJ,J,weight);
  ierr = PetscObjectSetName((PetscObject) weightedJ, "weightedJ");CHKERRQ(ierr);

  Vec weightedJtwo;
  ierr = VecDuplicate(Jtwo,&weightedJtwo); CHKERRQ(ierr);
  ierr = VecPointwiseMult(weightedJtwo,Jtwo,weight);
  ierr = PetscObjectSetName((PetscObject) weightedJtwo, "weightedJtwo");CHKERRQ(ierr);

  //Vec vR;
  ierr = VecDuplicate(J,&vR); CHKERRQ(ierr);
  GetRealPartVec(vR, 6*Nxyz);

  // VecFReal;
  if (lrzsqr)
    { ierr = VecDuplicate(J,&epsFReal); CHKERRQ(ierr); 
      ierr = PetscObjectSetName((PetscObject) epsFReal, "epsFReal");CHKERRQ(ierr);

      if (newQdef==0)
	{
	  sqrtomegaI = omega*cimag(csqrt(1+I/Qabs));
	  PetscPrintf(PETSC_COMM_WORLD,"the real part of sqrt cmpomega is %g and imag sqrt is % g ", omega*creal(csqrt(1+I/Qabs)), sqrtomegaI);
	  betar = 2*sqrtomegaI;
	  betai = betar/Qabs;
	}
      else
	{
	  double gamma;
	  gamma = omega/Qabs;
	  betar = 2*gamma*(1-1.0/pow(Qabs,2));
	  betai = 2*gamma*(2.0/Qabs);
	}

      ierr = VecDuplicate(J,&nb); CHKERRQ(ierr);
      ierr = PetscObjectSetName((PetscObject) nb, "nb"); CHKERRQ(ierr);
      
      ierr = VecDuplicate(J,&y); CHKERRQ(ierr);
      ierr = PetscObjectSetName((PetscObject) y, "y"); CHKERRQ(ierr);
      
      ierr = VecDuplicate(J,&xsqr); CHKERRQ(ierr); // xsqr = x*x;
      ierr = PetscObjectSetName((PetscObject) xsqr, "xsqr"); CHKERRQ(ierr);
      CongMat(PETSC_COMM_WORLD, &C, 6*Nxyz);
}
  /*----------- Define PML muinv vectors  */
 
  Vec muinvpml;
  MuinvPMLFull(PETSC_COMM_SELF, &muinvpml,Nx,Ny,Nz,Npmlx,Npmly,Npmlz,sigmax,sigmay,sigmaz,omega, LowerPML); 

  //double *muinv;
  muinv = (double *) malloc(sizeof(double)*6*Nxyz);
  int add=0;
  AddMuAbsorption(muinv,muinvpml,Qabs,add);
  ierr = VecDestroy(&muinvpml); CHKERRQ(ierr);  

  /*---------- Define PML eps vectors: epspml---------- */  
  Vec epspml; //epspmlQ, epscoef;
  ierr = VecDuplicate(J,&epspml);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) epspml,"EpsPMLFull"); CHKERRQ(ierr);
  EpsPMLFull(PETSC_COMM_WORLD, epspml,Nx,Ny,Nz,Npmlx,Npmly,Npmlz,sigmax,sigmay,sigmaz,omega, LowerPML);

  ierr = VecDuplicate(J,&epspmlQ);CHKERRQ(ierr);


  Vec epscoefone, epscoeftwo;
  ierr = VecDuplicate(J,&epscoefone);CHKERRQ(ierr);
  ierr = VecDuplicate(J,&epscoeftwo);CHKERRQ(ierr);
 
  // compute epspmlQ,epscoef;
  EpsCombine(D, weight, epspml, epspmlQ, epscoefone, Qabs, omegaone);
  EpsCombine(D, weight, epspml, epspmlQ, epscoeftwo, Qabs, omegatwo);
  /*--------- Setup the interp matrix ----------------------- */
  /* for a samll eps block, interp it into yee-lattice. The interp matrix A and PML epspml only need to generated once;*/
  

  //Mat A; 
  //new routine for myinterp;
  myinterp(PETSC_COMM_WORLD, &A, Nx,Ny,Nz, LowerPML*floor((Nx-Mx)/2),LowerPML*floor((Ny-My)/2),LowerPML*floor((Nz-Mz)/2), Mx,My,Mz,Mzslab, anisotropic); // LoweerPML*Npmlx,..,.., specify where the interp starts;  

  //Vec epsSReal, epsgrad, vgrad; // create compatiable vectors with A.
  ierr = MatGetVecs(A,&epsSReal, &epsgrad); CHKERRQ(ierr);  
  ierr = PetscObjectSetName((PetscObject) epsgrad, "epsgrad");CHKERRQ(ierr);
  ierr = VecDuplicate(epsSReal, &vgrad); CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) epsSReal, "epsSReal");CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) vgrad, "vgrad");CHKERRQ(ierr);
  
  /*---------Setup the epsmedium vector----------------*/
  //Vec epsmedium;
  ierr = VecDuplicate(J,&epsmedium); CHKERRQ(ierr);
  GetMediumVec(epsmedium,Nz,Mz,epsair,epssub);
 
  /*--------- Setup the finitie difference matrix-------------*/
  //Mat M;
  MoperatorGeneral(PETSC_COMM_WORLD, &M, Nx,Ny,Nz,hx,hy,hz, bx, by, bz,muinv,BCPeriod);
  free(muinv);

  /*--------Setup the KSP variables ---------------*/
  
  KSP kspone;
  PC pcone; 
  ierr = KSPCreate(PETSC_COMM_WORLD,&kspone);CHKERRQ(ierr);
  //ierr = KSPSetType(ksp, KSPPREONLY);CHKERRQ(ierr);
  ierr = KSPSetType(kspone, KSPGMRES);CHKERRQ(ierr);
  ierr = KSPGetPC(kspone,&pcone);CHKERRQ(ierr);
  ierr = PCSetType(pcone,PCLU);CHKERRQ(ierr);
  ierr = PCFactorSetMatSolverPackage(pcone,MATSOLVERPASTIX);CHKERRQ(ierr);
  ierr = PCSetFromOptions(pcone);
  int maxkspit = 20;
  ierr = KSPSetTolerances(kspone,1e-14,PETSC_DEFAULT,PETSC_DEFAULT,maxkspit);CHKERRQ(ierr);
  ierr = KSPSetFromOptions(kspone);CHKERRQ(ierr);

  KSP ksptwo;
  PC pctwo;
   ierr = KSPCreate(PETSC_COMM_WORLD,&ksptwo);CHKERRQ(ierr);
  //ierr = KSPSetType(ksp, KSPPREONLY);CHKERRQ(ierr);
  ierr = KSPSetType(ksptwo, KSPGMRES);CHKERRQ(ierr);
  ierr = KSPGetPC(ksptwo,&pctwo);CHKERRQ(ierr);
  ierr = PCSetType(pctwo,PCLU);CHKERRQ(ierr);
  ierr = PCFactorSetMatSolverPackage(pctwo,MATSOLVERPASTIX);CHKERRQ(ierr);
  ierr = PCSetFromOptions(pctwo);
  ierr = KSPSetTolerances(ksptwo,1e-14,PETSC_DEFAULT,PETSC_DEFAULT,maxkspit);CHKERRQ(ierr);
  ierr = KSPSetFromOptions(ksptwo);CHKERRQ(ierr);

  /*--------- Create the space for solution vector -------------*/
  //Vec x;
  ierr = VecDuplicate(J,&x);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) x, "Solution");CHKERRQ(ierr); 
  
  /*----------- Create the space for final eps -------------*/

  //Vec epsC, epsCi, epsP;
  ierr = VecDuplicate(J,&epsC);CHKERRQ(ierr);
  ierr = PetscObjectSetName((PetscObject) epsC, "EpsC");CHKERRQ(ierr);
  ierr = VecDuplicate(J,&epsCi);CHKERRQ(ierr);
  ierr = VecDuplicate(J,&epsP);CHKERRQ(ierr);

  ierr = VecSet(epsP,0.0); CHKERRQ(ierr);
  ierr = VecAssemblyBegin(epsP); CHKERRQ(ierr);
  ierr = VecAssemblyEnd(epsP); CHKERRQ(ierr); 

  /*------------ Create space used in the solver ------------*/
  //Vec vgradlocal,tmp, tmpa,tmpb;
  ierr = VecCreateSeq(PETSC_COMM_SELF, DegFree, &vgradlocal); CHKERRQ(ierr);
  ierr = VecDuplicate(J,&tmp); CHKERRQ(ierr);
  ierr = VecDuplicate(J,&tmpa); CHKERRQ(ierr);
  ierr = VecDuplicate(J,&tmpb); CHKERRQ(ierr);
 
  // Vec pickposvec; this vector is zero except that first entry is one;
  if (withepsinldos)
    { ierr = VecDuplicate(J,&pickposvec); CHKERRQ(ierr);
      ierr = VecSet(pickposvec,0.0); CHKERRQ(ierr);
      ierr = VecSetValue(pickposvec,posj+Jdirection*Nxyz,1.0,INSERT_VALUES);
      VecAssemblyBegin(pickposvec);
      VecAssemblyEnd(pickposvec);
    }
  /*------------ Create scatter used in the solver -----------*/
  //VecScatter scatter;
  //IS from, to;
  ierr =ISCreateStride(PETSC_COMM_SELF,DegFree,0,1,&from); CHKERRQ(ierr);
  ierr =ISCreateStride(PETSC_COMM_SELF,DegFree,0,1,&to); CHKERRQ(ierr);

  /*-------------Read the input file -------------------------*/

  double *epsoptAll;
  epsoptAll = (double *) malloc(DegFreeAll*sizeof(double));

  FILE *ptf;
  ptf = fopen(initialdata,"r");
  PetscPrintf(PETSC_COMM_WORLD,"reading from input files \n");

  int i;
  // set the dielectric at the center is fixed, and alwyas high
  //epsopt[0]=myub; is defined below near lb and ub;
  for (i=0;i<DegFree;i++)
    { //PetscPrintf(PETSC_COMM_WORLD,"current eps reading is %lf \n",epsopt[i]);
      fscanf(ptf,"%lf",&epsoptAll[i]);
    }
  epsoptAll[DegFreeAll-1]=0; //initialize auxiliary variable;
  fclose(ptf);



  /*----declare these data types, althought they may not be used for job 2 -----------------*/
 
  double mylb,myub, *lb=NULL, *ub=NULL;
  int maxeval, maxtime, mynloptalg;
  double maxf;
  nlopt_opt  opt;
  nlopt_result result;
  /*--------------------------------------------------------------*/
  /*----Now based on Command Line, Do the corresponding job----*/
  /*----------------------------------------------------------------*/


  //int Job; set Job to be gloabl variables;
  PetscOptionsGetInt(PETSC_NULL,"-Job",&Job,&flg);  MyCheckAndOutputInt(flg,Job,"Job","The Job indicator you set");
  
  int numofvar=(Job==1)*DegFreeAll + (Job==3);

  /*--------   convert the epsopt array to epsSReal (if job!=optmization) --------*/
  if (Job==2 || Job ==3)
    {
      // copy epsilon from file to epsSReal; (different from FindOpt.c, because epsilon is not degree-of-freedoms in computeQ.
      // i) create a array to read file (done above in epsopt); ii) convert the array to epsSReal;
      int ns, ne;
      ierr = VecGetOwnershipRange(epsSReal,&ns,&ne);
      for(i=ns;i<ne;i++)
	{ ierr=VecSetValue(epsSReal,i,epsoptAll[i],INSERT_VALUES); 
	  CHKERRQ(ierr); }      
      if(withepsinldos)
	{ epsatinterest = epsoptAll[cx*Ny*Nz + cy*Nz + cz]  + epsair;
	  PetscPrintf(PETSC_COMM_WORLD, " the relative permitivity at the point of current is %.16e \n ",epsatinterest);}
      ierr = VecAssemblyBegin(epsSReal); CHKERRQ(ierr);
      ierr = VecAssemblyEnd(epsSReal);  CHKERRQ(ierr);
    }

  if (Job==1 || Job==3)  // optimization bounds setup;
    {      
      PetscOptionsGetInt(PETSC_NULL,"-maxeval",&maxeval,&flg);  MyCheckAndOutputInt(flg,maxeval,"maxeval","max number of evaluation");
      PetscOptionsGetInt(PETSC_NULL,"-maxtime",&maxtime,&flg);  MyCheckAndOutputInt(flg,maxtime,"maxtime","max time of evaluation");
      PetscOptionsGetInt(PETSC_NULL,"-mynloptalg",&mynloptalg,&flg);  MyCheckAndOutputInt(flg,mynloptalg,"mynloptalg","The algorithm used ");

      PetscOptionsGetReal(PETSC_NULL,"-mylb",&mylb,&flg);  MyCheckAndOutputDouble(flg,mylb,"mylb","optimization lb");
      PetscOptionsGetReal(PETSC_NULL,"-myub",&myub,&flg);  MyCheckAndOutputDouble(flg,myub,"myub","optimization ub");

      
 
      lb = (double *) malloc(numofvar*sizeof(double));
      ub = (double *) malloc(numofvar*sizeof(double));

      // the dielectric constant at center is fixed!
      for(i=0;i<numofvar;i++)
	{
	  lb[i] = mylb;
	  ub[i] = myub;
	}  //initial guess, lower bounds, upper bounds;

      // set lower and upper bounds for auxiliary variable;
      lb[numofvar-1]=0;
      ub[numofvar-1]=1.0/0.0;

      //fix the dielectric at the center to be high for topology optimization;
      if (Job==1 && fixpteps==1)
	{
	  epsoptAll[0]=myub;
	  lb[0]=myub;
	  ub[0]=myub;
	}



      opt = nlopt_create(mynloptalg, numofvar);
      
      myfundatatypeshg data[2] = {{omegaone, bone, weightedJ, epscoefone,kspone},{omegatwo, btwo, weightedJtwo, epscoeftwo,ksptwo}};

      nlopt_add_inequality_constraint(opt,ldosconstraint, &data[0], 1e-8);
      nlopt_add_inequality_constraint(opt,ldosconstraint, &data[1], 1e-8);

      nlopt_set_lower_bounds(opt,lb);
      nlopt_set_upper_bounds(opt,ub);
      nlopt_set_maxeval(opt,maxeval);
      nlopt_set_maxtime(opt,maxtime);


      /*add functionality to choose local optimizer; */
      int mynloptlocalalg;
      nlopt_opt local_opt;
      PetscOptionsGetInt(PETSC_NULL,"-mynloptlocalalg",&mynloptlocalalg,&flg);  MyCheckAndOutputInt(flg,mynloptlocalalg,"mynloptlocalalg","The local optimization algorithm used ");
      if (mynloptlocalalg)
	{ 
	  local_opt=nlopt_create(mynloptlocalalg,numofvar);
	  nlopt_set_ftol_rel(local_opt, 1e-14);
	  nlopt_set_maxeval(local_opt,100000);
	  nlopt_set_local_optimizer(opt,local_opt);
	}
    }

  switch (Job)
    {
    case 1:
      {
	if (minapproach)
	  nlopt_set_min_objective(opt,maxminobjfun,NULL);// NULL: no data to be passed because of global variables;
	else
	  nlopt_set_max_objective(opt,maxminobjfun,NULL);

	result = nlopt_optimize(opt,epsoptAll,&maxf);
      }      
      break;
    case 2 :  //AnalyzeStructure
      { 
	int Linear, Eig, maxeigit;
	PetscOptionsGetInt(PETSC_NULL,"-Linear",&Linear,&flg);  MyCheckAndOutputInt(flg,Linear,"Linear","Linear solver indicator");
	PetscOptionsGetInt(PETSC_NULL,"-Eig",&Eig,&flg);  MyCheckAndOutputInt(flg,Eig,"Eig","Eig solver indicator");
	PetscOptionsGetInt(PETSC_NULL,"-maxeigit",&maxeigit,&flg);  MyCheckAndOutputInt(flg,maxeigit,"maxeigit","maximum number of Eig solver iterations is");

	/*----------------------------------*/
	//EigenSolver(Linear, Eig, maxeigit);
	/*----------------------------------*/

	OutputVec(PETSC_COMM_WORLD, weight,filenameComm, "weight.m");
      }
      break;   
    default:
      PetscPrintf(PETSC_COMM_WORLD,"--------Interesting! You're doing nothing!--------\n ");
 }


  if(Job==1 || Job==3)
    {
      /* print the optimization parameters */
#if 0
      double xrel, frel, fabs;
      // double *xabs;
      frel=nlopt_get_ftol_rel(opt);
      fabs=nlopt_get_ftol_abs(opt);
      xrel=nlopt_get_xtol_rel(opt);
      PetscPrintf(PETSC_COMM_WORLD,"nlopt frel is %g \n",frel);
      PetscPrintf(PETSC_COMM_WORLD,"nlopt fabs is %g \n",fabs);
      PetscPrintf(PETSC_COMM_WORLD,"nlopt xrel is %g \n",xrel);
      //nlopt_result nlopt_get_xtol_abs(const nlopt_opt opt, double *tol);
#endif
      /*--------------*/

      if (result < 0) {
	PetscPrintf(PETSC_COMM_WORLD,"nlopt failed! \n", result);
      }
      else {
	PetscPrintf(PETSC_COMM_WORLD,"found extremum  %0.16e\n", minapproach?1.0/maxf:maxf); 
      }

      PetscPrintf(PETSC_COMM_WORLD,"nlopt returned value is %d \n", result);


      if(Job==1)
	{ //OutputVec(PETSC_COMM_WORLD, epsopt,filenameComm, "epsopt.m");
	  //OutputVec(PETSC_COMM_WORLD, epsgrad,filenameComm, "epsgrad.m");
	  //OutputVec(PETSC_COMM_WORLD, vgrad,filenameComm, "vgrad.m");
	  //OutputVec(PETSC_COMM_WORLD, x,filenameComm, "x.m");
	  int rankA;
	  MPI_Comm_rank(PETSC_COMM_WORLD, &rankA);

	  if(rankA==0)
	    {
	      ptf = fopen(strcat(filenameComm,"epsopt.txt"),"w");
	      for (i=0;i<DegFree;i++)
		fprintf(ptf,"%0.16e \n",epsoptAll[i]);
	      fclose(ptf);
	      PetscPrintf(PETSC_COMM_WORLD,"the t parameter is %.8e \n",epsoptAll[DegFreeAll-1]);
	    }  
	}

      nlopt_destroy(opt);
    }
     


  ierr = PetscPrintf(PETSC_COMM_WORLD,"--------Done!--------\n ");CHKERRQ(ierr);

  /*------------------------------------*/
 

  /* ----------------------Destroy Vecs and Mats----------------------------*/ 

  free(epsoptAll);
  free(lb);
  free(ub);
  ierr = VecDestroy(&J); CHKERRQ(ierr);
  ierr = VecDestroy(&b); CHKERRQ(ierr);
  ierr = VecDestroy(&weight); CHKERRQ(ierr);
  ierr = VecDestroy(&weightedJ); CHKERRQ(ierr);
  ierr = VecDestroy(&vR); CHKERRQ(ierr);
  ierr = VecDestroy(&epspml); CHKERRQ(ierr);
  ierr = VecDestroy(&epspmlQ); CHKERRQ(ierr);
  ierr = VecDestroy(&epsSReal); CHKERRQ(ierr);
  ierr = VecDestroy(&epsgrad); CHKERRQ(ierr);
  ierr = VecDestroy(&vgrad); CHKERRQ(ierr);  
  ierr = VecDestroy(&epsmedium); CHKERRQ(ierr);
  ierr = VecDestroy(&epsC); CHKERRQ(ierr);
  ierr = VecDestroy(&epsCi); CHKERRQ(ierr);
  ierr = VecDestroy(&epsP); CHKERRQ(ierr);
  ierr = VecDestroy(&x); CHKERRQ(ierr);
  ierr = VecDestroy(&vgradlocal);CHKERRQ(ierr);
  ierr = VecDestroy(&tmp); CHKERRQ(ierr);
  ierr = VecDestroy(&tmpa); CHKERRQ(ierr);
  ierr = VecDestroy(&tmpb); CHKERRQ(ierr);
  ierr = MatDestroy(&A); CHKERRQ(ierr);  
  ierr = MatDestroy(&D); CHKERRQ(ierr);
  ierr = MatDestroy(&M); CHKERRQ(ierr);  
 

  ierr = VecDestroy(&epscoefone); CHKERRQ(ierr);
  ierr = VecDestroy(&epscoeftwo); CHKERRQ(ierr);
  ierr = KSPDestroy(&kspone);CHKERRQ(ierr);
  ierr = KSPDestroy(&ksptwo);CHKERRQ(ierr);

  ISDestroy(&from);
  ISDestroy(&to);

  if (withepsinldos)
    {ierr=VecDestroy(&pickposvec); CHKERRQ(ierr);}

  if (lrzsqr)
    {
      ierr=VecDestroy(&epsFReal); CHKERRQ(ierr);
      ierr=VecDestroy(&xsqr); CHKERRQ(ierr);
      ierr=VecDestroy(&y); CHKERRQ(ierr);
      ierr=VecDestroy(&nb); CHKERRQ(ierr);
      ierr=MatDestroy(&C); CHKERRQ(ierr);
    }

  ierr = VecDestroy(&bone); CHKERRQ(ierr);
  ierr = VecDestroy(&btwo); CHKERRQ(ierr);
  ierr = VecDestroy(&Jtwo); CHKERRQ(ierr);
  

  /*------------ finalize the program -------------*/

  {
    int rank;
    MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
    //if (rank == 0) fgetc(stdin);
    MPI_Barrier(PETSC_COMM_WORLD);
  }
  
  ierr = PetscFinalize(); CHKERRQ(ierr);

  return 0;
}
コード例 #14
0
nlopt_result
NLOPT_STDCALL nlopt_minimize_econstrained(
     nlopt_algorithm algorithm,
     int n, nlopt_func_old f, void *f_data,
     int m, nlopt_func_old fc, void *fc_data_, ptrdiff_t fc_datum_size,
     int p, nlopt_func_old h, void *h_data_, ptrdiff_t h_datum_size,
     const double *lb, const double *ub, /* bounds */
     double *x, /* in: initial guess, out: minimizer */
     double *minf, /* out: minimum */
     double minf_max, double ftol_rel, double ftol_abs,
     double xtol_rel, const double *xtol_abs,
     double htol_rel, double htol_abs,
     int maxeval, double maxtime)
{
     char *fc_data = (char *) fc_data_;
     char *h_data = (char *) h_data_;
     nlopt_opt opt;
     nlopt_result ret;
     int i;

     if (n < 0 || m < 0 || p < 0) return NLOPT_INVALID_ARGS;

     opt = nlopt_create(algorithm, (unsigned) n);
     if (!opt) return NLOPT_INVALID_ARGS;

     ret = nlopt_set_min_objective(opt, (nlopt_func) f, f_data);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     for (i = 0; i < m; ++i) {
	  ret = nlopt_add_inequality_constraint(opt, (nlopt_func) fc, 
						fc_data + i*fc_datum_size,
						0.0);
	  if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     }

     (void) htol_rel; /* unused */
     for (i = 0; i < p; ++i) {
	  ret = nlopt_add_equality_constraint(opt, (nlopt_func) h, 
					      h_data + i*h_datum_size,
					      htol_abs);
	  if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     }

     ret = nlopt_set_lower_bounds(opt, lb);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     ret = nlopt_set_upper_bounds(opt, ub);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     ret = nlopt_set_stopval(opt, minf_max);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     ret = nlopt_set_ftol_rel(opt, ftol_rel);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     ret = nlopt_set_ftol_abs(opt, ftol_abs);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     ret = nlopt_set_xtol_rel(opt, xtol_rel);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     ret = nlopt_set_xtol_abs(opt, xtol_abs);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }
     
     ret = nlopt_set_maxeval(opt, maxeval);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     ret = nlopt_set_maxtime(opt, maxtime);
     if (ret != NLOPT_SUCCESS) { nlopt_destroy(opt); return ret; }

     ret = nlopt_optimize(opt, x, minf);

     nlopt_destroy(opt);
     return ret;
}
コード例 #15
0
void
FitOrientation(
    const int NrOfFiles,
    const int nLayers,
    const double ExcludePoleAngle,
    double Lsd[nLayers],
    const long long int SizeObsSpots,
    double TiltsOrig[3],
    const double OmegaStart,
    const double OmegaStep,
    const double px,
    double ybc[nLayers],
    double zbc[nLayers],
    const double gs,
    double SpotsInfo[200][9],
    int nSpots,
    double OmegaRanges[MAX_N_OMEGA_RANGES][2],
    const int NoOfOmegaRanges,
    double BoxSizes[MAX_N_OMEGA_RANGES][4],
    double P0[nLayers][3],
    const int NrPixelsGrid,
    int *ObsSpotsInfo,
    double tol,
    double hkls[5000][4],
    double Thetas[5000],
    int n_hkls,
    double **SpotsOut,
    double *LsdFit,
    double *TiltsFit,
    double **BCsFit,
    double tolLsd,
    double tolLsdRel,
    double tolTilts,
    double tolBCsa,
    double tolBCsb)
{
    unsigned n;
    long int i,j;
    n  = 3+(nLayers*3)+(nSpots*3);
    double x[n],xl[n],xu[n];
    for (i=0;i<n;i++){
        x[i] = 0;
        xl[i] = 0;
        xu[i] = 0;
    }
    int count = 0;
    for (i=0;i<3;i++)
    {
        x[i] = TiltsOrig[count];
        xl[i] = x[i] - tolTilts;
        xu[i] = x[i] + tolTilts;
        count++;
    }
    count = 0;
    x[3] = Lsd[0];
    xl[3] = x[3] - tolLsd;
    xu[3] = x[3] + tolLsd;
    count++;
    for (i=4;i<nLayers+3;i++)
    {
        x[i] = Lsd[count] - Lsd[count-1];
        xl[i] = x[i] - tolLsdRel;
        xu[i] = x[i] + tolLsdRel;
        count++;
    }
    count = 0;
    for (i=3+nLayers;i<3+(nLayers*2);i++)
    {
        x[i] = ybc[count];
        x[i+nLayers] = zbc[count];
        xl[i] = x[i] - tolBCsa;
        xl[i+nLayers] = x[i+nLayers] - tolBCsb;
        xu[i] = x[i] + tolBCsa;
        xu[i+nLayers] = x[i+nLayers] + tolBCsb;
        count++;
    }
    count = 0;
    int ps;
    for( i=0; i<nSpots; i++)
    {
		for (j=0;j<3;j++){
			ps = i*3+j+3+(nLayers*3);
			x[ps] = SpotsInfo[i][6+j];
            xl[ps] = x[ps] - (tol*M_PI/180);
			xu[ps] = x[ps] + (tol*M_PI/180);
		}
    }
    //for (i=0;i<n;i++) printf("%f %f %f\n",x[i],xl[i],xu[i]);
	struct my_func_data f_data;
	f_data.NrOfFiles = NrOfFiles;
	f_data.nLayers = nLayers;
	f_data.n_hkls = n_hkls;
	for (i=0;i<5000;i++){
		f_data.hkls[i][0] = hkls[i][0];
		f_data.hkls[i][1] = hkls[i][1];
		f_data.hkls[i][2] = hkls[i][2];
		f_data.hkls[i][3] = hkls[i][3];
		f_data.Thetas[i] = Thetas[i];
	}
	f_data.ExcludePoleAngle = ExcludePoleAngle;
	f_data.SizeObsSpots = SizeObsSpots;
	f_data.P0 = allocMatrixF(nLayers,3);
	for (i=0;i<3;i++){
		for (j=0;j<nSpots;j++){
			f_data.XGrain[j][i] = SpotsInfo[j][2*i];
			f_data.YGrain[j][i] = SpotsInfo[j][2*i+1];
		}
		for (j=0;j<nLayers;j++){
			f_data.P0[j][i] = P0[j][i];
		}
	}
	for (i=0;i<MAX_N_OMEGA_RANGES;i++){
		for (j=0;j<2;j++){
			f_data.OmegaRanges[i][j] = OmegaRanges[i][j];
		}
		for (j=0;j<4;j++){
			f_data.BoxSizes[i][j] = BoxSizes[i][j];
		}
	}
	f_data.ObsSpotsInfo = &ObsSpotsInfo[0];
	f_data.OmegaStart = OmegaStart;
	f_data.OmegaStep = OmegaStep;
	f_data.px = px;
	f_data.gs = gs;
	f_data.nSpots = nSpots;
	f_data.NoOfOmegaRanges = NoOfOmegaRanges;
	f_data.NrPixelsGrid = NrPixelsGrid;
	struct my_func_data *f_datat;
	f_datat = &f_data;
	void* trp = (struct my_func_data *) f_datat;
	double tole = 1e-3;
	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LN_NELDERMEAD, n);
	nlopt_set_lower_bounds(opt, xl);
	nlopt_set_upper_bounds(opt, xu);
	nlopt_set_min_objective(opt, problem_function, trp);
	double minf=1;
	nlopt_optimize(opt, x, &minf);
	nlopt_destroy(opt);
    TiltsFit[0] = x[0];
    TiltsFit[1] = x[1];
    TiltsFit[2] = x[2];
    LsdFit[0] = x[3];
    for (i=1;i<nLayers;i++){
        LsdFit[i] = LsdFit[i-1] + x[3+i];
    }
    for (i=0;i<nLayers;i++){
        BCsFit[i][0] = x[3+nLayers+i];
        BCsFit[i][1] = x[3+nLayers+nLayers+i];
    }
    for (i=0;i<nSpots;i++){
		for (j=0;j<3;j++){
			ps = i*3+j+3+(nLayers*3);
			SpotsOut[i][j] = x[ps];
		}
		SpotsOut[i][3] = IndividualResults[i];
	}
}
コード例 #16
0
ファイル: TKF92_nlopt.c プロジェクト: ge11232002/TKF
/********************************************************************
 * nlopt main function
 * *****************************************************************/
SEXP TKF92LikelihoodFunction3DMain_nlopt(SEXP seq1IntR, SEXP seq2IntR,
    SEXP expectedLength, SEXP probMatR, SEXP eqFrequenciesR,
    SEXP method){
  int ncol, nrow;
  ncol = INTEGER(GET_DIM(probMatR))[1];
  nrow = INTEGER(GET_DIM(probMatR))[0];
  int i, j;

  // probMat
  gsl_matrix *probMat = gsl_matrix_alloc(nrow, ncol);
  for(i = 0; i < nrow; i++)
    for(j = 0; j < ncol; j++)
      gsl_matrix_set(probMat, i, j, REAL(probMatR)[i+j*ncol]);

  // eqFrequenciesR
  gsl_vector *eqFrequencies = gsl_vector_alloc(GET_LENGTH(eqFrequenciesR));
  for(i = 0; i < GET_LENGTH(eqFrequenciesR); i++){
    gsl_vector_set(eqFrequencies, i, REAL(eqFrequenciesR)[i]);
  }

  // seqInt preparation
  int *seq1Int, *seq2Int;
  seq1Int = (int *) R_alloc(GET_LENGTH(seq1IntR), sizeof(int));
  seq2Int = (int *) R_alloc(GET_LENGTH(seq2IntR), sizeof(int));
  for(i = 0; i < GET_LENGTH(seq1IntR); i++){
    seq1Int[i] = INTEGER(seq1IntR)[i];
  }
  for(i = 0; i < GET_LENGTH(seq2IntR); i++){
    seq2Int[i] = INTEGER(seq2IntR)[i];
  }
  
  // construct params
  struct TKF92LikelihoodFunction3D_params params;
  params.len = REAL(expectedLength)[0];
  params.substModel = probMat;
  params.eqFrequencies = eqFrequencies;
  params.seq1Int = seq1Int;
  params.seq2Int = seq2Int;
  params.SA = GET_LENGTH(seq1IntR);
  params.SB = GET_LENGTH(seq2IntR);

  // nlopt main procedure
  double lb[3] = {0.0494497, 1e-20, 1e-20}; // lower bounds
  double ub[3] = {2000, 0.1, 1-1e-20};  // upper bounds
  //double dx[3] = {20, 0.01, 0.1}; // The initial step size

  nlopt_opt opt;
  if(strcmp(CHAR(STRING_ELT(method, 0)), "NM") == 0){
    opt = nlopt_create(NLOPT_LN_NELDERMEAD, 3); /* algorithm and dimensionality */
  }else if(strcmp(CHAR(STRING_ELT(method, 0)), "Sbplx") == 0){
    opt = nlopt_create(NLOPT_LN_SBPLX, 3);
  }else if(strcmp(CHAR(STRING_ELT(method, 0)), "COBYLA") == 0){
    opt = nlopt_create(NLOPT_LN_COBYLA, 3);
  }else if(strcmp(CHAR(STRING_ELT(method, 0)), "BOBYQA") == 0){
    opt = nlopt_create(NLOPT_LN_BOBYQA, 3);
  }else if(strcmp(CHAR(STRING_ELT(method, 0)), "PRAXIS") == 0){
    opt = nlopt_create(NLOPT_LN_PRAXIS, 3);
  }else{
    error("Wrong optimisation method!");
  }

  nlopt_set_lower_bounds(opt, lb);
  nlopt_set_upper_bounds(opt, ub);
  
  nlopt_set_min_objective(opt, TKF92LikelihoodFunction3D_nlopt, &params);
  nlopt_set_ftol_rel(opt, F_TOL); // stopping criteria
  //nlopt_set_initial_step(opt, dx); // initial step size
  nlopt_set_maxeval(opt, MAX_ITER);

  double x[3] = {100, exp(-3), 0.5};  /* some initial guess */
  double minf; /* the minimum objective value, upon return */
  if (nlopt_optimize(opt, x, &minf) < 0) {
    Rprintf("nlopt failed!\n");
  }else{
    Rprintf("found minimum at f(%g,%g,%g) = %0.10g using %s algorithm\n",
        x[0], x[1], x[2], minf, CHAR(STRING_ELT(method, 0)));
  }

  SEXP ans, ansNames;
  PROTECT(ans = NEW_NUMERIC(4)); // a vector of distance, mu, r and the negative log likelihood
  PROTECT(ansNames = NEW_CHARACTER(4));
  REAL(ans)[0] = x[0];
  REAL(ans)[1] = x[1];
  REAL(ans)[2] = x[2];
  REAL(ans)[3] = minf;
  SET_STRING_ELT(ansNames, 0, mkChar("PAM"));
  SET_STRING_ELT(ansNames, 1, mkChar("Mu"));
  SET_STRING_ELT(ansNames, 2, mkChar("r"));
  SET_STRING_ELT(ansNames, 3, mkChar("negLogLikelihood"));
  SET_NAMES(ans, ansNames);

  // free everything
  nlopt_destroy(opt);
  gsl_vector_free(eqFrequencies);
  gsl_matrix_free(probMat);

  UNPROTECT(2);
  return ans;
}
コード例 #17
0
double ColorLines::findMagnitude(const Mat *img, Mat *alpha_mat, double a[3])
{
    int w=img->cols;
    int h=img->rows;
    int t=img->type();
    int c;


    if(img->type()==CV_8UC3){
        c=3;
    } else if(img->type()==CV_8UC1){
        c=1;
    }
    uchar *p_data=img->data;
    uchar *alpha_data=alpha_mat->data;

    //cout << *alpha_mat << endl;
    double img_div[h*w*c];
    double *alpha=(double*)malloc(h*w*sizeof(double));

    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            alpha[i*w+j]=(double)alpha_data[w*i+j]/255.0l;
            for(int k=0; k<c; k++){
                img_div[c*(w*i+j)+k]=(double(p_data[c*(w*i+j)+k])/255.0l)/a[k];
            }
        }
    }



    double *withoutA = (double*)malloc(h*w*c*sizeof(double));

    double temp;
    for(int i=0; i<h; i++){
        for(int j=0; j<w; j++){
            for(int k=0; k<c; k++){


                temp=(double(p_data[c*(w*i+j)+k])/255.0l)-alpha[w*i+j]*a[k];

                if(temp>0){
                    withoutA[c*(w*i+j)+k]=temp;
                } else{
                    withoutA[c*(w*i+j)+k]=0;
                }
            }
        }
    }


    double *gray=(double*)malloc(w*h*sizeof(double));
    double initMag=0.5;
    bool isNegative=true;

    while(isNegative){
            initMag+=0.1;
        isNegative=false;
        for(int i=0; i<h; i++){
            for(int j=0; j<w; j++){
                gray[w*i+j]=0;
                for(int k=0; k<c; k++){
                    temp=withoutA[c*(w*i+j)+k]/(1-alpha[w*i+j]/initMag);
                    isNegative=temp<0;
                    gray[w*i+j]+=temp*temp;
                }
                gray[w*i+j]=sqrt(gray[w*i+j]);

            }
        }
    }


    double *transmission=(double*)malloc(w*h*sizeof(double));
    for(int i=0; i<w*h; i++){
        transmission[i]=1-alpha[i]/initMag;
    }

    double alpha_min=transmission[0];
    double alpha_max=transmission[0];
    for(int i=1; i<w*h; i++){
        if(transmission[i]>alpha_max){
            alpha_max=transmission[i];
        } else if(transmission[i]<alpha_min){
            alpha_min=transmission[i];
        }

    }

    int numBins=50;
    double binW=(alpha_max-alpha_min)/(double)numBins;
    double mtrans[numBins+1];
    double mshading[numBins+1];
    mtrans[0]=alpha_min;
    mshading[0]=0;
    mtrans[numBins]=alpha_max;
    for(int i=1; i<numBins; i++){
        mtrans[i]=mtrans[i-1]+binW;
        mshading[i]=0;
    }

    double val;
    double *inBin=(double*)malloc(w*h*sizeof(double));
    int ind;

    for(int i=0; i<=numBins; i++){
        ind=0;
        val=mtrans[i]+binW/2.0;
        for(int j=0; j<w*h; j++){
            if(transmission[j]<val+binW/2.0 && transmission[j]>=val-binW/2.0){
                inBin[ind]=gray[j];
                ind++;
            }
        }
        if(ind>100){
            qsort(inBin, ind, sizeof(double), comp);
            mshading[i]=inBin[(int)(0.995*ind+0.5)-1];
        }
    }
    double ak[2];
    ak[0]=1;
    ak[1]=1;
    struct_fitError entrada;
    entrada.withoutA=withoutA;
    entrada.alpha=alpha;
    entrada.mshading=mshading;
    entrada.h=w;
    entrada.w=h;
    entrada.c=c;
    entrada.numBins=numBins;
    entrada.initMag=initMag;

    cout << " OPTIMIZATION " << endl;
    nlopt_opt opt;

    //algoritmos de minimização, nao sei qual e melhor..
    opt = nlopt_create(NLOPT_GN_DIRECT_L, 2);
    //opt = nlopt_create(NLOPT_GN_DIRECT, 2);
    //opt = nlopt_create(NLOPT_GN_CRS2_LM, 2);
    //opt = nlopt_create(NLOPT_GD_STOGO, 2);
    //opt = nlopt_create( NLOPT_GD_STOGO_RAND, 2);
    //opt = nlopt_create(NLOPT_GN_ISRES, 2);
    //opt = nlopt_create(NLOPT_GN_ESCH, 2);

    //valores maximos e minimos do espaço de busca, nao sei se 0 e 1 sao valores bons
    double lb[2]={0,0};
    double ub[2]={1,1};
    nlopt_set_lower_bounds(opt, lb);
    nlopt_set_upper_bounds(opt, ub);
    nlopt_set_min_objective(opt, fitError, &entrada);
    //acho que isso esta relacionado com a precisao, se aumentar o resultado fica ruim, se diminuir muito nao converge nunca
    nlopt_set_xtol_rel(opt, 1e-1);

    //numero maximo de iterações, pode ser que precise aumentar
    nlopt_set_maxeval(opt, 500);

    double minf;

    if (nlopt_optimize(opt, ak, &minf) < 0) {
            printf("nlopt failed!\n");
    }
    double mag=initMag/ak[0];
    free(alpha);
    free(gray);
    free(inBin);
    free(transmission);
    //printf("resultado final: %f %f %f\n", ak[0], ak[1], mag);
    return mag;

}
コード例 #18
0
void Fit2DPeaks(unsigned nPeaks, int NrPixelsThisRegion, double *z, int **UsefulPixels, double *MaximaValues,
				int **MaximaPositions, double *IntegratedIntensity, double *IMAX, double *YCEN, double *ZCEN, 
				double *RCens, double *EtaCens,double Ycen, double Zcen, double Thresh, int *NrPx,double *OtherInfo)
{
	unsigned n = 1 + (8*nPeaks);
	double x[n],xl[n],xu[n];
	x[0] = Thresh/2;
	xl[0] = 0;
	xu[0] = Thresh;
	int i;
	double *Rs, *Etas;
	Rs = malloc(NrPixelsThisRegion*2*sizeof(*Rs));
	Etas = malloc(NrPixelsThisRegion*2*sizeof(*Etas));
	for (i=0;i<NrPixelsThisRegion;i++){
		Rs[i] = CalcNorm2(UsefulPixels[i][0]-Ycen,UsefulPixels[i][1]-Zcen);
		Etas[i] = CalcEtaAngle(UsefulPixels[i][0]-Ycen,UsefulPixels[i][1]-Zcen);
	}
	double Width = sqrt(NrPixelsThisRegion/nPeaks);
	for (i=0;i<nPeaks;i++){
		x[(8*i)+1] = MaximaValues[i]; // Imax
		x[(8*i)+2] = CalcNorm2(MaximaPositions[i][0]-Ycen,MaximaPositions[i][1]-Zcen); //Radius
		x[(8*i)+3] = CalcEtaAngle(MaximaPositions[i][0]-Ycen,MaximaPositions[i][1]-Zcen); // Eta
		x[(8*i)+4] = 0.5; // Mu
		x[(8*i)+5] = Width; //SigmaGR
		x[(8*i)+6] = Width; //SigmaLR
		x[(8*i)+7] = atand(Width/x[(8*i)+2]); //SigmaGEta //0.5;
		x[(8*i)+8] = atand(Width/x[(8*i)+2]); //SigmaLEta //0.5;

		double dEta = rad2deg*atan(1/x[(8*i)+2]);
		xl[(8*i)+1] = MaximaValues[i]/2;
		xl[(8*i)+2] = x[(8*i)+2] - 1;
		xl[(8*i)+3] = x[(8*i)+3] - dEta;
		xl[(8*i)+4] = 0;
		xl[(8*i)+5] = 0.01;
		xl[(8*i)+6] = 0.01;
		xl[(8*i)+7] = 0.005;
		xl[(8*i)+8] = 0.005;

		xu[(8*i)+1] = MaximaValues[i]*2;
		xu[(8*i)+2] = x[(8*i)+2] + 1;
		xu[(8*i)+3] = x[(8*i)+3] + dEta;
		xu[(8*i)+4] = 1;
		xu[(8*i)+5] = 30;
		xu[(8*i)+6] = 30;
		xu[(8*i)+7] = 2;
		xu[(8*i)+8] = 2;
	}
	struct func_data f_data;
	f_data.NrPixels = NrPixelsThisRegion;
	f_data.Rs = &Rs[0];
	f_data.Etas = &Etas[0];
	f_data.z = &z[0];
	struct func_data *f_datat;
	f_datat = &f_data;
	void *trp = (struct func_data *)  f_datat;
	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LN_NELDERMEAD, n);
	nlopt_set_lower_bounds(opt, xl);
	nlopt_set_upper_bounds(opt, xu);
	nlopt_set_maxtime(opt, 300);
	nlopt_set_min_objective(opt, problem_function, trp);
	double minf;
	nlopt_optimize(opt, x, &minf);
	nlopt_destroy(opt);
	for (i=0;i<nPeaks;i++){
		IMAX[i] = x[(8*i)+1];
		RCens[i] = x[(8*i)+2];
		EtaCens[i] = x[(8*i)+3];
		if (x[(8*i)+5] > x[(8*i)+6]){
			OtherInfo[2*i] = x[(8*i)+5];
		}else{
			OtherInfo[2*i] = x[(8*i)+6];
		}
		if (x[(8*i)+7] > x[(8*i)+8]){
			OtherInfo[2*i+1] = x[(8*i)+7];
		}else{
			OtherInfo[2*i+1] = x[(8*i)+8];
		}
	}
	YZ4mREta(nPeaks,RCens,EtaCens,YCEN,ZCEN);
	CalcIntegratedIntensity(nPeaks,x,Rs,Etas,NrPixelsThisRegion,IntegratedIntensity,NrPx);
	free(Rs);
	free(Etas);
}
コード例 #19
0
int main(int argc, char *argv[])
{
     double XTOL = -1; /* to be set by "user" */
     int NHITS = -1;
     
     int c;
     while ((c = getopt(argc, argv, "N:t:")) != -1)
	  switch (c) {
	  case 'N':
	       NHITS = atoi(optarg);
	       break;
	  case 't':
	       XTOL = atof(optarg);
	       break;
	  case '?':
	       if (optopt == 'N' || optopt == 't')
		    fprintf(stderr, "Option -%c requires argument.\n", optopt);
	       else
		    fprintf(stderr, "unknown option -%c\n", optopt);
	       return 1;
	  default:
	       ;
	  }

     if (XTOL < 0 || NHITS < 0) {
	  fprintf(stderr, 
		  "please specify NHITS and XTOL with -N and -t\n");
	  return 1;
     }

     /* geometry like SNO+'s (as close to 9,000 PMTS as possible) */
     int NTHETA = 67;
     int NPHI = 134;
     struct pmtmap pmtmap;
     pmtmap.N = NPHI*NTHETA;
     pmtmap.nphi = NPHI;
     pmtmap.ntheta = NTHETA;


     struct event e1;

     struct pos_data data;
     data.p = &pmtmap;
     data.e = &e1;

     init_random();
     init_pmtmap(&data);

     make_event(&e1, NHITS);
     fill_pmt_info(&data);
     
     nlopt_opt opt;
     opt = nlopt_create(NLOPT_GN_ISRES, 3);
     double lb[3] = {-6, -6, -6};
     double ub[3] = {6, 6, 6};
     nlopt_set_lower_bounds(opt, lb);
     nlopt_set_upper_bounds(opt, ub);


     nlopt_set_min_objective(opt, mf_p, &data);
     double tols[3] = {XTOL, XTOL, XTOL};
     nlopt_set_xtol_abs(opt, tols);
     nlopt_set_maxtime(opt, 10.0); /* unstick this */
     nlopt_set_maxeval(opt, 4e5); /* if timing doesn't unstick it*/

     nlopt_add_inequality_constraint(opt, radius_check, &data, 1e-10);

     double x[3] = {0, 0, 0};
     double fval = mf_p(3, x, NULL, &data);

     nlopt_result ret;
     ret = nlopt_optimize(opt, x, &fval);

     if (ret > 0)
	  printf("%g %g %g\n", x[0] - e1.spawn_pos[0], 
		 x[1] - e1.spawn_pos[1],
		 x[2] - e1.spawn_pos[2]);
     else
	  fprintf(stderr, "optimizing failed with code %d\n", ret);

     return 0;
}
コード例 #20
0
ファイル: nloptcpp.cpp プロジェクト: bwiernik/OpenMx
void omxInvokeNLOPT(double *est, GradientOptimizerContext &goc)
{
	goc.optName = "SLSQP";
	goc.setupSimpleBounds();
	goc.useGradient = true;

	FitContext *fc = goc.fc;
	int oldWanted = fc->wanted;
	fc->wanted = 0;
	omxState *globalState = fc->state;
    
        nlopt_opt opt = nlopt_create(NLOPT_LD_SLSQP, fc->numParam);
	goc.extraData = opt;
        //local_opt = nlopt_create(NLOPT_LD_SLSQP, n); // Subsidiary algorithm
        
        //nlopt_set_local_optimizer(opt, local_opt);
        nlopt_set_lower_bounds(opt, goc.solLB.data());
        nlopt_set_upper_bounds(opt, goc.solUB.data());

	int eq, ieq;
	globalState->countNonlinearConstraints(eq, ieq);

	if (fc->CI) {
		nlopt_set_xtol_rel(opt, 5e-3);
		std::vector<double> tol(fc->numParam, std::numeric_limits<double>::epsilon());
		nlopt_set_xtol_abs(opt, tol.data());
	} else {
		// The *2 is there to roughly equate accuracy with NPSOL.
		nlopt_set_ftol_rel(opt, goc.ControlTolerance * 2);
		nlopt_set_ftol_abs(opt, std::numeric_limits<double>::epsilon());
	}
        
	nlopt_set_min_objective(opt, SLSQP::nloptObjectiveFunction, &goc);

	double feasibilityTolerance = Global->feasibilityTolerance;
	SLSQP::context ctx(goc);
        if (eq + ieq) {
		ctx.origeq = eq;
                if (ieq > 0){
			goc.inequality.resize(ieq);
			std::vector<double> tol(ieq, feasibilityTolerance);
			nlopt_add_inequality_mconstraint(opt, ieq, SLSQP::nloptInequalityFunction, &goc, tol.data());
                }
                
                if (eq > 0){
			goc.equality.resize(eq);
			std::vector<double> tol(eq, feasibilityTolerance);
			nlopt_add_equality_mconstraint(opt, eq, SLSQP::nloptEqualityFunction, &ctx, tol.data());
                }
	}
        
	int priorIterations = fc->iterations;

	int code = nlopt_optimize(opt, est, &fc->fit);
	if (ctx.eqredundent) {
		nlopt_remove_equality_constraints(opt);
		eq -= ctx.eqredundent;
		std::vector<double> tol(eq, feasibilityTolerance);
		nlopt_add_equality_mconstraint(opt, eq, SLSQP::nloptEqualityFunction, &ctx, tol.data());

		code = nlopt_optimize(opt, est, &fc->fit);
	}

	if (goc.verbose >= 2) mxLog("nlopt_optimize returned %d", code);

        nlopt_destroy(opt);

	fc->wanted = oldWanted;

	if (code == NLOPT_INVALID_ARGS) {
		Rf_error("NLOPT invoked with invalid arguments");
	} else if (code == NLOPT_OUT_OF_MEMORY) {
		Rf_error("NLOPT ran out of memory");
	} else if (code == NLOPT_FORCED_STOP) {
		if (fc->iterations - priorIterations <= 1) {
			goc.informOut = INFORM_STARTING_VALUES_INFEASIBLE;
		} else {
			goc.informOut = INFORM_ITERATION_LIMIT;
		}
	} else if (code == NLOPT_ROUNDOFF_LIMITED) {
		if (fc->iterations - priorIterations <= 2) {
			Rf_error("%s: Failed due to singular matrix E or C in LSQ subproblem or "
				 "rank-deficient equality constraint subproblem or "
				 "positive directional derivative in line search", goc.optName);
		} else {
			goc.informOut = INFORM_NOT_AT_OPTIMUM;  // is this correct? TODO
		}
	} else if (code < 0) {
		Rf_error("NLOPT fatal error %d", code);
	} else if (code == NLOPT_MAXEVAL_REACHED) {
		goc.informOut = INFORM_ITERATION_LIMIT;
	} else {
		goc.informOut = INFORM_CONVERGED_OPTIMUM;
	}
}
コード例 #21
0
int CNLopt::run(double (*error_func)(unsigned int nParams, const double* params, double* grad, void* misc))
{
	// Create a member function pointer

	unsigned int n_data = mWorkerThread->GetDataSize();
        mOpt = nlopt_create(mAlgorithm, mNParams);

	//	xopt = new double [mNParams];
	lb = new double [mNParams];
	ub = new double [mNParams];

	// Copy out the initial values for the parameters:
	CModelListPtr model_list = mWorkerThread->GetModelList();
	model_list->GetFreeParameters(mParams, mNParams, false);
	vector<string> names = model_list->GetFreeParamNames();
	vector< pair<double, double> > min_max = model_list->GetFreeParamMinMaxes();

	// Init parameter values
	for(int i = 0; i < mNParams; i++)
	{
		lb[i] = min_max[i].first;
		ub[i] = min_max[i].second;
		//	xopt = mParams[i];
	}

	nlopt_set_lower_bounds(mOpt,lb);
	nlopt_set_upper_bounds(mOpt,ub);

	nlopt_set_ftol_rel(mOpt, 1e-4); // stopping criterion = when chi2 changes by less than 0.1%
	nlopt_set_min_objective(mOpt, error_func, (void*)this);

	int major=0, minor=0, bugfix=0;
	nlopt_version(&major, &minor, &bugfix);
	printf("Starting NLopt version %d.%d.%d\n", major, minor, bugfix);
	printf("Algorithm = %s \n", nlopt_algorithm_name(mAlgorithm));


	if(mAlgorithm == NLOPT_G_MLSL_LDS) // set local optimizer to be used with a global search
	  {
	    printf("Secondary Algorithm = %s \n", nlopt_algorithm_name(mAlgorithmSecondary));
	    mOptSecondary = nlopt_create(mAlgorithmSecondary, mNParams);
	    nlopt_set_lower_bounds(mOptSecondary,lb);
	    nlopt_set_upper_bounds(mOptSecondary,ub);
	    nlopt_set_ftol_rel(mOptSecondary, 1e-4); // stopping criterion = when chi2 changes by less than 0.1%
	    nlopt_set_min_objective(mOptSecondary, error_func, (void*)this);
	    nlopt_set_local_optimizer(mOpt, mOptSecondary);
	  }

	mIsRunning = true;
	mEvals = 0;
	double minf;
	// Call NLopt.  Note, the results are saved in mParams upon completion.
	nlopt_result result = nlopt_optimize(mOpt, mParams, &minf);

	mIsRunning = false;
	printresult(mParams, mNParams, n_data, names, minf, result);

	delete(lb);
	delete(ub);

	nlopt_destroy(mOpt);
	if(mAlgorithm == NLOPT_G_MLSL_LDS) // also destroy local optimizer
	  {
	   nlopt_destroy(mOptSecondary);
	  }


	return mEvals;
}
コード例 #22
0
ファイル: minim.c プロジェクト: albertocbarrigon/maxdft
void minim_nlopt(density_t *ndft){

  nlopt_opt opt;
  double minf;
  int i, status;
  double *x;

  nlopt_function_data function_data;
  nlopt_par par;

  x  = (double *)malloc(ipf.npar*sizeof(double));
  for(i = 0; i < ipf.npar; i++) x[i] = gsl_vector_get(ipf.gamma, i);

  /* Here we choose the minimization method from NLOPT (check the
     avaible algorithms at
     http://ab-initio.mit.edu/wiki/index.php/NLopt_Algorithms)
     and specify the dimension of the problem */
  par.algorithm = 1;  parse_int("nlopt_algorithm", &par.algorithm);
  switch(par.algorithm){
  case 1 :
    opt = nlopt_create(NLOPT_LN_BOBYQA, ipf.npar);
    if(myid == 0)  printf("\n\n%s", nlopt_algorithm_name(NLOPT_LN_BOBYQA));
    break;
  case 2 :
    opt = nlopt_create(NLOPT_GN_DIRECT, ipf.npar);
    if(myid == 0)  printf("\n\n%s", nlopt_algorithm_name(NLOPT_GN_DIRECT));
    break;
  case 3 :
    opt = nlopt_create(NLOPT_GD_STOGO, ipf.npar);
    if(myid == 0)  printf("\n\n%s", nlopt_algorithm_name(NLOPT_GD_STOGO));
    break;
  case 4:
    opt = nlopt_create(NLOPT_GN_ESCH, ipf.npar);
    if(myid == 0)  printf("\n\n%s", nlopt_algorithm_name(NLOPT_GN_ESCH));
    break;
  default :
    if(myid == 0)  printf("\n\nWARNING: wrong choice for the NLOPT algorithm\nTHe optimization will start  with the default algorithm:");
    opt = nlopt_create(NLOPT_GN_DIRECT_L, ipf.npar);
    if(myid == 0)  printf("\n%s", nlopt_algorithm_name(NLOPT_GN_DIRECT_L));
    break;
  }

  nlopt_set_min_objective(opt, nlopt_gfunction, &function_data);

  par.rel_tol = 1e-4;  parse_double("nlopt_rel_tol", &par.rel_tol);
  nlopt_set_xtol_rel(opt, par.rel_tol);

  /* Set the lower and upper bounds of the optimization
     to a single constant lb or ub respectively */
  par.lb = -2.0;  parse_double("nlopt_lb", &par.lb);
  par.ub = 2.0;  parse_double("nlopt_ub", &par.ub);
  nlopt_set_lower_bounds1(opt, par.lb);
  nlopt_set_upper_bounds1(opt, par.ub);

  function_data.counter = 0;
  function_data.ndft = density_get_val(ndft);

  messages_basic("\n\n\nStarting the optimization.\n\n\n");

  if ((status = nlopt_optimize(opt, x, &minf)) <  0){
    if (myid == 0) printf("nlopt failed! status = %d\n", status);
    parallel_end(EXIT_FAILURE);
  }

  if(myid == 0) printf("Success. status = %d, iterations = %d, minf = %.12lg\n", status, function_data.counter, minf);
  if(myid == 0) {for(i = 0; i < ipf.npar; i++) printf("%.5f ", x[i]);}

  nlopt_destroy(opt);

  for(i = 0; i < ipf.npar; i++) gsl_vector_set(ipf.gamma, i, x[i]);
  ipf_write(ipf, ipf_ref, "pot");

  parallel_end(EXIT_SUCCESS);
}
コード例 #23
0
double Optimize_Torsion_Parameters(void)
{
	double lb[N_TOR_PARA] = { 
		-20.0, -PI, 
		-20.0, -PI, 
		-20.0, -PI, 
		-20.0, -PI, 
		-20.0, -PI, 
    -100 };
	double ub[N_TOR_PARA] = { 
		+20.0, +PI, 
		+20.0, +PI, 
		+20.0, +PI, 
		+20.0, +PI, 
		+20.0, +PI, 
    +100 };



//	double ub[N_TOR_PARA] = { 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0,  100.0 }; /* lower bounds */
	nlopt_opt opt;
	double Chi_SQ;
	int i, j;

	Chi_SQ_Min = 1.0E100;

	for(i=0; i<NRUN; i++)	{ // was 32
		ActiveRun = i;
		Chi_SQ_Min_Local[i] = 1.0E200;
		FailCount = Iteration = 0;

//		for(j=0; j<5; j++)	{
//			Para_Tor[2*j] = 0.1+1.0*rand(iseed);
//		}

		for( i=0; i<11; i++ ) { 
			Para_Tor[i]     = 0.; 
			IsPara_Fixed[i] = 0.;
		} // inital values		
		
		//opt = nlopt_create(NLOPT_LD_LBFGS, N_TOR_PARA);

    printf("=== Fitting ===\n" );
		opt = nlopt_create(NLOPT_LN_COBYLA, N_TOR_PARA);

		nlopt_set_lower_bounds(opt, lb);
		nlopt_set_upper_bounds(opt, ub);
		nlopt_set_min_objective(opt, Callback_Eval_Gradient, NULL);
		nlopt_set_xtol_rel(opt, 1e-8);

		if (nlopt_optimize(opt, Para_Tor, &Chi_SQ) < 0) {
			printf("nlopt didn't converge %lf %lf\n Please check carefully the rotamer results\n",Chi_SQ_Min, Chi_SQ);
		}
		else {
			printf("Chi_SQ_min = %lf  Chi_SQ = %lf\n", Chi_SQ_Min, Chi_SQ);
		}
		nlopt_destroy(opt);
	}

	memcpy(Para_Tor, Para_Best, sizeof(double)*N_TOR_PARA);
	CalObjectiveFunction_Tor(Para_Tor);



	return Chi_SQ_Min;
}
コード例 #24
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
     unsigned n;
     double *x, *x0, opt_f;
     nlopt_result ret;
     mxArray *x_mx, *mx;
     user_function_data d, dpre, *dfc = NULL, *dh = NULL;
     nlopt_opt opt = NULL;

     CHECK(nrhs == 2 && nlhs <= 3, "wrong number of arguments");

     /* options = prhs[0] */
     CHECK(mxIsStruct(prhs[0]), "opt must be a struct");
     
     /* x0 = prhs[1] */
     CHECK(mxIsDouble(prhs[1]) && !mxIsComplex(prhs[1])
	   && (mxGetM(prhs[1]) == 1 || mxGetN(prhs[1]) == 1),
	   "x must be real row or column vector");
     n = mxGetM(prhs[1]) * mxGetN(prhs[1]),
     x0 = mxGetPr(prhs[1]);

     CHECK(opt = make_opt(prhs[0], n), "error initializing nlopt options");

     d.neval = 0;
     d.verbose = (int) struct_val_default(prhs[0], "verbose", 0);
     d.opt = opt;

     /* function f = prhs[1] */
     mx = struct_funcval(prhs[0], "min_objective");
     if (!mx) mx = struct_funcval(prhs[0], "max_objective");
     CHECK(mx, "either opt.min_objective or opt.max_objective must exist");
     if (mxIsChar(mx)) {
	  CHECK(mxGetString(mx, d.f, FLEN) == 0,
		"error reading function name string (too long?)");
	  d.nrhs = 1;
	  d.xrhs = 0;
     }
     else {
	  d.prhs[0] = mx;
	  strcpy(d.f, "feval");
	  d.nrhs = 2;
	  d.xrhs = 1;
     }
     d.prhs[d.xrhs] = mxCreateDoubleMatrix(1, n, mxREAL);

     if ((mx = struct_funcval(prhs[0], "pre"))) {
	  CHECK(mxIsChar(mx) || mxIsFunctionHandle(mx),
		"pre must contain function handles or function names");
	  if (mxIsChar(mx)) {
	       CHECK(mxGetString(mx, dpre.f, FLEN) == 0,
                     "error reading function name string (too long?)");
	       dpre.nrhs = 2;
	       dpre.xrhs = 0;
	  }
	  else {
	       dpre.prhs[0] = mx;
	       strcpy(dpre.f, "feval");
	       dpre.nrhs = 3;
	       dpre.xrhs = 1;
	  }
	  dpre.verbose = d.verbose > 2;
	  dpre.opt = opt;
	  dpre.neval = 0;
	  dpre.prhs[dpre.xrhs] = d.prhs[d.xrhs];
	  dpre.prhs[d.xrhs+1] = mxCreateDoubleMatrix(1, n, mxREAL);
	  d.dpre = &dpre;

	  if (struct_funcval(prhs[0], "min_objective"))
	       nlopt_set_precond_min_objective(opt, user_function,user_pre,&d);
	  else
	       nlopt_set_precond_max_objective(opt, user_function,user_pre,&d);
     }
     else {
	  dpre.nrhs = 0;
	  if (struct_funcval(prhs[0], "min_objective"))
	       nlopt_set_min_objective(opt, user_function, &d);
	  else
	       nlopt_set_max_objective(opt, user_function, &d);
     }

     if ((mx = mxGetField(prhs[0], 0, "fc"))) {
	  int j, m;
	  double *fc_tol;
	  
	  CHECK(mxIsCell(mx), "fc must be a Cell array");
	  m = mxGetM(mx) * mxGetN(mx);;
	  dfc = (user_function_data *) mxCalloc(m, sizeof(user_function_data));
	  fc_tol = struct_arrval(prhs[0], "fc_tol", m, NULL);

	  for (j = 0; j < m; ++j) {
	       mxArray *fc = mxGetCell(mx, j);
	       CHECK(mxIsChar(fc) || mxIsFunctionHandle(fc),
		     "fc must contain function handles or function names");
	       if (mxIsChar(fc)) {
		    CHECK(mxGetString(fc, dfc[j].f, FLEN) == 0,
		     "error reading function name string (too long?)");
		    dfc[j].nrhs = 1;
		    dfc[j].xrhs = 0;
	       }
	       else {
		    dfc[j].prhs[0] = fc;
		    strcpy(dfc[j].f, "feval");
		    dfc[j].nrhs = 2;
		    dfc[j].xrhs = 1;
	       }
	       dfc[j].verbose = d.verbose > 1;
	       dfc[j].opt = opt;
	       dfc[j].neval = 0;
	       dfc[j].prhs[dfc[j].xrhs] = d.prhs[d.xrhs];
	       CHECK(nlopt_add_inequality_constraint(opt, user_function,
						     dfc + j,
						     fc_tol ? fc_tol[j] : 0)
		     > 0, "nlopt error adding inequality constraint");
	  }
     }


     if ((mx = mxGetField(prhs[0], 0, "h"))) {
	  int j, m;
	  double *h_tol;
	  
	  CHECK(mxIsCell(mx), "h must be a Cell array");
	  m = mxGetM(mx) * mxGetN(mx);;
	  dh = (user_function_data *) mxCalloc(m, sizeof(user_function_data));
	  h_tol = struct_arrval(prhs[0], "h_tol", m, NULL);

	  for (j = 0; j < m; ++j) {
	       mxArray *h = mxGetCell(mx, j);
	       CHECK(mxIsChar(h) || mxIsFunctionHandle(h),
		     "h must contain function handles or function names");
	       if (mxIsChar(h)) {
		    CHECK(mxGetString(h, dh[j].f, FLEN) == 0,
		     "error reading function name string (too long?)");
		    dh[j].nrhs = 1;
		    dh[j].xrhs = 0;
	       }
	       else {
		    dh[j].prhs[0] = h;
		    strcpy(dh[j].f, "feval");
		    dh[j].nrhs = 2;
		    dh[j].xrhs = 1;
	       }
	       dh[j].verbose = d.verbose > 1;
	       dh[j].opt = opt;
	       dh[j].neval = 0;
	       dh[j].prhs[dh[j].xrhs] = d.prhs[d.xrhs];
	       CHECK(nlopt_add_equality_constraint(opt, user_function,
						     dh + j,
						   h_tol ? h_tol[j] : 0)
		     > 0, "nlopt error adding equality constraint");
	  }
     }


     x_mx = mxCreateDoubleMatrix(mxGetM(prhs[1]), mxGetN(prhs[1]), mxREAL);
     x = mxGetPr(x_mx);
     memcpy(x, x0, sizeof(double) * n);

     ret = nlopt_optimize(opt, x, &opt_f);

     mxFree(dh);
     mxFree(dfc);
     mxDestroyArray(d.prhs[d.xrhs]);
     if (dpre.nrhs > 0) mxDestroyArray(dpre.prhs[d.xrhs+1]);
     nlopt_destroy(opt);

     plhs[0] = x_mx;
     if (nlhs > 1) {
	  plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
	  *(mxGetPr(plhs[1])) = opt_f;
     }
     if (nlhs > 2) {
	  plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
	  *(mxGetPr(plhs[2])) = (int) ret;
     }
}
コード例 #25
0
void
FitOrientation(
    const int NrOfFiles,
    const int nLayers,
    const double ExcludePoleAngle,
    double Lsd[nLayers],
    const long long int SizeObsSpots,
    const double XGrain[3],
    const double YGrain[3],
    double RotMatTilts[3][3],
    const double OmegaStart,
    const double OmegaStep,
    const double px,
    double ybc[nLayers],
    double zbc[nLayers],
    const double gs,
    double OmegaRanges[MAX_N_OMEGA_RANGES][2],
    const int NoOfOmegaRanges,
    double BoxSizes[MAX_N_OMEGA_RANGES][4],
    double P0[nLayers][3],
    const int NrPixelsGrid,
    int *ObsSpotsInfo,
    double EulerIn[3],
    double tol,
    double *EulerOutA,
    double *EulerOutB,
    double *EulerOutC,
    double *ResultFracOverlap,
    double hkls[5000][4],
    double Thetas[5000],
    int n_hkls)
{
	unsigned n;
    long int i,j;
    n  = 3;
    double x[n],xl[n],xu[n];
    for( i=0; i<n; i++)
    {
        x[i] = EulerIn[i];
        xl[i] = x[i] - (tol*M_PI/180);
        xu[i] = x[i] + (tol*M_PI/180);
    }
	struct my_func_data f_data;
	f_data.NrOfFiles = NrOfFiles;
	f_data.nLayers = nLayers;
	f_data.n_hkls = n_hkls;
	for (i=0;i<5000;i++){
		f_data.hkls[i][0] = hkls[i][0];
		f_data.hkls[i][1] = hkls[i][1];
		f_data.hkls[i][2] = hkls[i][2];
		f_data.hkls[i][3] = hkls[i][3];
		f_data.Thetas[i] = Thetas[i];
	}
	f_data.ExcludePoleAngle = ExcludePoleAngle;
	f_data.SizeObsSpots = SizeObsSpots;
	f_data.P0 = allocMatrixF(nLayers,3);
	for (i=0;i<3;i++){
		f_data.XGrain[i] = XGrain[i];
		f_data.YGrain[i] = YGrain[i];
		for (j=0;j<nLayers;j++){
			f_data.P0[j][i] = P0[j][i];
		}
		for (j=0;j<3;j++){
			f_data.RotMatTilts[i][j] = RotMatTilts[i][j];
		}
	}
	for (i=0;i<MAX_N_OMEGA_RANGES;i++){
		for (j=0;j<2;j++){
			f_data.OmegaRanges[i][j] = OmegaRanges[i][j];
		}
		for (j=0;j<4;j++){
			f_data.BoxSizes[i][j] = BoxSizes[i][j];
		}
	}
	f_data.ObsSpotsInfo = &ObsSpotsInfo[0];
	f_data.Lsd = &Lsd[0];
	f_data.ybc = &ybc[0];
	f_data.zbc = &zbc[0];
	f_data.OmegaStart = OmegaStart;
	f_data.OmegaStep = OmegaStep;
	f_data.px = px;
	f_data.gs = gs;
	f_data.NoOfOmegaRanges = NoOfOmegaRanges;
	f_data.NrPixelsGrid = NrPixelsGrid;
	struct my_func_data *f_datat;
	f_datat = &f_data;
	void* trp = (struct my_func_data *) f_datat;
	double tole = 1e-3;
	nlopt_opt opt;
	opt = nlopt_create(NLOPT_LN_NELDERMEAD, n);	
	nlopt_set_lower_bounds(opt, xl);
	nlopt_set_upper_bounds(opt, xu);
	nlopt_set_min_objective(opt, problem_function, trp);
	double minf=1;
	nlopt_optimize(opt, x, &minf);
	nlopt_destroy(opt);
    *ResultFracOverlap = minf;
    *EulerOutA = x[0];
    *EulerOutB = x[1];
    *EulerOutC = x[2];
}
コード例 #26
0
ファイル: 1d_rotamer_fitting.cpp プロジェクト: salotz/htmd
double Optimize_Torsion_Parameters(void)
{
	double lb[N_PARA_MAX], ub[N_PARA_MAX];
	double Chi_SQ;
	int i, j, Pos;

	n_Para = 10*n_Phi + 1;

	memset(Is_Para_Fixed, 0, sizeof(int)*n_Para);
//	memset(lb, 0, sizeof(double)*n_Para);
	lb[n_Phi*10] = -HUGE_VAL;
	for(i=0; i<n_Phi; i++)	{
		Pos = 10*i;
		for(j=0; j<10; j+=2)	{	// ten parameters
			lb[Pos+j] = -15.0;
			ub[Pos+j] = 15.0;
		}
		for(j=1; j<10; j+=2)	{	// ten parameters
			lb[Pos+j] = -M_PI;
			ub[Pos+j] = +M_PI;
		}

	}
	ub[n_Phi*10] = HUGE_VAL;


	opt = nlopt_create(NLOPT_LN_COBYLA, n_Para);

	nlopt_set_lower_bounds(opt, lb);
	nlopt_set_upper_bounds(opt, ub);
	nlopt_set_min_objective(opt, Callback_Eval_Gradient, NULL);
	nlopt_set_xtol_rel(opt, 1e-6);


	Collect_Torsion_Parameters();
	Assign_Torsion_Parameters();
	Cal_E_MM_Scaned();
	Cal_E_MM_Rotamer();
	Para_List[n_Phi*10] = E_Scan_QM_Mean-E_Scan_MM_Mean;	// energy shift
	E_Shift_0 = fabs(E_Scan_QM_Mean-E_Scan_MM_Mean);
	for(i=0; i<n_Phi; i++)	{
		Pos = 10*i;

		for(j=1; j<10; j+=2)	{	// the phase is fixed
			Is_Para_Fixed[Pos+j] = 1;
		}
	}

	Read_Parameters("saved-para.dat");

	Chi_SQ_Min = 1.0E100;
	memcpy(Para_Best, Para_List, sizeof(double)*n_Para);

	Chi_SQ = CalObjectiveFunction(Para_List, 0);
	if(ProgID == 0)	{
		fprintf(fFitting, "Iteration %4d  Chi^2 = %.8lf  Chi^2(1D) = %.8lf  Chi^2(rotamer) = %.8lf\n", 
			0, Chi_SQ, Chi_SQ_1D, Chi_SQ_Rotamer);
		fflush(fFitting);
	}

	FailCount = 0;
  int ret= nlopt_optimize(opt, Para_List, &Chi_SQ);
	if (ret < 0) {
		printf("nlopt failed! :%d\n", ret);
	}
	else {
		printf("Chi_SQ_min = %lf  Chi_SQ = %lf\n", Chi_SQ_Min, Chi_SQ);
	}


	memcpy(Para_List, Para_Best, sizeof(double)*n_Para);
	CalObjectiveFunction(Para_List, 1);

	nlopt_destroy(opt);

	return Chi_SQ_Min;
}
コード例 #27
0
int main(int argc, char *argv[]) {

    int opt=0, verb=0;
    int max_harm = 64, max_lag=0;
    int isub = 1;
    while ((opt=getopt(argc,argv,"hvI:H:L:"))!=-1) {
        switch (opt) {
            case 'v':
                verb++;
                break;
            case 'I':
                isub = atoi(optarg);
                break;
            case 'H':
                max_harm = atoi(optarg);
                break;
            case 'L':
                max_lag = atoi(optarg);
                break;
            case 'h':
                usage();
                exit(0);
                break;
        }
    }

    if (optind==argc) {
        usage();
        exit(1);
    }

    int i, rv;

    /* Open file */
    fitsfile *f;
    int status;
    fits_open_file(&f, argv[optind], READONLY, &status);
    fits_error_check_fatal();

    /* Get basic dims */
    struct cyclic_work w;
    cyclic_load_params(f, &w, &status);
    fits_error_check_fatal();
    if (verb) { 
        printf("Read nphase=%d npol=%d nchan=%d\n", 
                w.nphase, w.npol, w.nchan);
        fflush(stdout);
    }
    int orig_npol = w.npol;
    w.npol = 1;

    /* Init FFTs */
    fftwf_init_threads();
    fftwf_plan_with_nthreads(4);
    if (verb) { printf("Planning FFTs\n"); fflush(stdout); }
#define WF "/home/pdemores/share/cyclic_wisdom.dat"
    FILE *wf = fopen(WF,"r");
    if (wf!=NULL) { fftwf_import_wisdom_from_file(wf); fclose(wf); }
    rv = cyclic_init_ffts(&w);
    if (rv) {
        fprintf(stderr, "Error planning ffts (rv=%d)\n", rv);
        exit(1);
    }
    wf = fopen(WF,"w");
    if (wf!=NULL) { fftwf_export_wisdom_to_file(wf); fclose(wf); }

    /* Alloc some stuff */
    struct periodic_spectrum raw;
    struct cyclic_spectrum cs, model_cs;
    struct filter_time ht;
    struct filter_freq hf;
    struct profile_phase pp;
    struct profile_harm ph;

    raw.nphase = pp.nphase = w.nphase;
    raw.nchan = cs.nchan = hf.nchan = w.nchan;
    cs.nharm = ph.nharm =  w.nharm;
    ht.nlag = w.nlag;
    raw.npol = orig_npol;
    cs.npol = 1;

    model_cs.nchan = cs.nchan;
    model_cs.nharm = cs.nharm;
    model_cs.npol = cs.npol;

    cyclic_alloc_ps(&raw);
    cyclic_alloc_cs(&cs);
    cyclic_alloc_cs(&model_cs);
    filter_alloc_time(&ht);
    filter_alloc_freq(&hf);
    profile_alloc_phase(&pp);
    profile_alloc_harm(&ph);

#if 0  // XXX not implemented yet
    /* Check bounds */
    if (max_harm > w.nharm) { max_harm = w.nharm; }
    if (max_lag > w.nlag/2) { max_lag = w.nlag/2; }
    if (verb) {
        printf("Using max of %d harmonics and %d lags\n", max_harm, max_lag);
    }
#endif

    /* Load data */
    cyclic_load_ps(f, &raw, isub, &status);
    fits_error_check_fatal();

    /* Add polns w/o calibration */
    cyclic_pscrunch_ps(&raw, 1.0, 1.0);

    /* Initialize H, profile guesses */
    cyclic_fscrunch_ps(&pp, &raw);
    profile_phase2harm(&pp, &ph, &w);
    ht.data[0] = 1.0;
    for (i=1; i<ht.nlag; i++) { ht.data[i] = 0.0; }
    filter_profile_norm(&ht, &ph, w.nharm);
    profile_harm2phase(&ph, &pp, &w);

    /* convert input data to cyclic spectrum */
    cyclic_ps2cs(&raw, &cs, &w);

    /* could output initial profile */

    /* Fill in data struct for nlopt */
    struct cyclic_data cdata;
    cdata.cs = &cs;
    cdata.s0 = &ph;
    cdata.ht = &ht;
    cdata.model_cs = &model_cs;
    cdata.w = &w;

    /* Set up minimizer */
    const int dim = 2*(w.nharm-1) + 2*w.nlag; /* number of free params */
    printf("number of fit params = %d\n", dim);
    nlopt_opt op;
    op = nlopt_create(NLOPT_LN_COBYLA, dim);
    nlopt_set_min_objective(op, cyclic_ms_difference_nlopt, &cdata);
    nlopt_set_xtol_rel(op, 1e-4);

    /* Set up initial params */
    double *x = (double *)malloc(sizeof(double) * dim);
    double *xtmp = x;
    for (i=1; i<ph.nharm; i++) { 
        xtmp[0] = creal(ph.data[i]);
        xtmp[1] = cimag(ph.data[i]);
        xtmp += 2;
    }
    for (i=0; i<ht.nlag; i++) { 
        xtmp[0] = creal(ht.data[i]);
        xtmp[1] = cimag(ht.data[i]);
        xtmp += 2;
    }

    /* Run optimization */
    double min;
    if (nlopt_optimize(op, x, &min)) {
        fprintf(stderr, "nlopt_optimize failed\n");
        exit(1);
    }

    /* TODO: some kind of output */

    /* All done :) */
    nlopt_destroy(op);
    exit(0);
}
コード例 #28
0
void NloptOptimizationSolver<T>::solve ()
{
  START_LOG("solve()", "NloptOptimizationSolver");

  this->init ();

  unsigned int nlopt_size = this->system().solution->size();

  // We have to have an objective function
  libmesh_assert( this->objective_object );

  // Set routine for objective and (optionally) gradient evaluation
  {
    nlopt_result ierr =
      nlopt_set_min_objective(_opt,
                              __libmesh_nlopt_objective,
                              this);
    if (ierr < 0)
      libmesh_error_msg("NLopt failed to set min objective: " << ierr);
  }

  if (this->lower_and_upper_bounds_object)
    {
      // Need to actually compute the bounds vectors first
      this->lower_and_upper_bounds_object->lower_and_upper_bounds(this->system());

      std::vector<Real> nlopt_lb(nlopt_size);
      std::vector<Real> nlopt_ub(nlopt_size);
      for(unsigned int i=0; i<nlopt_size; i++)
        {
          nlopt_lb[i] = this->system().get_vector("lower_bounds")(i);
          nlopt_ub[i] = this->system().get_vector("upper_bounds")(i);
        }

      nlopt_set_lower_bounds(_opt, &nlopt_lb[0]);
      nlopt_set_upper_bounds(_opt, &nlopt_ub[0]);
    }

  // If we have an equality constraints object, tell NLopt about it.
  if (this->equality_constraints_object)
    {
      // NLopt requires a vector to specify the tolerance for each constraint.
      // NLopt makes a copy of this vector internally, so it's safe for us to
      // let it go out of scope.
      std::vector<double> equality_constraints_tolerances(this->system().C_eq->size(),
                                                          _constraints_tolerance);

      // It would be nice to call the C interface directly, at least it should return an error
      // code we could parse... unfortunately, there does not seem to be a way to extract
      // the underlying nlopt_opt object from the nlopt::opt class!
      nlopt_result ierr =
        nlopt_add_equality_mconstraint(_opt,
                                       equality_constraints_tolerances.size(),
                                       __libmesh_nlopt_equality_constraints,
                                       this,
                                       &equality_constraints_tolerances[0]);

      if (ierr < 0)
        libmesh_error_msg("NLopt failed to add equality constraint: " << ierr);
    }

  // If we have an inequality constraints object, tell NLopt about it.
  if (this->inequality_constraints_object)
    {
      // NLopt requires a vector to specify the tolerance for each constraint
      std::vector<double> inequality_constraints_tolerances(this->system().C_ineq->size(),
                                                            _constraints_tolerance);

      nlopt_add_inequality_mconstraint(_opt,
                                       inequality_constraints_tolerances.size(),
                                       __libmesh_nlopt_inequality_constraints,
                                       this,
                                       &inequality_constraints_tolerances[0]);
    }

  // Set a relative tolerance on the optimization parameters
  nlopt_set_ftol_rel(_opt, this->objective_function_relative_tolerance);

  // Set the maximum number of allowed objective function evaluations
  nlopt_set_maxeval(_opt, this->max_objective_function_evaluations);

  // Reset internal iteration counter
  this->_iteration_count = 0;

  // Perform the optimization
  std::vector<Real> x(nlopt_size);
  Real min_val = 0.;
  _result = nlopt_optimize(_opt, &x[0], &min_val);

  if (_result < 0)
    libMesh::out << "NLopt failed!" << std::endl;
  else
    libMesh::out << "NLopt obtained optimal value: "
                 << min_val
                 << " in "
                 << this->get_iteration_count()
                 << " iterations."
                 << std::endl;

  STOP_LOG("solve()", "NloptOptimizationSolver");
}
コード例 #29
0
double Geoometry_Optimization_With_Constraint(CMol *pMol)
{

	return (pMol->Cal_E(0));


	nlopt_opt opt, opt_AugLag;
	int Return_Opt, nAtom, nDim, i, iPos;
	double E_min, x[MAX_NUM_ATOM*3];

	Mol_ESP.Restrain_All_Torsions(1);	// apply soft restraints on all soft dihedrals

	nAtom = pMol->nAtom;
	nDim = 3 * nAtom;

	printf("\nMM before:\t");
	for(i=0; i<n_Phi; i++)	{
		printf("%3d %3d %3d %3d %8.4lf\n", DihList[i][0], DihList[i][1], DihList[i][2], DihList[i][3], 
			Mol_ESP.Query_Dihedral(DihList[i][0], DihList[i][1], DihList[i][2], DihList[i][3], 0, NULL));
	}

	double AUG_LAG_ICM_TOL = 1.0E-17;
	opt_AugLag = nlopt_create(NLOPT_LD_LBFGS_GEO, nDim);
	nlopt_set_min_objective(opt_AugLag, func_Geo_Opt_Constraint, pMol);

//	pMol->SavePdb("opt-free.pdb");

	for(i=0; i<pMol->nBond_Fixed; i++)	{
		int ret=0;
		pMol->Geo_Fix_r0[i].pMol = pMol;
		ret =nlopt_add_equality_constraint(opt_AugLag, Geo_Constraint_Bond, &(pMol->Geo_Fix_r0[i]), 2.0E-6);
		printf(" Fixing bond %d\n", i );
	}

	for(i=0; i<pMol->nAngle_Fixed; i++)	{
		int ret=0;
		pMol->Geo_Fix_theta0[i].pMol = pMol;
		ret=nlopt_add_equality_constraint(opt_AugLag, Geo_Constraint_Angle, &(pMol->Geo_Fix_theta0[i]), 2.0E-6);
		printf(" Fixing angle %d\n", i );
	}

	for(i=0; i<pMol->nPhi_Fixed; i++)	{
		int ret=0;
		pMol->Geo_Fix_phi0[i].pMol = pMol;
		ret=nlopt_add_equality_constraint(opt_AugLag, Geo_Constraint_Dihedral, &(pMol->Geo_Fix_phi0[i]), 2.0E-6);
		printf(" Fixing phi %d : %d\n", i, ret );
	}


	nlopt_set_xtol_rel(opt_AugLag, 2E-7);
	
	
//	opt = nlopt_create(NLOPT_LD_LBFGS_GEO, nDim);
//	opt = nlopt_create(NLOPT_LN_COBYLA, nDim);
//	nlopt_set_min_objective(opt, func_Geo_Opt_Constraint, pMol);
//	nlopt_set_xtol_rel(opt, 1E-7);

//	nlopt_set_local_optimizer(opt_AugLag, opt);
//	nlopt_destroy(opt);

	for(i=0; i<nAtom; i++)	{
		iPos = 3*i;
		x[iPos  ] = pMol->x[i];
		x[iPos+1] = pMol->y[i];
		x[iPos+2] = pMol->z[i];
	}
	
	Iter_Opt_Constrained = 0;
	Return_Opt = nlopt_optimize(opt_AugLag, x, &E_min);
	if (Return_Opt < 0) {
		printf("nlopt failed : %d\n", Return_Opt);
	}
//	else {
//		printf("After constrained optimization, E = %12.6lf\n", E_min);
//	}

	nlopt_destroy(opt_AugLag);

	printf("MM after:\t");
	for(i=0; i<n_Phi; i++)	{
		printf("%3d %3d %3d %3d %8.4lf\n", DihList[i][0], DihList[i][1], DihList[i][2], DihList[i][3], 
			Mol_ESP.Query_Dihedral(DihList[i][0], DihList[i][1], DihList[i][2], DihList[i][3], 0, NULL));
	}

	Mol_ESP.Restrain_All_Torsions(0);	// lift soft restraints on all soft dihedrals

	return (pMol->Cal_E(0));
}
コード例 #30
0
ファイル: 1d-fitting.cpp プロジェクト: mj-harvey/gaamp-local
double Optimize_Torsion_Parameters(void)
{
	double lb[N_TOR_PARA] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -100.0 }; /* lower bounds */
	double ub[N_TOR_PARA] = { 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0, 12.0,  100.0 }; /* lower bounds */

//	double ub[N_TOR_PARA] = { 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0,  100.0 }; /* lower bounds */
	double Phase[32][5]={{0, 0, 0, 0, 0}, {0, 0, 0, 0, PI}, {0, 0, 0, PI, 0}, {0, 0, 0, PI, PI}, {0, 0, PI, 0, 0}, {0, 0, PI, 0, PI}, {0, 0, PI, PI, 0}, {0, 0, PI, PI, PI}, {0, PI, 0, 0, 0}, {0, PI, 0, 0, PI}, 
						{0, PI, 0, PI, 0}, {0, PI, 0, PI, PI}, {0, PI, PI, 0, 0}, {0, PI, PI, 0, PI}, {0, PI, PI, PI, 0}, {0, PI, PI, PI, PI}, {PI, 0, 0, 0, 0}, {PI, 0, 0, 0, PI}, {PI, 0, 0, PI, 0}, {PI, 0, 0, PI, PI},
						{PI, 0, PI, 0, 0}, {PI, 0, PI, 0, PI}, {PI, 0, PI, PI, 0}, {PI, 0, PI, PI, PI}, {PI, PI, 0, 0, 0}, {PI, PI, 0, 0, PI}, {PI, PI, 0, PI, 0}, {PI, PI, 0, PI, PI}, {PI, PI, PI, 0, 0}, {PI, PI, PI, 0, PI}, 
						{PI, PI, PI, PI, 0}, {PI, PI, PI, PI, PI}};
	nlopt_opt opt;
	double Chi_SQ;
	int i, j;

	Chi_SQ_Min = 1.0E100;

	iseed = time(NULL);
	
	for(i=0; i<32; i++)	{
		ActiveRun = i;
		Chi_SQ_Min_Local[i] = 1.0E200;
		FailCount = Iteration = 0;

//		for(j=0; j<5; j++)	{
//			Para_Tor[2*j] = 0.1+1.0*rand(iseed);
//		}
		
		Para_Tor[0] = Para_Tor[2] = Para_Tor[4] = Para_Tor[6] = Para_Tor[8] = 1.0;


		for(j=0; j<5; j++)	{
			Para_Tor[2*j+1] = Phase[i][j];
			lb[2*j+1] = Para_Tor[2*j+1];
			ub[2*j+1] = Para_Tor[2*j+1];
		}
//		Para_Tor[1] = Para_Tor[3] = Para_Tor[5] = Para_Tor[7] = Para_Tor[9] = 0.0;
		Para_Tor[10] = 0.0;
		
		IsPara_Fixed[1] = IsPara_Fixed[3] = IsPara_Fixed[5] = IsPara_Fixed[7] = IsPara_Fixed[9] = 1;

		//for test
//		IsPara_Fixed[6] = 1;	Para_Tor[6] = 0.0;

		
		opt = nlopt_create(NLOPT_LD_LBFGS, N_TOR_PARA);

		nlopt_set_lower_bounds(opt, lb);
		nlopt_set_upper_bounds(opt, ub);
		nlopt_set_min_objective(opt, Callback_Eval_Gradient, NULL);
		nlopt_set_xtol_rel(opt, 1e-8);

		if (nlopt_optimize(opt, Para_Tor, &Chi_SQ) < 0) {
			printf("nlopt didn't converge %lf %lf\n Please check carefully the rotamer results\n",Chi_SQ_Min, Chi_SQ);
		}
		else {
			printf("Chi_SQ_min = %lf  Chi_SQ = %lf\n", Chi_SQ_Min, Chi_SQ);
		}
		nlopt_destroy(opt);
	}

	memcpy(Para_Tor, Para_Best, sizeof(double)*N_TOR_PARA);
	CalObjectiveFunction_Tor(Para_Tor);



	return Chi_SQ_Min;
}