示例#1
0
	void params_test() {
		float bestScore = MAX_FLOAT;
		float bestC1 = 0.0f;
		float bestC2 = 0.0f;
		float bestOMEGA = 0.0f;
		int bestREHOPE = 0;
		int bestIndex = -1;

		const int CHECKS = 20;
		const int MEAN = 20;
		// i sprawdzen losowych wartosci
		for(int i=0; i<CHECKS; i++) {
			std::cout << "Check " << i + 1 << " of " << CHECKS << std::endl;
			float C1 = randf(-1.9f, 1.9f);
			float C2 = randf(-1.9f, 1.9f);
			float OMEGA = randf(-1.9f, 1.9f);
			int REHOPE = ((rand() % 50) + 1) * 10;
			float avScore = 0.0f;
			float avScoreSA = 0.0f;
			float avScoreRS = 0.0f;
			// usrednienie dla j grafow
			for(int j=0; j<MEAN; j++) {
				Graph g(20, 1.0f, 10.0f);
				PSO::TspSwarm swarm(&g, g.V(), C1, C2, OMEGA, REHOPE);
				SA::SimulatedAnnealing sa(&g);
				RS::RandomSearch rnd(&g);
				swarm.compute(false);
				sa.compute(false);
				rnd.compute(false);
				avScore += swarm.getBestCost();
				avScoreSA += sa.getBestCost();
				avScoreRS += rnd.getBestCost();
			}
			avScore /= static_cast<float>(MEAN);
			avScoreSA /= static_cast<float>(MEAN);
			avScoreRS /= static_cast<float>(MEAN);
			std::cout << "Average score (" << MEAN << " checks): " << avScore << " (SA: " << avScoreSA 
				<< ", RS: " << avScoreRS << ")" << std::endl;
			if(avScore - avScoreSA < bestScore) {
				bestIndex = i + 1;
				bestScore = avScore - avScoreSA;
				bestC1 = C1;
				bestC2 = C2;
				bestOMEGA = OMEGA;
				bestREHOPE = REHOPE;
			}
		}
		std::cout << "Best index: " << bestIndex << std::endl;
		std::cout << "Best C1: " << bestC1 << std::endl;
		std::cout << "Best C2: " << bestC2 << std::endl;
		std::cout << "Best OMEGA: " << bestOMEGA << std::endl;
		std::cout << "Best REHOPE: " << bestREHOPE << std::endl;

		same_graphs_test(bestC1, bestC2, bestOMEGA, bestREHOPE);
	}
void LinesVisualisation::performStepComputation()
{

    // do not perform painting if not visible
    if(!isVisible())
        return;

    clearGraphs();
    QVector<double> x, y;

    // Paint the best
    for (int i = 0; i < swarm()->size(); i++) {
        const Particle *particle = (*swarm())[i];
        x.clear();
        y.clear();
        y = particle->position;
        for (int j = 0; j < swarm()->dimension(); j++) {
            x.append(j + 1);
        }
        addGraph();
        graph(i)->setData(x, y);
        graph(i)->setPen(VisualisationHelper::rainbowCoding(i, swarm()->size()));
    }
    xAxis->setRange(0, swarm()->dimension());
    if (swarm()->dimension() < 20)
    {
        xAxis->setAutoTickStep(false);
        xAxis->setTickStep(1);
    }
    rescaleAxes(true);
    setInteraction(QCP::iRangeDrag, true);
    setInteraction(QCP::iRangeZoom, true);
    replot();
}
FitterResults SwarmFitterInterface::runFitter(ModelTuningParameters * startPoint) {

	int numberOfFlies = (int)(10.0+2.0*sqrt((double)toInt(fixedParams["Dimensions"])));

	showMessage("Running Swarm Optimization with " + str(numberOfFlies) + " flies\n",3,fixedParams); 

	vector< ModelTuningParameters > results; 

	int maxInformed = 3;
	double w = 1.0/(2.0*log(2.0));
	double c = 0.5 + log(2.0);
	
	double tempBestValue = 0;
	///True if tempBestValue is initialized
	bool initBest = false; 

	int numberOfRuns = toInt(fixedParams["NumberOfRuns"]);
	if (numberOfRuns < 0) crash("SwarmFitterInterface","Negative number of runs !!");

	MTRand randGen( toInt(fixedParams["Seed"]) );

	vector< SwarmFly > swarm(numberOfFlies, SwarmFly(w, c, &randGen, FixedParameters(fixedParams.getGlobals(),true)));

	vector< ModelTuningParameters > startPoints(numberOfFlies,ModelTuningParameters(*startPoint));

	ModelTuningParameters startX;
	ModelTuningParameters startY;

	//////////////////////////////////
	/// Initialize the swarm flies ///
	//////////////////////////////////
	for (int i = 0; i < numberOfFlies; i++) {
		startPoints[i] = swarm[i].calculateRandomPosition();				
	}
	
	errorValue->calculateParallelErrorValue(startPoints);
	results.insert(results.end(),startPoints.begin(),startPoints.end()); 


	for (int i = 0; i < numberOfFlies; i++) {
		swarm[i].setNewPositionErrorValue(startPoints[i]);
	}

	///////////////////////////
	/// Initialize topology ///
	///////////////////////////
	randomizeTopology(swarm, maxInformed, randGen);
	
	/////////////////////
	/// Run Algorithm ///
	/////////////////////
	vector< ModelTuningParameters > flyPositions(numberOfFlies);

	for (int i = 0; i < numberOfRuns; i++) {		
		for (int j = 0; j < numberOfFlies; j++) {
			flyPositions[j] = swarm[j].calculateNewPosition();
		}

		errorValue->calculateParallelErrorValue(flyPositions);
		results.insert(results.end(),flyPositions.begin(),flyPositions.end()); 

		for (int j = 0; j < numberOfFlies; j++) {
			swarm[j].setNewPositionErrorValue(flyPositions[j]);
		}
		showMessage( "Best solution after run " + str(i) + " : " + SwarmFly::bestGlobalSolution.toString() + " : " + str(SwarmFly::bestGlobalSolution.getErrorValue()) + "\n",2,fixedParams);
		if (SwarmFly::bestGlobalSolution.getErrorValue() < tempBestValue || !initBest) {
			tempBestValue = SwarmFly::bestGlobalSolution.getErrorValue();
			initBest = true;
		}
		else {
			showMessage("No better solution found in the last run: Randomizing swarm topology\n",3,fixedParams); 
			//randomizeWorst(swarm);
			randomizeTopology(swarm, maxInformed, randGen);
		}

	}

	return FitterResults(results);
}
示例#4
0
int sw_main(int argc, char** argv) {
	srand( time( 0 ) );
	init_rand( rand() );
	
	// Index variables
	int j;

	// Used for normalization
	short _min = 32000;
	short _max = -32000;

	// Configuration Parameters
	int MESH_SIZE,NUM_PARTICLES,ITERATIONS,NUM_PEAKS,MAX_SIZE,MAX_INDEX;

	// Read in the paramaters
	sscanf(argv[1], "%d", &MESH_SIZE);
	sscanf(argv[2], "%d", &NUM_PARTICLES);
	sscanf(argv[3], "%d", &ITERATIONS);
	sscanf(argv[4], "%d", &NUM_PEAKS);
	
	MAX_SIZE = MESH_SIZE * MESH_SIZE;
	MAX_INDEX = MAX_SIZE - 1;

	// Print Configuration
	printf( "Mesh Size : %d\n", MESH_SIZE);
	printf( "Number of Particles : %d\n", NUM_PARTICLES);
	printf( "Iterations : %d\n", ITERATIONS);
	printf( "Number of Peaks : %d\n", NUM_PEAKS);
	
	// Generate peaks
	int* peaks = (int*)calloc(sizeof(int), NUM_PEAKS);
	for( j = 0 ; j < NUM_PEAKS ; j++ ) {
		peaks[j] = (int)uniform(0 , MAX_INDEX );
		printf( "Peak Position : %d\n" , peaks[j] );
	}
	
	// Generate particles
	Point* particles = (Point*)calloc( sizeof( Point ) , NUM_PARTICLES );
	for( j = 0 ; j < NUM_PARTICLES ; j++ ) {
		int p = uniform( 0 , NUM_PEAKS );
		int l = (int)uniform( 0 , MAX_INDEX );
		particles[j].x = uniform( 0 , MESH_SIZE - 1);
		particles[j].y = uniform( 0 , MESH_SIZE - 1 );
		particles[j].dirt = uniform( 0 , 50 );
		particles[j].dx = peaks[p] % MESH_SIZE;
		particles[j].dy = peaks[p] / MESH_SIZE;
	}
	
	// Run!
	for ( j = 0 ; j < ITERATIONS ; j++ ) {
		swarm(particles,NUM_PARTICLES,MESH_SIZE);
	}
	
	// Copy over particles to grid	
	short* grid = (short*)calloc( sizeof(short) , MAX_SIZE );	
	for( j = 0 ; j < NUM_PARTICLES ; j++ ) {
		int pos = particles[j].x + particles[j].y * MESH_SIZE;
		if( pos > MAX_SIZE ) {
			printf("Error : %d\n" , pos );
		}
		grid[pos]++;
	}free( particles );
	
	int max_ind = -1;
	for( j = 0 ; j < MAX_SIZE ; j++ ) {
		if( grid[j] < _min ) _min = grid[j];
		if( grid[j] > _max ) {max_ind = j;_max = grid[j];}
	}
	printf("Min: %d Max:%d\n" , _min , _max );	
	printf("x: %d y: %d\n" , max_ind % MESH_SIZE , max_ind / MESH_SIZE );
	
	out( "file.pgm" , grid, MESH_SIZE , _min , _max );

	free(grid);
	free(peaks);
	return 1;
}