summaryrefslogtreecommitdiff
path: root/src/explicitsimulation.h
blob: 78cb904be3a6f128513d0605ed7e938637566879 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifndef GENETIC_EXPLICIT_SIMULATION_H
#define GENETIC_EXPLICIT_SIMULATION_H

#include "genetic/population.h"
#include "genetic/config.h"

#include <bu/thread.h>
#include <bu/mutex.h>
#include <bu/synchroqueue.h>

namespace Genetic
{
	class Operator;
	class FitnessFunction;

	class ExplicitSimulation
	{
	public:
		ExplicitSimulation( Operator *pOper, FitnessFunction *pFunc,
				int iThreads, int iPopSize, float fKeep, float fRandom,
				bool bKeepBest=true, bool bRecalcSurvivors=false );
		virtual ~ExplicitSimulation();

		void timestep();
		const Population &getPopulation() const { return xPop; }

		Genetic::PhenotypeId selectWeighted();

		double getMinFitness() const { return dMinFitness; }
		double getMaxFitness() const { return dMaxFitness; }
		double getFitness( Genetic::PhenotypeId id ) const
			{ return hFitness.get( id ); }

	protected:
		void updateFitness();
		void setFitness( Genetic::PhenotypeId, double dFitness );
		void workDone();
		void setRunning( bool b );
		bool isRunning();

	protected:
		Population xPop;
		Operator *pOper;

	private:
		int iPopSize;
		float fKeep;
		float fRandom;
		bool bKeepBest;
		bool bRecalcSurvivors;
		typedef Bu::Hash<Genetic::PhenotypeId, double> FitnessHash;
		FitnessHash hFitness;
		double dMinFitness;
		double dMaxFitness;
		double dTotalFitness;
		PhenotypeId uMaxFitness;

		Bu::Mutex mFitness;
		Bu::Condition cWorkDone;
		typedef Bu::SynchroQueue<Phenotype *> WorkQueue;
		WorkQueue qWork;
		int iWorkDone;
		bool bRunning;
		Bu::Mutex mRunning;

		class Processor : public Bu::Thread
		{
		public:
			Processor( ExplicitSimulation &rSim, FitnessFunction *pFunc,
					WorkQueue &rqWork, int iId );
			virtual ~Processor();

		protected:
			virtual void run();

			ExplicitSimulation &rSim;
			FitnessFunction *pFunc;
			WorkQueue &rqWork;
			int iId;
		};

		typedef Bu::List<Processor *> ProcessorList;
		ProcessorList lProcessor;
	};
};

#endif