Пример #1
0
void perturb(Polygon_with_holes_2& p, Number_type epsilon) {
  perturb(p.outer_boundary(), epsilon);
  // Polygon_with_holes_2 q(p.outer_boundary());
  for (Polygon_with_holes_2::Hole_iterator it = p.holes_begin(); it != p.holes_end(); ++it) {
    perturb(*it, epsilon);
    // q.add_hole();
  }
  // p = q;
}
Пример #2
0
static void recursive_keep(double x, double y, double width, double length, double height, int level)
{
	int i;

	if (irandomn(1000) < 300) {
		xlate(x, y, 0);
		keep_block(width, length, height);
		endxlate();
		xlate(0, 0, height);
		recursive_keep(x, y, width, length, perturb(height, 0.2), level);
		endxlate();
		return;
	}

	if (level == 0 || irandomn(1000) < 300) {
		xlate(x, y, 0);
			xkeep_topper(width, length, height, 1);
		endxlate();
		return;
	}

	i = irandomn(100);

	xlate(x, y, 0);
	keep_block(width, length, height);
	endxlate();
	xlate(0, 0, height);
	if ((level % 2) == 0) {
		double offset, nw1, nw2, x1, x2;
		offset = randomn(width * 0.2) - (0.1 * width);
		offset = 0.0;
		nw1 = (width / 2.0) + offset;
		nw2 = (width - nw1); 
		x1 = x - offset / 2.0 -0.25 * width;
		x2 = x + 0.25 * width  - offset / 2.0;
		printf("/* x/y = %lf,%lf, o=%lf nw1 = %lf, nw2 = %lf, x1 = %lf, x2 = %lf */\n",
			x, y, offset, nw1, nw2, x1, x2);
		recursive_keep(x1, y, nw1, length, perturb(height, 0.2), level - 1);
		recursive_keep(x2, y, nw2, length, perturb(height, 0.2), level - 1);
	} else {
		double offset, nl1, nl2, y1, y2;
		offset = randomn(length * 0.2) - (0.1 * length);
		offset = 0.0;
		nl1 = (length / 2.0) + offset;
		nl2 = (length - nl1);
		y1 = y - offset / 2.0 - 0.25 * length;
		y2 = y + 0.25 * length - offset / 2.0;
		printf("/* x/y = %lf,%lf, o=%lf nl1 = %lf, nl2 = %lf, y1 = %lf, y2 = %lf */\n",
			x, y, offset, nl1, nl2, y1, y2);
		recursive_keep(x, y1, width, nl1, perturb(height, 0.2), level - 1);
		recursive_keep(x, y2, width, nl2, perturb(height, 0.2), level - 1);
	}
	endxlate();
}
Пример #3
0
void perturb(Polygon_2& p, Number_type epsilon) {
  Polygon_2::Vertex_iterator vit;
  for (vit = p.vertices_begin(); vit != p.vertices_end(); ++vit) {
    Point_2 pnt = *vit;
    // Make sure we get a consistent perturbation with each point across runs
    const static Number_type prime = 827;
    srand((int)(pnt.x() + prime*(pnt.y() + prime*pnt.z())));
    pnt = Point_25_<Kernel>(perturb(pnt.x(), epsilon), perturb(pnt.y(), epsilon), pnt.z(), pnt.id());
    p.set(vit, pnt);
  }

  p = Polygon_2(p.vertices_begin(), unique(p.vertices_begin(), p.vertices_end()));
}
Пример #4
0
void Userwork_in_loop(MeshS *pM)
{
  GridS *pGrid;
  int nl,nd;
  Real newtime;

  for (nl=0; nl<(pM->NLevels); nl++){
    for (nd=0; nd<(pM->DomainsPerLevel[nl]); nd++){
      if (pM->Domain[nl][nd].Grid != NULL){

        pGrid = pM->Domain[nl][nd].Grid;

        if (isnan(pGrid->dt)) ath_error("Time step is NaN!");

        if (idrive == 0) {  /* driven turbulence */
          /* Integration has already been done, but time not yet updated */
          newtime = pGrid->time + pGrid->dt;

#ifndef IMPULSIVE_DRIVING
          /* Drive on every time step */
          perturb(pGrid, pGrid->dt);
#endif /* IMPULSIVE_DRIVING */

          if (newtime >= (tdrive+dtdrive)) {
            /* If we start with large time steps so that tdrive would get way
             * behind newtime, this makes sure we don't keep generating after
             * dropping down to smaller time steps */
            while ((tdrive+dtdrive) <= newtime) tdrive += dtdrive;

#ifdef IMPULSIVE_DRIVING
              /* Only drive at intervals of dtdrive */
              perturb(pGrid, dtdrive);
#endif /* IMPULSIVE_DRIVING */

              /* Compute new spectrum after dtdrive.  Putting this after perturb()
               * means we won't be applying perturbations from a new power spectrum
               * just before writing outputs.  At the very beginning, we'll go a
               * little longer before regenerating, but the energy injection rate
               * was off on the very first timestep anyway.  When studying driven
               * turbulence, all we care about is the saturated state. */
              generate();
          }
        }
      }
    }
  }

  return;
}
Пример #5
0
static void xkeep_topper(double width, double length, double height, int rot)
{
	if (rot)
		rotate(90, 0, 0, 1);
	if (irandomn(100) < 30) {
		english_house(width, length, height, min(width, length) * 0.75);
		if (rot)
			endrotate();
		return;
	}
	if (irandomn(100) < 30) {
		gothic_hall(length, width, height, 3, 2, length * 0.1, 1);
		if (rot)
			endrotate();
		return;
	}
	if (rot)
		endrotate();
	rotate(90, 0, 0, 1);
	crenelated_rectangle(length, width, height * 0.2, length * 0.1, length * 0.05);
	endrotate();
	if (irandomn(1000) < 500)
		generic_tower(0, 0, min(length, width) / 3.0,
				perturb(height * 2.0, 0.2), 0);
}
Пример #6
0
static void wall(double x1, double y1, double x2, double y2, double thickness, double height)
{
	double angle;
	double dist;
	double clen, ch, c;

	height = perturb(height, 0.1);
	angle = atan2(y2 - y1, x2 - x1);
	printf("/* %lf, %lf, angle = %d */\n", (y2 - y1), (x2 - x1), (int) (angle * 180.0 / M_PI));
	dist = hypot(x2 - x1, y2 - y1);
	xlate(x1, y1, 0);
	rotate(angle * 180 / M_PI, 0, 0, 1);
	/*diff(); */
	cube(dist, thickness, height, 0);
	c = 0.0;
	ch = thickness;
	clen = thickness *1.5;
	while (c < dist) {
		xlate(c, 0, height - thickness);
		cube(clen, ch, ch * 2, 0);
		endxlate();
		c += clen + thickness;
	}
	/* enddiff(); */
	endrotate();
	endxlate();
}
Пример #7
0
static void generic_tower(double x, double y, double r, double h, int flying_allowed)
{
	double origh = h;
	double origr = r;
	int flying = (irandomn(100) < 30) && flying_allowed;
	h = perturbup(h, TOWER_HEIGHT_RANDOMNESS);
	r = perturb(r, TOWER_RADIUS_RANDOMNESS);
	switch (irandomn(20)) {
	case 0: angular_tower(x, y, origr, origh, flying, 90.0);
		break;
	case 1:	angular_tower(x, y, r, h, flying, 90.0);
		break;
	case 2: pointy_tower(x, y, r, h, flying, 5.0);
		break;
	case 3: angular_tower(x, y, r, h, flying, 72.0);
		break;
	case 4: angular_tower(x, y, r, h, flying, 90.0);
		break;
	case 5: angular_tower(x, y, r, h, flying, 60.0);
		break;
	case 6: angular_tower(x, y, r, h, flying, 45.0);
		break;
	case 7: pointy_tower(x, y, r, h, flying, 72.0);
		break;
	case 8: pointy_tower(x, y, r, h, flying, 90.0);
		break;
	case 9: pointy_tower(x, y, r, h, flying, 60.0);
		break;
	case 10: pointy_tower(x, y, r, h, flying, 45.0);
		break;
	default:
		round_tower(x, y, r, h, flying );
		break;
	}
}
Пример #8
0
int main(int argc, char *argv[])
{
  double x,y;
  int i;
  int xyz=0;

  startgraphics();
  randinit();

  D2=4*R*R;

  for (i=0; n<N; i++)
  {
    tryInsert();
    perturb();
    if (counter>5500)
    {
      drawObjects();
      check4event();
      counter=0;
  printf(".");
    }
  }

  while(1)
  {
    drawObjects();
    check4event();
    sleep(1);
  }
}
void SrTerrain::calHeight(float* height)
{
	memset(height, 0, sizeof(float) * mParam.mNumCols * mParam.mNumRows);

	addPerlinNoise(height, mParam.mYSize);
	perturb(height, mParam.mF, mParam.mD);
	for (int i = 0; i < 10; i++ )
		erode(height, mParam.mErode);
	smoothen(height);
}
Пример #10
0
 bool GMWMI::get_seed (Point<float>& p)
 {
   Interp interp (interp_template);
   do {
     init_seeder.get_seed (p);
     if (find_interface (p, interp)) {
       if (perturb (p, interp))
         return true;
     }
   } while (1);
   return false;
 }
Пример #11
0
void Compute_dQdBeta_CTSE(Real* dQdB, SolutionSpace<Real>& space, Int beta)
{
  RCmplx perturb(0.0, 1.0e-11);

  Mesh<Real>* rm = space.m;

  SolutionSpace<RCmplx> cspace(space);
  Mesh<RCmplx>* cm = cspace.m;
  PObj<RCmplx>* cp = cspace.p;
  EqnSet<RCmplx>* ceqnset = cspace.eqnset;

  std::vector<SolutionSpaceBase<RCmplx>*> cSolSpaces;
  cSolSpaces.push_back(&cspace);

  SolutionOrdering<RCmplx> operations;
  std::string name = cspace.name;
  operations.Insert("Iterate " + name);
  operations.Finalize(cSolSpaces);

  Int cnnode = cm->GetNumNodes();

  Real* dxdb = new Real[cnnode*3];

  Get_dXdB(space.param->path+space.param->spacename, dxdb, rm, beta);

  //perturb complex part by dxdb*perturb
  for(Int i = 0; i < cnnode; i++){
    for(Int j = 0; j < 3; j++){
      cm->xyz[i*3 + j] += dxdb[i*3 + j]*perturb;
    }
  }
  //update xyz coords
  cp->UpdateXYZ(cm->xyz);
  //calculate metrics with new grid positions
  cm->CalcMetrics();
  
  //create a temporary operations vector with just a single space iterator on it
  //run solver
  Solve(cSolSpaces, operations);

  for(Int i = 0; i < cnnode; i++){
    for(Int j = 0; j < ceqnset->neqn; j++){
      dQdB[i*ceqnset->neqn + j] = 
	imag(cspace.q[i*(ceqnset->neqn+ceqnset->nauxvars) + j]) / imag(perturb);
    }
  }
  
  delete [] dxdb;

  return;
}
Пример #12
0
void perturb(Slice& slice, Number_type epsilon) {
  list<string> components;
  slice.components(back_inserter(components));
  for (list<string>::const_iterator it = components.begin();
       it != components.end();
       ++it)
  {
    for (Slice::Contour_iterator cit = slice.begin(*it);
	 cit != slice.end(*it);
	 ++cit)
    {
      perturb((*cit)->polygon(), epsilon);
    }
  }
}
/* 
 * return the optimal solution for n items (first is e) and
 * capacity c. Value so far is v.
 */
int knapsack(struct item *e, int c, int n, int v)
{
  int with, without, best;
  double ub;

  /* base case: full knapsack or no items */
  if (c < 0)
    return INT_MIN;

  if (n == 0 || c == 0)
    return v;		/* feasible solution, with value v */

  ub = (double) v + c * e->value / e->weight;

  if (ub < best_so_far) {
    /* prune ! */
    return INT_MIN;
  }
  /* 
   * compute the best solution without the current item in the knapsack 
   */
  perturb(prob, n, length);
  without = cilk_spawn knapsack(e + 1, c, n - 1, v);

  /* compute the best solution with the current item in the knapsack */
  with = cilk_spawn knapsack(e + 1, c - e->weight, n - 1, v + e->value);

  cilk_sync;

  best = with > without ? with : without;

  /* 
   * notice the race condition here. The program is still
   * correct, in the sense that the best solution so far
   * is at least best_so_far. Moreover best_so_far gets updated
   * when returning, so eventually it should get the right
   * value. The program is highly non-deterministic.
   */
  if (best > best_so_far)
    best_so_far = best;

  return best;
}
    inline void step_dt(const base::Time& dt){
        if(mode == base::JointState::POSITION)
        {
            j_state.position = j_setpoint.position;
            j_state.speed = j_setpoint.speed;
            j_state.effort = j_setpoint.effort;

            trunc_to_limit(base::JointState::POSITION);
            trunc_to_limit(base::JointState::SPEED);
            trunc_to_limit(base::JointState::EFFORT);
        }
        else if(mode == base::JointState::SPEED)
        {
            j_state.speed = j_setpoint.speed;
            j_state.effort = j_setpoint.effort;


            trunc_to_limit(base::JointState::SPEED);
            trunc_to_limit(base::JointState::EFFORT);

            j_state.position += j_setpoint.speed*dt.toSeconds();

            trunc_to_limit(base::JointState::POSITION);
        }
        else if(mode == base::JointState::EFFORT)
        {
            j_state.effort = j_setpoint.effort;

            trunc_to_limit(base::JointState::EFFORT);

            j_state.speed += j_setpoint.effort*dt.toSeconds();
            j_state.position += j_setpoint.speed*dt.toSeconds();

            trunc_to_limit(base::JointState::POSITION);
            trunc_to_limit(base::JointState::SPEED);
        }

        perturb(dt.toSeconds());
    }
Пример #15
0
void moremap() {
    float rx,ry,nrx,nry,px,py;
    int f,i,j,k,c,x,y,ix,iy,displayloop;
    // Generate some more of the map
    for (maploop=1; maploop<scrwid*scrhei/20; maploop++) {
        rx=(float)mmx/scrwid*2-1;
        ry=(float)(mmy-scrhei/2)/scrwid*2;

        /* From QB later
           SUB move (x, y)
           IF fon%(1) THEN
           x = x * var(1): y = y * var(1)
           END IF
           IF fon%(6) THEN
           x = var(1) * SGN(x) * ABS(x) ^ var(6)
           y = var(1) * SGN(y) * ABS(y) ^ var(6)
           END IF
           IF fon%(2) THEN
           nx = x * COS(var(2)) + y * SIN(var(2))
           ny = -x * SIN(var(2)) + y * COS(var(2))
           x = nx
           y = ny
           END IF
           IF fon%(3) THEN
           'y = y - .01 * (y - 1)
           'y = 1 + .99 * (y - 1)
           'y = (y + 1) * .7 - 1
           y = y * var(3)
           END IF
           IF fon%(4) THEN
           y = (y - 1) * var(4) + 1
           END IF
           IF fon%(5) THEN
           x = x + var(5) * x
           END IF
           IF fon%(7) THEN
           IF fon%(10) THEN
           IF fon%(9) THEN
           x = x + var(7) * (-1 + 2 * (p% MOD 2))
           ELSE
           x = x + var(7) * (-1 + 2 * (p% MOD 50) / 49)
           END IF
           ELSE
           x = x + var(7)
           END IF
           END IF
           IF fon%(8) THEN
           IF fon%(10) THEN
           IF fon%(9) THEN
           y = y + var(8) * (-1 + 2 * (p% MOD 2))
           ELSE
           y = y + var(8) * (-1 + 2 * (p% MOD 50) / 49)
           END IF
           ELSE
           y = y + var(8)
           END IF
           END IF
           END SUB
        */

        if (fon[0]) {
            rx = mysgn(rx)/var[7]*mypow(myabs(rx),1/var[0]);
            ry = mysgn(ry)/var[7]*mypow(myabs(ry),1/var[0]);
        }
        if (fon[1]) {
            rx = rx / var[1];
            ry = ry / var[1];
        }
        if (fon[2]) {
            nrx = rx * cos(var[2]) + ry * sin(var[2]);
            nry = -rx * sin(var[2]) + ry * cos(var[2]);
            rx = nrx;
            ry=nry;
        }
        if (fon[3]) {
            ry = ry - mysgn(ry) * sin(var[6]*pi*myabs(ry)) * var[3];
        }
        if (fon[4]) {
            ry = ((myabs(ry) - 1) / var[4] + 1) * mysgn(ry);
        }
        if (fon[5]) {
            rx = rx - mysgn(rx) * sin(var[6]*pi*myabs(rx)) * var[5];
        }
        px=(rx+1)/2*scrwid;
        py=scrhei/2+(ry)/2*scrwid;
        ix=(int)px;
        iy=(int)py;
        if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
            ix=px;
            iy=py;
        }
        amount[mmx][mmy][0][0][makingmap]=((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
        amount[mmx][mmy][1][0][makingmap]=((float)px-(float)ix)*((float)(iy+1)-(float)py);
        amount[mmx][mmy][0][1][makingmap]=((float)ix+1-(float)px)*((float)py-(float)iy);
        amount[mmx][mmy][1][1][makingmap]=((float)px-(float)ix)*((float)py-(float)iy);
        pix[mmx][mmy][makingmap]=ix;
        piy[mmx][mmy][makingmap]=iy;
        if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
            pix[mmx][mmy][makingmap]=scrwid/2;
            piy[mmx][mmy][makingmap]=scrhei/2;
            for (i=0; i<=1; i++) {
                for (j=0; j<=1; j++) {
                    amount[mmx][mmy][i][j][makingmap]=0;
                }
            }
        }
        mmx++;
        if (mmx>=scrwid) {
            mmx=0;
            mmy++;
            if (mmy>=scrhei) {
                mmy=0;
                tmpmap=usingmap;
                usingmap=makingmap;
                makingmap=tmpmap;
                for (f=0; f<fs; f++) {
                    perturb(f);
                }
            }
        }
    }
}
Пример #16
0
void Compute_dRdQ_Product_MatrixFree(SolutionSpace<RCmplx>& cspace, Real* vector, Real* prod)
{
  RCmplx perturb(0.0, 1.0e-11);
  Mesh<RCmplx>* cm = cspace.m;
  Param<RCmplx>* param = cspace.param;
  EqnSet<RCmplx>* ceqnset = cspace.eqnset;
  RCmplx* q = cspace.q;
  PObj<RCmplx>* p = cspace.p;

  Int cnnode = cm->GetNumNodes();
  Int cgnode = cm->GetNumParallelNodes();
  Int cnbnode = cm->GetNumBoundaryNodes();

  Int neqn = ceqnset->neqn;
  Int nvars = ceqnset->nauxvars + neqn;

  for(Int i = 0; i < cnnode; i++){
    RCmplx* iq = &q[i*nvars + 0];
    for(Int j = 0; j < neqn; j++){
      iq[j] += vector[i*neqn + j]*perturb;
    }
    ceqnset->ComputeAuxiliaryVariables(iq);
  }
  p->UpdateGeneralVectors(q, nvars);

  //the gaussian source is sometimes used to modify boundary velocities, etc.
  //pre-compute it for bc call
  if(cspace.param->gaussianSource){
    cspace.gaussian->ApplyToResidual();
  }

  UpdateBCs(&cspace);
  p->UpdateGeneralVectors(q, nvars);
  
  //now, compute gradients and limiters
  if(param->sorder > 1 || param->viscous){
    for(Int i = 0; i < (cnnode+cnbnode+cgnode); i++){
      ceqnset->NativeToExtrapolated(&q[i*nvars]);
    }
    cspace.grad->Compute();
    cspace.limiter->Compute(&cspace);
    for(Int i = 0; i < (cnnode+cnbnode+cgnode); i++){
      ceqnset->ExtrapolatedToNative(&q[i*nvars]);
    }
  }

  //it is assumed that this routine is going to be called iteratively,
  //therefore, calling the turbulence model here, will slowly converge the
  //turbulence model towards the correct sensitivity
  //This should theoretically be converged here at every call to this routine,
  //but that is horribly costly.... so we cheat
  //WARNING: ---- for now, we assume frozen turbulence models
  if(param->viscous && false){
    cspace.turb->Compute();
    if(param->gcl){
      std::cout << "MATRIX FREE: COMPUTE GCL FOR TURB MODEL!" << std::endl;
    }
  }

  //Now compute residual, this only works for spatial residual right now
  SpatialResidual(&cspace);
  ExtraSourceResidual(&cspace);

  //Now do the CTSE derivative part
  for(Int i = 0; i < cnnode; i++){
    for(Int j = 0; j < neqn; j++){
      prod[i*neqn + j] = imag(cspace.crs->b[i*neqn + j])/imag(perturb);
    }
  }

  //re-zero the complex part of the q vector in case we reuse the cspace
  for(Int i = 0; i < cnnode; i++){
    RCmplx* iq = &q[i*nvars + 0];
    for(Int j = 0; j < neqn; j++){
      iq[j] = real(iq[j]);
    }
    ceqnset->ComputeAuxiliaryVariables(iq);
  }
  p->UpdateGeneralVectors(q, nvars);

  return;
}
Пример #17
0
void LayerNet::anneal (
   TrainingSet *tptr ,        // Training set to use
   struct LearnParams *lptr , // User's general learning parameters
   LayerNet *bestnet ,        // Work area used to keep best network
   int init                   // Use zero suffix (initialization) anneal parms?
   )
{
   int ntemps, niters, setback, reg, nvars, key, user_quit ;
   int i, iter, improved, ever_improved, itemp ;
   long seed, bestseed ;
   char msg[80] ;
   double tempmult, temp, fval, bestfval, starttemp, stoptemp, fquit ;
   SingularValueDecomp *sptr ;
   struct AnnealParams *aptr ; // User's annealing parameters
                             
   aptr = lptr->ap ;

/*
   The parameter 'init' is nonzero if we are initializing
   weights for learning.  If zero we are attempting to break
   out of a local minimum.  The main effect  of this parameter
   is whether or not we use the zero suffix variables in the
   anneal parameters.
   A second effect is that regression is used only for
   initialization, not for escape.
*/

   if (init) {
      ntemps = aptr->temps0 ;
      niters = aptr->iters0 ;
      setback = aptr->setback0 ;
      starttemp = aptr->start0 ;
      stoptemp = aptr->stop0 ;
      }
   else {
      ntemps = aptr->temps ;
      niters = aptr->iters ;
      setback = aptr->setback ;
      starttemp = aptr->start ;
      stoptemp = aptr->stop ;
      }

/*
   Initialize other local parameters.  Note that there is no sense using
   regression if there are no hidden layers.  Also, regression is almost
   always counterproductive for local minimum escape.
*/

   fquit = lptr->quit_err ;
   reg = init  &&  nhid1  &&  (lptr->init != 1) ;

/*
   Allocate the singular value decomposition object for REGRESS.
   Also allocate a work area for REGRESS to preserve matrix.
*/

   if (reg) {
      if (nhid1 == 0)         // No hidden layer
         nvars = nin + 1 ;
      else if (nhid2 == 0)    // One hidden layer
         nvars = nhid1 + 1 ;
      else                    // Two hidden layers
         nvars = nhid2 + 1 ;

      MEMTEXT ( "ANNEAL: new SingularValueDecomp" ) ;
      sptr = new SingularValueDecomp ( tptr->ntrain , nvars , 1 ) ;

      if ((sptr == NULL)  || ! sptr->ok) {
         memory_message (
            "for annealing with regression. Try ANNEAL NOREGRESS.");
         if (sptr != NULL)
            delete sptr ;
         neterr = 1.0 ; // Flag failure to LayerNet::learn which called us
         return ;
         }
      }

/*
   For every temperature, the center around which we will perturb is the
   best point so far.  This is kept in 'bestnet', so initialize it to the
   user's starting estimate.   Also, initialize 'bestfval', the best
   function value so far, to be the function value at that starting point.
*/

   copy_weights ( bestnet , this ) ; // Current weights are best so far
   if (init)
      bestfval = 1.e30 ;  // Force it to accept SOMETHING
   else 
      bestfval = trial_error ( tptr ) ;

/*
   This is the temperature reduction loop and the iteration within
   temperature loop.  We use a slick trick to keep track of the
   best point at a given temperature.  We certainly don't want to
   replace the best every time an improvement is had, as then we
   would be moving our center about, compromising the global nature
   of the algorithm.  We could, of course, have a second work area
   in which we save the 'best so far for this temperature' point.
   But if there are a lot of variables, the usual case, this wastes
   memory.  What we do is to save the seed of the random number
   generator which created the improvement.  Then later, when we
   need to retrieve the best, simply set the random seed and
   regenerate it.  This technique also saves a lot of copying time
   if many improvements are made for a single temperature.
*/

   temp = starttemp ;
   tempmult = exp( log( stoptemp / starttemp ) / (ntemps-1)) ;
   ever_improved = 0 ;                       // Flags if improved at all
   user_quit = 0 ;                           // Flags user pressed ESCape

   for (itemp=0 ; itemp<ntemps ; itemp++) {  // Temp reduction loop

      improved = 0 ;                         // Flags if this temp improved

      if (init) {
         sprintf ( msg , "\nANNEAL temp=%.2lf ", temp ) ;
         progress_message ( msg ) ;
         }

      for (iter=0 ; iter<niters ; iter++) {  // Iters per temp loop

         seed = longrand () ;                // Get a random seed
         slongrand ( seed ) ;                // Brute force set it
         perturb (bestnet, this, temp, reg) ;// Randomly perturb about best

         if (reg)                            // If using regression, estimate
            fval = regress ( tptr , sptr ) ; // out weights now
         else                                // Otherwise just evaluate
            fval = trial_error ( tptr ) ;

         if (fval < bestfval) {              // If this iteration improved
            bestfval = fval ;                // then update the best so far
            bestseed = seed ;                // and save seed to recreate it
            ever_improved = improved = 1 ;   // Flag that we improved

            if (bestfval <= fquit)           // If we reached the user's
               break ;                       // limit, we can quit

            iter -= setback ;                // It often pays to keep going
            if (iter < 0)                    // at this temperature if we
               iter = 0 ;                    // are still improving
            }
         }                                   // Loop: for all iters at a temp

      if (improved) {                        // If this temp saw improvement
         slongrand ( bestseed ) ;            // set seed to what caused it
         perturb (bestnet, this, temp, reg) ;// and recreate that point
         copy_weights ( bestnet , this ) ;   // which will become next center
         slongrand ( bestseed / 2 + 999 ) ;  // Jog seed away from best

         if (init) {
            sprintf ( msg , " err=%.3lf%% ", 100.0 * bestfval ) ;
            progress_message ( msg ) ;
            }
         }

      if (bestfval <= fquit)  // If we reached the user's
         break ;              // limit, we can quit

/***********************************************************************
      if (kbhit()) {          // Was a key pressed?
         key = getch () ;     // Read it if so
         while (kbhit())      // Flush key buffer in case function key
            getch () ;        // or key was held down
         if (key == 27) {     // ESCape
            user_quit = 1 ;   // Flags user that ESCape was pressed
            break ;
            }
	    }
***********************************************************************/


      if (user_quit)
         break ;

      temp *= tempmult ;      // Reduce temp for next pass
      }                       // through this temperature loop


/*
   The trials left this weight set and neterr in random condition.
   Make them equal to the best, which will be the original
   if we never improved.

   Also, if we improved and are using regression, recall that bestnet
   only contains the best hidden weights, as we did not bother to run
   regress when we updated bestnet.  Do that now before returning.
*/

   copy_weights ( this , bestnet ) ; // Return best weights in this net
   neterr = bestfval ;               // Trials destroyed weights, err

   if (ever_improved  &&  reg)
      neterr = regress ( tptr , sptr ) ; // regressed output weights

   if (reg) {
      MEMTEXT ( "ANNEAL: delete SingularValueDecomp" ) ;
      delete sptr ;
      }
}
Пример #18
0
void problem(Grid *pGrid, Domain *pD)
{
  int i, is=pGrid->is, ie = pGrid->ie;
  int j, js=pGrid->js, je = pGrid->je;
  int k, ks=pGrid->ks, ke = pGrid->ke;

  rseed = (pGrid->my_id+1);
  initialize(pGrid, pD);
  tdrive = 0.0;

  /* Initialize uniform density and momenta */
  for (k=ks-nghost; k<=ke+nghost; k++) {
    for (j=js-nghost; j<=je+nghost; j++) {
      for (i=is-nghost; i<=ie+nghost; i++) {
        pGrid->U[k][j][i].d = rhobar;
        pGrid->U[k][j][i].M1 = 0.0;
        pGrid->U[k][j][i].M2 = 0.0;
        pGrid->U[k][j][i].M3 = 0.0;
      }
    }
  }

#ifdef MHD
  /* Initialize uniform magnetic field */
  for (k=ks-nghost; k<=ke+nghost; k++) {
    for (j=js-nghost; j<=je+nghost; j++) {
      for (i=is-nghost; i<=ie+nghost; i++) {
        pGrid->U[k][j][i].B1c  = B0;
        pGrid->U[k][j][i].B2c  = 0.0;
        pGrid->U[k][j][i].B3c  = 0.0;
        pGrid->B1i[k][j][i] = B0;
        pGrid->B2i[k][j][i] = 0.0;
        pGrid->B3i[k][j][i] = 0.0;
      }
    }
  }
#endif /* MHD */

  /* Set the initial perturbations.  Note that we're putting in too much
   * energy this time.  This is okay since we're only interested in the
   * saturated state. */
  generate();
  perturb(pGrid, dtdrive);

  /* If decaying turbulence, no longer need the driving memory */
  if (idrive == 1) {
    ath_pout(0,"De-allocating driving memory.\n");

    /* Free Athena-style arrays */
    free_3d_array(dv1);
    free_3d_array(dv2);
    free_3d_array(dv3);

    /* Free FFTW-style arrays */
    ath_3d_fft_free(fv1);
    ath_3d_fft_free(fv2);
    ath_3d_fft_free(fv3);
  }

  return;
}
Пример #19
0
void foo() {
  printf("-------- before ---------\n");
  /*cilk_sleep(500000);*/
  perturb(1, 1, 500000);
  printf("-------- after ---------\n");
}
Пример #20
0
void compute_kernels(const struct ecalib_conf* conf, long nskerns_dims[5], complex float** nskerns_ptr, unsigned int SN, float svals[SN], const long caldims[DIMS], const complex float* caldata)
{
	assert(1 == md_calc_size(DIMS - 5, caldims + 5));

	nskerns_dims[0] = conf->kdims[0];
	nskerns_dims[1] = conf->kdims[1];
	nskerns_dims[2] = conf->kdims[2];
	nskerns_dims[3] = caldims[3];

	long N = md_calc_size(4, nskerns_dims);

	assert(N > 0);
	nskerns_dims[4] = N;

	complex float* nskerns = md_alloc(5, nskerns_dims, CFL_SIZE);
	*nskerns_ptr = nskerns;

	complex float (*vec)[N] = xmalloc(N * N * sizeof(complex float));

	assert((NULL == svals) || (SN == N));
	float* val = (NULL != svals) ? svals : xmalloc(N * FL_SIZE);

	debug_printf(DP_DEBUG1, "Build calibration matrix and SVD...\n");

#ifdef CALMAT_SVD
	calmat_svd(conf->kdims, N, vec, val, caldims, caldata);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++) 
#ifndef FLIP
			nskerns[i * N + j] = (vec[j][i]) * (conf->weighting ? val[i] : 1.);
#else
			nskerns[i * N + j] = (vec[j][N - 1 - i]) * (conf->weighting ? val[N - 1 - i] : 1.);
#endif
#else
	covariance_function(conf->kdims, N, vec, caldims, caldata);

	debug_printf(DP_DEBUG1, "Eigen decomposition... (size: %ld)\n", N);

	// we could apply Nystroem method here to speed it up

	float tmp_val[N];
	lapack_eig(N, tmp_val, vec);

	for (int i = 0; i < N; i++)
		val[i] = sqrtf(tmp_val[N - 1 - i]);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++) 
#ifndef FLIP
			nskerns[i * N + j] = vec[N - 1 - i][j] * (conf->weighting ? val[i] : 1.);	// flip
#else
			nskerns[i * N + j] = vec[i][j] * (conf->weighting ? val[N - 1 - i] : 1.);	// flip
#endif
#endif

	if (conf->perturb > 0.) {

		long dims[2] = { N, N };
		perturb(dims, nskerns, conf->perturb);
	}

#ifndef FLIP
	nskerns_dims[4] = number_of_kernels(conf, N, val);
#else
	nskerns_dims[4] = N - number_of_kernels(conf, N, val);
#endif

	if (NULL == svals)
		free(val);

	free(vec);
}
Пример #21
0
int main(void) {

    int f,i,j,k,c,x,y,ix,iy,displayloop;
    int usingmap,makingmap,mmx,mmy,tmpmap,maploop;
    float rx,ry,nrx,nry,px,py;
    RGB rgb;
    FILE *fp;

    img=(uchar **)calloc(scrhei,sizeof(uchar *));
    for (y=0; y<scrhei; y++) {
        img[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        for (x=0; x<scrwid; x++) {
            img[y][x]=myrnd()*255;
        }
    }
    img2=(uchar **)calloc(scrhei,sizeof(uchar *));
    for (y=0; y<scrhei; y++) {
        img2[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        for (x=0; x<scrwid; x++) {
            img2[y][x]=myrnd()*255;
        }
    }

    srand((int)time(NULL));

    usingmap=0;
    makingmap=1;
    mmx=0;
    mmy=0;

    /* Originals from QB
    op[0] = 1; damp[0] = .999; force[0] = .005;
    op[1] = 1.02; damp[1] = .999; force[1] = .002;
    op[2] = 0; damp[2] = .999; force[2] = .002;
    op[3] = 1; damp[3] = .999; force[3] = .005;
    op[4] = 1; damp[4] = .999; force[4] = .005;
    op[5] = 0; damp[5] = .999; force[5] = .002;
    */

// 0 Accelerate
    op[0] = 1;
    damp[0] = .999;
    force[0] = .005;
// 1 Velocity
    op[1] = 1.02;
    damp[1] = .999;
    force[1] = .01;
// 2 Rotation
    op[2] = 0;
    damp[2] = .999;
    force[2] = .05;
// 3 Drip
    op[3] = 1;
    damp[3] = .999;
    force[3] = .03;
// 4 Dribble
    op[4] = 1;
    damp[4] = .999;
    force[4] = .01;
// 5 Slide
    op[5] = 0;
    damp[5] = .999;
    force[5] = .01;

    for (f=0; f<fs; f++) {
        var[f] = op[f];
        fon[f]=1;
    }

    allegro_init ();
    install_keyboard ();
    install_timer ();
    set_gfx_mode (GFX_AUTODETECT, scrwid, scrhei, 0, 0);
    set_pallete (desktop_palette);
    _farsetsel(screen->seg);
    for (c=0; c<=255; c++) {
        rgb.r=saw(0,c);
        rgb.g=saw(256/3,c);
        rgb.b=saw(2*256/3,c);
        set_color(c,&rgb);
    }

    while(!key[KEY_ESC]) {

        // Generate some more of the map
        for (maploop=1; maploop<scrwid*scrhei/15; maploop++) {
            rx=(float)mmx/scrwid*2-1;
            ry=(float)(mmy-scrhei/2)/scrwid*2;
            if (fon[1]) {
                rx = rx / var[1];
                ry = ry / var[1];
            }
            if (fon[0]) {
                rx = mysgn(rx)/var[1]*mypow(myabs(rx),1/var[6]);
                ry = mysgn(ry)/var[1]*mypow(myabs(ry),1/var[6]);
            }
            if (fon[2]) {
                nrx = rx * cos(var[2]) + ry * sin(var[2]);
                nry = -rx * sin(var[2]) + ry * cos(var[2]);
                rx = nrx;
                ry=nry;
            }
            if (fon[3]) {
                ry = ry / var[3];
            }
            if (fon[4]) {
                ry = ((myabs(ry) - 1) / var[4] + 1) * mysgn(ry);
            }
            if (fon[5]) {
                rx = rx + var[5] * mysgn(rx);
            }
            px=(rx+1)/2*scrwid;
            py=scrhei/2+(ry)/2*scrwid;
            ix=(int)px;
            iy=(int)py;
            amount[mmx][mmy][0][0][makingmap]=((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
            amount[mmx][mmy][1][0][makingmap]=((float)px-(float)ix)*((float)(iy+1)-(float)py);
            amount[mmx][mmy][0][1][makingmap]=((float)ix+1-(float)px)*((float)py-(float)iy);
            amount[mmx][mmy][1][1][makingmap]=((float)px-(float)ix)*((float)py-(float)iy);
            pix[mmx][mmy][makingmap]=ix;
            piy[mmx][mmy][makingmap]=iy;
            if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
                pix[mmx][mmy][makingmap]=scrwid/2;
                piy[mmx][mmy][makingmap]=scrhei/2;
                for (i=0; i<=1; i++) {
                    for (j=0; j<=1; j++) {
                        amount[mmx][mmy][i][j][makingmap]=0;
                    }
                }
            }
            mmx++;
            if (mmx>=scrwid) {
                mmx=0;
                mmy++;
                if (mmy>=scrhei) {
                    mmy=0;
                    tmpmap=usingmap;
                    usingmap=makingmap;
                    makingmap=tmpmap;
                    for (f=0; f<fs; f++) {
                        perturb(f);
                    }
                    for (i=0; i<4; i++) {
                        f = myrnd() * fs;
                        if (myrnd()<.8) {
                            if (myrnd()<.5)
                                fon[f] = 1;
                            else
                                fon[f]=0;
                        }
                    }
                }
            }
        }

        // Animate
        for (x=0; x<scrwid; x++) {
            for (y=0; y<scrhei; y++) {
                c=0;
                for (i=0; i<=1; i++) {
                    for (j=0; j<=1; j++) {
                        c=c+amount[x][y][i][j][usingmap]*img[piy[x][y][usingmap]+j][pix[x][y][usingmap]+i];
                    }
                }
                c--;
                img2[y][x]=c;
            }
        }
        /*        for (y=0;y<scrhei;y++) {
                for (x=0;x<scrwid;x++) {
                  _farpokeb(screen->seg, (unsigned long)screen->line[y]+x, img2[y][x]);
                }
                }*/
        for (y=0; y<scrhei; y++) {
            movedata(_my_ds(), img2[y], screen->seg, bmp_write_line(screen,y), scrwid);
        }
        for (f=0; f<fs; f++) {
            if (fon[f]) {
                hline(screen, scrwid/2, f*2, scrwid/2+(var[f] - op[f]) * scrwid * 4, 0);
            }
        }
        imgtmp=img;
        img=img2;
        img2=imgtmp;
        for (i=1; i<=5; i++) {
            mycircle(myrnd()*scrwid,myrnd()*scrhei,2+myrnd()*8,myrnd()*255);
        }
    }

}
Пример #22
0
void moremap() {
  float rx,ry,nrx,nry,px,py;
  int f,i,j,k,c,x,y,ix,iy,displayloop;
  // Generate some more of the map
  for (maploop=1;maploop<scrwid*scrhei/framespermap;maploop++) {
    rx=2.0*(float)mmx/(float)scrwid-1.0;
    ry=2.0*(float)(mmy-scrhei/2)/(float)scrwid;
    
    if (fon[8]) {
      ry=(ry-1)/var[8]+1;
    }
    if (fon[9]) {
      rx=rx+var[9]*rx;
    }
    if (fon[10]) {
      rx=rx+var[10];
    }
    if (fon[11]) {
      ry=ry+var[11];
    }
    if (fon[0]) {
			rx = rx + (var[7]-1.0)*0.2 * sin((20.0+30.0*(var[8]-1.0))*ry);
			ry = ry - (var[7]-1.0)*0.2 * sin((20.0+30.0*(var[8]-1.0))*rx);
    }
    if (fon[1]) {
      rx = rx / var[1]; ry = ry / var[1];
    }
    if (fon[2]) {
      nrx = rx * cos(var[2]) + ry * sin(var[2]);
      nry = -rx * sin(var[2]) + ry * cos(var[2]);
      rx = nrx; ry=nry;
    }
    if (fon[3]) {
      // ry = ry + mysgn(ry) * sin(var[6]*pi*myabs(ry)) * var[3];
			rx = rx + (var[4]-1.0)*0.3 * sin((20.0+30.0*(var[3]-1.0))*ry);
    }
    if (fon[5]) {
      // rx = rx + mysgn(rx) * sin(var[6]*pi*myabs(rx)) * var[5];
			ry = ry + (var[3]-1.0)*0.2 * sin((20.0+30.0*(var[4]-1.0))*rx);
    }
/*    if (fon[4]) {
      ry = ((myabs(ry) - 1) / var[4] + 1) * mysgn(ry);
    }*/
    px=(rx+1)/2*scrwid;
    py=scrhei/2+(ry)/2*scrwid;
    ix=(int)px;
    iy=(int)py;
    if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
      ix=px; iy=py;
    }
    amount[mmx][mmy][0][0][makingmap]=amountmax*((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
    amount[mmx][mmy][1][0][makingmap]=amountmax*((float)px-(float)ix)*((float)(iy+1)-(float)py);
    amount[mmx][mmy][0][1][makingmap]=amountmax*((float)ix+1-(float)px)*((float)py-(float)iy);
    amount[mmx][mmy][1][1][makingmap]=amountmax*((float)px-(float)ix)*((float)py-(float)iy);
    pix[mmx][mmy][makingmap]=ix;
    piy[mmx][mmy][makingmap]=iy;
    if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
/*      pix[mmx][mmy][makingmap]=scrwid/2;
      piy[mmx][mmy][makingmap]=scrhei/2;
      for (i=0;i<=1;i++) {
        for (j=0;j<=1;j++) {
          amount[mmx][mmy][i][j][makingmap]=0;
        }
      }*/
/*      pix[mmx][mmy][makingmap]=myrnd()*(scrwid-1);
      piy[mmx][mmy][makingmap]=myrnd()*(scrhei-1);
      for (i=0;i<=1;i++) {
        for (j=0;j<=1;j++) {
          amount[mmx][mmy][i][j][makingmap]=myrnd()/4;
        }
      }*/
      pix[mmx][mmy][makingmap]=( mmx<scrwid-1 ? mmx : mmx-1 );
      piy[mmx][mmy][makingmap]=( mmy<scrhei-1 ? mmy : mmy-1 );
			float splitall=myrnd();
			float splitleft=myrnd();
			float splitright=myrnd();
      amount[mmx][mmy][0][0][makingmap]=amountmax/4;
      amount[mmx][mmy][1][0][makingmap]=amountmax/4;
      amount[mmx][mmy][0][1][makingmap]=amountmax/4;
      amount[mmx][mmy][1][1][makingmap]=amountmax/4;
    }
    mmx++;
    if (mmx>=scrwid) {
      mmx=0;
      mmy++;
      if (mmy>=scrhei) {
        mmy=0;
        tmpmap=usingmap;
        usingmap=makingmap;
        makingmap=tmpmap;
        int rep=4;
        if (myrnd()<0.2)
          rep=200;
        for (int r=1;r<=rep;r++) {
        for (f=0;f<fs;f++) {
          perturb(f);
/*          if (myabs(var[f]-op[f])<force[f])
            fon[f]=( myrnd()<0.6 ? 1 : 0 );*/
        }
        }
      }
    }
  }
}
Пример #23
0
int init_candy(void) {

				frameno=0;
  register int i,j,x,y;
  

  srand((int)time(NULL));
  
  usingmap=0; makingmap=1; mmx=0; mmy=0;

  img=JBmp(scrwid,scrhei);
  img2=JBmp(scrwid,scrhei);

  for (y=0;y<scrhei;y++) {
    for (x=0;x<scrwid;x++) {
      // img.bmp[y][x]=256*y/scrhei;
      // img.bmp[y][x]=0;
      img.bmp[y][x]=255;
      if (x<scrwid-1 && y<scrhei-1) {
        pix[x][y][usingmap]=x;
        piy[x][y][usingmap]=y;
        for (i=0;i<=1;i++)
        for (j=0;j<=1;j++)
          amount[x][y][i][j][usingmap]=amountmax/4;
      }
    }
  }
  
  /* Originals from QB
     op[0] = 1; damp[0] = .999; force[0] = .005;
     op[1] = 1.02; damp[1] = .999; force[1] = .002;
     op[2] = 0; damp[2] = .999; force[2] = .002;
     op[3] = 1; damp[3] = .999; force[3] = .005;
     op[4] = 1; damp[4] = .999; force[4] = .005;
     op[5] = 0; damp[5] = .999; force[5] = .002;
  */
  
  /* From QB later
     name$(1) = "Velocity"
     op(1) = 1: damp(1) = .999: force(1) = .002
     name$(2) = "Rotation"
     op(2) = 0: damp(2) = .999: force(2) = .002
     name$(3) = "Drip"
     op(3) = 1: damp(3) = .999: force(3) = .005
     name$(4) = "Dribble"
     op(4) = 1: damp(4) = .999: force(4) = .005
     name$(5) = "Slide"
     op(5) = 0: damp(5) = .999: force(5) = .002
     name$(6) = "Accelerate"
     op(6) = 1: damp(6) = .999: force(6) = .005
     name$(7) = "xDisplace"
     op(7) = 0: damp(7) = .999: force(7) = .005
     name$(8) = "yDisplace"
     op(8) = 0: damp(8) = .999: force(8) = .005
     REM 9 and 10 are options for splitting displacements (no var)
     name$(9) = "2d/3d split"
     name$(10) = "Split"
  */
  
  // 0 Accelerate
  op[0] = 1; damp[0] = .9; force[0] = .01;
  // 1 Velocity
  op[1] = 1; damp[1] = .9; force[1] = .01;
  // 2 Rotation
  op[2] = 0; damp[2] = .9; force[2] = .02;
  // 5 x splurge
  op[5] = 0; damp[5] = .9; force[5] = .01;
  op[6]=2;damp[6]=.99;force[6]=.01;
  op[3] = 1; damp[3] = .9; force[3] = .01;
  op[4] = 1; damp[4] = .9; force[4] = .01;
  op[7]=1;damp[7]=.99;force[7]=.01;
  // Dribble
  op[8] = 1; damp[8] = .9; force[8] = .01;
  // Slide
  op[9] = 0; damp[9] = .9; force[9] = .01;
  // xDisplace
  op[10] = 0; damp[10] = .9; force[10] = .01;
  // yDisplace
  op[11] = 0; damp[11] = .9; force[11] = .01;
  
  for (f=0;f<fs;f++) {
    var[f] = op[f];
    fon[f]=1;
  }

  for (j=1;j<=10000;j++)
  for (i=0;i<fs;i++)
    perturb(i);

  for (i=0;i<=framespermap;i++) {
    moremap();
  }
  
  #ifdef ALLEGRO
    allegrosetup(scrwid,scrhei);
    // _farsetsel(screen->seg);
  #endif
  
  redocolors();

}
Пример #24
0
double VRP::RTR_solve(int heuristics, int intensity, int max_stuck, int max_perturbs,
                      double dev, int nlist_size, int perturb_type, int accept_type, bool verbose)
{
    ///
    /// Uses the given parameters to generate a 
    /// VRP solution via record-to-record travel.
    /// Assumes that data has already been imported into V and that we have
    /// some existing solution.
    /// Returns the objective function value of the best solution found
    ///

    // Make sure accept_type is either VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT - matters only
    // for the downhill phase as we use VRPH_LI_ACCEPT in the diversification phase

    if(accept_type!=VRPH_BEST_ACCEPT && accept_type!=VRPH_FIRST_ACCEPT)
        report_error("%s: accept_type must be VRPH_BEST_ACCEPT or VRPH_FIRST_ACCEPT\n");

    int ctr, n, j,  i,  R, random, fixed, neighbor_list, objective, tabu;

    random=fixed=neighbor_list=0;

    if(heuristics & VRPH_RANDOMIZED)
        random=VRPH_RANDOMIZED;

    if(heuristics & VRPH_FIXED_EDGES)
        fixed=VRPH_FIXED_EDGES;

    if(heuristics & VRPH_USE_NEIGHBOR_LIST)
        neighbor_list=VRPH_USE_NEIGHBOR_LIST;

    objective=VRPH_SAVINGS_ONLY;
    // default strategy

    if(heuristics & VRPH_MINIMIZE_NUM_ROUTES)
        objective=VRPH_MINIMIZE_NUM_ROUTES;


    if(heuristics & VRPH_TABU)
    {
        tabu=VRPH_TABU; // We will use a primitive Tabu Search in the uphill phase
        // Clear the tabu list
        this->tabu_list->empty();
    }
    else
        tabu=0;

    n=num_nodes;

    // Define the heuristics we will use

    OnePointMove OPM;
    TwoPointMove TPM;
    TwoOpt         TO;
    OrOpt         OR;
    ThreeOpt     ThreeO;
    CrossExchange    CE;
    ThreePointMove ThreePM;

    double start_val;
    int *perm;
    perm=new int[this->num_nodes];


    j=VRPH_ABS(this->next_array[VRPH_DEPOT]);
    for(i=0;i<this->num_nodes;i++)
    {
        perm[i]=j;
        if(!routed[j])
            report_error("%s: Unrouted node in solution!!\n");

        j=VRPH_ABS(this->next_array[j]);
    }
    if(j!=VRPH_DEPOT)
        report_error("%s: VRPH_DEPOT is not last node in solution!!\n");


    int rules;

    // Set the neighbor list size used in the improvement search
    neighbor_list_size=VRPH_MIN(nlist_size, this->num_nodes);

    // Set the deviation
    deviation=dev;

    int num_perturbs=0;

    record=this->total_route_length;
    this->best_total_route_length=this->total_route_length;
    this->export_solution_buff(this->current_sol_buff);
    this->export_solution_buff(this->best_sol_buff);

    normalize_route_numbers();

    ctr=0;


uphill:
    // Start an uphill phase using the following "rules":
    double beginning_best=this->best_total_route_length;
    rules=VRPH_LI_ACCEPT+VRPH_RECORD_TO_RECORD+objective+random+fixed+neighbor_list+tabu;

    if(verbose)
        printf("Uphill starting at %5.2f\n",this->total_route_length);
    
    for(int k=1;k<intensity;k++)
    {
        start_val=total_route_length;

        if(heuristics & ONE_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)
            {
#if FIXED_DEBUG
                if(fixed && !check_fixed_edges("Before 1PM\n"))
                    fprintf(stderr,"Error before OPM search(%d)\n",perm[i-1]);
#endif
                OPM.search(this,perm[i-1],rules);

#if FIXED_DEBUG
                if(fixed && !check_fixed_edges("After 1PM\n"))
                {
                    fprintf(stderr,"Error after OPM search(%d)\n",perm[i-1]);
                    this->show_route(this->route_num[perm[i-1]]);
                }
#endif
            }
        }


        if(heuristics & TWO_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TPM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY);

            //check_fixed_edges("After 2PM\n");

        }


        if(heuristics & THREE_POINT_MOVE)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                ThreePM.search(this,perm[i-1],rules + VRPH_INTER_ROUTE_ONLY);

            //check_fixed_edges("After 3PM\n");

        }



        if(heuristics & TWO_OPT)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            //check_fixed_edges("After TO\n");


        }        


        if(heuristics & OR_OPT)
        {
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],4,rules);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],3,rules);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],2,rules);

            //check_fixed_edges("After OR\n");

        }

        if(heuristics & THREE_OPT)
        {
            normalize_route_numbers();
            R=total_number_of_routes;

            for(i=1; i<=R; i++)    
                ThreeO.route_search(this,i,rules-neighbor_list);

            //check_fixed_edges("After 3O\n");

        }

        if(heuristics & CROSS_EXCHANGE)
        {
            normalize_route_numbers();
            this->find_neighboring_routes();
            R=total_number_of_routes;

            for(i=1; i<=R-1; i++)    
            {
                for(j=0;j<1;j++)
                    CE.route_search(this,i, route[i].neighboring_routes[j],rules-neighbor_list); 
            }

            //check_fixed_edges("After CE\n");
        }
    }

    if(total_route_length<record)
        record = total_route_length;

    if(verbose)
    {
        printf("Uphill complete\t(%d,%5.2f,%5.2f)\n",count_num_routes(),total_route_length, record);
        printf("# of recorded routes: %d[%d]\n",total_number_of_routes,count_num_routes());

    }

    if(this->best_total_route_length<beginning_best-VRPH_EPSILON)
    {
        if(verbose)
            printf("New best found in uphill!\n");
        // We found a new best solution during the uphill phase that might
        // now be "forgotten"!! I have seen this happen where it is never recovered
        // again, so we just import it and start the downhill phase with this solution...
        //this->import_solution_buff(this->best_sol_buff);

    }

downhill:

    // Now enter a downhill phase
    double orig_val=total_route_length;
    if(verbose)
        printf("Downhill starting at %f (best=%f)\n",orig_val,this->best_total_route_length);


    if((heuristics & ONE_POINT_MOVE)|| (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {
            // One Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)
                OPM.search(this,perm[i-1],rules );


            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }

    }



    if((heuristics & TWO_POINT_MOVE) || (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {
            // Two Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TPM.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }

    }



    if((heuristics & TWO_OPT)|| (heuristics & KITCHEN_SINK) )
    {
        // Do inter-route first a la Li
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+neighbor_list+accept_type;
        for(;;)
        {

            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }

        // Now do both intra and inter
        rules=VRPH_DOWNHILL+objective+random+fixed+neighbor_list+accept_type;

        for(;;)
        {

            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                TO.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }

    if((heuristics & THREE_POINT_MOVE) || (heuristics & KITCHEN_SINK) )
    {
        rules=VRPH_DOWNHILL+VRPH_INTER_ROUTE_ONLY+objective+random+fixed+accept_type+neighbor_list;
        for(;;)
        {
            // Three Point Move
            start_val=total_route_length;

            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                ThreePM.search(this,perm[i-1],rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 

        }
    }


    if((heuristics & OR_OPT) || (heuristics & KITCHEN_SINK))
    {

        rules=VRPH_DOWNHILL+ objective +random +fixed + accept_type + neighbor_list;

        for(;;)
        {
            // OrOpt
            start_val=total_route_length;
            if(random)
                random_permutation(perm, this->num_nodes);

            for(i=1;i<=n;i++)    
                OR.search(this,perm[i-1],4,rules);
            for(i=1;i<=n;i++)
                OR.search(this,perm[i-1],3,rules);
            for(i=1;i<=n;i++)
                OR.search(this,perm[i-1],2,rules);


            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }

    if((heuristics & THREE_OPT) || (heuristics & KITCHEN_SINK) )
    {
        normalize_route_numbers();
        R= total_number_of_routes;
        rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type;
        for(;;)
        {
            // 3OPT
            start_val=total_route_length;

            for(i=1;i<=R;i++)    
                ThreeO.route_search(this,i,rules);

            if(VRPH_ABS(total_route_length-start_val)<VRPH_EPSILON)
                break; 
        }
    }


    if( (heuristics & CROSS_EXCHANGE) )
    {
        normalize_route_numbers();
        this->find_neighboring_routes();
        R=total_number_of_routes;

        rules=VRPH_DOWNHILL+objective+VRPH_INTRA_ROUTE_ONLY+ random +fixed + accept_type;

        for(i=1; i<=R-1; i++)    
        {
            for(j=0;j<=1;j++)
                CE.route_search(this,i, route[i].neighboring_routes[j], rules); 
        }
    }


    // Repeat the downhill phase until we find no more improvements
    if(total_route_length<orig_val-VRPH_EPSILON)
        goto downhill;
    if(verbose)
        printf("Downhill complete: %5.2f[downhill started at %f] (%5.2f)\n",total_route_length,orig_val,
        this->best_total_route_length);


    if(total_route_length < record-VRPH_EPSILON)    
    {
        // New record - reset ctr
        ctr=1;
        record=total_route_length;
    }
    else
        ctr++;

    if(ctr<max_stuck)
        goto uphill;

    if(ctr==max_stuck)
    {
        if(num_perturbs<max_perturbs)
        {
            if(verbose)
                printf("perturbing\n");
            if(perturb_type==VRPH_LI_PERTURB)
                perturb();
            else
                osman_perturb(VRPH_MAX(20,num_nodes/10),.5+lcgrand(20));

            // Reset record
            this->record=this->total_route_length;
            if(tabu)
                this->tabu_list->empty();

            ctr=1;
            num_perturbs++;
            goto uphill;
        }
    }


    if(verbose)
    {
        if(has_service_times==false)
            printf("BEST OBJ:  %f\n",best_total_route_length);
        else
            printf("BEST OBJ:  %f\n",best_total_route_length-total_service_time);
    }

    delete [] perm; 

    // Import the best solution found
    this->import_solution_buff(best_sol_buff);

    if(has_service_times==false)
        return best_total_route_length;
    else
        return best_total_route_length-total_service_time;


}
Пример #25
0
int main(void) {
  
  int f,i,j,k,c,x,y,ix,iy,displayloop;
  int usingmap,makingmap,mmx,mmy,tmpmap,maploop;
    float rx,ry,nrx,nry,px,py,thru,ctmp;
  RGB rgb;
  FILE *fp;
  
  srand((int)time(NULL));
  
  usingmap=0; makingmap=1; mmx=0; mmy=0;
  

   img=(uchar **)calloc(scrhei,sizeof(uchar *));
    img2=(uchar **)calloc(scrhei,sizeof(uchar *));
    for (y=0;y<scrhei;y++) {
        img[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        img2[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        for (x=0;x<scrwid;x++) {
            img[y][x]=255*y/scrhei;
            img2[y][x]=myrnd()*255;
            if (x<scrwid-1 && y<scrhei-1) {
              pix[x][y][usingmap]=x;
              piy[x][y][usingmap]=y;
              for (i=0;i<=1;i++)
                for (j=0;j<=1;j++)
                  amount[x][y][i][j][usingmap]=(float)1/4;
            }
        }
    }
  
  /* Originals from QB
     op[0] = 1; damp[0] = .999; force[0] = .005;
     op[1] = 1.02; damp[1] = .999; force[1] = .002;
     op[2] = 0; damp[2] = .999; force[2] = .002;
     op[3] = 1; damp[3] = .999; force[3] = .005;
     op[4] = 1; damp[4] = .999; force[4] = .005;
     op[5] = 0; damp[5] = .999; force[5] = .002;
     */
  
  // 0 Accelerate
  op[0] = 1; damp[0] = .999; force[0] = .005;
  // 1 Velocity
  op[1] = 1.02; damp[1] = .999; force[1] = .01;
  // 2 Rotation
  op[2] = 0; damp[2] = .995; force[2] = .03;
  // 3 y splurge
  op[3] = 0; damp[3] = .999; force[3] = .01;
  // 4 Dribble
  op[4] = 1; damp[4] = 0; force[4] = .01;
  // 5 x splurge
  op[5] = 0; damp[5] = .999; force[5] = .01;
  op[6]=2;damp[6]=.9999;force[6]=.01;
  op[7]=1;damp[7]=.999;force[7]=.01;
  
  
  for (f=0;f<fs;f++) {
    var[f] = op[f];
    fon[f]=1;
  }
  
  allegrosetup(scrwid,scrhei);
  _farsetsel(screen->seg);

  starttimer();

  while(!key[KEY_ESC]) {
    
    // Generate some more of the map
    for (maploop=1;maploop<scrwid*scrhei/20;maploop++) {
      rx=(float)mmx/scrwid*2-1;
      ry=(float)(mmy-scrhei/2)/scrwid*2;
      if (fon[0]) {
        rx = mysgn(rx)/var[7]*mypow(myabs(rx),1/var[0]);
        ry = mysgn(ry)/var[7]*mypow(myabs(ry),1/var[0]);
      }
      if (fon[1]) {
        rx = rx / var[1]; ry = ry / var[1];
      }
      if (fon[2]) {
        nrx = rx * cos(var[2]) + ry * sin(var[2]);
        nry = -rx * sin(var[2]) + ry * cos(var[2]);
        rx = nrx; ry=nry;
      }
      if (fon[3]) {
        ry = ry - mysgn(ry) * sin(var[6]*pi*myabs(ry)) * var[3];
      }
      if (fon[4]) {
        ry = ((myabs(ry) - 1) / var[4] + 1) * mysgn(ry);
      }
      if (fon[5]) {
        rx = rx - mysgn(rx) * sin(var[6]*pi*myabs(rx)) * var[5];
      }
      px=(rx+1)/2*scrwid;
      py=scrhei/2+(ry)/2*scrwid;
      ix=(int)px;
      iy=(int)py;
      if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
        ix=px; iy=py;
      }
      amount[mmx][mmy][0][0][makingmap]=((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
      amount[mmx][mmy][1][0][makingmap]=((float)px-(float)ix)*((float)(iy+1)-(float)py);
      amount[mmx][mmy][0][1][makingmap]=((float)ix+1-(float)px)*((float)py-(float)iy);
      amount[mmx][mmy][1][1][makingmap]=((float)px-(float)ix)*((float)py-(float)iy);
      pix[mmx][mmy][makingmap]=ix;
      piy[mmx][mmy][makingmap]=iy;
      if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
        pix[mmx][mmy][makingmap]=scrwid/2;
        piy[mmx][mmy][makingmap]=scrhei/2;
        for (i=0;i<=1;i++) {
          for (j=0;j<=1;j++) {
            amount[mmx][mmy][i][j][makingmap]=0;
          }
        }
      }
      mmx++;
      if (mmx>=scrwid) {
        mmx=0;
        mmy++;
        if (mmy>=scrhei) {
          mmy=0;
          tmpmap=usingmap;
          usingmap=makingmap;
          makingmap=tmpmap;
          for (f=0;f<fs;f++) {
            perturb(f);
          }
        }
      }
    }
    
    // Animate
    for (x=0; x<scrwid; x++) {
      for (y=0; y<scrhei; y++) {
        c=0;
        for (i=0;i<=1;i++) {
          for (j=0;j<=1;j++) {
            c=c+amount[x][y][i][j][usingmap]*img[piy[x][y][usingmap]+j][pix[x][y][usingmap]+i];
          }
        }
        c--;
        img2[y][x]=c;
      }
    }
    /* for (y=0;y<scrhei;y++) {
         for (x=0;x<scrwid;x++) {
           _farpokeb(screen->seg, (unsigned long)screen->line[y]+x, img2[y][x]);
         }
       }*/
    for (y=0; y<scrhei; y++) {
      movedata(_my_ds(), img2[y], screen->seg, bmp_write_line(screen,y), scrwid);
    }
    for (f=0;f<fs;f++) {
      if (fon[f]) {
        hline(screen, scrwid/2, f*2, scrwid/2+(var[f] - op[f]) * scrwid * 4, 0);
      }
    }
        toff=toff-(float)1/128;
    for (c=0;c<=255;c++) {
      thru=saw((float)c/255-toff);
      rgb.r=huefor(thru,(float)0);
      rgb.g=huefor(thru,(float)1/3);
      rgb.b=huefor(thru,(float)2/3);
      set_color(c,&rgb);
    }
    imgtmp=img;
    img=img2;
    img2=imgtmp;
    for (i=1;i<=5;i++) {
      mycircle(myrnd()*scrwid,myrnd()*scrhei,2+myrnd()*8,myrnd()*255);
    }
    framedone();
  }

  allegro_exit();
  displayframespersecond();

}
Пример #26
0
int LayerNet::ssg_core (
   TrainingSet *tptr ,        // Training set to use
   struct LearnParams *lptr , // User's general learning parameters
   LayerNet *avgnet ,         // Work area used to keep average weights
   LayerNet *bestnet ,        // And the best so far
   double *work1 ,            // Gradient work vector
   double *work2 ,            // Ditto
   double *grad ,             // Ditto
   double *avg_grad ,         // Ditto
   int n_grad                 // Length of above vectors
   )
{
   int ntemps, niters, setback, reg, nvars, user_quit ;
   int i, iter, itemp, n_good, n_bad, use_grad ;
   char msg[80] ;
   double tempmult, temp, fval, bestfval, starttemp, stoptemp, fquit ;
   double avg_func, new_fac, gradlen, grad_weight, weight_used ;
   enum RandomDensity density ;
   SingularValueDecomp *sptr ;
   struct AnnealParams *aptr ; // User's annealing parameters

   aptr = lptr->ap ;

   ntemps = aptr->temps0 ;
   niters = aptr->iters0 ;
   setback = aptr->setback0 ;
   starttemp = aptr->start0 ;
   stoptemp = aptr->stop0 ;
   if (aptr->random0 == ANNEAL_GAUSSIAN)
      density = NormalDensity ;
   else if (aptr->random0 == ANNEAL_CAUCHY)
      density = CauchyDensity ;

   if (! (ntemps * niters))
      return 0 ;

/*
   Initialize other local parameters.  Note that there is no sense using
   regression if there are no hidden layers.
*/

   use_grad = (grad != NULL) ;
   fquit = lptr->quit_err ;
   reg = nhid1 ;

/*
   Allocate the singular value decomposition object for REGRESS.
   Also allocate a work area for REGRESS to preserve matrix.
*/

   if (reg) {                 // False if no hidden layers
      if (nhid2 == 0)         // One hidden layer
         nvars = nhid1_n ;
      else                    // Two hidden layers
         nvars = nhid2_n ;

      i = (model == NETMOD_COMPLEX)  ?  2 * tptr->ntrain : tptr->ntrain ;

      if (i < nvars) {
         warning_message ( "Too few training sets for regression." ) ;
         reg = 0 ;
         }
      else {
         MEMTEXT ( "SSG: new SingularValueDecomp" ) ;
         sptr = new SingularValueDecomp ( i , nvars , 1 ) ;

         if ((sptr == NULL)  || ! sptr->ok) {
            memory_message (
               "for SS(G) with regression.  Using total randomization.");
            if (sptr != NULL)
               delete sptr ;
            reg = 0 ;
            }
         }
      }

/*
   For the basic algorithm, we will keep the current 'average' network
   weight set in avgnet.  This will be the moving center about which the
   perturbation is done.
   Although not directly related to the algorithm itself, we keep track
   of the best network ever found in bestnet.  That is what the user
   will get at the end.
*/

   copy_weights ( bestnet , this ) ; // Current weights are best so far
   copy_weights ( avgnet , this ) ;  // Center of perturbation
   bestfval = trial_error ( tptr ) ;

/*
   If this is being used to initialize the weights, make sure that they are
   not identically zero.  Do this by setting bestfval huge so that
   SOMETHING is accepted later.
*/

   if (nhid1) {
      i = nhid1 * nin_n ;
      while (i--) {
         if (fabs(hid1_coefs[i]) > 1.e-10)
            break ;
         }
      if (i < 0)
         bestfval = 1.e30 ;
      }

/*
   Initialize by cumulating a bunch of points
*/

   normal_message ( "Initializing..." ) ;
   avg_func = 0.0 ;                       // Mean function around center
   if (use_grad) {
      for (i=0 ; i<n_grad ; i++)          // Zero the mean gradient
         avg_grad[i] = 0.0 ;
      }

   for (iter=0 ; iter<niters ; iter++) {  // Initializing iterations

      perturb ( avgnet , this , starttemp , reg , density ) ; // Move point

      if (reg)                            // If using regression, estimate
         fval = regress ( tptr , sptr ) ; // out weights now, ignore fval
      if (use_grad)                       // Also need gradient?
         fval = gradient ( tptr , work1 , work2 , grad ) ; // fval redundant
      else if (! reg)                     // If reg we got fval from regress
         fval = trial_error ( tptr ) ;

      avg_func += fval ;                  // Cumulate mean function

      if (use_grad) {                     // Also need gradient?
         for (i=0 ; i<n_grad ; i++)       // Cumulate mean gradient
            avg_grad[i] += grad[i] ;
         }

      if (fval < bestfval) {              // If this iteration improved
         bestfval = fval ;                // then update the best so far
         copy_weights ( bestnet , this ) ; // Keep the network
         if (bestfval <= fquit)           // If we reached the user's
            goto FINISH ;                 // limit, we can quit
         }

      if ((user_quit = user_pressed_escape ()) != 0)
         goto FINISH ;

      } // Loop: for all initial iters

   avg_func /= niters ;          // Mean of all points around avgnet
   new_fac = 1.0 / niters ;      // Weight of each point

   sprintf ( msg , "  avg=%.6lf  best=%.6lf", avg_func, bestfval ) ;
   progress_message ( msg ) ;

   if (use_grad) {               // Also need gradient?
      gradlen = 0.0 ;            // Will cumulate grad length
      for (i=0 ; i<n_grad ; i++) {  // Find gradient mean and length
         avg_grad[i] /= niters ;
         gradlen += avg_grad[i] * avg_grad[i] ;
         }
      gradlen = sqrt ( gradlen ) ;
      grad_weight = 0.5 ;
      }

/*
   This is the temperature reduction loop and the iteration within
   temperature loop.
*/

   temp = starttemp ;
   tempmult = exp( log( stoptemp / starttemp ) / (ntemps-1)) ;
   user_quit = 0 ;                           // Flags user pressed ESCape

   for (itemp=0 ; itemp<ntemps ; itemp++) {  // Temp reduction loop

      n_good = n_bad = 0 ;                   // Counts better and worse

      sprintf ( msg , "Temp=%.3lf ", temp ) ;
      normal_message ( msg ) ;

      for (iter=0 ; iter<niters ; iter++) {  // Iters per temp loop

         if ((n_bad >= 10)  &&
             ((double) n_good / (double) (n_good+n_bad)  <  0.15))
            break ;

         perturb ( avgnet , this , temp ,
                   reg , density ) ;         // Randomly perturb about center

         if (use_grad)                       // Bias per gradient?
            weight_used = shift ( grad , this , grad_weight , reg ) ;

         if (reg) {                          // If using regression, estimate
            fval = regress ( tptr , sptr ) ; // out weights now
            if ((user_quit = user_pressed_escape ()) != 0)
               break ;
            if (fval >= avg_func) {          // If this would raise mean
               ++n_bad ;                     // Count this bad point for user
               continue ;                    // Skip it and try again
               }
            }

         if (use_grad)                       // Need gradient, fval redundant
            fval = gradient ( tptr , work1 , work2 , grad ) ;
         else if (! reg)                     // If reg we got fval from regress
            fval = trial_error ( tptr ) ;

         if ((user_quit = user_pressed_escape ()) != 0)
            break ;

         if (fval >= avg_func) {             // If this would raise mean
            ++n_bad ;                        // Count this bad point for user
            continue ;                       // Skip it and try again
            }

         ++n_good ;

         if (fval < bestfval) {              // If this iteration improved
            bestfval = fval ;                // then update the best so far
            copy_weights ( bestnet , this ) ; // Keep the network

            if (bestfval <= fquit)           // If we reached the user's
               break ;                       // limit, we can quit

            iter -= setback ;                // It often pays to keep going
            if (iter < 0)                    // at this temperature if we
               iter = 0 ;                    // are still improving
            }

         adjust ( avgnet , this , reg , new_fac ) ; // Move center slightly
         avg_func = new_fac * fval  +  (1.0 - new_fac) * avg_func ;
         if (use_grad) {
            grad_weight = new_fac * weight_used + (1.0 - new_fac) * grad_weight ;
            for (i=0 ; i<n_grad ; i++)          // Adjust mean gradient
               avg_grad[i] = new_fac * grad[i] + (1.0 - new_fac) * avg_grad[i] ;
            }
         }                                   // Loop: for all iters at a temp

/*
   Iters within temp loop now complete
*/

      sprintf ( msg , " %.3lf%% improved  avg=%.5lf  best=%.5lf",
         100.0 * n_good / (double) (n_good+n_bad), avg_func, bestfval ) ;
      progress_message ( msg ) ;

      if (use_grad) {
         gradlen = 0.0 ;                        // Will cumulate grad length
         for (i=0 ; i<n_grad ; i++)             // Find gradient length
            gradlen += avg_grad[i] * avg_grad[i] ;
         gradlen = sqrt ( gradlen ) ;
         sprintf ( msg , "  grad=%.5lf", gradlen ) ;
         progress_message ( msg ) ;
         }

      if (bestfval <= fquit)  // If we reached the user's
         break ;              // limit, we can quit

      if (user_quit)
         break ;

      temp *= tempmult ;      // Reduce temp for next pass
      }                       // through this temperature loop


/*
   The trials left this weight set and neterr in random condition.
   Make them equal to the best, which will be the original
   if we never improved.
*/

FINISH:
   copy_weights ( this , bestnet ) ; // Return best weights in this net
   neterr = bestfval ;               // Trials destroyed weights, err

   if (reg) {
      MEMTEXT ( "SSG: delete SingularValueDecomp" ) ;
      delete sptr ;
      }

   if (user_quit)
      return 1 ;
   else
      return 0 ;
}