示例#1
0
    void ShortcutProcessor::doPathPruning()
    {
        THROW_VR_EXCEPTION_IF(!initSolution(), "Could not init");

        unsigned int i = 0;

        while (i < optimizedPath->getNrOfPoints() - 2)
        {
            Eigen::VectorXf startConfig = optimizedPath->getPoint(i);
            Eigen::VectorXf endConfig = optimizedPath->getPoint(i + 2);

            if (cspace->isPathValid(startConfig, endConfig))
            {
                optimizedPath->erasePosition(i + 1);

                if (i > 0)
                {
                    i--;
                }
            }
            else
            {
                i++;
            }
        }
    }
示例#2
0
    bool ShortcutProcessor::selectCandidatesRandom(int& storeStartIndex, int& storeEndIndex, int maxSolutionPathDist)
    {
        if (!optimizedPath)
            if (!initSolution())
            {
                return false;
            }

        if (!optimizedPath || optimizedPath->getNrOfPoints() <= 2)
        {
            return false;
        }

        if (maxSolutionPathDist < 2)
        {
            maxSolutionPathDist = 2;
        }

        storeStartIndex = (int)(rand() % (optimizedPath->getNrOfPoints() - 2));

        int remainig = optimizedPath->getNrOfPoints() - 2 - storeStartIndex;

        if (remainig > maxSolutionPathDist)
        {
            remainig = maxSolutionPathDist;
        }

        if (remainig <= 0)
        {
            return false;
        }

        int dist = 2 + rand() % (remainig);
        storeEndIndex = storeStartIndex + dist;

        if (storeStartIndex < 0 || storeEndIndex < 0)
        {
            return false;
        }

        if (storeEndIndex > (int)optimizedPath->getNrOfPoints() - 1)
        {
            return false;
        }

        if (storeStartIndex > (int)optimizedPath->getNrOfPoints() - 1)
        {
            return false;
        }

        if ((storeEndIndex - storeStartIndex) <= 1)
        {
            return false;
        }

        return true;
    }
示例#3
0
    CSpacePathPtr ShortcutProcessor::shortenSolutionRandom(int shortenLoops /*=300*/, int maxSolutionPathDist)
    {
        stopOptimization = false;
        THROW_VR_EXCEPTION_IF((!cspace || !path), "NULL data");
        THROW_VR_EXCEPTION_IF(!initSolution(), "Could not init...");
        int counter = 0;

        if (optimizedPath->getNrOfPoints() <= 2)
        {
            return optimizedPath;
        }

        int result = 0;
        int beforeCount = (int)optimizedPath->getNrOfPoints();
        float beforeLength = optimizedPath->getLength();

        if (verbose)
        {
            SABA_INFO << ": solution size before shortenSolutionRandom:" << beforeCount << std::endl;
            SABA_INFO << ": solution length before shortenSolutionRandom:" << beforeLength << std::endl;
        }

        clock_t startT = clock();

        int red;
        int loopsOverall = 0;

        while (counter < shortenLoops && !stopOptimization)
        {
            loopsOverall++;
            red = tryRandomShortcut(maxSolutionPathDist);

            counter++;
            result += red;
        }

        if (stopOptimization)
        {
            SABA_INFO << "optimization was stopped" << std::endl;
        }

        int afterCount = (int)optimizedPath->getNrOfPoints();
        float afterLength = optimizedPath->getLength();
        clock_t endT = clock();
        float timems = (float)(endT - startT) / (float)CLOCKS_PER_SEC * 1000.0f;

        if (verbose)
        {
            SABA_INFO << ": shorten loops: " << loopsOverall << std::endl;
            SABA_INFO << ": shorten time: " << timems << " ms " << std::endl;
            SABA_INFO << ": solution size after ShortenSolutionRandom (nr of positions) : " << afterCount << std::endl;
            SABA_INFO << ": solution length after ShortenSolutionRandom : " << afterLength << std::endl;
        }

        return optimizedPath;
    }
示例#4
0
    bool ShortcutProcessor::validShortcut(int startIndex, int endIndex)
    {
        if (!optimizedPath)
            if (!initSolution())
            {
                return false;
            }

        Eigen::VectorXf s = optimizedPath->getPoint(startIndex);
        Eigen::VectorXf e = optimizedPath->getPoint(endIndex);
        Eigen::VectorXf d = e - s;

        // test line between start and end
        float distShortcut = d.norm();
        float distPath = optimizedPath->getLength(startIndex, endIndex);

        // -------------------------------------------------------------------
        // DEBUG
        if (verbose)
        {
            std::cout << "-- distShortcut: " << distShortcut << " distPath: " << distPath << std::endl;
        }

        // -------------------------------------------------------------------

        if (distShortcut >= distPath * 0.99f)
        {
            if (verbose)
            {
                cout << "Path is not shorter..." << endl;
            }

            return false;
        }

        // -------------------------------------------------------------------
        // DEBUG
        if (verbose)
        {
            std::cout << ": Shortcut Path shorter!" << std::endl;
        }

        // -------------------------------------------------------------------

        return cspace->isPathValid(s, e);
    }
示例#5
0
    int ShortcutProcessor::doShortcut(int startIndex, int endIndex)
    {
        if (!optimizedPath)
            if (!initSolution())
            {
                return 0;
            }

        if (!optimizedPath || !cspace || startIndex < 0 || endIndex < 0 || startIndex >= (int)optimizedPath->getNrOfPoints() || endIndex >= (int)optimizedPath->getNrOfPoints())
        {
            return 0;
        }

        for (int i = endIndex - 1; i >= startIndex + 1; i--)
        {
            // erase solution positions
            optimizedPath->erasePosition(i);
        }

        if (verbose)
        {
            float distPathtest = optimizedPath->getLength(startIndex, startIndex + 1);
            std::cout << "-- erased intermediate positions, distPath startIndex to (startIndex+1): " << distPathtest << std::endl;
        }

        /*cout << "all2:" << endl;
        optimizedPath->print();*/

        Eigen::VectorXf s = optimizedPath->getPoint(startIndex);
        Eigen::VectorXf e = optimizedPath->getPoint(startIndex + 1);

        // create intermediate path
        CSpacePathPtr intermediatePath = cspace->createPath(s, e);
        int newP = 0;

        if (intermediatePath->getNrOfPoints() > 2)
        {
            newP = intermediatePath->getNrOfPoints() - 2;
            /*cout << "before:" << endl;
            optimizedPath->print();
            cout << "interm path:" << endl;
            intermediatePath->print();*/
            intermediatePath->erasePosition(intermediatePath->getNrOfPoints() - 1);
            intermediatePath->erasePosition(0);
            /*cout << "interm path without start end:" << endl;
            intermediatePath->print();*/
            optimizedPath->insertTrajectory(startIndex + 1, intermediatePath);
            /*cout << "after:" << endl;
            optimizedPath->print(); */
        }

        if (verbose)
        {
            float sum = 0.0f;

            for (int u = startIndex; u <= startIndex + newP; u++)
            {
                float distPathtest2 = optimizedPath->getLength(u, u + 1);
                sum += distPathtest2;
                std::cout << "---- intermediate position: " << u << ", distPath to next pos: " << distPathtest2 << ", sum:" << sum << std::endl;
            }
        }

        int nodes = endIndex - startIndex - 1 + newP;

        if (verbose)
        {
            std::cout << "-- end, nodes: " << nodes << std::endl;
        }


        return nodes;
    }
示例#6
0
int main(int argc, char *argv[])
{
  register int n, k;

  char    rayFileName[14], inputLine[MAX_LINE_SIZE];
  bool_t  result, exit_on_EOF, to_obs, initialize, crosscoupling,
          analyze_output, equilibria_only;
  int     Nspect, Nread, Nrequired, checkPoint, *wave_index = NULL;
  double  muz, *S, *chi, *J;
  FILE   *fp_out, *fp_ray, *fp_stokes;
  XDR     xdrs;
  ActiveSet *as;

  setOptions(argc, argv);
  getCPU(0, TIME_START, NULL);
  SetFPEtraps();

  /* --- Read input data and initialize --             -------------- */

  readInput();
  spectrum.updateJ = FALSE;

  /* --- Read input data for atmosphere --             -------------- */

  getCPU(1, TIME_START, NULL);
  MULTIatmos(&atmos, &geometry);

  /* --- Read direction cosine for ray --              -------------- */

  if ((fp_ray = fopen(RAY_INPUT_FILE, "r")) == NULL) {
    sprintf(messageStr, "Unable to open inputfile %s", RAY_INPUT_FILE);
    Error(ERROR_LEVEL_2, argv[0], messageStr);
  }
  
  getLine(fp_ray, COMMENT_CHAR, inputLine, exit_on_EOF=TRUE);
  Nread = sscanf(inputLine, "%lf", &muz);
  checkNread(Nread, Nrequired=1, argv[0], checkPoint=1);

  if (muz <= 0.0  ||  muz > 1.0) {
    sprintf(messageStr,
	    "Value of muz = %f does not lie in interval <0.0, 1.0]\n", muz);
    Error(ERROR_LEVEL_2, argv[0], messageStr);
  }

  if (input.StokesMode == FIELD_FREE ||
      input.StokesMode == POLARIZATION_FREE) {
    input.StokesMode = FULL_STOKES;
  }
  /* --- redefine geometry for just this one ray --    -------------- */

  atmos.Nrays = geometry.Nrays = 1;
  geometry.muz[0] = muz;
  geometry.mux[0] = sqrt(1.0 - SQ(geometry.muz[0]));
  geometry.muy[0] = 0.0;
  geometry.wmu[0] = 1.0;
  if (atmos.Stokes) Bproject();

  input.startJ = OLD_J;

  readAtomicModels();
  readMolecularModels();
  SortLambda();

  getBoundary(&geometry);

  /* --- Open file with background opacities --        -------------- */

  if (atmos.moving || input.StokesMode) {
    strcpy(input.background_File, "background.ray");
    Background(analyze_output=FALSE, equilibria_only=FALSE);
  } else {
    Background(analyze_output=FALSE, equilibria_only=TRUE);

    if ((atmos.fd_background =
	 open(input.background_File, O_RDONLY, 0)) == -1) {
      sprintf(messageStr, "Unable to open inputfile %s",
	      input.background_File);
      Error(ERROR_LEVEL_2, argv[0], messageStr);
    }
    readBRS();
  }
  convertScales(&atmos, &geometry);

  getProfiles();
  initSolution();
  initScatter();

  getCPU(1, TIME_POLL, "Total initialize");

  /* --- Solve radiative transfer equations --         -------------- */

  solveSpectrum(FALSE, FALSE);

  /* --- Write emergent spectrum to output file --     -------------- */
 
  sprintf(rayFileName, "spectrum_%4.2f", muz);
  if ((fp_out = fopen(rayFileName, "w" )) == NULL) {
    sprintf(messageStr, "Unable to open output file %s", rayFileName);
    Error(ERROR_LEVEL_2, argv[0], messageStr);
  }
  xdrstdio_create(&xdrs, fp_out, XDR_ENCODE);

  result = xdr_double(&xdrs, &muz);
  result = xdr_vector(&xdrs, (char *) spectrum.I[0], spectrum.Nspect,
		      sizeof(double), (xdrproc_t) xdr_double);

  /* --- Read wavelength indices for which chi and S are to be
         written out for the specified direction --    -------------- */

  Nread = fscanf(fp_ray, "%d", &Nspect);
  checkNread(Nread, 1, argv[0], checkPoint=2);

  if (Nspect > 0) {
    wave_index = (int *) malloc(Nspect * sizeof(int));
    Nread = 0;
    while (fscanf(fp_ray, "%d", &wave_index[Nread]) != EOF) Nread++;
    checkNread(Nread, Nspect, argv[0], checkPoint=3);
    fclose(fp_ray);

    chi = (double *) malloc(atmos.Nspace * sizeof(double));
    if (atmos.Stokes)
      S = (double *) malloc(4 * atmos.Nspace * sizeof(double));
    else
      S = (double *) malloc(atmos.Nspace * sizeof(double));
  }
  result = xdr_int(&xdrs, &Nspect);

  /* --- Go through the list of wavelengths --         -------------- */

  if (Nspect > 0  &&  input.limit_memory)
    J = (double *) malloc(atmos.Nspace * sizeof(double));

  for (n = 0;  n < Nspect;  n++) {
    if (wave_index[n] < 0  ||  wave_index[n] >= spectrum.Nspect) {
      sprintf(messageStr, "Illegal value of wave_index[n]: %4d\n"
	      "Value has to be between 0 and %4d\n", 
	      wave_index[n], spectrum.Nspect);
      Error(ERROR_LEVEL_2, argv[0], messageStr);
      continue;
    }
    sprintf(messageStr, "Processing n = %4d, lambda = %9.3f [nm]\n",
	    wave_index[n], spectrum.lambda[wave_index[n]]);
    Error(MESSAGE, NULL, messageStr);

    as = &spectrum.as[wave_index[n]];
    alloc_as(wave_index[n], crosscoupling=FALSE);
    Opacity(wave_index[n], 0, to_obs=TRUE, initialize=TRUE);
    readBackground(wave_index[n], 0, to_obs=TRUE);

    if (input.limit_memory) {
      readJlambda(wave_index[n], J);
    } else
      J = spectrum.J[wave_index[n]];

    /* --- Add the continuum opacity and emissivity -- -------------- */   

    for (k = 0;  k < atmos.Nspace;  k++) {
      chi[k] = as->chi[k] + as->chi_c[k];
      S[k]   = (as->eta[k] + as->eta_c[k] + as->sca_c[k]*J[k]) / chi[k];
    }
    result = xdr_int(&xdrs, &wave_index[n]);
    result = xdr_vector(&xdrs, (char *) chi, atmos.Nspace,
			sizeof(double), (xdrproc_t) xdr_double);
    result = xdr_vector(&xdrs, (char *) S, atmos.Nspace,
			sizeof(double), (xdrproc_t) xdr_double);

    free_as(wave_index[n], crosscoupling=FALSE);
  }

  /* --- If magnetic fields are present --             -------------- */
  
  if (atmos.Stokes || input.backgr_pol) {
    result = xdr_vector(&xdrs, (char *) spectrum.Stokes_Q[0],
			spectrum.Nspect, sizeof(double),
			(xdrproc_t) xdr_double);
    result = xdr_vector(&xdrs, (char *) spectrum.Stokes_U[0],
			spectrum.Nspect, sizeof(double),
			(xdrproc_t) xdr_double);
    result = xdr_vector(&xdrs, (char *) spectrum.Stokes_V[0],
			spectrum.Nspect, sizeof(double),
			(xdrproc_t) xdr_double);
  }

  if (Nspect > 0  &&  input.limit_memory)
    free(J);

  xdr_destroy(&xdrs);
  fclose(fp_out);
  printTotalCPU();
}
示例#7
0
void H1_heuristic (Problem * pb, Solution * s)
{
  initSolution (s);
  checkSolution (s, pb);

  /* build one route for each request */
  double distance = 0.0;
  for (uint16 req = 0; req < pb->nb_requests; ++req)
  {
    /* the four nodes involved */
    uint16 out  = s->id_out + req;
    uint16 pic  = pb->requests[req].orig->id;
    uint16 del  = pb->requests[req].dest->id;
    uint16 in   = s->id_in + req;

    /* set the next - prev chain */
    s->next[out] = pic;
    s->next[pic] = del;
    s->next[del] = in;
    s->prev[pic] = out;
    s->prev[del] = pic;
    s->prev[in]  = del;

    /* set the travel time */
    double arrival = 0.0;
    if (arrival < pb->nodes[0].open)
      arrival = pb->nodes[0].open;
    s->arrival[out] = arrival;
    arrival += pb->nodes[0].service;
    arrival += pb->duration[0][pic];
    if (arrival < pb->nodes[pic].open)
      arrival = pb->nodes[pic].open;
    s->arrival[pic] = arrival;
    arrival += pb->nodes[pic].service;
    arrival += pb->duration[pic][del];
    if (arrival < pb->nodes[del].open)
      arrival = pb->nodes[del].open;
    s->arrival[del] = arrival;
    arrival += pb->nodes[del].service;
    arrival += pb->duration[del][0];
    if (arrival < pb->nodes[0].open)
      arrival = pb->nodes[0].open;
    s->arrival[in] = arrival;

    /* compute the latest arrival time */
    double latest = pb->nodes[0].close;
    s->latest[in] = latest;
    latest -= pb->duration[del][0] + pb->nodes[del].service;
    if (latest > pb->nodes[del].close)
      latest = pb->nodes[del].close;
    s->latest[del] = latest;
    latest -= pb->duration[pic][del] + pb->nodes[pic].service;
    if (latest > pb->nodes[pic].close)
      latest = pb->nodes[pic].close;
    s->latest[pic] = latest;
    latest -= pb->duration[0][pic] + pb->nodes[0].service;
    if (latest > pb->nodes[0].close)
      latest = pb->nodes[0].close;
    s->latest[out] = latest;

    /* set the capacity */
    uint16 amount = pb->requests[req].amount;
    s->load[out] = 0;
    s->load[pic] = 0;
    s->load[del] = amount;
    s->load[in]  = 0;

    /* update the number of vehicles used */
    ++s->nb_vehicles;

    /* update the total distance */
    distance += pb->duration[0][pic] +
                pb->duration[pic][del] +
                pb->duration[del][0];
  }

  s->distance = distance;
}
示例#8
0
int main()
{
	int timer = 0,step,solution=0, useNew, accepted;
	
	float temp = INIT_TEMP;
	memberType current,working,best;
	
	FILE *fp;
	
	fp=fopen("stats.txt", "w");
	
	srand(time(NULL));
	
	initSolution(&current);
	computeEnergy(&current);
	
	best.energy=100.0;
	
	copySolution(&working, &current);
	
	while( temp > FIN_TEMP )
	{
		printf("\n Temperature = %f", temp);
		
		accepted = 0;
		
		/* Monte Carlo step*/
		
		for( step = 0; step < STEPS; step++);
		{
			useNew=0;
			
			tweakSolution(&working);
			computeEnergy(&working);
			
			if(working.energy <= current.energy)
			{
				useNew = 1;
			}
			else
			{
				float test = rand() % 1;
				float delta = working.energy - current.energy;
				float calc = exp(-delta/temp);
				
				if(calc > test)
				{
					accepted++;
					useNew = 1;
				}
			}
		}
		
		if(useNew)
		{
			useNew = 0;
			copySolution(&current, &working);
			
			if(current.energy < best.energy)
			{
				copySolution(&best, &current);
				solution = 1;
			}
			
			else
			{
				copySolution(&working, &current);
			}
			
		}
	
	
	fprintf(fp, "%d %f %f %d \n", timer++, temp, best.energy, accepted);
	printf("Best Energy = %f\n", best.energy);
	
	temp *= ALPHA;
	}
	
	fclose(fp);
	
	if(solution)
	{
		emitSolution(&best);
	}
	
	return 0;
}
示例#9
0
int main(int argc, char *argv[])
{
  bool_t analyze_output, equilibria_only;
  int    niter, nact;

  Atom *atom;
  Molecule *molecule;

  /* --- Read input data and initialize --             -------------- */

  setOptions(argc, argv);
  getCPU(0, TIME_START, NULL);
  SetFPEtraps();

  readInput();
  spectrum.updateJ = TRUE;
 
  getCPU(1, TIME_START, NULL);
  readAtmos(&atmos, &geometry);
  if (atmos.Stokes) Bproject();
  fillMesh(&geometry);

  readAtomicModels();
  readMolecularModels();
  SortLambda();
  
  getBoundary(&atmos, &geometry);

  Background(analyze_output=TRUE, equilibria_only=FALSE);

  getProfiles();
  initSolution();
  initScatter();

  getCPU(1, TIME_POLL, "Total initialize");
 
  /* --- Solve radiative transfer for active ingredients -- --------- */

  Iterate(input.NmaxIter, input.iterLimit);

  adjustStokesMode(atom);
  niter = 0;
  while (niter < input.NmaxScatter) {  
    if (solveSpectrum(FALSE, FALSE) <= input.iterLimit) break;
    niter++;
  }
  /* --- Write output files --                     ------------------ */
 
  getCPU(1, TIME_START, NULL);

  writeInput();
  writeAtmos(&atmos);
  writeGeometry(&geometry);
  writeSpectrum(&spectrum);
  writeFlux(FLUX_DOT_OUT);

  for (nact = 0;  nact < atmos.Nactiveatom;  nact++) {
    atom = atmos.activeatoms[nact];

    writeAtom(atom);
    writePopulations(atom);
    writeRadRate(atom);
    writeCollisionRate(atom);
    writeDamping(atom);
  } 
  for (nact = 0;  nact < atmos.Nactivemol;  nact++) {
    molecule = atmos.activemols[nact];
    writeMolPops(molecule);
  }

  writeOpacity();

  getCPU(1, TIME_POLL, "Write output");
  printTotalCPU();
}