Example #1
0
Type objective_function<Type>::operator() ()
{
  DATA_VECTOR(observed);

  PARAMETER_VECTOR(population);
  PARAMETER(log_process_error);
  PARAMETER(log_obs_error);
  
  Type process_error = exp(log_process_error);
  Type obs_error     = exp(log_obs_error);
  
  int n_obs          = observed.size();  // number of observations
  
  Type nll           = 0; // negative log likelihood
  
  // likelihood for state transitions
  for(int y=1; y<n_obs; y++){
    Type m = population[y-1];
    nll   -= dnorm(population(y), m, process_error, true);
  }
  
  // likelihood for observations
  for(int y=0; y<n_obs; y++){
    nll -= dnorm(observed(y), population(y), obs_error, true);
  }
  
  ADREPORT(process_error);
  ADREPORT(obs_error);
  
  return nll;
}
Example #2
0
		// Connects stub to the workflow
		void GaRDGAStub::Connected()
		{
			GaBasicStub::Connected();

			GaCachedPopulation population( GetWorkflowStorage(), _populationID );

			// register statistics trackers required by RDGA
			population.GetData().RegisterTracker( Population::GaPopulationSizeTracker::TRACKER_ID, &_sizeTracker );

			// create data objects required by the RDGA and insert them to workflow data storage 

			Population::GaChromosomeGroup* selectionOutput = new Population::GaChromosomeGroup();
			Population::GaChromosomeGroup* coulingOutput = new Population::GaChromosomeGroup();

			Common::Workflows::GaDataStorage* bgStorage = _brachGroup->GetData();
			bgStorage->AddData( new Common::Workflows::GaDataEntry<Population::GaChromosomeGroup>( GADID_SELECTION_OUTPUT, selectionOutput ), Common::Workflows::GADSL_BRANCH_GROUP );
			bgStorage->AddData( new Common::Workflows::GaDataEntry<Population::GaChromosomeGroup>( GADID_COUPLING_OUTPUT, coulingOutput ), Common::Workflows::GADSL_BRANCH_GROUP );

			// create flow steps that 

			_checkStep = new GaCheckPopulationStep( GetWorkflowStorage(), _populationID );
			_initStep = new Common::Workflows::GaSimpleMethodExecStep<Population::GaPopulation, Common::Workflows::GaMethodExecIgnoreBranch<Population::GaPopulation> >
				( &Population::GaPopulation::Initialize, GetWorkflowStorage(), _populationID );

			_selectionStep = new Population::GaSelectionStep( 
				Population::GaSelectionSetup( &_selectionOperation, &_selectionParameters, &Population::SelectionOperations::GaTournamentSelectionConfig(
				Fitness::GaFitnessComparatorSetup( &_scaledFitnessComparator, &Fitness::Comparators::GaSimpleComparatorParams(), NULL ), _mating ) ),
				GetWorkflowStorage(), _populationID, bgStorage, GADID_SELECTION_OUTPUT );

			_couplingStep = new Population::GaCouplingStep( Population::GaCouplingSetup( &_couplingOperation, &_couplingParameters, &Population::GaCouplingConfig( _mating ) ),
				bgStorage, GADID_SELECTION_OUTPUT, bgStorage, GADID_COUPLING_OUTPUT );

			_nopStep = new Common::Workflows::GaNopStep();

			_fitnessStep = new Population::GaPopulationFitnessStep( GetWorkflowStorage(), _populationID );

			_replacementStep = new Population::GaReplacementStep( Population::GaReplacementSetup( &_rdgaOperation, &_rdgaParameters, &Multiobjective::RDGA::GaRDGAConfig( *_grid ) ),
				bgStorage, GADID_COUPLING_OUTPUT, GetWorkflowStorage(), _populationID );

			_nextGenStep = new Common::Workflows::GaSimpleMethodExecStep<Population::GaPopulation>( &Population::GaPopulation::NextGeneration, GetWorkflowStorage(), _populationID );

			Common::Workflows::GaBranchGroupFlow* flow = _brachGroup->GetBranchGroupFlow();

			// connect created flow steps 

			flow->SetFirstStep( _checkStep );
			flow->ConnectSteps( _checkStep, _selectionStep, 1 );
			flow->ConnectSteps( _selectionStep, _couplingStep, 0 );
			flow->ConnectSteps( _couplingStep, _nopStep, 0 );

			flow->ConnectSteps( _fitnessStep, _replacementStep, 0 );

			flow->ConnectSteps( _replacementStep, _nextGenStep, 0 );
			
			// do not use fitness step if population does not have to be re-evaluated in each generation
			_fitnessConnection = UseFitnessStep() ? flow->ConnectSteps( _nopStep, _fitnessStep, 0 ) : flow->ConnectSteps( _nopStep, _replacementStep, 0 );

			flow->ConnectSteps( _checkStep, _initStep, 0 );
			flow->ConnectSteps( _initStep, _nopStep, 0 );
		}
State MiPlusLambdaStrategy::operator () (const int mi, const int lambda, const int iterations, const int p,const int threads, const std::vector<State*>& initialStates) const{
	std::vector<State*> results;	
	#pragma omp parallel for shared(results) num_threads(threads)
	for (int pi =0; pi <p; ++pi)
	{
		int iter=0;
		//Inicjacja
		std::vector<State*> population (initialStates);
		while (iter<iterations) {
			//Reprodukcja
			for (int i =0; i <lambda; ++i){
				population.push_back(new State(population[rand()%mi]));
			}
			//Krzyżowanie
			for (int i =0; i <lambda/2; ++i){
				population[mi+2*i]->crossover(population[mi+2*i+1]);
			}
			//Mutacja
			for (int i =0; i <lambda; ++i){
				population[mi+i]->mutate();
			}
			//Ocena i wybor kolejnej populacji
			sort(population.begin(),population.end(),compare);
			population.resize(mi);
			++iter;
		}
		results.push_back(new State(population[0]));
	}
	sort(results.begin(),results.end(),compare);
	return results[0];
//	return initialStates[0];
}
template <typename T2> array<T2> flatten()
{
    array<T2> result;

//allocate

    result.allocate(population());

//copy

    int index=0;

    for(int i=0; i<count(); i++)
    {
        auto& current=at(i);

        for(int j=0; j<current.count(); j++)
        {
            result[index]=current[j];

            //next

            index++;
        }
    }

//consistent

    check(index==result.count());

    return result;
}
Example #5
0
		// Disconnects stub from the workflow
		void GaRDGAStub::Disconnecting()
		{
			Common::Workflows::GaBranchGroupFlow* flow = _brachGroup->GetBranchGroupFlow();

			// disconnect and destroy flow steps created by the stub

			flow->RemoveStep( _checkStep, true, true );
			flow->RemoveStep( _initStep, true, true );
			flow->RemoveStep( _selectionStep, true, true );
			flow->RemoveStep( _couplingStep, true, true );
			flow->RemoveStep( _replacementStep, true, true );
			flow->RemoveStep( _nopStep, true, true );
			flow->RemoveStep( _fitnessStep, true, true );
			flow->RemoveStep( _nextGenStep, true, true );

			// clear internal bookkeeping
			Clear();

			// remove data from the workflow storage
			Common::Workflows::GaDataStorage* bgStorage = _brachGroup->GetData();
			bgStorage->RemoveData( GADID_SELECTION_OUTPUT, Common::Workflows::GADSL_BRANCH_GROUP );
			bgStorage->RemoveData( GADID_COUPLING_OUTPUT, Common::Workflows::GADSL_BRANCH_GROUP );

			GaCachedPopulation population( GetWorkflowStorage(), _populationID );

			// remove statistics trackers
			population.GetData().UnregisterTracker( Population::GaPopulationSizeTracker::TRACKER_ID );
			population.GetData().UnregisterTracker( Population::GaScaledFitnessTracker::TRACKER_ID );

			population.Clear();

			GaBasicStub::Disconnecting();
		}
Example #6
0
MMKPSolution MMKP_BBA::run(std::vector<MMKPSolution> initialPopulation){
    
    //init initial parameters
    //init MMKPBatSolution vector
    std::vector<MMKPBatSolution> population(initialPopulation.size());
    for(int i=0;i<initialPopulation.size();i++){
        population[i].solution = initialPopulation[i];
    }
    MMKP_BBA::initBatParemeters(population);
    
    this->currentGeneration = 0;
    bool terminationCriterion = false;
    this->convergenceData.empty();
    this->convergenceIteration = 0;
    currentFuncEvals = 0;
    
    MMKP_BBA::quickSort(population,0,(population.size()-1));
    MMKPSolution bestSolution;
    for(int i=0;i<population.size();i++){
        if(this->dataSet.isFeasible(population[i].solution)){
            bestSolution =  population[i].solution;
            break;
        }
    }
    
    std::tuple<int,float> temp(currentFuncEvals,bestSolution.getProfit());
    this->convergenceData.push_back(temp);
    
    //main loop
    while(!terminationCriterion){
        
        MMKP_BBA::globalSearch(population);
        MMKP_BBA::quickSort(population,0,(population.size()-1));
        
        for(int i=0;i<population.size();i++){
            if(this->dataSet.isFeasible(population[i].solution)){
                if(population[i].solution.getProfit() > bestSolution.getProfit()){
                    bestSolution =  population[i].solution;
                    this->convergenceIteration = currentGeneration;
                    break;
                }
            }
        }

        std::tuple<int,float> temp(currentFuncEvals,bestSolution.getProfit());
        this->convergenceData.push_back(temp);
        
        if(currentGeneration >= this->parameters.numberOfGenerations){
            terminationCriterion = true;
        }
        this->currentGeneration++;
    }
    
    return bestSolution;
}
void MainWindow::startEvolve()
{
    this->dateback_sbox->setDisabled( true );
    this->dateback_btn->setDisabled( true );

    nth_gen_indi.clear();
    select_operator_indi.clear();
    crossover_operator_indi.clear();
    mutation_operator_indi.clear();

    Population population( this->individual_num_input->value(), this->crossover_rate_input->value(), mutation_rate_input->value(),
                         this->range_min_input->value(), this->range_max_input->value(), min_btn->isChecked() ? SELECT_MIN : SELECT_MAX);

    qint16 gene_num = generation_num_input->value();

    population.calculate_fitness();

    for( qint16 i = 0; i < gene_num; i++)
    {
        saveNthSample( population );
        populateNthPlot( i, nth_gen_indi.at( i ) );

        population.select_operator_elitist_strategy();
        //population.select_operator_roulette();
        saveSelectSample( population );
        populateSelectPlot( select_operator_indi.at( i ) );

        population.crossover_operator();
        population.calculate_fitness();
        saveCrossSample( population );
        populateCrossPlot( crossover_operator_indi.at( i ) );

        population.mutate_operator();
        population.calculate_fitness();
        saveMutationSample( population );
        populateMutationPlot( mutation_operator_indi.at( i ) );
    }

    start_evolve ->setDisabled( true );
    dateback_btn->setDisabled( false );
    dateback_sbox->setDisabled( false );
    dateback_sbox->setRange( 1, gene_num );

    qint16 best_indi_index = population.find_best_individual_index();
    qreal best_x_value = population.getValueAt( best_indi_index );
    qreal best_y_value = UtilityFunction::f( population.getValueAt( best_indi_index ) );

    QString x_value, y_value, result_string;
    x_value.setNum(best_x_value, 'f', 5);
    y_value.setNum(best_y_value, 'f', 5);
    result_string.append( QString("当x=") ).append( x_value ).append(QString("时 ")).append( min_btn->isChecked() ? QString( "最小值y=") : QString("最大值y=") ).append( y_value);
    result_label->setVisible( true );
    result_label->setText( result_string );
}
Example #8
0
void Simulation::run() {
    _timer.start();
    Population population(_problem);
    if (solve(population) == true)
        _display.basicLine("Solution found in " + std::to_string(_currentGeneration) + " generations(s) ");
    else
        _display.basicLine("Solution not found, best candidate is: ");
    _problem->print(population.best());
    _timer.stop();
    _problem->giveBestSolution(population.best());
    if (config.verbose)
        _display.basicLine("Simulation took " + std::to_string(_timer.getTime()) + "s");
}
Example #9
0
int main()
{
	GaInitialize();

	{
		Chromosome::GaMatingConfig matingConfiguration(
			Chromosome::GaCrossoverSetup( &crossover, &Chromosome::GaCrossoverParams( 0.8f, 2 ), NULL ),
			Chromosome::GaMutationSetup( &mutation, &Chromosome::GaMutationParams( 0.03f, false ), NULL ) );

		float gridSize[] = { 0.5, 0.5 };

		Algorithm::Stubs::GaPAESStub paesStub( WDID_POPULATION, WDID_POPULATION_STATS, 
			Chromosome::GaInitializatorSetup( &initializator, NULL, &Chromosome::GaInitializatorConfig() ),
			Population::GaPopulationFitnessOperationSetup( &populationFitnessOperation, NULL, &Fitness::GaFitnessOperationConfig( &Fitness::Representation::GaMVFitnessParams( 2 ) ) ),
			Fitness::GaFitnessComparatorSetup( &fitnessComparator, &Fitness::Comparators::GaSimpleComparatorParams( Fitness::Comparators::GACT_MINIMIZE_ALL ), NULL ),
			Population::GaPopulationParams( 33, 1 ),
			Chromosome::GaMutationSetup( &mutation, &Chromosome::GaMutationParams( 0.03f, false ), NULL ),
			Multiobjective::PAES::GaPAESSelectionParams( PTID_CURRENT_SOLUTION, PTID_CROSSOVER_BUFFER),
			Multiobjective::PAES::GaPAESParams( CTID_DOMINANCE, CTID_HYPERBOX, CTID_HYPERBOX_INFO, PTID_HYPERBOX_INFO_BUFFER, PTID_CURRENT_SOLUTION, PTID_CROWDING_STORAGE ),
			Common::Grid::GaHyperGrid<Fitness::GaFitness, float, Multiobjective::GaFitnessCoordiantesGetter<float> >( gridSize, 2 ) );

		Common::Workflows::GaWorkflow workflow( NULL );

		workflow.RemoveConnection( *workflow.GetFirstStep()->GetOutboundConnections().begin(), true );

		Common::Workflows::GaWorkflowBarrier* br1 = new Common::Workflows::GaWorkflowBarrier();
		paesStub.Connect( workflow.GetFirstStep(), br1 );

		Common::Workflows::GaBranchGroup* bg1 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( br1, workflow.GetLastStep(), 0 );

		Algorithm::StopCriteria::GaStopCriterionStep* stopStep = new Algorithm::StopCriteria::GaStopCriterionStep( 
			Algorithm::StopCriteria::GaStopCriterionSetup( &stopCriterion, &Algorithm::StopCriteria::GaGenerationCriterionParams( 1000 ), NULL ),
			workflow.GetWorkflowData(), WDID_POPULATION_STATS );

		Common::Workflows::GaBranchGroupTransition* bt1 = new Common::Workflows::GaBranchGroupTransition();

		bg1->GetBranchGroupFlow()->SetFirstStep( stopStep );
		bg1->GetBranchGroupFlow()->ConnectSteps( stopStep, bt1, 0 );
		workflow.ConnectSteps( bt1, paesStub.GetStubFlow().GetFirstStep(), 1 );

		Common::Workflows::GaDataCache<Population::GaPopulation> population( workflow.GetWorkflowData(), WDID_POPULATION );

		population.GetData().GetEventManager().AddEventHandler( Population::GaPopulation::GAPE_NEW_GENERATION, &newGenHandler );

		workflow.Start();
		workflow.Wait();
	}

	GaFinalize();
}
Example #10
0
int main()
{
	GaInitialize();

	{
		Chromosome::GaMatingConfig matingConfiguration(
			Chromosome::GaCrossoverSetup( &crossover, &Chromosome::GaCrossoverParams( 0.8f, 2 ), NULL ),
			Chromosome::GaMutationSetup( &mutation, &Chromosome::GaMutationParams( 0.03f, false ), NULL ) );

		Algorithm::Stubs::GaSPEAStub speaStub( WDID_POPULATION, WDID_POPULATION_STATS, 
			Chromosome::GaInitializatorSetup( &initializator, NULL, &Chromosome::GaInitializatorConfig() ),
			Population::GaPopulationFitnessOperationSetup( &populationFitnessOperation, NULL, &Fitness::GaFitnessOperationConfig( &Fitness::Representation::GaMVFitnessParams( 2 ) ) ),
			Fitness::GaFitnessComparatorSetup( &fitnessComparator, &Fitness::Comparators::GaSimpleComparatorParams( Fitness::Comparators::GACT_MINIMIZE_ALL ), NULL ),
			Population::GaPopulationParams( 64, 0 ),
			Chromosome::GaMatingSetup( &mating, NULL, &matingConfiguration ),
			Population::GaCouplingSetup(),
			Population::SelectionOperations::GaTournamentSelectionParams( 32, PTID_CROSSOVER_BUFFER, -1, 2,
			Population::SelectionOperations::GaTournamentSelectionParams::GATST_ROULETTE_WHEEL_SELECTION ),
			Multiobjective::SPEA::GaSPEAParams( CTID_DOMINANCE_LIST, CTID_STRENGTH, CTID_DOMINATED, PTID_CLUSTER_STORAGE ) );

		Common::Workflows::GaWorkflow workflow( NULL );

		workflow.RemoveConnection( *workflow.GetFirstStep()->GetOutboundConnections().begin(), true );

		Common::Workflows::GaWorkflowBarrier* br1 = new Common::Workflows::GaWorkflowBarrier();
		speaStub.Connect( workflow.GetFirstStep(), br1 );

		Common::Workflows::GaBranchGroup* bg1 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( br1, workflow.GetLastStep(), 0 );

		Algorithm::StopCriteria::GaStopCriterionStep* stopStep = new Algorithm::StopCriteria::GaStopCriterionStep( 
			Algorithm::StopCriteria::GaStopCriterionSetup( &stopCriterion, &Algorithm::StopCriteria::GaGenerationCriterionParams( 100 ), NULL ),
			workflow.GetWorkflowData(), WDID_POPULATION_STATS );

		Common::Workflows::GaBranchGroupTransition* bt1 = new Common::Workflows::GaBranchGroupTransition();

		bg1->GetBranchGroupFlow()->SetFirstStep( stopStep );
		bg1->GetBranchGroupFlow()->ConnectSteps( stopStep, bt1, 0 );
		workflow.ConnectSteps( bt1, speaStub.GetStubFlow().GetFirstStep(), 1 );

		Common::Workflows::GaDataCache<Population::GaPopulation> population( workflow.GetWorkflowData(), WDID_POPULATION );

		population.GetData().GetEventManager().AddEventHandler( Population::GaPopulation::GAPE_NEW_GENERATION, &newGenHandler );

		workflow.Start();
		workflow.Wait();
	}

	GaFinalize();
}
Example #11
0
float chronoSelection(ParametersMap* parametersMap, unsigned repetitions)
{
    AuxTask auxTask;
    Individual* example = auxTask.getExample(parametersMap);
    unsigned populationSize = parametersMap->getNumber(Population::SIZE);

    Population population(&auxTask, example, populationSize, 5);
    population.setParams(parametersMap);

    START_CHRONO
        population.nextGeneration();
    STOP_CHRONO

    return chrono.getSeconds();
}
Example #12
0
int main(int argc, char* argv[]) {


  const size_t N_total(8636);
  const double obsTime(50.0);

  Parameters parms;
  AIPopulation population(8636,50.0,"/home/stsiab/AI/trunk/MCMC_input/kieran");

  AIModel model(&parms, &population);

  population.loadEpiData("/home/stsiab/AI/trunk/MCMC_input/ss.18.0.1.ipt");

  return EXIT_SUCCESS;
}
void MainWindow::checkOriginal()
{
    Population population( this->individual_num_input->value(), this->crossover_rate_input->value(), mutation_rate_input->value(),
                         this->range_min_input->value(), this->range_max_input->value(), min_btn->isChecked() ? SELECT_MIN : SELECT_MAX);

    qint16 size = population.getIndividualNum();
    QPolygonF samples;
    for( qint16 i = 0; i < size; i ++)
    {
        samples += QPointF( population.getValueAt( i ), UtilityFunction::f( population.getValueAt( i ) ) );
    }

    original_plot->setSamples( samples );

    check_original_fun->setDisabled( true );

}
Example #14
0
int main(int argc, char** argv) {

	//parparser parser(argc, argv);

	//long inititalPosition = parser.get("x").asLong();

	srand(time(0));

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

	MPICHECK(MPI_Init(&argc, &argv));
	//-----------------------------------------------------------------------------

	int commSize = 0;
	int rank = 0;
	MPICHECK(MPI_Comm_size(MPI_COMM_WORLD, &commSize));
	MPICHECK(MPI_Comm_rank(MPI_COMM_WORLD, &rank));

	const int nextProc = rank == commSize - 1 ? 0 : rank + 1;
	const int prevProc = rank == 0 ? commSize - 1 : rank - 1;

	vector<Individ> population(islandSize);
	for (int i = 0; i < islandSize; ++i) {
		population[i].init(problemSize);
	}

	for (int i = 1; i <= iterationsThreshold; ++i) {
		select(population);
		crossoverPopulation(population);
		mutatePopulation(population);

		if (i % migrationFreq == 0) {
			migrate(population, nextProc, prevProc);
		}

		cout << getBestFitness(population, rank, commSize) << "\n";
	}
	
	//-----------------------------------------------------------------------------


	//-----------------------------------------------------------------------------
	MPICHECK(MPI_Finalize());
	return 0;
}
Example #15
0
int main(){
    MiniMap<int> population(100);

    population.set("Manhattan", 1626000);
    population.set("Brooklyn", 2592000);
    population.set("Queens", 2296000);
    population.set("Bronx", 1419000);
    population.set("Staten Island", 472621);

    std::cout << "Population of Manhattan: " << *population.get("Manhattan") << "\n";

    if (population.get("Brooklyn") == nullptr) std::cout << "Population of Brooklyn: " << "undefined\n";
    else std::cout << "Population of Brooklyn: " << *population.get("Brooklyn") << "\n";

    population.remove("Brooklyn");

    if (population.get("Brooklyn") == nullptr) std::cout << "Population of Brooklyn: " << "undefined\n";
    else std::cout << "Population of Brooklyn: " << *population.get("Brooklyn") << "\n";

    std::cout << population.load() << "\n";
    return 0;
}
    EndCriteria::Type DifferentialEvolution::minimize(Problem& p, const EndCriteria& endCriteria) {
        EndCriteria::Type ecType;

        upperBound_ = p.constraint().upperBound(p.currentValue());
        lowerBound_ = p.constraint().lowerBound(p.currentValue());
        currGenSizeWeights_ = Array(configuration().populationMembers,
                                    configuration().stepsizeWeight);
        currGenCrossover_ = Array(configuration().populationMembers,
                                  configuration().crossoverProbability);

        std::vector<Candidate> population(configuration().populationMembers,
                                          Candidate(p.currentValue().size()));
        fillInitialPopulation(population, p);

        std::partial_sort(population.begin(), population.begin() + 1, population.end(),
                          sort_by_cost());
        bestMemberEver_ = population.front();
        Real fxOld = population.front().cost;
        Size iteration = 0, stationaryPointIteration = 0;

        // main loop - calculate consecutive emerging populations
        while (!endCriteria.checkMaxIterations(iteration++, ecType)) {
            calculateNextGeneration(population, p.costFunction());
            std::partial_sort(population.begin(), population.begin() + 1, population.end(),
                              sort_by_cost());
            if (population.front().cost < bestMemberEver_.cost)
                bestMemberEver_ = population.front();
            Real fxNew = population.front().cost;
            if (endCriteria.checkStationaryFunctionValue(fxOld, fxNew, stationaryPointIteration,
                                                         ecType))
                break;
            fxOld = fxNew;
        };
        p.setCurrentValue(bestMemberEver_.values);
        p.setFunctionValue(bestMemberEver_.cost);
        return ecType;
    }
    void TestSetupSolveException() throw (Exception)
    {
        // First set up SimulationTime (this is usually handled by a simulation object)
        SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0, 1);

        // Create a SimpleTargetAreaModifier
        MAKE_PTR(SimpleTargetAreaModifier<2>, p_modifier);

        // Create a cell population whose type should not be used with a SimpleTargetAreaModifier
        HoneycombMeshGenerator generator(4, 4, 0);
        MutableMesh<2,2>* p_mesh = generator.GetMesh();

        std::vector<CellPtr> cells;
        CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator;
        cells_generator.GenerateBasic(cells, p_mesh->GetNumNodes());

        MeshBasedCellPopulation<2> population(*p_mesh, cells);

        // Test that the correct exception is thrown if we try to call UpdateTargetAreas() on the population
        TS_ASSERT_THROWS_THIS(p_modifier->SetupSolve(population, "unused_argument"),
            "AbstractTargetAreaModifiers are to be used with a VertexBasedCellPopulation only");
        CellBasedEventHandler::Reset(); // Otherwise logging has been started but not stopped due to exception above.

    }
Example #18
0
File: pop.c Project: zj9205/ECS-30
int main()
{
    int year;

    printf("Enter a year after 1990> ");
    scanf("%d", &year);

    FILE*pop;
    pop = fopen("CHRISpop.txt", "w");
    fprintf(pop, "Predicted Gotham City population for %d (in thousands): %.3lf\n"  , year, population(year));

    return 0;
}//main
Example #19
0
int main( int argc , char *argv[] )
{
    rng_type rng;

    trainings_data_type c = gpcxx::generate_evenly_spaced_test_data< 3 >( -5.0 , 5.0 + 0.1 , 0.4 , []( double x1 , double x2 , double x3 ) {
                        return  1.0 / ( 1.0 + pow( x1 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x2 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x3 , -4.0 ) ); } );
    gpcxx::normalize( c.y );
    

    std::ofstream fout1( "testdata.dat" );
    for( size_t i=0 ; i<c.x[0].size() ; ++i )
        fout1 << c.y[i] << " " << c.x[0][i] << " " << c.x[1][i] << " " << c.x[2][i] << "\n";
    fout1.close();
    
    auto eval = gpcxx::make_static_eval< value_type , symbol_type , eval_context_type >(
        fusion::make_vector(
            fusion::make_vector( 'x' , []( eval_context_type const& t ) { return t[0]; } )
          , fusion::make_vector( 'y' , []( eval_context_type const& t ) { return t[1]; } )
          , fusion::make_vector( 'z' , []( eval_context_type const& t ) { return t[2]; } )          
          ) ,
        fusion::make_vector(
            fusion::make_vector( 's' , []( double v ) -> double { return std::sin( v ); } )
          , fusion::make_vector( 'c' , []( double v ) -> double { return std::cos( v ); } ) 
          , fusion::make_vector( 'e' , []( double v ) -> double { return std::exp( v ); } ) 
          , fusion::make_vector( 'l' , []( double v ) -> double { return ( std::abs( v ) < 1.0e-20 ) ? log( 1.0e-20 ) : std::log( std::abs( v ) ); } ) 
          ) ,
        fusion::make_vector(
            fusion::make_vector( '+' , std::plus< double >() )
          , fusion::make_vector( '-' , std::minus< double >() )
          , fusion::make_vector( '*' , std::multiplies< double >() ) 
          , fusion::make_vector( '/' , std::divides< double >() ) 
          ) );
    typedef decltype( eval ) eval_type;
    typedef eval_type::node_attribute_type node_attribute_type;
    
    typedef gpcxx::basic_tree< node_attribute_type > tree_type;
    typedef std::vector< tree_type > population_type;
    typedef gpcxx::static_pipeline< population_type , fitness_type , rng_type > evolver_type;

    
    size_t population_size = 1000;
    size_t generation_size = 20;
    double number_elite = 1;
    double mutation_rate = 0.0;
    double crossover_rate = 0.6;
    double reproduction_rate = 0.3;
    size_t min_tree_height = 8 , max_tree_height = 8;
    size_t tournament_size = 15;


    // generators< rng_type > gen( rng );
    auto terminal_gen = eval.get_terminal_symbol_distribution();
    auto unary_gen = eval.get_unary_symbol_distribution();
    auto binary_gen = eval.get_binary_symbol_distribution();
    gpcxx::node_generator< node_attribute_type , rng_type , 3 > node_generator {
        { 2.0 * double( terminal_gen.num_symbols() ) , 0 , terminal_gen } ,
        { double( unary_gen.num_symbols() ) , 1 , unary_gen } ,
        { double( binary_gen.num_symbols() ) , 2 , binary_gen } };

    auto tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );
    

    evolver_type evolver( number_elite , mutation_rate , crossover_rate , reproduction_rate , rng );
    std::vector< double > fitness( population_size , 0.0 );
    std::vector< tree_type > population( population_size );


    auto fitness_f = gpcxx::regression_fitness< eval_type >( eval );
    evolver.mutation_function() = gpcxx::make_mutation(
        gpcxx::make_simple_mutation_strategy( rng , node_generator ) ,
        gpcxx::make_tournament_selector( rng , tournament_size ) );
    evolver.crossover_function() = gpcxx::make_crossover( 
        gpcxx::make_one_point_crossover_strategy( rng , max_tree_height ) ,
        gpcxx::make_tournament_selector( rng , tournament_size ) );
    evolver.reproduction_function() = gpcxx::make_reproduce( gpcxx::make_tournament_selector( rng , tournament_size ) );
    
    gpcxx::timer timer;



    // initialize population with random trees and evaluate fitness
    timer.restart();
    for( size_t i=0 ; i<population.size() ; ++i )
    {
        tree_generator( population[i] );
        fitness[i] = fitness_f( population[i] , c );
    }
    std::cout << gpcxx::indent( 0 ) << "Generation time " << timer.seconds() << std::endl;
    std::cout << gpcxx::indent( 1 ) << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 1 , 10 ) << std::endl;
    std::cout << gpcxx::indent( 1 ) << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl;
    std::cout << gpcxx::indent( 1 ) << std::endl << std::endl;

    timer.restart();
    for( size_t generation=1 ; generation<=generation_size ; ++generation )
    {
        gpcxx::timer iteration_timer;
        iteration_timer.restart();
        evolver.next_generation( population , fitness );
        double evolve_time = iteration_timer.seconds();
        iteration_timer.restart();
        std::transform( population.begin() , population.end() , fitness.begin() , [&]( tree_type const &t ) { return fitness_f( t , c ); } );
        double eval_time = iteration_timer.seconds();
        
        std::cout << gpcxx::indent( 0 ) << "Generation " << generation << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Evolve time " << evolve_time << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Eval time " << eval_time << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 2 , 10 ) << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;
    }
    std::cout << "Overall time : " << timer.seconds() << std::endl;

    return 0;
}
Example #20
0
int main(int argc, char* argv[])
{
    srand (time(0));    

    if(argc < 4)
    {
        cerr << "ERROR: The number of arguments is incorrect" << endl << "Enter:\targ_1 = user_definition_file\t arg_2 = genetic_encoding_file\t arg_3 = port_number";
        return -1;
    }

    if(system((char*)"mkdir -p NEAT_organisms") == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to create folder 'NEAT_organisms'" << endl;
    }

    if(system("rm -f NEAT_organisms/*") == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to remove files inside of 'NEAT_organisms'" << endl;
    }

    SimFiles * simfile = new SimFiles();
    Fitness * fitness = new Fitness();
    RobotVREP * vrep = new RobotVREP(false, atoi(argv[3]));   

    // ============= VREP INITIALIZATIONS ============= //
    
    Joint * rightWheel = new Joint((char*)"SCALE", (char*)"motor_der");
    Joint * leftWheel = new Joint((char*)"SCALE", (char*)"motor_izq");
    vrep->addJoint(rightWheel);
    vrep->addJoint(leftWheel);

    VisionSensor * visionSensor = new VisionSensor((char*)"VisionSensor");
    vrep->addVisionSensor(visionSensor);

    Object * centerDummy = new Object((char*)"modi_dummy");
    Object * Modi = new Object((char*)"MODI");
    vrep->addObject(centerDummy);
    vrep->addObject(Modi);
    
    CollisionObject * chasis = new CollisionObject((char*)"Collision_MODI_1#");
    CollisionObject * rueda1 = new CollisionObject((char*)"Collision_MODI_2#");
    CollisionObject * rueda2 = new CollisionObject((char*)"Collision_MODI_3#");
    vrep->addCollisionObject(chasis);
    vrep->addCollisionObject(rueda1);
    vrep->addCollisionObject(rueda2);
    vector < CollisionObject * > structure = {chasis, rueda1, rueda2};
    
    vector < Object * > cubes;

    // Set random position of Obstacles

    double y0 = -2;

    for(int cp_y = 0; cp_y < 9; cp_y++)
    {   
        double x0 = -2 + 0.25*(cp_y%2);

        for(int cp_x = 0; cp_x < 8 + (cp_y + 1)%2; cp_x++)
        {            
            if(9*cp_y + cp_x != 40)
            {
                stringstream sstm1;
                sstm1 << "Obstacle" << 9*cp_y+cp_x<< "#";

                Object * obstacle = new Object((char*)sstm1.str().c_str());
                vrep->addObject(obstacle);

                double rand1 = rand()%201 - 100;
                double rand2 = rand()%201 - 100;

                vector < double > position;

                position.push_back(x0 + rand1/100*.10);
                position.push_back(y0 + rand2/100*.10);
                position.push_back(0.05);

                vrep->setObjectPosition(obstacle, position);

                cubes.push_back(obstacle);
            }

            x0 = x0 + 0.5;
        }

        y0 = y0 + 0.5;
    }

    // ================================================ //

    // ========== NEAT INITIALIZATIONS =========== //

    vector < double > output(2,0.0);
    vector < double > input(NX*NY+2,0.0);

    Population population(argv[1], argv[2], (char *)"NEAT_RIAR", (char *)"./NEAT_organisms");

    // ================================================ //
    
    namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.

    int finalChampionGeneration = 0;
    int finalChampionPopulation = 0;
    double finalChampionFitness = 0.0;

    for(int g = 0; g < population.GENERATIONS; g++)
    {
        fitness->resetGenerationValues();

        int generationChampionPopulation = 0;
        double generationChampionFitness = 0.0;
     
        for(int p = 0; p < population.POPULATION_MAX; p++)
        {
            fitness->resetPopulationValues();

            int sim_time = 0;
            bool flag = true;
            int flag_times = 0;
            double rightVel = 0.0;
            double leftVel = 0.0;

            vrep->setJointTargetVelocity(rightWheel, 0.0);
            vrep->setJointTargetVelocity(leftWheel, 0.0);

            double rand1 = rand()%201 - 100;
            double rand2 = rand()%201 - 100;
            double rand3 = rand()%201 - 100;

            vector < double > position, orientation;

            position.push_back(rand1/100*.10);
            position.push_back(rand2/100*.10);
            position.push_back(0.03011);

            orientation.push_back(0);
            orientation.push_back(0);
            orientation.push_back(rand3/100*M_PI);
            
            vrep->setObjectPosition(Modi, position);
            vrep->setObjectOrientation(Modi, orientation);

            unsigned char * image;
            Mat frameRGB = Mat(NX, NY, CV_8UC3);
            Mat frameGRAY = Mat(NX, NY, CV_8UC1);

            stringstream message1, message2, video_name;            

            message1 << "Generation " << g << " Population " << p;
            vrep->addStatusbarMessage((char*)message1.str().c_str());

            video_name << "G" << g << "P" << p;
            //vrep->changeVideoName((char *)video_name.str().c_str(), simx_opmode_oneshot_wait);

            simfile->openRobotMovementFile(g, p);
            simfile->openRobotMotorVelocityFile(g, p);
            
            clog << "=======  G" << g << " P" << p << "  =======  " << endl;

            vrep->startSimulation(simx_opmode_oneshot_wait);

            timeval tv1, tv2;       
            gettimeofday(&tv1, NULL);            

            while(sim_time < TIME_SIMULATION && flag)
            {            
                image = vrep->getVisionSensorImage(visionSensor);  
                frameRGB.data = image;
                flip(frameRGB, frameRGB, 0);
                cvtColor(frameRGB,frameGRAY,CV_BGR2GRAY);
                
                Mat tmp = frameGRAY;
                Mat frame = tmp;

                resize(tmp, frame, Size(0,0) , 6.0, 6.0, (int)INTER_NEAREST );
                imshow( "Display window", frame );
                waitKey(10);

                for(int i = 0; i < NY; i++)
                {
                    for(int j = 0;j < NX; j++)
                    {
                        input.at(i*NX + j) = (double)frame.at<uchar>(i,j)/255*2-1;
                    }
                }
                
                input.at(NX*NY) = (double)((2.0/(MAX_VEL - MIN_VEL))*(rightVel - MIN_VEL) - 1.0);
                input.at(NX*NY + 1) = (double)((2.0/(MAX_VEL - MIN_VEL))*(leftVel - MIN_VEL) - 1.0);

                output = population.organisms.at(p).eval(input);

                rightVel = output.at(0) + rightVel;
                leftVel = output.at(1) + leftVel;

                if(rightVel > MAX_VEL) rightVel = MAX_VEL;
                else if(rightVel < MIN_VEL) rightVel = MIN_VEL;
                if(leftVel > MAX_VEL) leftVel = MAX_VEL;
                else if(leftVel < MIN_VEL) leftVel = MIN_VEL;

                vrep->setJointTargetVelocity(rightWheel,-rightVel);
                vrep->setJointTargetVelocity(leftWheel,leftVel);                                              

                if(sim_time > TIME_INIT_MEASURING)
                {
                    position = vrep->getObjectPosition(centerDummy);
                    orientation = vrep->getObjectOrientation(centerDummy);

                    simfile->addRobotMovementFile((double)sim_time/1000000.0, position, orientation.at(2));
                    simfile->addRobotMotorVelocityFile((double)sim_time/1000000.0, rightVel, leftVel);

                    fitness->measuringValues(position, rightVel, leftVel, vrep->readCollision(structure));

                    if (abs(orientation.at(0)) > 0.78 || abs(orientation.at(1)) > 0.78)
                    {
                        flag_times++;
                        if(flag_times > 10) flag = false;
                    }else
                        flag_times = 0;
                }                         

                usleep(DELTA_TIME - EXECUTION_TIME);
                sim_time += DELTA_TIME;
            }            

            vrep->stopSimulation(simx_opmode_oneshot_wait);

            gettimeofday(&tv2, NULL);
            long int simulationtime = ((tv2.tv_sec - tv1.tv_sec)*1000000L + tv2.tv_usec) - tv1.tv_usec;   

            simfile->closeRobotMovementFile();
            simfile->closeRobotMotorVelocityFile();  

            if (flag)
            {                
                population.organisms.at(p).fitness = fitness->calculateFitness();             
                simfile->addFileResults(fitness->getFitness(), g, p);

                clog << "Fitness:\t" << fitness->getFitness() << endl;
                clog << "Distance:\t" << fitness->getDistance() << endl;
                clog << "Tiempo de simulación:\t" << (double)simulationtime/1000000 << endl;
                clog << endl;            

                message2 << "FITNESS : " << fitness->getFitness();
                vrep->addStatusbarMessage((char*)message2.str().c_str());

                if(generationChampionFitness < fitness->getFitness())
                {
                    generationChampionPopulation = p;
                    generationChampionFitness = fitness->getFitness();
                }
            }
            else
            {
                clog << "OVERTURNING! The simulation has stopped" << endl;
                population.organisms.at(p).fitness = FAILED_FITNESS;
            }                
        }

        simfile->addFileChampion(generationChampionFitness, g, generationChampionPopulation);
        simfile->addFileFitness(fitness->getGenerationFitness(), g);        

        //////////////////////////// SAVE CHAMPION FILES /////////////////////////////////

        stringstream generation_champion_filename;
        generation_champion_filename << "NEAT_organisms/Champion_G" << g << "P" << generationChampionPopulation << ".txt";
        population.organisms.at(generationChampionPopulation).save((char *)generation_champion_filename.str().c_str());

        stringstream cp_gen_champion_movement, cp_gen_champion_motorVelocity;

        cp_gen_champion_movement << "cp simulation_files/movement/movement_G" << g << "P" << generationChampionPopulation << ".txt ./simulation_files/movement/Champion_G" << g << "P" << generationChampionPopulation << ".txt";
        cp_gen_champion_motorVelocity << "cp simulation_files/motorVelocity/motorVelocity_G" << g << "P" << generationChampionPopulation << ".txt ./simulation_files/motorVelocity/Champion_G" << g << "P" << generationChampionPopulation << ".txt";

        if(system((char*)cp_gen_champion_movement.str().c_str()) == -1)
        {
            cerr << "TRAIN ERROR:\tFailed to copy the Champion movement File" << endl;
        }
        else
        {
            if(system("rm -f ./simulation_files/movement/movement_G*.txt") == -1)
            {
                cerr << "TRAIN ERROR:\tFailed to remove useless files" << endl;
            }
        }

        if(system((char*)cp_gen_champion_motorVelocity.str().c_str()) == -1)
        {
            cerr << "TRAIN ERROR:\tFailed to copy the Champion motor velocity File" << endl;
        }
        else
        {
            if(system("rm -f ./simulation_files/motorVelocity/motorVelocity_G*.txt") == -1)
            {
                cerr << "TRAIN ERROR:\tFailed to remove useless files" << endl;
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////

        population.epoch();        

        if(finalChampionFitness < generationChampionFitness)
        {
            finalChampionGeneration = g;
            finalChampionPopulation = generationChampionPopulation;
            finalChampionFitness = generationChampionFitness;
        }
    }

    //////////////////////////// SAVE CHAMPION FILES /////////////////////////////////

    stringstream cp_champion_organism, cp_champion_movement, cp_champion_motorVelocity;
    
    cp_champion_organism << "cp NEAT_organisms/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./NEAT_organisms/Champion.txt";
    cp_champion_movement << "cp simulation_files/movement/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./simulation_files/movement/Champion.txt";
    cp_champion_motorVelocity << "cp simulation_files/motorVelocity/Champion_G" << finalChampionGeneration << "P" << finalChampionPopulation << ".txt ./simulation_files/motorVelocity/Champion.txt";
        
    if(system((char*)cp_champion_organism.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Organism File" << endl;
    }

    if(system((char*)cp_champion_movement.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Movement File" << endl;
    }

    if(system((char*)cp_champion_motorVelocity.str().c_str()) == -1)
    {
        cerr << "TRAIN ERROR:\tFailed to copy the Champion Motor Velocity File" << endl;
    }
    
    ///////////////////////////////////////////////////////////////////////////////////

    clog << "Fitness champion: " << finalChampionFitness << "\n\n"<< endl;

    delete(vrep);
    delete(simfile);
    delete(fitness);
    
    return(0);
}
Example #21
0
CRAlgorithmStatistics CRGenetics::execute()
{
  CRAlgorithmStatistics ret;
  solved = false;
  
  // Load some needed stuff
  if (config->debug) {
    cout << "CRGenetics::run --> Loading system data.\n";
  }
  
  GeneticConfig &config = dynamic_cast<GeneticConfig&>(* (this->config));
  
  iterations = 0;
  struct timeval t1, t2;
  gettimeofday(&t1, NULL);

  if (!ret.getError()) {
    // Make a first simulation to check if there exist some collisions in the system
    if (config.debug) {
      cout << "CRGenetics::run --> Simulating system in order to check for collisions...\n";
    }
    
    bool collision;
    float min_distance;
    if ( sim->run(collision) ) { // Simulating the whole system saving trajectory.
      if (!collision) {
	      cout << "CRGenetics::run --> No collisions found. It is not necessary to run GA algorithm.\n";
// 				cout << "CRGenetics::run --> Min distance = " << min_distance << endl;
	      
	      ret.setSolved(false);
	      ret.setCollisionDetected(false);
      } else {
	      ret.setCollisionDetected(true);
	      cout << "CRGenetics::run --> Collisions found, initiating the CR Algorithm\n";
// 				cout << "CRGenetics::run --> Min distance = " << min_distance << endl;
      }
    } else {
      cerr << "CRGenetics::run --> An error was found while simulating the system. Aborting.\n";
      ret.setError(true);
    }
	
  }
  
  if ( !ret.getError() && ret.getCollisionDetected() ) {
    // Beggining of the algorithm.
    
    // Associate the objetive and population initializer functions to genome and population
    if (config.debug) {
      cout << "CRGenetics::run --> Associating the proper functions to genome algorithm\n";
    }
    
    if (bounds == NULL) {
      cerr << "CRGenetics::execute() --> This should not happen: bounds = NULL\n";
      return ret;
    }
    
    GARealGenome genome(*bounds, CRALgorithmObjective, (void *)this);
    setGeneticOperators(genome);
    
    // The same process has to be applied to the population
    GAPopulation population(genome, config.population);
    if (config.initializer_type == "Deterministic") {
      population.initializer(GAPopulationInitializer);
    }

    // Define parameters. There is an option to do this from file.
    population.userData((void *) this);

    if (config.debug) {
      cout << "CRGenetics::run --> Creating the algorithm.\n";
    }
    
    delete algorithm;
    algorithm = new GASimpleGA(population);
    cout << "CRGenetics::run --> Setting the GAAlgorithm parameters.\n";
    setGeneticParameters();
    
    if (!config.custom_evolution) {
      if (config.debug) {
	cout << "CRGenetics::run --> Letting the algorithm evolve.\n";
      }
      algorithm->evolve();
    } else {
      customEvolution(ret, t1, true);
    }
    
    // Calculate spended time and show it
    gettimeofday(&t2,NULL);
    cout << "\n\n CRGenetics::run --> Spended time = " << functions::showTime(t1,t2) << endl;
    ret.setExecutionTime(functions::calculateLapseTime(t1, t2));

    // Get best flight plan
    GARealGenome &best = (GARealGenome &) algorithm->statistics().bestIndividual();
    vector<FlightPlan> best_wp(getGeneticFlightPlan(best));
    
    // Get the minimum objetive value and store it for statistics purposes...
    ret.setMinObjetive( best.score() );
    
    // Show the best flight plan
    cout << "CRGenetics::run --> Evolution finished. Best flight plan:\n";
    cout << functions::printToStringVector(best_wp) << endl;
    
    // Show genetic statistics
    cout << algorithm->statistics() << endl;
    
    // Check for collisions in the solution
    bool collision;
// 		float min_d;
    
    
    bool ok;
    try {
      ok = simulateSystem(best_wp, collision);
    } catch(...) {
      ok = false;
    }

    
    
    if (collision || !ok) {
      if (!ok) {
	cerr << "CRGenetics::run --> Error while simulating the best flight plan\n";
      }
      ret.setSolved(false);
      cout  << "CRGenetics::run --> The problem was not solved.\n"; // Min distance = " << min_d << "\n";
    } else {
      cout  << "CRGenetics::run --> The problem was solved successfully.\n";// Min distance = " << min_d << "\n";
    
      if (config.export_trajectories) {
	if (sim->exportTrajectory(config.trajectory_filename)) {
	  cout << "Trajectories exported successfully.\n";
	}
      }
      if (config.export_solution) {
	if (exportSolution(config.solution_filename, best_wp)) {
		cout << "CRGenetics::execute() --> Solution flight plans exported successfully.\n";
	}
      }
      if (config.export_evolution) {
	
      }
		    
      ret.setSolved(true);
    }
	
  }
  
  return ret;
}
Example #22
0
CRAlgorithmStatistics CRGenetics::execute_one_vs_all(std::vector<std::vector<functions::RealVector> > &traj, bool initialize) {
  functions::FormattedTime t1, t2;
  struct timeval t;
  gettimeofday(&t, NULL);
  
  t1.getTime();
  CRAlgorithmStatistics ret;
  GeneticConfig &config = dynamic_cast<GeneticConfig&>(* (this->config));
  
  sim->setTrajectories(traj);
  
  if (config.debug) {
    cout << "CRGenetics::run --> Associating the proper functions to genome algorithm\n";
  }
    
  if (bounds == NULL) {
    cerr << "CRGenetics::execute_one_vs_all() --> This should not happen: bounds = NULL\n";
    return ret;
  } 
  
  if (initialize) {
    GARealGenome genome(*bounds, CRALgorithmOneObjective, (void *)this);
    setGeneticOperators(genome);
  
    // The same process has to be applied to the population
    GAPopulation population(genome, config.population);
    if (config.initializer_type == "Deterministic") {
      population.initializer(GAPopulationInitializer);
    }

    delete algorithm;
    algorithm = new GASimpleGA(population);
    setGeneticParameters();
  }
  
  // Run genetics
  if (!config.custom_evolution) {
      if (config.debug) {
	cout << "CRGenetics::run --> Letting the algorithm evolve.\n";
      }
      algorithm->evolve();
    } else {
      customEvolution(ret, t, initialize);
    }
    
  // Calculate spended time and show it
  t2.getTime();
  ret.setExecutionTime(t2 - t1);
  
  // Get best flight plan
  GARealGenome &best = (GARealGenome &) algorithm->statistics().bestIndividual();
  FlightPlan best_wp(get1vsAllFlightPlan(geneToVector(best)));
    
  // Get the minimum objetive value and store it for statistics purposes...
  ret.setMinObjetive( best.score() );
    
  // Show the best flight plan
  cout << "CRGenetics::run --> Evolution finished. Best flight plan:\n";
  cout << best_wp.toString() << endl;
  
  sim->getParticle(0)->getController()->setFlightPlan(best_wp);
  
  if (config.export_trajectories) {
	if (sim->exportTrajectory(config.trajectory_filename)) {
	  cout << "Trajectories exported successfully.\n";
	}
      }
    
  return ret;
}
Example #23
0
int main( int argc , char *argv[] )
{
    rng_type rng;
    
    trainings_data_type c;
    generate_test_data( c , -5.0 , 5.0 + 0.1 , 0.4 , []( double x1 , double x2 , double x3 ) {
                        return  1.0 / ( 1.0 + pow( x1 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x2 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x3 , -4.0 ) ); } );
    gpcxx::normalize( c.y );
    

    std::ofstream fout1( "testdata.dat" );
    for( size_t i=0 ; i<c.x[0].size() ; ++i )
        fout1 << c.y[i] << " " << c.x[0][i] << " " << c.x[1][i] << " " << c.x[2][i] << "\n";
    fout1.close();
    

	gpcxx::uniform_symbol< node_type > terminal_gen { std::vector< node_type >{
        node_type { gpcxx::array_terminal< 0 >{} , "x" } ,
        node_type { gpcxx::array_terminal< 1 >{} , "y" } ,
        node_type { gpcxx::array_terminal< 2 >{} , "z" } } };
    gpcxx::uniform_symbol< node_type > unary_gen { std::vector< node_type >{
        node_type { gpcxx::sin_func{} , "s" } ,
        node_type { gpcxx::cos_func{} , "c" } ,
        node_type { gpcxx::exp_func{} , "e" } ,
        node_type { gpcxx::log_func{} , "l" } } };
    gpcxx::uniform_symbol< node_type > binary_gen { std::vector< node_type > {
        node_type { gpcxx::plus_func{} , "+" } ,
        node_type { gpcxx::minus_func{} , "-" } ,
        node_type { gpcxx::multiplies_func{} , "*" } ,
        node_type { gpcxx::divides_func{} , "/" }    
    } };
    
    gpcxx::node_generator< node_type , rng_type , 3 > node_generator {
        { double ( terminal_gen.num_symbols() ) , 0 , terminal_gen } ,
        { double ( unary_gen.num_symbols() ) , 1 , unary_gen } ,
        { double ( binary_gen.num_symbols() ) , 2 , binary_gen } };
    
    size_t population_size = 512;
    size_t generation_size = 20;
    double number_elite = 1;
    double mutation_rate = 0.0;
    double crossover_rate = 0.6;
    double reproduction_rate = 0.3;
    size_t max_tree_height = 8;
    size_t tournament_size = 15;
    

    auto tree_generator = gpcxx::make_basic_generate_strategy( rng , node_generator , max_tree_height , max_tree_height );
    // size_t min_tree_height = 1
    // auto new_tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );


    typedef gpcxx::static_pipeline< population_type , fitness_type , rng_type > evolver_type;
    evolver_type evolver( number_elite , mutation_rate , crossover_rate , reproduction_rate , rng );
    std::vector< double > fitness( population_size , 0.0 );
    std::vector< tree_type > population( population_size );


    evolver.mutation_function() = gpcxx::make_mutation(
        gpcxx::make_simple_mutation_strategy( rng , node_generator ) ,
        gpcxx::make_tournament_selector( rng , tournament_size ) );
    evolver.crossover_function() = gpcxx::make_crossover( 
        gpcxx::make_one_point_crossover_strategy( rng , max_tree_height ) ,
        gpcxx::make_tournament_selector( rng , tournament_size ) );
    evolver.reproduction_function() = gpcxx::make_reproduce(
        gpcxx::make_tournament_selector( rng , tournament_size ) );
    
    gpcxx::timer timer;
    auto fitness_f = gpcxx::make_regression_fitness( evaluator() );

    // initialize population with random trees and evaluate fitness
    timer.restart();
    for( size_t i=0 ; i<population.size() ; ++i )
    {
        tree_generator( population[i] );
        fitness[i] = fitness_f( population[i] , c );
    }
    std::cout << gpcxx::indent( 0 ) << "Generation time " << timer.seconds() << std::endl;
    std::cout << gpcxx::indent( 1 ) << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 1 , 10 ) << std::endl;
    std::cout << gpcxx::indent( 1 ) << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl;
    std::cout << gpcxx::indent( 1 ) << std::endl << std::endl;
    
    write_height_hist( population , "initial_height.hist" );
    write_size_hist( population , "initial_size.hist" );
    
    timer.restart();
    for( size_t generation=1 ; generation<=generation_size ; ++generation )
    {
        gpcxx::timer iteration_timer;
        iteration_timer.restart();
        evolver.next_generation( population , fitness );
        double evolve_time = iteration_timer.seconds();
        iteration_timer.restart();
        std::transform( population.begin() , population.end() , fitness.begin() , [&]( tree_type const &t ) { return fitness_f( t , c ); } );
        double eval_time = iteration_timer.seconds();
        
        write_height_hist( population , "height_" + std::to_string( generation ) + ".hist" );
        write_size_hist( population , "size_" + std::to_string( generation ) + ".hist" );
        
        std::cout << gpcxx::indent( 0 ) << "Generation " << generation << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Evolve time " << evolve_time << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Eval time " << eval_time << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 2 , 10 ) << std::endl;
        std::cout << gpcxx::indent( 1 ) << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;
    }
    std::cout << "Overall time : " << timer.seconds() << std::endl;


// 	generate_data();
// 	init_constants();
// 	init_node_types();   // init generators
// 	init_population();
// 	evolve();
// 	report();

    return 0;
}
bool EpidemicDataSet::loadNodePopulationFile(const char * filename)
{
    // make sure we have appropriate number of stratifications
    if(stratifications_.size() < 2)
    {
        put_flog(LOG_ERROR, "need at least 2 stratification, got %i", stratifications_.size());
        return false;
    }

    std::ifstream in(filename);

    if(in.is_open() != true)
    {
        put_flog(LOG_ERROR, "could not load file %s", filename);
        return false;
    }

    // full shape of population variable: [time][node][stratifications...]
    blitz::TinyVector<int, 2+NUM_STRATIFICATION_DIMENSIONS> shape;
    shape(0) = 1; // one time step
    shape(1) = numNodes_;

    for(int j=0; j<NUM_STRATIFICATION_DIMENSIONS; j++)
    {
        shape(2 + j) = stratifications_[j].size();
    }

    blitz::Array<float, 2+NUM_STRATIFICATION_DIMENSIONS> population(shape);

    population = 0.;

    // the data file contains population data stratified only by the first two stratifications
    // stratification values of 0 are assumed for all other stratifications

    // use boost tokenizer to parse the file
    typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer;

    std::vector<std::string> vec;
    std::string line;

    // read (and ignore) header
    getline(in, line);

    while(getline(in, line))
    {
        Tokenizer tok(line);

        vec.assign(tok.begin(), tok.end());

        // each line is: county, fips, <population data>...
        if(vec.size() != 2+stratifications_[0].size()*stratifications_[1].size())
        {
            put_flog(LOG_ERROR, "number of values != %i, == %i", 2+stratifications_[0].size()*stratifications_[1].size(), vec.size());
            return false;
        }

        int time = 0;
        int nodeId = atoi(vec[1].c_str());

        if(nodeIdToIndex_.count(nodeId) == 0)
        {
            put_flog(LOG_ERROR, "could not map nodeId %i to an index", nodeId);
            return false;
        }

        int nodeIndex = nodeIdToIndex_[nodeId];

        // the CSV orders by the second stratification, then first stratification... (first stratification varies fastest)
        for(int j=0; j<(int)stratifications_[1].size(); j++)
        {
            for(int i=0; i<(int)stratifications_[0].size(); i++)
            {
                // array position; all indices initialized to 0
                blitz::TinyVector<int, 2+NUM_STRATIFICATION_DIMENSIONS> index(0);

                index(0) = time;
                index(1) = nodeIndex;
                index(2) = i;
                index(3) = j;

                // all other stratification indices are zero

                population(index) = atof(vec[2+j*(int)stratifications_[0].size() + i].c_str());
            }
        }
    }

    // add to regular variables map
    variables_["population"].reference(population);

    return true;
}
Example #25
0
int main()
{
	GaInitialize();

	{

		int values[ Problems::TNG::TNG_NUMBER_COUNT ];

		values[ 0 ] = GaGlobalRandomIntegerGenerator->Generate( 1, 9 );
		values[ 1 ] = GaGlobalRandomIntegerGenerator->Generate( 1, 9 );
		values[ 2 ] = GaGlobalRandomIntegerGenerator->Generate( 1, 9 );
		values[ 3 ] = GaGlobalRandomIntegerGenerator->Generate( 1, 9 );
		values[ 4 ] = ( 10 + GaGlobalRandomIntegerGenerator->Generate( 0, 2 ) * 5 );
		values[ 5 ] = ( 25 + GaGlobalRandomIntegerGenerator->Generate( 0, 3 ) * 25 );

		int target = ( GaGlobalRandomIntegerGenerator->Generate( 100, 999 ) );

		Chromosome::GaMatingConfig matingConfiguration(
			Chromosome::GaCrossoverSetup( &crossover, &Chromosome::GaCrossoverPointParams( 0.8f, 2, 1 ), NULL ),
			Chromosome::GaMutationSetup( &mutation, &Chromosome::GaMutationSizeParams( 0.3f, true, 2L ), NULL ) );

		Chromosome::GaInitializatorSetup initializatorSetup( &initializator, NULL, &Chromosome::GaInitializatorConfig(
			&Problems::TNG::TngConfigBlock( values, target, &Chromosome::Representation::GaBinaryChromosomeParams() ) ) );
		Fitness::GaFitnessComparatorSetup fitnessComparatorSetup( &fitnessComparator, &Fitness::Comparators::GaSimpleComparatorParams( Fitness::Comparators::GACT_MAXIMIZE_ALL ), NULL );

		Algorithm::Stubs::GaSimpleGAStub::GaStatTrackersCollection trackers;
		trackers[ Population::GaPopulationSizeTracker::TRACKER_ID ] =  &sizeTracker;
		trackers[ Population::GaRawFitnessTracker::TRACKER_ID ] =  &rawTracker;
		trackers[ Population::GaScaledFitnessTracker::TRACKER_ID ] =  &scaledTracker;

		Population::GaSelectionSetup selectionSetup( &selection, &Population::SelectionOperations::GaDuplicatesSelectionParams( 8, 1, 2 ),
			&Population::GaCouplingConfig( Chromosome::GaMatingSetup( &mating, NULL, &matingConfiguration ) ) );

		Population::GaReplacementSetup replacementSetup( &replacement, &Population::ReplacementOperations::GaRandomReplacementParams( 8, 4, 3 ),
			&Population::GaReplacementConfig( Chromosome::GaChromosomeComparatorSetup( &chromosomeComparator, NULL, NULL ) ) );

		Population::GaScalingSetup scalingSetup( &scaling, &Population::ScalingOperations::GaScalingFactorParams( 2.0f )/*&Population::ScalingOperations::GaShareFitnessParams( 0.2f, 1.0f, 4 )*/,
			&Population::ScalingOperations::GaShareFitnessScalingConfig( NULL, Chromosome::GaChromosomeComparatorSetup( &chromosomeComparator, NULL, NULL ) ) );

		/*
		Population::GaPopulation* population = new Population::GaPopulation( Population::GaPopulationParams( 32, 0, Population::GaPopulationParams::GAPFO_FILL_ON_INIT ),
		Chromosome::GaInitializatorSetup( &initializator, NULL, &Chromosome::GaInitializatorConfig(
		&Problems::TNG::TngConfigBlock( values, target, &Chromosome::Representation::GaBinaryChromosomeParams() ) ) ),
		Population::GaPopulationFitnessOperationSetup( &populationFitnessOperation, NULL, &Fitness::GaFitnessOperationConfig() ),
		fitnessComparatorSetup );
		*/

		Algorithm::Stubs::GaSimpleGAStub simpleGA(  WDID_POPULATION, WDID_POPULATION_STATS,
			initializatorSetup,
			Population::GaPopulationFitnessOperationSetup( &populationFitnessOperation, NULL, &Fitness::GaFitnessOperationConfig() ),
			fitnessComparatorSetup,
			Population::GaPopulationParams( 32, 0, Population::GaPopulationParams::GAPFO_FILL_ON_INIT ),
			trackers,
			Chromosome::GaMatingSetup(),
			selectionSetup,
			Population::GaCouplingSetup(),
			replacementSetup,
			scalingSetup,
			Population::GaFitnessComparatorSortingCriteria( fitnessComparatorSetup, Population::GaChromosomeStorage::GAFT_RAW ) );

		/*
		Common::Workflows::GaWorkflow workflow( NULL );
		Common::Workflows::GaDataStorage* storage = workflow.GetWorkflowData();

		storage->AddData( new Common::Workflows::GaDataEntry<Population::GaPopulation>( 1, population ), Common::Workflows::GADSL_WORKFLOW );
		storage->AddData( new Common::Workflows::GaDataEntry<Statistics::GaStatistics>( 2, Common::Memory::GaAutoPtr<Statistics::GaStatistics>( &population->GetStatistics(),
		Common::Memory::GaNoDeletionPolicy<Statistics::GaStatistics>::GetInstance() ) ), Common::Workflows::GADSL_WORKFLOW );
		storage->AddData( new Common::Workflows::GaDataEntry<Population::GaChromosomeGroup>( 3, new Population::GaChromosomeGroup( false ) ), Common::Workflows::GADSL_WORKFLOW );

		Common::Workflows::GaWorkflowBarrier* br1 = new Common::Workflows::GaWorkflowBarrier();
		Common::Workflows::GaWorkflowBarrier* br2 = new Common::Workflows::GaWorkflowBarrier();

		Common::Workflows::GaBranchGroup* bg1 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( workflow.GetFirstStep(), br1, 0 );
		Common::Workflows::GaBranchGroup* bg2 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( br1, br2, 0 );
		Common::Workflows::GaBranchGroup* bg3 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( br2, workflow.GetLastStep(), 0 );

		Common::Workflows::GaFlowStep* initStep =
		new Common::Workflows::GaSimpleMethodExecStep<Population::GaPopulation, Common::Workflows::GaMethodExecIgnoreBranch<Population::GaPopulation> >(
		&Population::GaPopulation::Initialize, storage, 1 );

		bg1->GetBranchGroupFlow()->SetFirstStep( initStep );

		Common::Workflows::GaFlowStep* sortStep = new Population::GaSortPopulationStep<Population::GaFitnessSortingCriteria>( storage, 1, Population::GaFitnessSortingCriteria( population ) );

		Common::Workflows::GaFlowStep* scalingStep = new Population::GaScalingStep(
		Population::GaScalingSetup( &scaling, &Population::ScalingOperations::GaScalingFactorParams( 2.0f ), //&Population::ScalingOperations::GaShareFitnessParams( 0.2f, 1.0f, 4 ),
		&Population::ScalingOperations::GaShareFitnessScalingConfig( NULL, Chromosome::GaChromosomeComparatorSetup( &chromosomeComparator, NULL, NULL ) ) ), storage, 1 );

		Chromosome::GaMatingConfig matingConfiguration(
		Chromosome::GaCrossoverSetup( &crossover, &Chromosome::GaCrossoverPointParams( 0.8f, 2, 1 ), NULL ),
		Chromosome::GaMutationSetup( &mutation, &Chromosome::GaMutationSizeParams( 0.3f, true, 2L ), NULL ) );

		Common::Workflows::GaFlowStep* selectionStep = new Population::GaSelectionStep(
		Population::GaSelectionSetup( &selection, &Population::SelectionOperations::GaDuplicatesSelectionParams( 8, 1, 2 ),
		&Population::GaCouplingConfig( Chromosome::GaMatingSetup( &mating, NULL, &matingConfiguration ) ) ), storage, 1, storage, 3 );

		Common::Workflows::GaFlowStep* replacementStep = new Population::GaReplacementStep(
		Population::GaReplacementSetup( &replacement, &Population::ReplacementOperations::GaRandomReplacementParams( 8, 4, 3 ),
		&Population::GaReplacementConfig( Chromosome::GaChromosomeComparatorSetup( &chromosomeComparator, NULL, NULL ) ) ),
		storage, 3, storage, 1 );

		Common::Workflows::GaFlowStep* nextGenStep = new Common::Workflows::GaSimpleMethodExecStep<Population::GaPopulation>( &Population::GaPopulation::NextGeneration, storage, 1 );

		Common::Workflows::GaBranchGroupFlow* flow2 = bg2->GetBranchGroupFlow();
		flow2->SetFirstStep( sortStep );
		flow2->ConnectSteps( sortStep, scalingStep, 0 );
		flow2->ConnectSteps( scalingStep, nextGenStep, 0 );
		flow2->ConnectSteps( selectionStep, replacementStep, 0 );
		flow2->ConnectSteps( replacementStep, sortStep, 0 );

		Fitness::Representation::GaSVFitness<float> targetFitness( 1.0f, Common::Memory::GaSmartPtr<const Fitness::GaFitnessParams>::NullPtr );

		Algorithm::StopCriteria::GaStopCriterionStep* stopStep = new Algorithm::StopCriteria::GaStopCriterionStep(
		Algorithm::StopCriteria::GaStopCriterionSetup( &stopCriterion,
		&Algorithm::StopCriteria::GaStatsCriterionParams<Fitness::GaFitness>(
		Population::GADV_BEST_FITNESS, targetFitness, Algorithm::StopCriteria::GAST_STOP_IF_EQUAL_TO,
		Algorithm::StopCriteria::GaStatsCriterionComparator<Fitness::GaFitness>( fitnessComparatorSetup ) ), NULL ), storage, 2 );

		Common::Workflows::GaBranchGroupTransition* bt32 = new Common::Workflows::GaBranchGroupTransition();

		Common::Workflows::GaBranchGroupFlow* flow3 = bg3->GetBranchGroupFlow();

		flow3->SetFirstStep( stopStep );
		flow3->ConnectSteps( stopStep, bt32, 0 );
		workflow.ConnectSteps( bt32, selectionStep, 1 );

		population->GetEventManager().AddEventHandler( Population::GaPopulation::GAPE_NEW_GENERATION, &newGenHandler );

		workflow.Start();
		workflow.Wait();
		*/

		Common::Workflows::GaWorkflow workflow( NULL );

		workflow.RemoveConnection( *workflow.GetFirstStep()->GetOutboundConnections().begin(), true );

		Common::Workflows::GaWorkflowBarrier* br1 = new Common::Workflows::GaWorkflowBarrier();
		simpleGA.Connect( workflow.GetFirstStep(), br1 );

		Common::Workflows::GaBranchGroup* bg1 = (Common::Workflows::GaBranchGroup*)workflow.ConnectSteps( br1, workflow.GetLastStep(), 0 );

		Fitness::Representation::GaSVFitness<float> targetFitness( 1.0f, Common::Memory::GaSmartPtr<const Fitness::GaFitnessParams>::NullPtr );

		Algorithm::StopCriteria::GaStopCriterionStep* stopStep = new Algorithm::StopCriteria::GaStopCriterionStep(
			Algorithm::StopCriteria::GaStopCriterionSetup( &stopCriterion,
			&Algorithm::StopCriteria::GaStatsCriterionParams<Fitness::GaFitness>(
			Population::GADV_BEST_FITNESS, targetFitness, Algorithm::StopCriteria::GAST_STOP_IF_EQUAL_TO,
			Algorithm::StopCriteria::GaStatsCriterionComparator<Fitness::GaFitness>( fitnessComparatorSetup ) ), NULL ), workflow.GetWorkflowData(), WDID_POPULATION_STATS );

		Common::Workflows::GaBranchGroupTransition* bt1 = new Common::Workflows::GaBranchGroupTransition();

		bg1->GetBranchGroupFlow()->SetFirstStep( stopStep );
		bg1->GetBranchGroupFlow()->ConnectSteps( stopStep, bt1, 0 );
		workflow.ConnectSteps( bt1, simpleGA.GetStubFlow().GetFirstStep(), 1 );

		Common::Workflows::GaDataCache<Population::GaPopulation> population( workflow.GetWorkflowData(), WDID_POPULATION );

		population.GetData().GetEventManager().AddEventHandler( Population::GaPopulation::GAPE_NEW_GENERATION, &newGenHandler );

		workflow.Start();
		workflow.Wait();
	}

	GaFinalize();

	return 0;
}
Example #26
0
int main( int argc , char** argv )
{
    auto options = dynsys::get_options();
    auto positional_options = dynsys::get_positional_options();
    
    po::options_description cmdline_options;
    cmdline_options.add( options ).add( positional_options.second );
    
    po::variables_map vm;
    try
    {
        po::store( po::command_line_parser( argc , argv ).options( cmdline_options ).positional( positional_options.first ).run() , vm );
        po::notify( vm );
    }
    catch( std::exception& e )
    {
        std::cerr << "Error " << e.what() << "\n\n";
        std::cerr << cmdline_options << "\n";
        return -1;
    }
    
    dynsys::rng_type rng;
    
    
    //[ create_lorenz_data
    auto training_data = dynsys::generate_data();
    
    std::array< std::pair< double , double > , dynsys::dim > xstat , ystat;
    for( size_t i=0 ; i<dynsys::dim ; ++i )
    {
        xstat[i].first = ystat[i].first = 0.0;
        xstat[i].second = ystat[i].second = 1.0;
    }
    if( vm.count( "normalize" ) )
    {
        xstat = dynsys::normalize_data( training_data.first );
        ystat = dynsys::normalize_data( training_data.second );
    }
    // plot_data( training_data );
    //]
    
    //[ lorenz_define_node_generator
    auto node_generator = dynsys::create_node_generator();
    //]
    
    
    //[ define_gp_parameters
//     size_t population_size = 256;
//     size_t generation_size = 20;
    size_t population_size = 512 * 32;
    size_t generation_size = 2000;
    
    
    size_t number_elite = 1;
    double mutation_rate = 0.2;
    double crossover_rate = 0.6;
    double reproduction_rate = 0.3;
    size_t min_tree_height = 1 , max_tree_height = 8;
    size_t tournament_size = 15;
    //]

    //[ define_population_and_fitness
    using population_type = std::vector< dynsys::tree_type >;
    using fitness_type = std::vector< double >;
    //]
    
    //[ define_evolution
    using evolver_type = gpcxx::dynamic_pipeline< population_type , fitness_type , dynsys::rng_type >;
    evolver_type evolver( rng , number_elite );
    //]
    
    //[define_evaluator
    using evaluator = struct {
        using context_type = gpcxx::regression_context< double , dynsys::dim >;
        using value_type = double;
        value_type operator()( dynsys::tree_type const& t , context_type const& c ) const {
            return t.root()->eval( c );
        } };
    //]
        
    //[define_genetic_operators
    auto tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );
    auto fitness_f = gpcxx::make_regression_fitness( evaluator {} );
    evolver.add_operator(
        gpcxx::make_mutation(
            gpcxx::make_point_mutation( rng , tree_generator , max_tree_height , 20 ) ,
            gpcxx::make_tournament_selector( rng , tournament_size )
        ) , mutation_rate );
    evolver.add_operator(
        gpcxx::make_crossover( 
            gpcxx::make_one_point_crossover_strategy( rng , 10 ) ,
            gpcxx::make_tournament_selector( rng , tournament_size )
        ) , crossover_rate );
    evolver.add_operator(
        gpcxx::make_reproduce(
            gpcxx::make_tournament_selector( rng , tournament_size )
        ) , reproduction_rate );
    //]

    
    std::ofstream fout { vm[ "evolution" ].as< std::string >() };
    std::ofstream fout2 { vm[ "result" ].as< std::string >() };
    fout2.precision( 14 );
    for( size_t j=0 ; j<dynsys::dim ; ++j )
        fout2 << xstat[j].first << " " << xstat[j].second << " " << ystat[j].first << " " << ystat[j].second << "\n";
    fout2 << std::endl << std::endl;
    
    
    
    std::array< dynsys::tree_type , dynsys::dim > winner;
    for( size_t dimension = 0 ; dimension < dynsys::dim ; ++dimension )
    {
        fitness_type fitness ( population_size , 0.0 );
        population_type population ( population_size );

        gpcxx::regression_training_data< double , dynsys::dim > problem;
        for( size_t i=0 ; i<training_data.first.size() ; ++i )
        {
            problem.y.push_back( training_data.second[i][ dimension ] );
            for( size_t j=0 ; j<dynsys::dim ; ++j )
                problem.x[j].push_back( training_data.first[i][j] );
        }
        
        //[init_population
        for( size_t i=0 ; i<population.size() ; ++i )
        {
            tree_generator( population[i] );
            fitness[i] = fitness_f( population[i] , problem );
        }
        
        std::cout << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness ) << std::endl;
        std::cout << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl;
        std::cout << std::endl << std::endl;
        //]
        
        //[main_loop
        for( size_t i=0 ; i<generation_size ; ++i )
        {
            evolver.next_generation( population , fitness );
            for( size_t i=0 ; i<population.size() ; ++i )
                fitness[i] = fitness_f( population[i] , problem );
            
            std::cout << "Iteration " << i << std::endl;
            std::cout << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 1 ) << std::endl;
            std::cout << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;
            
            fout << "Iteration " << i << std::endl;
            fout << "Best individuals" << std::endl << gpcxx::best_individuals( population , fitness , 1 ) << std::endl;
            fout << "Statistics : " << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;
            
            auto min_fitness = * ( std::min_element( fitness.begin() , fitness.end() ) );
            if( std::abs( min_fitness ) < 1.0e-7 )
            {
                std::cout << "Minimal fitness is small then 1.0e-7. Stopping now." << std::endl << std::endl << std::endl << std::endl;
                fout << "Minimal fitness is small then 1.0e-7. Stopping now." << std::endl << std::endl << std::endl << std::endl;
                break;
            }
        }
        //]
        
        fout2 << gpcxx::best_individuals( population , fitness , 0 ) << std::endl << std::endl;
        
        std::vector< size_t > idx;
        gpcxx::sort_indices( fitness , idx );
        winner[dimension] = population[ idx[0] ];
    }
    
    std::ofstream winner_out { vm[ "winner" ].as< std::string >() };
    winner_out << dynsys::serialize_winner( winner , xstat , ystat ) << "\n";
    
    
    return 0;
}
Example #27
0
void PlayTest_Tune(unsigned int rollbacks, unsigned int plays, unsigned int population_size, unsigned int tournament_size, unsigned int latency) {
	std::mt19937 rng(RandomSeed());

	// create initial population
	std::vector<TuneElement> population(population_size);
	for(unsigned int i = 0; i < population_size; ++i) {
		GetDefaultHeuristicParameters(&population[i].m_parameters);
		population[i].m_score = 20000; // guess, should be relatively low
	}

	// simulate plays
	std::vector<TuneElement> history(plays);
	std::vector<std::future<unsigned int> > futures(latency);
	for(unsigned int p = 0; p < plays + latency; ++p) {
		std::cout << "Tune progress: " << 100 * p / (plays + latency) << "%" << std::endl;

		// add completed play to the population
		if(p >= latency) {
			history[p - latency].m_score = futures[p % latency].get();
			population[(p - latency) % population_size] = history[p - latency];
		}

		// tournament selection
		TuneElement best1, best2;
		GetDefaultHeuristicParameters(&best1.m_parameters);
		GetDefaultHeuristicParameters(&best2.m_parameters);
		best1.m_score = 0;
		best2.m_score = 0;
		for(unsigned int t = 0; t < tournament_size; ++t) {
			unsigned int sel1 = rng() % population_size;
			if(population[sel1].m_score > best1.m_score)
				best1 = population[sel1];
			unsigned int sel2 = rng() % population_size;
			if(population[sel2].m_score > best2.m_score)
				best2 = population[sel2];
		}

		// create winner
		HeuristicParameters winner;
		std::cout << "Winner (" << best1.m_score << "|" << best2.m_score << "): ";
		for(unsigned int i = 0; i < PARAM_COUNT; ++i) {
			winner.m_values[i] = (best1.m_parameters.m_values[i] + best2.m_parameters.m_values[i] + (rng() & 1)) / 2;
			std::cout << winner.m_values[i] << " ";
		}
		std::cout << std::endl;

		if(p < plays) {

			// do some mutations
			for(unsigned int i = 0; i < PARAM_COUNT; ++i) {
				winner.m_values[i] = Mutate(winner.m_values[i], PARAMETERS_MIN[i], PARAMETERS_MAX[i], PARAMETERS_STEP[i], rng);
			}

			// start the job
			history[p].m_parameters = winner;
			futures[p % latency] = StartJob(PlayTest, winner, rollbacks, (BoardDB*) NULL, (std::mutex*) NULL);

		}

	}

	std::cout << "scores = array([\n\t";
	for(unsigned int p = 0; p < plays; ++p) {
		std::cout << history[p].m_score;
		if(p != plays - 1) {
			if(p % 20 == 19)
				std::cout << ",\n\t";
			else
				std::cout << ", ";
		}
	}
	std::cout << "])" << std::endl;

	// calculate population average
	HeuristicParameters population_average;
	std::cout << "Population average: ";
	for(unsigned int i = 0; i < PARAM_COUNT; ++i) {
		population_average.m_values[i] = 0;
		for(unsigned int p = 0; p < population_size; ++p) {
			population_average.m_values[i] += population[p].m_parameters.m_values[i];
		}
		population_average.m_values[i] = (population_average.m_values[i] + population_size / 2) / population_size;
		std::cout << population_average.m_values[i] << " ";
	}
	std::cout << std::endl;

}
Example #28
0
/**
 * Run the co-evolution algorithm
 *
 * @param[in,out] pop input/output pagmo::population to be evolved.
 */
void cstrs_co_evolution::evolve(population &pop) const
{	
	// Let's store some useful variables.
	const problem::base &prob = pop.problem();
	const population::size_type pop_size = pop.size();
	const problem::base::size_type prob_dimension = prob.get_dimension();

	// get the constraints dimension
	problem::base::c_size_type prob_c_dimension = prob.get_c_dimension();

	//We perform some checks to determine wether the problem/population are suitable for co-evolution
	if(prob_c_dimension < 1) {
		pagmo_throw(value_error,"The problem is not constrained and co-evolution is not suitable to solve it");
	}
	if(prob.get_f_dimension() != 1) {
		pagmo_throw(value_error,"The problem is multiobjective and co-evolution is not suitable to solve it");
	}

	// Get out if there is nothing to do.
	if(pop_size == 0) {
		return;
	}

	//get the dimension of the chromosome of P2
	unsigned int pop_2_dim = 0;
	switch(m_method)
	{
	case algorithm::cstrs_co_evolution::SIMPLE:
	{
		pop_2_dim = 2;
		break;
	}
	case algorithm::cstrs_co_evolution::SPLIT_NEQ_EQ:
	{
		pop_2_dim = 4;
		break;
	}
	case algorithm::cstrs_co_evolution::SPLIT_CONSTRAINTS:
		pop_2_dim = 2*prob.get_c_dimension();
		break;
	default: 
		pagmo_throw(value_error,"The constraints co-evolutionary method is not valid.");
		break;
	}

	// split the population into two populations
	// the population P1 associated to the modified problem with penalized fitness
	// and population P2 encoding the penalty weights
	
	// Populations size
	population::size_type pop_1_size = pop_size;
	population::size_type pop_2_size = m_pop_penalties_size;

	//Creates problem associated to P2
	problem::cstrs_co_evolution_penalty prob_2(prob,pop_2_dim,pop_2_size);
	prob_2.set_bounds(m_pen_lower_bound,m_pen_upper_bound);

	//random initialization of the P2 chromosome (needed for the fist generation)
	std::vector<decision_vector> pop_2_x(pop_2_size);
	std::vector<fitness_vector> pop_2_f(pop_2_size);

	for(population::size_type j=0; j<pop_2_size; j++) {
		pop_2_x[j] = decision_vector(pop_2_dim,0.);
		// choose random coefficients between lower bound and upper bound
		for(population::size_type i=0; i<pop_2_dim;i++) {
			pop_2_x[j][i] = boost::uniform_real<double>(m_pen_lower_bound,m_pen_upper_bound)(m_drng);
		}
	}

	//vector of the population P1. Initialized with clones of the original population
	std::vector<population> pop_1_vector;
	for(population::size_type i=0; i<pop_2_size; i++){
		pop_1_vector.push_back(population(pop));
	}

	// Main Co-Evolution loop
	for(int k=0; k<m_gen; k++) {
		// for each individuals of pop 2, evolve the current population,
		// and store the position of the feasible idx
		for(population::size_type j=0; j<pop_2_size; j++) {

			problem::cstrs_co_evolution prob_1(prob, pop_1_vector.at(j), m_method);

			// modify the problem by setting decision vector encoding penalty
			// coefficients w1 and w2 in prob 1
			prob_1.set_penalty_coeff(pop_2_x.at(j));

			// creating the POPULATION 1 instance based on the
			// updated prob 1

			// prob_1 is a BASE_META???? THE CLONE OF prob_1 IN POP_1 IS AT THE LEVEL OF
			// THE BASE CLASS AND NOT AT THE LEVEL OF THE BASE_META, NO?!?
			population pop_1(prob_1,0);

			// initialize P1 chromosomes. The fitnesses related to problem 1 are computed
			for(population::size_type i=0; i<pop_1_size; i++) {
				pop_1.push_back(pop_1_vector.at(j).get_individual(i).cur_x);
			}

			// evolve the P1 instance
			m_original_algo->evolve(pop_1);

			//updating the original problem population (computation of fitness and constraints)
			pop_1_vector.at(j).clear();
			for(population::size_type i=0; i<pop_1_size; i++){
				pop_1_vector.at(j).push_back(pop_1.get_individual(i).cur_x);
			}

			// set up penalization variables needs for the population 2
			// the constraints has not been evaluated yet.
			prob_2.update_penalty_coeff(j,pop_2_x.at(j),pop_1_vector.at(j));

		}
		// creating the POPULATION 2 instance based on the
		// updated prob 2
		population pop_2(prob_2,0);

		// compute the fitness values of the second population
		for(population::size_type i=0; i<pop_2_size; i++) {
			pop_2.push_back(pop_2_x[i]);
		}

		m_original_algo_penalties->evolve(pop_2);

		// store the new chromosomes
		for(population::size_type i=0; i<pop_2_size; i++) {
			pop_2_x[i] = pop_2.get_individual(i).cur_x;
			pop_2_f[i] = pop_2.get_individual(i).cur_f;
		}

		// Check the exit conditions (every 40 generations, just as DE)
		if(k % 40 == 0) {
			// finds the best population
			population::size_type best_idx = 0;
			for(population::size_type j=1; j<pop_2_size; j++) {
				if(pop_2_f[j][0] < pop_2_f[best_idx][0]) {
					best_idx = j;
				}
			}

			const population &current_population = pop_1_vector.at(best_idx);

			decision_vector tmp(prob_dimension);

			double dx = 0;
			for(decision_vector::size_type i=0; i<prob_dimension; i++) {
				tmp[i] = current_population.get_individual(current_population.get_worst_idx()).best_x[i] -
						current_population.get_individual(current_population.get_best_idx()).best_x[i];
				dx += std::fabs(tmp[i]);
			}

			if(dx < m_xtol ) {
				if (m_screen_output) {
					std::cout << "Exit condition -- xtol < " << m_xtol << std::endl;
				}
				break;
			}

			double mah = std::fabs(current_population.get_individual(current_population.get_worst_idx()).best_f[0] -
					current_population.get_individual(current_population.get_best_idx()).best_f[0]);

			if(mah < m_ftol) {
				if(m_screen_output) {
					std::cout << "Exit condition -- ftol < " << m_ftol << std::endl;
				}
				break;
			}

			// outputs current values
			if(m_screen_output) {
				std::cout << "Generation " << k << " ***" << std::endl;
				std::cout << "    Best global fitness: " << current_population.champion().f << std::endl;
				std::cout << "    xtol: " << dx << ", ftol: " << mah << std::endl;
				std::cout << "    xtol: " << dx << ", ftol: " << mah << std::endl;
			}
		}
	}

	// find the best fitness population in the final pop
	population::size_type best_idx = 0;
	for(population::size_type j=1; j<pop_2_size; j++) {
		if(pop_2_f[j][0] < pop_2_f[best_idx][0]) { 
			best_idx = j;
		}
	}

	// store the final population in the main population
	// can't avoid to recompute the vectors here, otherwise we
	// clone the problem stored in the population with the
	// pop = operator!
	pop.clear();
	for(population::size_type i=0; i<pop_1_size; i++) {
		pop.push_back(pop_1_vector.at(best_idx).get_individual(i).cur_x);
	}
}
Example #29
0
int main(int argc, char **argv)
{
    gsl_rng_env_setup();

    T = gsl_rng_default;
    r = gsl_rng_alloc (T);
    gsl_rng_set(r, time(NULL));

    Graph *g = new Graph();
	g->addVertex(Vertex(1, "v1", 0, 0, 0, 1.0, 1.0, 1.0));
	g->addVertex(Vertex(2, "v2", 0, 0, 0, 1.0, 0.2, 0.2));
	g->addVertex(Vertex(3, "v3", 0, 0, 0, 0.2, 1.0, 0.2));
	g->addVertex(Vertex(4, "v4", 0, 0, 0, 0.2, 0.2, 1.0));

	g->addEdge(1, 2);
	g->addEdge(1, 3);
	g->addEdge(3, 4);

	ptr population(new std::vector<Graph>(4, *g));
	/*
	std::cout << "Population" << std::endl;
	printgraph(population);

	ptr reproduced = reproduce(population);
	std::cout << "Reproduced" << std::endl;
	printgraph(reproduced);

	ptr offsprings = genetic(reproduced);
	std::cout << "Offsprings" << std::endl;
	printgraph(offsprings);

	population = succession(population, offsprings);
	std::cout << "After one iteration" << std::endl;
	printgraph(population);
	*/

	int iterationcount = 0;
	double bestv = best(population);
	double bestvold = bestv * 2;

	std::cout << "best " << bestv << "; bestvold " << bestvold << std::endl;
	while (fabs(bestvold - bestv)/bestvold > 0.00000001)
	{
		++iterationcount;
		ptr offsprings = genetic(reproduce(population));
		population = succession(population, offsprings);
		bestvold = bestv;
		bestv = best(population);
	}

	std::cout << "Possible result found after " << iterationcount << "iterations: " << std::endl;
	printgraph(population);

	const Graph *bestgraph = bestg(population);
	for (Graph::vertices_const_iterator i = bestgraph->vertices.begin(); i != bestgraph->vertices.end(); ++i)
	{
		const Vertex &v = i->second;
		std::cout << "\"" << v.name << "\"";
		std::cout << "\t@" << v.x << " " << v.y << " " << v.z;
		std::cout << "\tcolor" << v.r << " " << v.g << " " << v.b;
		std::cout << "\tfrozen light size 1.0" << std::endl;
	}

    gsl_rng_free (r);
	return 0;
}