void itsHybridEstimationOfDistribution::intensification()
{
  if ( getIntensificationMethod() == "simplex" ) {
    simplex();
  
  } else if ( getIntensificationMethod() == "selection" ) {
    selection();
  
  } else { // "selection-simplex"
    selection();
    simplex();
  }
}
Esempio n. 2
0
int main(int argc, char *argv[]) {

  double x1d[] = {-5.0}; // our initial guess
  double f_min1d = simplex(mycostfun1d, x1d, 1, 1e-8, 1, NULL, NULL);
  printf("f_min=%f\n", f_min1d);
  printf("x_min=%f\n", x1d[0]);

  double x2d[] = {-5.0, -5.0}; // our initial guess
  double f_min2d = simplex(mycostfun2d, x2d, 2, 1e-8, 1, NULL, NULL);
  printf("f_min=%f\n", f_min2d);
  printf("x_min=(%f,%f)\n", x2d[0], x2d[1]);

  return 0;
}
    void FittedBondDiscountCurve::FittingMethod::calculate() {

        FittingCost& costFunction = *costFunction_;
        Constraint constraint = NoConstraint();

        // start with the guess solution, if it exists
        Array x(size(), 0.0);
        if (!curve_->guessSolution_.empty()) {
            x = curve_->guessSolution_;
        }

        Simplex simplex(curve_->simplexLambda_);
        Problem problem(costFunction, constraint, x);

        Natural maxStationaryStateIterations = 100;
        Real rootEpsilon = curve_->accuracy_;
        Real functionEpsilon =  curve_->accuracy_;
        Real gradientNormEpsilon = curve_->accuracy_;

        EndCriteria endCriteria(curve_->maxEvaluations_,
                                maxStationaryStateIterations,
                                rootEpsilon,
                                functionEpsilon,
                                gradientNormEpsilon);

        simplex.minimize(problem,endCriteria);
        solution_ = problem.currentValue();

        numberOfIterations_ = problem.functionEvaluation();
        costValue_ = problem.functionValue();

        // save the results as the guess solution, in case of recalculation
        curve_->guessSolution_ = solution_;
    }
Esempio n. 4
0
int main(int argc, char *argv[]){
  if (argc > 1) { // usage: cmd datafile
    read_tableau(&tab, argv[1]);
  }
  print_tableau(&tab,"Initial");
  simplex(&tab);
  return 0;
}
Esempio n. 5
0
int tclFit(ClientData data,Tcl_Interp* interp,int argc, char *argv[])
{
  int i;
  int npar2;
  double val[512];
  double scal[512];
  int   used[512];
  char method[256];
  char *p,**pp,**pp2;

  if (argc != 2) {
    fprintf(stderr,"%s: specify array with parameters\n",argv[0]);
    return 1;
  }
  iter=0;
  strcpy(array,argv[1]);
  intrp = interp;

  TclGetString(interp,function,array,"function",1,"");

  TclGetString(interp,method,array,"fitmethod",0,"simplex");  
  
  p=Tcl_GetVar2(interp,array,"values",0);
  if (p == NULL)
    TclError(interp,"array must contain a variable 'values'");

  if (Tcl_SplitList(interp,p,&npar,&pp) != TCL_OK) {
    fprintf(stderr,"%s\n",interp->result);
    exit(1);
  }
  for (i=0;i<npar;i++) {
    if (Tcl_SplitList(interp,pp[i],&npar2,&pp2) != TCL_OK) {
      fprintf(stderr,"%s\n",interp->result);
      exit(1);
    }
    if (npar2 != 4)
       TclError(interp,"invalid number of parameters in 'values'"); 
    strcpy(name[i+1],pp2[0]);
    if (Tcl_GetDouble(interp,pp2[1],&val[i+1]) != TCL_OK)
       TclError(interp,"getdouble(1)");
    if (Tcl_GetDouble(interp,pp2[2],&scal[i+1]) != TCL_OK)
       TclError(interp,"getdouble(2)");    
    if (Tcl_GetInt(interp,pp2[3],&used[i+1]) != TCL_OK)
       TclError(interp,"getint(3)");
    free(pp2);
  }
  free(pp);
  if (!strcmp(method,"simplex")) {
    simplex(func,npar,used,val,scal);
  } else {
    return TclError(interp,"fit: unknown method '%s' (known method: simplex)",method);
  }
  return TCL_OK;
}
Esempio n. 6
0
TEST(MathFunctions, inverse_softmax) {
  std::vector<double> simplex(2);
  std::vector<double> y(2);
  
  simplex[0] = 0.2;
  simplex[1] = 0.8;

  stan::math::inverse_softmax(simplex, y);
  EXPECT_FLOAT_EQ(log(0.2), y[0]);
  EXPECT_FLOAT_EQ(log(0.8), y[1]);
}
Esempio n. 7
0
template<class T> Tuple<Vector<T,2>,Vector<T,3>> Triangle<Vector<T,2>>::
closest_point(const Vector<T,2>& location) const
{
    TV closest;
    Vector<T,3> weights = barycentric_coordinates(location);
    // project closest point to the triangle if it's not already inside it
    if(weights.x<0){
        T a23=interpolation_fraction(simplex(X[1],X[2]),location); // Check edge X[1]--X[2]
        if(a23<0){
            if(weights.z<0){ // Closest point is on edge X[0]--X[1]
                T a12=clamp<T>(interpolation_fraction(simplex(X[0],X[1]),location),0,1);weights=Vector<T,3>(1-a12,a12,0);closest=weights.x*X[0]+weights.y*X[1];}
            else{weights=Vector<T,3>(0,1,0);closest=X[1];}} // Closest point is X[1]
        else if(a23>1){
            if(weights.y<0){ // Closest point is on edge X[0]--X[2]
                T a13=clamp<T>(interpolation_fraction(simplex(X[0],X[2]),location),0,1);weights=Vector<T,3>(1-a13,0,a13);closest=weights.x*X[0]+weights.z*X[2];}
            else{weights=Vector<T,3>(0,0,1);closest=X[2];}} // Closest point is X[2]
        else{weights=Vector<T,3>(0,1-a23,a23);closest=weights.y*X[1]+weights.z*X[2];}} // Closest point is on edge X[1]--X[2]
    else if(weights.y<0){
        T a13=interpolation_fraction(simplex(X[0],X[2]),location); // Check edge X[0]--X[2]
        if(a13<0){
            if(weights.z<0){ // Closest point is on edge X[0]--X[1]
                T a12=clamp<T>(interpolation_fraction(simplex(X[0],X[1]),location),0,1);weights=Vector<T,3>(1-a12,a12,0);closest=weights.x*X[0]+weights.y*X[1];}
            else{weights=Vector<T,3>(1,0,0);closest=X[0];}} // Closest point is X[0]
        else if(a13>1){weights=Vector<T,3>(0,0,1);closest=X[2];} // Closest point is X[2]
        else{weights=Vector<T,3>(1-a13,0,a13);closest=weights.x*X[0]+weights.z*X[2];}} // Closest point is on edge X[0]--X[2]
    else if(weights.z<0){ // Closest point is on edge X[0]--X[1]
        T a12=clamp<T>(interpolation_fraction(simplex(X[0],X[1]),location),0,1);weights=Vector<T,3>(1-a12,a12,0);closest=weights.x*X[0]+weights.y*X[1];}
    else
        closest=weights.x*X[0]+weights.y*X[1]+weights.z*X[2]; // Point is interior to the triangle
    return tuple(closest,weights);
}
Esempio n. 8
0
int main()
{
  double start[] = {-1.2,1.0};
  double min;
  int i;
  
  min=simplex(rosen,start,2,1.0e-4,1);
  
  for (i=0;i<2;i++) {
    printf("%f\n",start[i]);
  }
  return 0;
}
Esempio n. 9
0
int MtxLP::Simplex(bool presolve){
    int rv;
    glp_smcp parm;
    init_smcp(&parm);
    parm.presolve = presolve;
    parm.msg_lev = msg_lev;
    parm.it_lim = it_lim;
    parm.tm_lim = tm_lim;
    rv = simplex(&parm);
    if (kind == EXACT)
        rv = exact(&parm);
    return rv;
}
Esempio n. 10
0
TEST(MathFunctions, softmax) {
  std::vector<double> x;
  x.push_back(1.0);
  x.push_back(-1.0);
  x.push_back(2.0);
  std::vector<double> simplex(3);
  stan::math::softmax<std::vector<double>,double>(x,simplex);
  EXPECT_FLOAT_EQ(1.0, simplex[0] + simplex[1] + simplex[2]);
  double sum = exp(1.0) + exp(-1.0) + exp(2.0);
  EXPECT_FLOAT_EQ(exp(1.0)/sum, simplex[0]);
  EXPECT_FLOAT_EQ(exp(-1.0)/sum, simplex[1]);
  EXPECT_FLOAT_EQ(exp(2.0)/sum, simplex[2]);
}
Esempio n. 11
0
void testSimplex3(){
 
 double **x;
 int n=2;
 
 x = allocateDoubleMatrix(n+1,n);
 x[0][0]=0.9; x[0][1]=0.9;
 x[1][0]=0.9; x[1][1]=1.1;
 x[2][0]=1.1; x[2][1]=0.9; 
 
 printf("\nSimplex\n");
 simplex(testFunctionSimplexFit,x,n);
 printf("%f %f\n",x[0][0],x[0][1]);

}
Esempio n. 12
0
TEST(MathFunctions, inverse_softmax_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();

  std::vector<double> simplex(2);
  std::vector<double> y(2);
  
  simplex[0] = nan;
  simplex[1] = nan;

  stan::math::inverse_softmax(simplex, y);
  EXPECT_PRED1(boost::math::isnan<double>,
               y[0]);

  EXPECT_PRED1(boost::math::isnan<double>,
               y[1]);
}
Esempio n. 13
0
TEST(MathFunctions, softmax_exception) {
  std::vector<double> x;
  x.push_back(1.0);
  x.push_back(-1.0);
  x.push_back(2.0);
  std::vector<double> simplex(2);
  
  // dl: EXPECT_THROW is not able to handle this templating
  //EXPECT_THROW(stan::math::softmax<std::vector<double>,double>(x,simplex), std::invalid_argument);
  try{
    stan::math::softmax<std::vector<double>,double>(x,simplex);
    FAIL();
  } catch (std::invalid_argument e) {
    SUCCEED();
  }
}
Esempio n. 14
0
int main(int argc, char * argv[]) {
	// parse command line arguments
	parse_args(argc, argv);
	// read lp
	int m, n;
	lp_t * p = read_bg_filename(filename, &m, &n);
	if (trace >= 7) write_bg(stdout, m, n, p);
	// solve lp
    timing_t timer;
    timer_start(&timer);
	unsigned int count = simplex(m, n, p);
    timer_stop(&timer);
    // print results
    if (trace == 8) write_bg(stdout, m, n, p);
    printf("%d %d %"lp_t_fmt1" %d %ld %ld\n", m, n, -p[0], count, timer.realtime, timer.cputime);
	return 0;
}
Esempio n. 15
0
/*
 * Jim Demmel's generic blocking theorem
 */
static void demmel_factors(unsigned int D, unsigned int N, float blocking[N], long (*strs[D])[N])
{
	float delta[D][N];

	for (unsigned int d = 0; d < D; d++)
		for (unsigned int n = 0; n < N; n++)
			delta[d][n] = (0 != (*strs[d])[n]) ? 1. : 0.;


	// now maximize 1^T x subject to Delta x <= 1
	// M^{x_n} yields blocking factors where M is cache size (maybe needs to be devided by D?)

	float ones[MAX(N, D)];
	for (unsigned int n = 0; n < MAX(N, D); n++)
		ones[n] = 1.;

	simplex(D, N, blocking, ones, ones, (const float (*)[N])delta);
}
Esempio n. 16
0
// the main program
//
int main(int argc, char *argv[]) {

  double x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  double y[] = {18, 5, 17, 38, 40, 106, 188, 234, 344, 484};

  optim_extras stuff;     // declare struct of extra stuff
  stuff.n = 10;           // x,y array length
  stuff.x = x;            // x data array
  stuff.y = y;            // y data array
  stuff.modfn = &e28mod;  // the address of the model function e28mod()

  double b[] = {.1,.1,.1,.1};                                   // our initial guess
  double f_min = simplex(e28cost, b, 4, 1e-8, 1, NULL, &stuff); // optimize!
  printf("f_min=%f\n", f_min);
  printf("x_min=(%f,%f,%f,%f)\n", b[0],b[1],b[2],b[3]);

  return 0;
}
Esempio n. 17
0
/*-------------------------------------------------------------------------*/
double minimize_global(double p[MAX_VARS], uint32 ndim,
			double limits[MAX_VARS][2],
			double tol, uint32 iter_limit,
			objective_func callback, 
			void *extra)
{
	uint32 i, j;
	double simp[MAX_VARS+1][MAX_VARS];
	double scores[MAX_VARS+1];
	double impulse, best_score;
	uint32 seed1 = 1111111;
	uint32 seed2 = 2222222;
	uint32 iter = 0;

	best_score = 1e100;

	for (i = 0; i < ndim + 1; i++) {
		for (j = 0; j < ndim; j++) {
			uint32 val = get_rand(&seed1, &seed2);
			simp[i][j] = limits[j][0] + 
				     (double)val / 4294967296.0 *
				     (limits[j][1] - limits[j][0]);
		}
		scores[i] = callback(simp[i], extra);
		if (scores[i] < best_score)
			best_score = scores[i];
	}

	impulse = best_score * 0.1;

	while (iter < iter_limit) {

		iter += 80;

		if (simplex(simp, scores, p, &best_score, 
			impulse, &seed1, &seed2, ndim, tol, 80,
			callback, extra) == 0)
			break;

		impulse *= 0.99;
	}

	return best_score;
}
Esempio n. 18
0
void testSimplex(){
 
 double **x;
 int n=2; 
 
 x = allocateDoubleMatrix(n+1,n);
 x[0][0]=0.0; x[0][1]=0.0;
 x[1][0]=1.2; x[1][1]=0.0;
 x[2][0]=0.0; x[2][1]=0.8; 
 
/* x[0][0]=-1.200000; x[0][1]=1.000000; 
 x[1][0]=-0.234074; x[1][1]=1.258819; 
 x[2][0]=-0.941181; x[2][1]=1.965926; */

 printf("\nSimplex\n");
 simplex(testFunctionSimplex,x,n);
 printf("%f %f\n",x[0][0],x[0][1]);

}
Esempio n. 19
0
int main()
{
    ifstream cin("lp.in");
    int i,j;    
    while( cin>>n>>m && !cin.fail() )
    {
        for(j=1; j<=n; j++) cin>>c[j]; cin>>ans; c[0]=0;
        for(i=1; i<=m; i++){ for(j=1; j<=n; j++) cin>>a[i][j]; cin>>rhs[i]; }
        switch( simplex(n, m, c, a, rhs, ans, x) )
        {
            case OPTIMAL :
                printf("OPTIMAL\n%10lf\n",ans); 
                for(j=1;j<=n;j++) printf("x[ %2d ] = %10lf\n",j,x[j]); 
                break;
            case UNBOUNDED :
                printf("UNBOUNDED\n");  break;
            case INFEASIBLE :
                printf("INFEASIBLE\n"); break;
        }   printf("\n");
    }
    return 0;
}
Esempio n. 20
0
void NelderMeadSolver::solve(const Function& function,
                             SolverResults* results) const
{
	double global_start_time = wall_time();

	// Dimension of problem.
	size_t n = function.get_number_of_scalars();

	if (n == 0) {
		results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
		return;
	}

	// The Nelder-Mead simplex.
	std::vector<SimplexPoint> simplex(n + 1);

	// Copy the user state to the current point.
	Eigen::VectorXd x;
	function.copy_user_to_global(&x);

	initialize_simplex(function, x, &simplex);

	SimplexPoint mean_point;
	SimplexPoint reflection_point;
	SimplexPoint expansion_point;
	mean_point.x.resize(n);
	reflection_point.x.resize(n);
	expansion_point.x.resize(n);

	double fmin  = std::numeric_limits<double>::quiet_NaN();
	double fmax  = std::numeric_limits<double>::quiet_NaN();
	double fval  = std::numeric_limits<double>::quiet_NaN();
	double area  = std::numeric_limits<double>::quiet_NaN();
	double area0 = std::numeric_limits<double>::quiet_NaN();
	double length  = std::numeric_limits<double>::quiet_NaN();
	double length0 = std::numeric_limits<double>::quiet_NaN();

	Eigen::MatrixXd area_mat(n, n);

	//
	// START MAIN ITERATION
	//
	results->startup_time   += wall_time() - global_start_time;
	results->exit_condition = SolverResults::INTERNAL_ERROR;
	int iter = 0;
	int n_shrink_in_a_row = 0;
	while (true) {

		//
		// In each iteration, the worst point in the simplex
		// is replaced with a new one.
		//
		double start_time = wall_time();

		mean_point.x.setZero();
		fval = 0;
		// Compute the mean of the best n points.
		for (size_t i = 0; i < n; ++i) {
			mean_point.x += simplex[i].x;
			fval         += simplex[i].value;
		}
		fval         /= double(n);
		mean_point.x /= double(n);
		fmin = simplex[0].value;
		fmax = simplex[n].value;

		const char* iteration_type = "n/a";

		// Compute the reflexion point and evaluate it.
		reflection_point.x = 2.0 * mean_point.x - simplex[n].x;
		reflection_point.value = function.evaluate(reflection_point.x);

		bool is_shrink = false;
		if (simplex[0].value <= reflection_point.value &&
			reflection_point.value < simplex[n - 1].value) {
			// Reflected point is neither better nor worst in the
			// new simplex.
			std::swap(reflection_point, simplex[n]);
			iteration_type = "Reflect 1";
		}
		else if (reflection_point.value < simplex[0].value) {
			// Reflected point is better than the current best; try
			// to go farther along this direction.

			// Compute expansion point.
			expansion_point.x = 3.0 * mean_point.x - 2.0 * simplex[n].x;
			expansion_point.value = function.evaluate(expansion_point.x);

			if (expansion_point.value < reflection_point.value) {
				std::swap(expansion_point, simplex[n]);
				iteration_type = "Expansion";
			}
			else {
				std::swap(reflection_point, simplex[n]);
				iteration_type = "Reflect 2";
			}
		}
		else {
			// Reflected point is still worse than x[n]; contract.
			bool success = false;

			if (simplex[n - 1].value <= reflection_point.value &&
			    reflection_point.value < simplex[n].value) {
				// Try to perform "outside" contraction.
				expansion_point.x = 1.5 * mean_point.x - 0.5 * simplex[n].x;
				expansion_point.value = function.evaluate(expansion_point.x);

				if (expansion_point.value <= reflection_point.value) {
					std::swap(expansion_point, simplex[n]);
					success = true;
					iteration_type = "Outside contraction";
				}
			}
			else {
				// Try to perform "inside" contraction.
				expansion_point.x = 0.5 * mean_point.x + 0.5 * simplex[n].x;
				expansion_point.value = function.evaluate(expansion_point.x);

				if (expansion_point.value < simplex[n].value) {
					std::swap(expansion_point, simplex[n]);
					success = true;
					iteration_type = "Inside contraction";
				}
			}

			if (! success) {
				// Neither outside nor inside contraction was acceptable;
				// shrink the simplex toward the best point.
				for (size_t i = 1; i < n + 1; ++i) {
					simplex[i].x = 0.5 * (simplex[0].x + simplex[i].x);
					simplex[i].value = function.evaluate(simplex[i].x);
					iteration_type = "Shrink";
					is_shrink = true;
				}
			}
		}

		std::sort(simplex.begin(), simplex.end());

		results->function_evaluation_time += wall_time() - start_time;

		//
		// Test stopping criteriea
		//
		start_time = wall_time();
		
		// Compute the area of the simplex.
		length = 0;
		for (size_t i = 0; i < n; ++i) {
			area_mat.col(i) = simplex[i].x - simplex[n].x;
			length = std::max(length, area_mat.col(i).norm());
		}
		area = std::abs(area_mat.determinant());
		if (iter == 0) {
			area0 = area;
			length0 = length;
		}

		if (area / area0 < this->area_tolerance) {
			results->exit_condition = SolverResults::GRADIENT_TOLERANCE;
			break;
		}

		if (area == 0) {
			results->exit_condition = SolverResults::GRADIENT_TOLERANCE;
			break;
		}

		if (length / length0 < this->length_tolerance) {
			results->exit_condition = SolverResults::GRADIENT_TOLERANCE;
			break;
		}

		if (is_shrink) {
			n_shrink_in_a_row++;
		}
		else {
			n_shrink_in_a_row = 0;
		}
		if (n_shrink_in_a_row > 50) {
			results->exit_condition = SolverResults::GRADIENT_TOLERANCE;
			break;
		}

		if (iter >= this->maximum_iterations) {
			results->exit_condition = SolverResults::NO_CONVERGENCE;
			break;
		}

		if (this->callback_function) {
			CallbackInformation information;
			information.objective_value = simplex[0].value;
			information.x = &simplex[0].x;

			if (!callback_function(information)) {
				results->exit_condition = SolverResults::USER_ABORT;
				break;
			}
		}
		results->stopping_criteria_time += wall_time() - start_time;

		//
		// Restarting
		//
		//if (area / area1 < 1e-10) {
		//	x = simplex[0].x;
		//	initialize_simplex(function, x, &simplex);
		//	area1 = area;
		//	if (this->log_function) {
		//		this->log_function("Restarted.");
		//	}
		//}

		//
		// Log the results of this iteration.
		//
		start_time = wall_time();

		int log_interval = 1;
		if (iter > 30) {
			log_interval = 10;
		}
		if (iter > 200) {
			log_interval = 100;
		}
		if (iter > 2000) {
			log_interval = 1000;
		}
		if (this->log_function && iter % log_interval == 0) {
			char str[1024];
				if (iter == 0) {
					this->log_function("Itr     min(f)     avg(f)     max(f)    area    length   type");
				}
				std::sprintf(str, "%6d %+.3e %+.3e %+.3e %.3e %.3e %s",
					iter, fmin, fval, fmax, area, length, iteration_type);
			this->log_function(str);
		}
		results->log_time += wall_time() - start_time;

		iter++;
	}

	// Return the best point as solution.
	function.copy_global_to_user(simplex[0].x);
	results->total_time += wall_time() - global_start_time;

	if (this->log_function) {
		char str[1024];
		std::sprintf(str, " end   %+.3e                       %.3e %.3e", fval, area, length);
		this->log_function(str);
	}
}
Esempio n. 21
0
int twoPhases(int rows, int new_columns, float new_tableau[rows][new_columns]) {

   int i,j;

   // Building artificial variables
   float objFunc[new_columns];

   for (j = 0; j < new_columns; j++) // saving the objective function
      objFunc[j] = new_tableau[0][j];

   for (j = 0; j < new_columns-rows+1; j++) // preparing the 1st row with zeros..
      new_tableau[0][j] = 0;

   for (j = new_columns-rows+1; j < new_columns; j++) // .. and ones
      new_tableau[0][j] = 1;

   i = 1;
   for (j = new_columns-rows+1; j < new_columns; j++) // identity matrix
         new_tableau[i++][j] = 1;

   // Print new_tableau
   printf("\n=== PRINT TABLEAU [ID MATRIX] ===\n");
   for (i = 0; i < rows; i++) {
      for (j = 0; j < new_columns; j++)
         printf("(%d,%d): %.3f\t", i, j, new_tableau[i][j]);
      printf("\n");
   }

   for (i = 1; i < rows; i++) // subtracting the other rows from 0th row 
      for (j = 0; j < new_columns; j++)
         new_tableau[0][j] = new_tableau[0][j] - new_tableau[i][j];

   // Print new_tableau
   printf("\n=== PRINT TABLEAU [1st PHASE] ===\n");
   for (i = 0; i < rows; i++) {
      for (j = 0; j < new_columns; j++)
         printf("(%d,%d): %.3f\t", i, j, new_tableau[i][j]);
      printf("\n");
   }

   /* === SIMPLEX PHASE 1 === */
   simplex(rows, new_columns, new_tableau);
   
   if(new_tableau[0][0] < 0 - EPSILON) {
      printf("[#] Unfeasible problem!\n\n");
      return 1;
   }
   else {
      for (j = 0; j < new_columns; j++)
         new_tableau[0][j] = objFunc[j];

      printf("\n=== PRINT TABLEAU [w -> z] ===\n");
      for (i = 0; i < rows; i++) {
         for (j = 0; j < new_columns-rows+1; j++)
            printf("(%d,%d): %.3f\t", i, j, new_tableau[i][j]);
         printf("\n");
      }

      // check for adjusting
      for (j = 1; j < new_columns-rows+1; j++)
          if(new_tableau[0][j] != 0)
             for (i = 1; i < rows; i++)
                 if (new_tableau[i][j] == 1)
                     pivot(i, j, rows, new_columns, new_tableau);
      return 0;
   }
}
Esempio n. 22
0
void decimate_inplace(MutableTriangleTopology& mesh, RawField<TV,VertexId> X,
                      const T distance, const T max_angle, const int min_vertices, const T boundary_distance) {
  if (mesh.n_vertices() <= min_vertices)
    return;
  const T area = sqr(distance);
  const T sign_sqr_min_cos = sign_sqr(max_angle > .99*pi ? -1 : cos(max_angle));

  // Finds the best edge to collapse v along.  Returns (q(e),dst(e)).
  const auto best_collapse = [&mesh,X](const VertexId v) {
    Quadric q = compute_quadric(mesh,X,v);

    // Find the best edge, ignoring normal constraints
    T min_q = inf;
    HalfedgeId min_e;
    for (const auto e : mesh.outgoing(v)) {
      const T qx = q(X[mesh.dst(e)]);
      if (min_q > qx) {
        min_q = qx;
        min_e = e;
      }
    }
    return tuple(min_q,mesh.dst(min_e));
  };

  // Initialize quadrics and heap
  Heap heap(mesh.n_vertices_);
  for (const auto v : mesh.vertices()) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.inv_heap[v] = heap.heap.append(tuple(v,qe.x,qe.y));
  }
  heap.make();

  // Update the quadric information for a vertex
  const auto update = [&heap,best_collapse,area](const VertexId v) {
    const auto qe = best_collapse(v);
    if (qe.x <= area)
      heap.set(v,qe.x,qe.y);
    else
      heap.erase(v);
  };

  // Repeatedly collapse the best vertex
  while (heap.size()) {
    const auto v = heap.pop();

    // Do these vertices still exist?
    if (mesh.valid(v.x) && mesh.valid(v.y)) {
      const auto e = mesh.halfedge(v.x,v.y);

      // Is the collapse invalid?
      if (e.valid() && mesh.is_collapse_safe(e)) {
        const auto vs = mesh.src(e),
                   vd = mesh.dst(e);
        const auto xs = X[vs],
                   xd = X[vd];

        // Are we moving a boundary vertex too far from its two boundary lines?
        {
          const auto b = mesh.halfedge(vs);
          if (mesh.is_boundary(b)) {
            const auto x0 = X[mesh.dst(b)],
                       x1 = X[mesh.src(mesh.prev(b))];
            if (   line_point_distance(simplex(xs,x0),xd) > boundary_distance
                || line_point_distance(simplex(xs,x1),xd) > boundary_distance)
              goto bad;
          }
        }

        // Do the normals change too much?
        if (sign_sqr_min_cos > -1)
          for (const auto ee : mesh.outgoing(vs))
            if (e!=ee && !mesh.is_boundary(ee)) {
              const auto v2 = mesh.opposite(ee);
              if (v2 != vd) {
                const auto x1 = X[mesh.dst(ee)],
                           x2 = X[v2];
                const auto n0 = cross(x2-x1,xs-x1),
                           n1 = cross(x2-x1,xd-x1);
                if (sign_sqr(dot(n0,n1)) < sign_sqr_min_cos*sqr_magnitude(n0)*sqr_magnitude(n1))
                  goto bad;
              }
            }

        // Collapse vs onto vd, then update the heap
        mesh.unsafe_collapse(e);
        if (mesh.n_vertices() <= min_vertices)
          break;
        update(vd);
        for (const auto e : mesh.outgoing(vd))
          update(mesh.dst(e));
      }
    }
    bad:;
  }
}
Esempio n. 23
0
OptimizerResult DeviceOptimizerAmoeba::optimize()
{
    // see algo at : https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
    assert(_pDevice!=0);

    double dMeritOrig=compute_demerit();
    OpticalDevice deviceOrig(*_pDevice);

    if(_parameters.empty())
        return eNothingToOptimize;

    // init simplex with the center of the definition domain
    vector<ParameterSet> simplex(_parameters.size()+1);
    {
        ParameterSet& param=simplex[0];
        param=_parameters;
        for(unsigned int i=0;i<_parameters.size();i++)
        {
            param[i].dValue=(param[i].dMin+param[i].dMax)*0.5;
        }
    }

    // then init simplex with the semi edge of the definition domain
    for(unsigned int i=1;i<simplex.size();i++)
    {
        ParameterSet& param=simplex[i];
        param=simplex[0];

        // expand the i-1 axis
        DeviceOptimizerParameter& paramToExpand=param[i-1];
        paramToExpand.dValue=paramToExpand.dValue+(paramToExpand.dMax-paramToExpand.dMin)/8.;
    }

    //compute solution at each param
    vector<double> vdDemerit(simplex.size());
    for(unsigned int i=0;i<simplex.size();i++)
    {
        apply_parameter(simplex[i]);
        vdDemerit[i]=compute_demerit();
    }

    int iIter=0,iMaxIter=AMOEBA_MAX_ITER;
    bool bStopCriteria=false;
    unsigned int iBest=0;
    double dBestMerit=vdDemerit[0];
    while((iIter<iMaxIter) && (bStopCriteria==false))
    {
        //get the best, worse and secondworse solution index
        dBestMerit=vdDemerit[0];
        iBest=0;
        int iWorse=0;
        double dWorse=vdDemerit[0];
        int iSecondWorse=0; (void)iSecondWorse;
        double dSecondWorse=vdDemerit[0];
        for(unsigned int i=1;i<simplex.size();i++)
        {
            if(vdDemerit[i]<dBestMerit)
            {
                iBest=i;
                dBestMerit=vdDemerit[i];
            }

            if(vdDemerit[i]>dWorse)
            {
                iWorse=i;
                dWorse=vdDemerit[i];
            }
        }
        //find the second worse
        for(unsigned int i=1;i<simplex.size();i++)
            if( ((int)i!=iWorse) && (vdDemerit[i]>dSecondWorse) )
            {
                //   iSecondWorse=i; //TODO not used?
                dSecondWorse=vdDemerit[i];
            }

        assert(dBestMerit<=dSecondWorse);
        assert(dSecondWorse<=dWorse);

        //search the best solution on the line (worse,mean)
        const ParameterSet& paramWorse=simplex[iWorse];

        //compute param mean
        ParameterSet paramMean=paramWorse;
        for(unsigned int i=0;i<paramMean.size();i++)
            paramMean[i].dValue=0.;
        for(unsigned int iS=0;iS<simplex.size();iS++)
        {
            if((int)iS==iWorse)
                continue;

            const ParameterSet& param=simplex[iS];
            for(unsigned int i=0;i<param.size();i++)
                paramMean[i].dValue+=param[i].dValue;
        }
        for(unsigned int i=0;i<paramMean.size();i++)
            paramMean[i].dValue/=simplex.size()-1.;

        bool bFound=false;

        //reflexion case
        ParameterSet paramMirror=paramMean;
        bool bOutOfDomain=false;
        for(unsigned int i=0;i<paramMirror.size();i++)
        {
            paramMirror[i].dValue+=(paramMean[i].dValue-paramWorse[i].dValue);
            if( (paramMirror[i].dValue<paramMirror[i].dMin ) || (paramMirror[i].dValue>paramMirror[i].dMax ) )
                bOutOfDomain=true;
        }

        double dMirror=SPOT_SIZE_INFINITY;
        if(!bOutOfDomain)
        {
            apply_parameter(paramMirror);
            dMirror=compute_demerit();
        }

        if( (dBestMerit<=dMirror) && (dMirror<dSecondWorse) )
        {
            //replace Worst by mirror
            simplex[iWorse]=paramMirror;
            vdDemerit[iWorse]=dMirror;
            bFound=true;
        }

        //expansion
        if(!bFound && (dMirror<dBestMerit))
        {
            //compute paramMirrorFar
            ParameterSet paramMirrorFar=paramMean;
            bool bOutOfDomain=false;
            for(unsigned int i=0;i<paramMirrorFar.size();i++)
            {
                paramMirrorFar[i].dValue+=2*(paramMirror[i].dValue-paramMean[i].dValue);
                if( (paramMirrorFar[i].dValue<paramMirrorFar[i].dMin ) || (paramMirrorFar[i].dValue>paramMirrorFar[i].dMax ) )
                    bOutOfDomain=true;
            }
            double dMirrorFar=SPOT_SIZE_INFINITY;
            if(!bOutOfDomain)
            {
                apply_parameter(paramMirrorFar);
                dMirrorFar=compute_demerit();
            }

            if(dMirrorFar<dBestMerit)
            {
                simplex[iWorse]=paramMirrorFar;
                vdDemerit[iWorse]=dMirrorFar;
                bFound=true;
            }
            else
            {
                simplex[iWorse]=paramMirror;
                vdDemerit[iWorse]=dMirror;
                bFound=true;
            }
        }

        //contraction
        if(!bFound)
        {
            assert(dMirror>=dSecondWorse);
            ParameterSet paramMirrorContracted=paramMean;
            for(unsigned int i=0;i<paramMirrorContracted.size();i++)
                paramMirrorContracted[i].dValue+=0.5*(paramWorse[i].dValue-paramMean[i].dValue);
            apply_parameter(paramMirrorContracted);
            double dContracted=compute_demerit();
            if(dContracted<dWorse)
            {
                simplex[iWorse]=paramMirrorContracted;
                vdDemerit[iWorse]=dContracted;
                bFound=true;
            }
        }

        //reduction
        if(!bFound)
        {
            for(unsigned int i=0;i<simplex.size();i++)
            {
                const ParameterSet& paramBest=simplex[iBest];
                if(i!=iBest)
                {
                    ParameterSet& paramReducted=simplex[i];
                    for(unsigned int j=0;j<paramReducted.size();j++)
                        paramReducted[j].dValue=paramBest[j].dValue+0.5*(paramReducted[j].dValue-paramBest[j].dValue);

                    apply_parameter(paramReducted);
                    vdDemerit[i]=compute_demerit();
                }
            }
            bFound=true; //  keep for debug
        }

        assert(bFound);

        //compute the parameter range
        // stop criteria based on the simplex size
        vector<double> vdMinParam(_parameters.size(),SPOT_SIZE_INFINITY);
        vector<double> vdMaxParam(_parameters.size(),-SPOT_SIZE_INFINITY);
        for(unsigned int i=0;i<simplex.size();i++)
        {
            const ParameterSet& param=simplex[i];
            for(unsigned int j=0;j<param.size();j++)
            {
                if(param[j].dValue<vdMinParam[j])
                    vdMinParam[j]=param[j].dValue;
                if(param[j].dValue>vdMaxParam[j])
                    vdMaxParam[j]=param[j].dValue;
            }
        }

        bStopCriteria=true;
        for(unsigned int i=0;i<vdMinParam.size();i++)
        {
            if(vdMaxParam[i]-vdMinParam[i]>_parameters[i].dResolution)
                bStopCriteria=false;
        }

        iIter++;
    }

    if(dBestMerit<SPOT_SIZE_INFINITY/2)
    {
        if( (dBestMerit<dMeritOrig) && (iIter>=0) )
        {
            _parameters=simplex[iBest];
            apply_parameter(_parameters);
            return eBetterSolutionFound;
        }
    }
    //restore device original settings
    *_pDevice=deviceOrig;
    return eNoBetterSolution;
}
Esempio n. 24
0
  double Basic_MCT2_332_Calculator::mct2_332_Sq(const LorentzTransverseVector& visA,
					       const LorentzTransverseVector& visB,
					       const TwoVector& ptmiss,
					       const double mEachInvisible){


    mCT2Fcn theFCN(ptmiss.px(),
	 	   ptmiss.py(),
		   mEachInvisible,
		   visA.px(),
		   visA.py(),
		   visA.mass(),
		   visB.px(),
		   visB.py(),
		   visB.mass());

    const double massScale = (
			      ptmiss.pt() +
			      mEachInvisible +
			      visA.pt()  +
			      visA.mass() +
			      visB.pt() +
			      visB.mass()
			      )/6.0;
    // DANG! Try to get rid of Minuit output:
    //std::ofstream    DANG_log("/dev/null");
    //std::streambuf * DANG_save = std::cerr.rdbuf();
    //if (DANG_log.is_open()) {
    //  std::cerr.rdbuf(DANG_log.rdbuf());
    // }

    double guessx = 0.5*(ptmiss.px());
    double guessy = 0.5*(ptmiss.py());
    
    MnUserParameters upar;
    upar.Add("etx", guessx, 0.02*massScale); 
    upar.Add("ety", guessy, 0.02*massScale);
    const int highQuality=2;    

    // Usually migrad produces the best minumum.
    // But when the minimum is in a fold, migrad can fail badly.
    // On the fold, simplex does well.  We therefore do both separately
    // and record the answer of the one that did best.
    
    // Further to the above notes, it now seems that by choosing the massScale sensibly, and by making the "tolerance" (the second argument to the call that extracts the FunctionMinimum below) much smaller, the simplex algorithm seems to work so well that we don't need the migrad algorithm.  This is good news, as the migrad algorithm produces lots of error output that we can't get rid of.

    MnSimplex simplex(theFCN, upar, highQuality);
    FunctionMinimum minS = simplex(0,massScale*0.000001);
    //const double etxAtMin = minS.UserState().Value("etx");
    //const double etyAtMin = minS.UserState().Value("ety");
    //MnMigrad migrad(theFCN, upar, highQuality);
    //FunctionMinimum minM = migrad(0,massScale*0.000001);
    //const double best = fmin(minS.Fval(), minM.Fval());
    const double best = minS.Fval();

    // DANG! Undoing our attempt to get rid of Minuit output:
    //if (DANG_log.is_open()) {
    //  std::cerr.rdbuf(DANG_save);
    //}

    return best;    
  }
Esempio n. 25
0
int main(int argc, char** argv) {
        sf::RenderWindow* RenderWin = new sf::RenderWindow(sf::VideoMode(WIDTH, HEIGHT, 32), "lol test");
        RenderWin->UseVerticalSync(true);

        // Collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration.
		boost::shared_ptr<btDefaultCollisionConfiguration> collisionConfiguration(new btDefaultCollisionConfiguration());

        // Use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded).
		boost::shared_ptr<btCollisionDispatcher> dispatcher(new btCollisionDispatcher(collisionConfiguration.get()));

        // btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep.
		boost::shared_ptr<btBroadphaseInterface> broadphase(new btDbvtBroadphase());

        // The default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded).

		boost::shared_ptr<btVoronoiSimplexSolver> simplex(new btVoronoiSimplexSolver());
		boost::shared_ptr<btMinkowskiPenetrationDepthSolver> pd_solver(new btMinkowskiPenetrationDepthSolver());
		boost::shared_ptr<btSequentialImpulseConstraintSolver> solver(new btSequentialImpulseConstraintSolver());

		boost::shared_ptr<btDiscreteDynamicsWorld> dynamicsWorld(new btDiscreteDynamicsWorld(dispatcher.get(), broadphase.get(), solver.get(), collisionConfiguration.get()));

		boost::shared_ptr<btConvex2dConvex2dAlgorithm::CreateFunc> convex_algo_2d(new btConvex2dConvex2dAlgorithm::CreateFunc(simplex.get(),pd_solver.get()));
		
		dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get());
		dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get());
		dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get());
		dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE, new btBox2dBox2dCollisionAlgorithm::CreateFunc());

        // Set gravity to 9.8m/s² along y-axis.
        dynamicsWorld->setGravity(btVector3(0, 1, 0));

        // Get us some debug output. Without this, we'd see nothing at all.
		boost::shared_ptr<DebugDraw> debugDraw(new DebugDraw(RenderWin));
        debugDraw->setDebugMode(btIDebugDraw::DBG_DrawWireframe);

        dynamicsWorld->setDebugDrawer(debugDraw.get());

        // Keep track of the shapes, we release memory at exit.
        // Make sure to re-use collision shapes among rigid bodies whenever possible!
        btAlignedObjectArray<btCollisionShape*> collisionShapes;

        // Create a ground body.
        btScalar thickness(0.2);
		boost::shared_ptr<btCollisionShape> groundShape(new btBoxShape(btVector3(btScalar(WIDTH / 2 * METERS_PER_PIXEL), thickness, btScalar(10))));
        collisionShapes.push_back(groundShape.get());
        btTransform groundTransform(btQuaternion(0, 0, 0, 1), btVector3(WIDTH / 2 * METERS_PER_PIXEL, HEIGHT * METERS_PER_PIXEL, 0));
        // Using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects.
		boost::shared_ptr<btDefaultMotionState> groundMotionState(new btDefaultMotionState(groundTransform));
        btRigidBody::btRigidBodyConstructionInfo ground_rbInfo(0, groundMotionState.get(), groundShape.get(), btVector3(0, 0, 0));
		boost::shared_ptr<btRigidBody> ground_body(new btRigidBody(ground_rbInfo));
		ground_body->setLinearFactor(btVector3(1,1,0));
		ground_body->setAngularFactor(btVector3(0,0,1));
        // Add the body to the dynamics world.
        dynamicsWorld->addRigidBody(ground_body.get());

        // Create left wall.
        btTransform leftWallTransform(btQuaternion(0, 0, 1, 1), btVector3(0, HEIGHT / 2 * METERS_PER_PIXEL, 0));
		boost::shared_ptr<btDefaultMotionState> leftWallMotionState(new btDefaultMotionState(leftWallTransform));
        btRigidBody::btRigidBodyConstructionInfo leftWall_rbInfo(0, leftWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0));
		boost::shared_ptr<btRigidBody> leftwall_body(new btRigidBody(leftWall_rbInfo));
		leftwall_body->setLinearFactor(btVector3(1,1,0));
		leftwall_body->setAngularFactor(btVector3(0,0,1));
        // Add the body to the dynamics world.
        dynamicsWorld->addRigidBody(leftwall_body.get());

        // Create right wall.
        btTransform rightWallTransform(btQuaternion(0, 0, 1, 1), btVector3(WIDTH * METERS_PER_PIXEL, HEIGHT / 2 * METERS_PER_PIXEL, 0));
		boost::shared_ptr<btDefaultMotionState> rightWallMotionState(new btDefaultMotionState(rightWallTransform));
        btRigidBody::btRigidBodyConstructionInfo rightWall_rbInfo(0, rightWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0));
		boost::shared_ptr<btRigidBody> rightwall_body(new btRigidBody(rightWall_rbInfo));
		rightwall_body->setLinearFactor(btVector3(1,1,0));
		rightwall_body->setAngularFactor(btVector3(0,0,1));
        // Add the body to the dynamics world.
        dynamicsWorld->addRigidBody(rightwall_body.get());

        // Create ceiling
        btTransform topWallTransform(btQuaternion(0, 0, 0, 1), btVector3(WIDTH / 2 * METERS_PER_PIXEL, 0, 0));
		boost::shared_ptr<btDefaultMotionState> topWallMotionState(new btDefaultMotionState(topWallTransform));
        btRigidBody::btRigidBodyConstructionInfo topWall_rbInfo(0, topWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0));
		boost::shared_ptr<btRigidBody> topwall_body(new btRigidBody(topWall_rbInfo));
		topwall_body->setLinearFactor(btVector3(1,1,0));
		topwall_body->setAngularFactor(btVector3(0,0,1));
        // Add the body to the dynamics world.
        dynamicsWorld->addRigidBody(topwall_body.get());


        // Create dynamic rigid body.

        //btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1));
		boost::shared_ptr<btCollisionShape> colShape(new btSphereShape(btScalar(0.6)));
        collisionShapes.push_back(colShape.get());

        /// Create Dynamic Objects
        btTransform startTransform;
        startTransform.setIdentity();

        btScalar mass(1.f);

        //rigidbody is dynamic if and only if mass is non zero, otherwise static
        bool isDynamic = (mass != 0.f);

        btVector3 localInertia(0, 0, 0);
        if (isDynamic)
                colShape->calculateLocalInertia(mass,localInertia);

        startTransform.setOrigin(btVector3(2, 5, 0));

        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
		boost::shared_ptr<btDefaultMotionState> myMotionState(new btDefaultMotionState(startTransform));
        btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState.get(),colShape.get(),localInertia);
		boost::shared_ptr<btRigidBody> body(new btRigidBody(rbInfo));
		body->setLinearFactor(btVector3(1,1,0));
		body->setAngularFactor(btVector3(0,0,1));

        dynamicsWorld->addRigidBody(body.get());

		// Create lulz
		boost::ptr_list<btRigidBody> body_list;
		boost::ptr_list<btDefaultMotionState> motionstate_list;
		boost::ptr_list<btCollisionShape> colshape_list;
		for (int i=0;i <= 10; ++i) {
			if (i < 5)
				colshape_list.push_back(new btSphereShape(btScalar(sf::Randomizer::Random(0.1f, 0.8f))));
			else
				colshape_list.push_back(new btBoxShape(btVector3(sf::Randomizer::Random(0.1f,0.8f), sf::Randomizer::Random(0.1f,0.8f), 10)));
			if (isDynamic)
                colshape_list.back().calculateLocalInertia(mass,localInertia);
			collisionShapes.push_back(&(colshape_list.back()));
			startTransform.setIdentity();
			startTransform.setOrigin(btVector3(i,i,0));
			motionstate_list.push_back(new btDefaultMotionState(startTransform));
			btRigidBody* lol = new btRigidBody(btRigidBody::btRigidBodyConstructionInfo(mass,&(motionstate_list.back()),&(colshape_list.back()),localInertia));
			lol->setLinearFactor(btVector3(1,1,0));
			lol->setAngularFactor(btVector3(0,0,1));
            body_list.push_back(lol);
		}
		BOOST_FOREACH (btRigidBody& body, body_list) {
			dynamicsWorld->addRigidBody(&body);
		}
Esempio n. 26
0
main()
{
    int i, j, n, m1, m2, m3, ixr[9], ixc[9];
    double eps = 1.0e-10;
    double a[8][10] = {{0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0},
        {0.5, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0},
        {0.5, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0},
        {0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0},
        {0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0},
        {0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0},
        {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}
    };

    n = 9;
    m1 = 5;
    m2 = 1;
    m3 = 0;

    i = simplex(a, n, m1, m2, m3, ixr, ixc, eps);        /* 调用函数*/
    printf("aaa:: %d\n", i);

    for (j = 1; j <= n; j++) {                        /* 提取出值为0的x标号*/
        if (ixr[j] < n) {
            printf("x%d = 0.00\n", ixr[j]);
        }
    }

    for (i = 1; i <= n; i++) {                       /* 提取出值不为0的x标号*/
        if (ixc[i] < n) {
            printf("x%d =%5.2f\n", ixc[i], a[i][0]);
        }
    }

    printf("fopt = %5.2f\n", a[0][0]);                /* 函数的极小值*/
    printf("\nlast simplex:\n");                      /* 打印最终的单纯形表*/
    printf("      b    ");

    for (j = 1; j < 9; j++) {
        if (ixr[j] < n + m1 + m2) {                  /* 跳过辅助问题的变量z*/
            printf("x%d    ", ixr[j]);
        }
    }

    printf("\n");
    printf("f  ");

    for (j = 0; j < 9; j++) {
        if (ixr[j] < n + m1 + m2) {                  /* 跳过辅助问题的变量z*/
            printf("%5.2f ", a[0][j]);
        }
    }

    printf("\n");

    for (i = 1; i < 7; i++) {
        printf("x%d ", ixc[i]);                      /* 本行对应的变量标号*/

        for (j = 0; j < 9; j++) {
            if (ixr[j] < n + m1 + m2) {              /* 跳过辅助问题的变量z*/
                printf("%5.2f ", a[i][j]);
            }
        }

        printf("\n");
    }

}
Esempio n. 27
0
TEST(MathFunctions, inverse_softmax_exception) {
  std::vector<double> simplex(2);
  std::vector<double> y(3);
  EXPECT_THROW(stan::math::inverse_softmax< std::vector<double> >(simplex, y), 
               std::invalid_argument);
}
int main(int argc, char *argv[])
{
    char ch;
    char str[STR_BUFFSIZE];

    char plom_help_string[] =
        "PLOM ksimplex\n"
        "usage:\n"
        "ksimplex [implementation] [--no_dem_sto] [--no_white_noise] [--no_diff]\n"
        "                          [-s, --DT <float>] [--eps_abs <float>] [--eps_rel <float>]\n"
        "                          [-p, --path <path>] [-i, --id <integer>]\n"
        "                          [-g, --freeze_forcing <float>]\n"
        "                          [--prior] [--transf]\n"
        "                          [-l, --LIKE_MIN <float>] [-S, --size <float>] [-M, --iter <integer>]\n"
	"                          [-q, --quiet] [-P, --pipe]"
        "                          [-h, --help]\n"
        "where implementation is 'sde' (default)\n"
        "options:\n"
	"\n"
        "-q, --quiet          no verbosity\n"
        "-P, --pipe           pipe mode (echo theta.json on stdout)\n"
	"\n"
        "--no_dem_sto       turn off demographic stochasticity (if possible)\n"
        "--no_white_noise       turn off environmental stochasticity (if any)\n"
        "--no_diff         turn off drift (if any)\n"
	"\n"
        "-s, --DT           Initial integration time step\n"
	"--eps_abs          Absolute error for adaptive step-size control\n"
	"--eps_rel          Relative error for adaptive step-size control\n"
        "-g, --freeze_forcing  freeze the metadata to their value at the specified time\n"
	"\n"
        "--prior            to maximize posterior density in natural space\n"
        "--transf           to maximize posterior density in transformed space (if combined with --prior)\n"
        "-p, --path         path where the outputs will be stored\n"
        "-i, --id           general id (unique integer identifier that will be appended to the output files)\n"
        "-l, --LIKE_MIN     particles with likelihood smaller that LIKE_MIN are considered lost\n"
        "-M, --iter         maximum number of iterations\n"
        "-S, --size         simplex size used as a stopping criteria\n"
        "-b, --no_traces    do not write the traces\n"
	"-o, --nb_obs       number of observations to be fitted (for tempering)"
        "--help             print the usage on stdout\n";

    // simplex options
    M = 10;
    CONVERGENCE_STOP_SIMPLEX = 1e-6;

    // general options
    GENERAL_ID =0;
    snprintf(SFR_PATH, STR_BUFFSIZE, "%s", DEFAULT_PATH);
    J=1;
    LIKE_MIN = 1e-17;
    LOG_LIKE_MIN = log(1e-17);
    int nb_obs = -1;
    double freeze_forcing = -1.0;

    // options
    OPTION_PRIOR = 0;
    OPTION_TRANSF = 0;

    double dt = 0.0, eps_abs = PLOM_EPS_ABS, eps_rel = PLOM_EPS_REL;

    enum plom_print print_opt = PLOM_PRINT_BEST;

    enum plom_implementations implementation;
    enum plom_noises_off noises_off = 0;


    static struct option long_options[] = {
        {"help",       no_argument,       0, 'h'},
        {"no_trace",   no_argument,  0, 'b'},

	{"no_dem_sto", no_argument,       0, 'x'},
	{"no_white_noise", no_argument,       0, 'y'},
	{"no_diff",   no_argument,       0, 'z'},


	{"DT",         required_argument, 0, 's'},
	{"eps_abs",    required_argument, 0, 'v'},
	{"eps_rel",    required_argument, 0, 'w'},

	{"freeze_forcing", required_argument, 0, 'g'},

        {"path",       required_argument, 0, 'p'},
        {"id",         required_argument, 0, 'i'},

        {"prior",  no_argument, &OPTION_PRIOR,  1},
        {"transf", no_argument, &OPTION_TRANSF, 1},

        {"LIKE_MIN", required_argument, 0, 'l'},
        {"iter",     required_argument,   0, 'M'},
        {"size",     required_argument,   0, 'S'},
	{"nb_obs", required_argument,  0, 'o'},

	{"quiet",  no_argument,       0, 'q'},
	{"pipe",  no_argument,       0, 'P'},

        {0, 0, 0, 0}
    };

    int option_index = 0;
    while ((ch = getopt_long (argc, argv, "qPhxyzs:v:w:i:l:p:S:M:o:bg:", long_options, &option_index)) != -1) {
        switch (ch) {
        case 0:
            break;

        case 'x':
            noises_off = noises_off | PLOM_NO_DEM_STO;
            break;
        case 'y':
            noises_off = noises_off | PLOM_NO_ENV_STO;
            break;
        case 'z':
            noises_off = noises_off | PLOM_NO_DRIFT;
            break;
        case 's':
            dt = atof(optarg);
            break;
        case 'v':
            eps_abs = atof(optarg);
            break;
        case 'w':
            eps_rel = atof(optarg);
            break;
        case 'h':
            print_log(plom_help_string);
            return 1;
        case 'b':
            print_opt &= ~PLOM_PRINT_BEST;
            break;
        case 'p':
            snprintf(SFR_PATH, STR_BUFFSIZE, "%s", optarg);
            break;
        case 'i':
            GENERAL_ID = atoi(optarg);
            break;
        case 'g':
            freeze_forcing = atof(optarg);
            break;
	case 'o':
	    nb_obs = atoi(optarg);
            break;
        case 'l':
            LIKE_MIN = atof(optarg);
            LOG_LIKE_MIN = log(LIKE_MIN);
            break;
        case 'M':
            M = atoi(optarg);
            break;
        case 'S':
            CONVERGENCE_STOP_SIMPLEX = atof(optarg);
            break;

        case 'q':
	    print_opt |= PLOM_QUIET;
            break;
        case 'P':
	    print_opt |= PLOM_PIPE | PLOM_QUIET;
            break;

        case '?':
            /* getopt_long already printed an error message. */
            return 1;

        default:
            snprintf(str, STR_BUFFSIZE, "Unknown option '-%c'\n", optopt);
            print_err(str);
            return 1;
        }
    }
    argc -= optind;
    argv += optind;

    if(argc == 0) {
	implementation = PLOM_ODE; //with Kalman the SDE uses f_pred of PLOM_ODE (OK will do better)...
    } else {
        if (!strcmp(argv[0], "sde")) {
            implementation = PLOM_ODE;
        } else {
            print_log(plom_help_string);
            return 1;
        }
    }
    plom_unlink_done(SFR_PATH, GENERAL_ID);
    json_t *settings = load_settings(PATH_SETTINGS);

    int64_t time_begin, time_end;
    if (!(print_opt & PLOM_QUIET)) {
	snprintf(str, STR_BUFFSIZE, "Starting plom-ksimplex with the following options: i = %d, LIKE_MIN = %g", GENERAL_ID, LIKE_MIN);
	print_log(str);
	time_begin = s_clock();
    }

    json_t *theta = load_json();
    struct s_kalman *p_kalman = build_kalman(theta, settings, implementation, noises_off, OPTION_PRIOR, dt, eps_abs, eps_rel, freeze_forcing, nb_obs);
    json_decref(settings);

    simplex(p_kalman->p_best, p_kalman->p_data, p_kalman, f_simplex_kalman, CONVERGENCE_STOP_SIMPLEX, M, print_opt);

    if (!(print_opt & PLOM_QUIET)) {
	time_end = s_clock();
	struct s_duration t_exec = time_exec(time_begin, time_end);
	snprintf(str, STR_BUFFSIZE, "Done in:= %dd %dh %dm %gs", t_exec.d, t_exec.h, t_exec.m, t_exec.s);
	print_log(str);
    }

    plom_print_done(theta, p_kalman->p_data, p_kalman->p_best, SFR_PATH, GENERAL_ID, print_opt);

    if (!(print_opt & PLOM_QUIET)) {
	print_log("clean up...");
    }

    json_decref(theta);

    clean_kalman(p_kalman);

    return 0;
}
 inline
 const Point<NumDimensions<TSimplex>::Value>&
 SimplexVertices<TSimplex, iNumVertices>::operator[](std::size_t index) const {
     return simplex().vertex(int(index));
 }