void ShapeImprovementWrapper::run_wrapper( Mesh* mesh,
                                           ParallelMesh* pmesh,
                                           MeshDomain* domain,
                                           Settings* settings,
                                           QualityAssessor* qa,
                                           MsqError& err )
{
    // Define an untangler
  UntangleBetaQualityMetric untangle_metric( untBeta );
  LPtoPTemplate untangle_func( 2, &untangle_metric );
  ConjugateGradient untangle_global( &untangle_func );
  TerminationCriterion untangle_inner, untangle_outer;
  untangle_global.use_global_patch();
  untangle_inner.add_absolute_quality_improvement( 0.0 );
  untangle_inner.add_absolute_successive_improvement( successiveEps );
  untangle_outer.add_iteration_limit( 1 );
  untangle_global.set_inner_termination_criterion( &untangle_inner );
  untangle_global.set_outer_termination_criterion( &untangle_outer );

    // define shape improver
  IdealWeightInverseMeanRatio inverse_mean_ratio;
  inverse_mean_ratio.set_averaging_method( QualityMetric::LINEAR );
  LPtoPTemplate obj_func( 2, &inverse_mean_ratio );
  FeasibleNewton feas_newt( &obj_func );
  TerminationCriterion term_inner, term_outer;
  feas_newt.use_global_patch();
  qa->add_quality_assessment( &inverse_mean_ratio );
  term_inner.add_absolute_gradient_L2_norm( gradNorm );
  term_inner.add_relative_successive_improvement( successiveEps );
  term_outer.add_iteration_limit( pmesh ? parallelIterations : 1 );
  feas_newt.set_inner_termination_criterion( &term_inner );
  feas_newt.set_outer_termination_criterion( &term_outer );

    // Apply CPU time limit to untangler
  if (maxTime > 0.0)
    untangle_inner.add_cpu_time( maxTime );
  
    // Run untangler
  InstructionQueue q1;
  Timer totalTimer;
  q1.set_master_quality_improver( &untangle_global, err ); MSQ_ERRRTN(err);
  q1.add_quality_assessor( qa, err ); MSQ_ERRRTN(err);
  q1.run_common( mesh, pmesh, domain, settings, err ); MSQ_ERRRTN(err);
  
    // If limited by CPU time, limit next step to remaning time
  if (maxTime > 0.0) {
    double remaining = maxTime - totalTimer.since_birth();
    if (remaining <= 0.0 ){
      MSQ_DBGOUT(2) << "Optimization is terminating without perfoming shape improvement." << std::endl;
      remaining = 0.0;
    }
    term_inner.add_cpu_time( remaining );
  }
  
    // Run shape improver
  InstructionQueue q2;
  q2.set_master_quality_improver( &feas_newt, err ); MSQ_ERRRTN(err);
  q2.add_quality_assessor( qa, err ); MSQ_ERRRTN(err);
  q2.run_common( mesh, pmesh, domain, settings, err ); MSQ_ERRRTN(err);
}
Ejemplo n.º 2
0
void MeshOpt::trustRegion(hier::Patch<NDIM>& patch)
{
    MsqError err;
    MeshImpl* mesh = createLocalMesh(patch);

    PlanarDomain domain(PlanarDomain::XY);
    IdealWeightInverseMeanRatio inverse_mean_ratio(err);
    LPtoPTemplate obj_func(&inverse_mean_ratio,2,err);
    TrustRegion t_region(&obj_func);
    t_region.use_global_patch();
    TerminationCriterion tc_inner;
    tc_inner.add_absolute_gradient_L2_norm(1e-6);
    tc_inner.add_iteration_limit(1);
    t_region.set_inner_termination_criterion(&tc_inner);
    QualityAssessor m_ratio_qa(&inverse_mean_ratio);
    m_ratio_qa.disable_printing_results();

    InstructionQueue queue;
    queue.add_quality_assessor(&m_ratio_qa,err);
    queue.set_master_quality_improver(&t_region,err);
    queue.add_quality_assessor(&m_ratio_qa,err);
    MeshDomainAssoc mesh_and_domain = MeshDomainAssoc(mesh,&domain);
    queue.run_instructions(&mesh_and_domain,err);
    tbox::pout<< "Shape optimization completed." << std::endl;

//    std::string file_name = "2__patch_3.vtk";
//    mesh->write_vtk(file_name.c_str(), err);

    transformMeshtoPatch(mesh,patch,err);



    d_flag =2;

    return;
}
Ejemplo n.º 3
0
// evaluate obj_func at point x
double Solver::computeObjective(double *x)
{
   return obj_func(x, aux_func_data);
}
Ejemplo n.º 4
0
/**
 * The differential evolution optimization algorithm.
 *
 * params       a structure holding configuration parameters which are 
 *              common to all transmitters;
 * tx_params    a structure holding transmitter-specific configuration 
 *              parameters;
 * D            dimension of the search space;
 * NP           population size, try with 20 * `D`;
 * Gmax         number of generations to evolve the solution, try with 1000;
 * CR           cross-over probability factor [0,1], try with 0.9;
 * F            differential weight factor [0, 2], try with 0.9;
 * reset_seed   whether to reset the random seed between runs or not;
 * radio_zone   radio zone under optimization, used for objective calculation;
 * X_low        lower bound of the search vector, should be `D` long;
 * X_up         upper bound of the search vector, should be `D` long;
 * comm         the object used to communicate with the workers;
 *
 */
static void 
de (Parameters     *params,
    Tx_parameters  *tx_params,
    const int       D, 
    const int       NP, 
    const int       Gmax, 
    const double    CR, 
    const double    F,
    const char      reset_seed,
    const char      radio_zone,
    const double   *X_low,
    const double   *X_up,
    MPI_Comm       *comm)
{
    register int i, j, k, r1, r2, r3, jrand, numofFE = 0;
    int index = -1;
    double **popul, **next, **ptr, *iptr, *U, min_value = DBL_MAX, totaltime = 0.0;
    clock_t starttime, endtime;

    //
    // reset the random seed?
    //
    if (reset_seed)
        srand (time (0));
    else
        srand (0);

    // Printing out information about optimization process for the user	

    printf ("*** INFO: DE parameters\t");
    printf ("NP = %d, Gmax = %d, CR = %.2f, F = %.2f\n",
            NP, Gmax, CR, F);

    printf ("*** INFO: Optimization problem dimension is %d.\n", D);

    /* Starting timer    */
    starttime = clock();


    /* Allocating memory for current and next populations, intializing
      current population with uniformly distributed random values and
      calculating value for the objective function	*/

    popul = (double **)malloc(NP*sizeof(double *));
    if (popul == NULL) perror("malloc");

    next = (double **)malloc(NP*sizeof(double *));
    if (next == NULL) perror("malloc");

    for (i=0; i < NP; i++)
    {
        popul[i] = (double *)malloc((D+1)*sizeof(double));
        if (popul[i] == NULL) perror("malloc");

        for (j=0; j < D; j++)
            popul[i][j] = X_low[j] + (X_up[j] - X_low[j])*URAND;

        popul[i][D] = obj_func (params,
                                tx_params,
                                radio_zone,
                                popul[i],
                                comm);
        numofFE++;

        next[i] = (double *)malloc((D+1)*sizeof(double));
        if (next[i] == NULL) perror("malloc");
    }

    /* Allocating memory for a trial vector U	*/

    U = (double *)malloc((D+1)*sizeof(double));
    if (U == NULL) perror("malloc");

    /* The main loop of the algorithm	*/

    for (k=0; k < Gmax; k++)
    {

      for (i=0; i < NP; i++)	/* Going through whole population	*/
      {

         /* Selecting random indeces r1, r2, and r3 to individuals of
            the population such that i != r1 != r2 != r3	*/

         do
         {
            r1 = (int)(NP*URAND);
         } while( r1==i );
         do
         {
            r2 = (int)(NP*URAND);
         } while( r2==i || r2==r1);
         do
         {
            r3 = (int)(NP*URAND);
         } while( r3==i || r3==r1 || r3==r2 );

         jrand = (int)(D*URAND);

         /* Mutation and crossover	*/

         for (j=0; j < D; j++)
         {
            if (URAND < CR || j == jrand)
            {
               U[j] = popul[r3][j] + F*(popul[r1][j] - popul[r2][j]);
            }
            else
               U[j] = popul[i][j];
            //
            // check that all components of the trial vector
            // are within the allowed values
            //
            if (U[j] < X_low[j])
                U[j] = X_low[j];
            if (U[j] > X_up[j])
                U[j] = X_up[j];
         }

         U[D] = obj_func (params,
                          tx_params,
                          radio_zone,
                          U,
                          comm);
         numofFE++;

         printf ("Generation %d/%d\tscore %20.10f\n", k, Gmax, U[D]);

         /* Comparing the trial vector 'U' and the old individual
            'next[i]' and selecting better one to continue in the
            next population.	*/

         if (U[D] <= popul[i][D])
         {
            iptr = U;
            U = next[i];
            next[i] = iptr;
         }
         else
         {
            for (j=0; j <= D; j++)
                next[i][j] = popul[i][j];
         }

      }	/* End of the going through whole population	*/


      /* Pointers of old and new populations are swapped	*/

      ptr = popul;
      popul = next;
      next = ptr;

    }	/* End of the main loop		*/


    /* Stopping timer	*/

    endtime = clock();
    totaltime = (double)(endtime - starttime);

    //
    // output the final population
    //
    for (i=0; i < NP; i++)
    {
        for (j=0; j <= D; j++)
            fprintf (stdout, "%.15f ", popul[i][j]);
        fprintf (stdout, "\n");
    }

    //
    // finding the best individual
    //
    for (i=0; i < NP; i++)
    {
        if (popul[i][D] < min_value)
        {
            min_value = popul[i][D];
            index = i;
        }
    }

    //
    // print out information about optimization process for the user
    //
    printf ("Execution time: %.3f s\n", totaltime / (double)CLOCKS_PER_SEC);
    printf ("Number of objective function evaluations: %d\n", numofFE);

    printf ("[Solution]\n");
    for (i=0; i < D; i++)
      printf("p%d = %.15f\n", i, popul[index][i]);

    printf ("\nObjective function value: ");
    printf ("%.15f\n", popul[index][D]);

    //
    // copy the solution values to the internal structure,
    // used for coverage calculation
    //
    for (i = 0; i < D; i ++)
        params->clutter_loss[i] = popul[index][i];

    /* Freeing dynamically allocated memory	*/ 
    for (i=0; i < NP; i++)
    {
      free(popul[i]);
      free(next[i]);
    }
    free(popul);
    free(next);
    free(U);
}
Ejemplo n.º 5
0
static lbfgsfloatval_t evaluate(void *instance, const lbfgsfloatval_t *x, lbfgsfloatval_t *g,
        int n, lbfgsfloatval_t step)
{
    return obj_func(x, g, 0.01);
}
Ejemplo n.º 6
0
  void PSO<T>::minimize(T* end_c, const T* start_c,
    const T* radius_c, const bool* angle_coeff, 
    T (*obj_func)(const T* coeff), 
    void (*coeff_update_func)(T* coeff)) {

    eng.seed();
    if (verbose) {
      cout << "Starting PSO optimization..." << endl;
    }

    // Initialize all random swarm particles to Uniform(c_lo_, c_hi_)
    for (uint32_t i = 0; i < num_coeffs_; i++) {
      T rad = fabs(radius_c[i]);
      c_lo_[i] = start_c[i] - rad;
      c_hi_[i] = start_c[i] + rad;
      // According to paper (forgot title), 0.5x search space
      // is best for multi-modal distributions.
      vel_max_[i] = rad;
    }

    // Make the 0th particle the same as the start  --> Important for systems
    // that use the last frame as a start guess
    copyVec(swarm_[0]->pos, start_c); 

    // Stochasticly sample for the other particles
    for (uint32_t j = 0; j < num_coeffs_; j++) {
      std::tr1::uniform_real_distribution<T> c_dist(c_lo_[j], c_hi_[j]);
      for (uint32_t i = 1; i < swarm_size_; i++) {
        T uniform_rand_num = c_dist(eng);  // [c_lo_, c_hi_)
        swarm_[i]->pos[j] = uniform_rand_num;
      }
    }

    // evaluate the agent's function values, calculate residue and set the best
    // position and residue for the particle x_i as it's starting position
    best_residue_global_ = std::numeric_limits<T>::infinity();
    for (uint32_t i = 0; i < swarm_size_; i++) {
      if (coeff_update_func) {
        coeff_update_func(swarm_[i]->pos);
      }
      swarm_[i]->residue = obj_func(swarm_[i]->pos);
      swarm_[i]->best_residue = swarm_[i]->residue;
      copyVec(swarm_[i]->best_pos, swarm_[i]->pos);
      if (swarm_[i]->residue < best_residue_global_) {
        best_residue_global_ = swarm_[i]->residue;
        copyVec(best_pos_global_, swarm_[i]->pos);
      }
    }

    // Initialize random velocity to Uniform(-2*radius_c, 2*radius_c)
    for (uint32_t j = 0; j < num_coeffs_; j++) {
      std::tr1::uniform_real_distribution<T> c_dist(-2 * fabs(radius_c[j]),
        2 * fabs(radius_c[j]));
      for (uint32_t i = 0; i < swarm_size_; i++) {
        T uniform_rand_num = c_dist(eng);  // [-2*radius_c, 2*radius_c)
        swarm_[i]->vel[j] = uniform_rand_num;
      }
    }

    T phi = phi_p + phi_g;
    if (phi <= 4) {
      throw std::runtime_error("ERROR: kappa_ = phi_p + phi_g <= 4!");
    }
    kappa_ = (T)2.0 / fabs((T)2.0 - phi - sqrt(phi * phi - (T)4 * phi));

    if (verbose) {
      cout << "Iteration 0:" << endl;
      cout << "  --> min residue of swarm = " << best_residue_global_ << endl;
      cout << "  --> Agent residues: <";
      for (uint32_t i = 0; i < swarm_size_; i++) {
        cout << swarm_[i]->residue;
        if (i != swarm_size_ - 1) { cout << ", "; }
      }
      cout << ">" << endl;
    }

    uint64_t num_iterations = 0;
    T delta_coeff = std::numeric_limits<T>::infinity();
    do {
      // For each particle, i in the swarm:
      for (uint32_t i = 0; i < swarm_size_; i++) {
        SwarmNode<T>* cur_node = swarm_[i];
        // For each dimension d:
        for (uint32_t d = 0; d < num_coeffs_; d++) {
          T r_p = dist_real(eng);  // [0,1)
          T r_g = dist_real(eng);  // [0,1)
          // Update the velocity
          cur_node->vel[d] = kappa_ * (cur_node->vel[d] + 
            (phi_p * r_p * (cur_node->best_pos[d] - cur_node->pos[d])) + 
            (phi_g * r_g * (best_pos_global_[d] - cur_node->pos[d])));
          // Limit the velocity as discussed in the paper "An Off-The-Shelf PSO"
          if (cur_node->vel[d] > vel_max_[d]) {
            cur_node->vel[d] = vel_max_[d];
          }
          if (cur_node->vel[d] < -vel_max_[d]) {
            cur_node->vel[d] = -vel_max_[d];
          }
        }  // for each dimension

        // Update the particle's postion
        for (uint32_t d = 0; d < num_coeffs_; d++) {
          cur_node->pos[d] = cur_node->pos[d] + cur_node->vel[d];
        }

        if (coeff_update_func) {
          coeff_update_func(cur_node->pos);
        }

        // Evaluate the function at the new position
        cur_node->residue = obj_func(cur_node->pos);

        if (cur_node->residue < cur_node->best_residue) {
          cur_node->best_residue = cur_node->residue;
          copyVec(cur_node->best_pos, cur_node->pos);
        }

        if (cur_node->residue < best_residue_global_) {
          best_residue_global_ = cur_node->residue;
          copyVec(best_pos_global_, cur_node->pos);
        }
      }  // for each agent

      num_iterations ++;

      // Calculate the spread in coefficients
      if (delta_coeff_termination > 0) {
        T l2_norm = 0;
        for (uint32_t j = 0; j < num_coeffs_; j++) {
          cur_c_min_[j] = std::numeric_limits<T>::infinity();
          cur_c_max_[j] = -std::numeric_limits<T>::infinity();
          for (uint32_t i = 0; i < swarm_size_; i++) {
            cur_c_min_[j] = std::min<T>(cur_c_min_[j], swarm_[i]->pos[j]);
            cur_c_max_[j] = std::max<T>(cur_c_max_[j], swarm_[i]->pos[j]);
          }
          delta_c_[j] = cur_c_max_[j] - cur_c_min_[j];
          l2_norm += delta_c_[j] * delta_c_[j];
        }
        l2_norm = sqrt(l2_norm);
        delta_coeff = l2_norm;
      } else {
        delta_coeff = std::numeric_limits<T>::infinity();
      }

      if (verbose) {
        cout << "Iteration " << num_iterations << ":" << endl;
        cout << "  --> min residue of swarm = " << best_residue_global_ << endl;
        cout << "  --> delta_coeff = " << delta_coeff << endl;
      }
    } while (num_iterations <= max_iterations && 
             delta_coeff >= delta_coeff_termination);
    
    if (verbose) {
      cout << endl << "Finished PSO optimization with ";
      cout << "residue " << best_residue_global_ << endl;
    }

    copyVec(end_c, best_pos_global_);
  }
Ejemplo n.º 7
0
/*
 * iterate over all loadobjects in the same address space calling the
 * callback function "obj_func".
 */
static int
inprocess_loadobj_iter(void *opq, tnfctl_ind_obj_f *obj_func, void *cd)
{
	Elf3264_Dyn	*dtdebug = opq;
	struct r_debug	*r_dbg;
	struct link_map *lmap;
	char		path[MAXPATHLEN];
	int		procfd;
	tnfctl_ind_obj_info_t	loadobj;
	int		retval = 0;	/* sucessful return */

	DBG_TNF_PROBE_0(inprocess_loadobj_iter_start, "libtnfctl",
			"start inprocess_loadobj_iter; sunw%verbosity 1");

	r_dbg = (struct r_debug *)dtdebug->d_un.d_ptr;

	DBG_TNF_PROBE_1(inprocess_loadobj_iter_1, "libtnfctl",
		"sunw%verbosity 1",
		tnf_string, link_map_state,
		(r_dbg->r_state == RT_CONSISTENT) ? "RT_CONSISTENT" :
			(r_dbg->r_state == RT_ADD) ? "RT_ADD" : "RT_DELETE");

	/* bail if link map is not consistent */
	if (r_dbg->r_state != RT_CONSISTENT)
		return (1);

	(void) sprintf(path, PROCFORMAT, (int) getpid());

	/*
	 * opening /proc readonly, so debuggers can still run
	 * We use /proc in order to get fd on the object.
	 */
	procfd = open(path, O_RDONLY);
	if (procfd == -1)
		return (1);

	for (lmap = r_dbg->r_map; lmap; lmap = lmap->l_next) {
		loadobj.text_base = lmap->l_addr;
		loadobj.data_base = lmap->l_addr;
		loadobj.objname = lmap->l_name;
		/*
		 * client of this interface should deal with -1 for objfd,
		 * so no error checking is needed on this ioctl
		 */
		loadobj.objfd = ioctl(procfd, PIOCOPENM, &(lmap->l_addr));

		retval = obj_func(opq, &loadobj, cd);

		/* close the fd */
		if (loadobj.objfd != -1)
			close(loadobj.objfd);

		/* check for error */
		if (retval == 1)
			goto end_of_func;
	}

end_of_func:
	close(procfd);

	DBG_TNF_PROBE_0(inprocess_loadobj_iter_end, "libtnfctl",
			"end inprocess_loadobj_iter; sunw%verbosity 1");
	return (retval);
}