EvolvingObjects
|
00001 00024 //----------------------------------------------------------------------------- 00025 00026 #ifndef eoSharing_h 00027 #define eoSharing_h 00028 00029 #include <eoPerf2Worth.h> 00030 #include <utils/eoDistance.h> 00031 00040 class dMatrix : public std::vector<double> 00041 { 00042 public: 00043 // Ctor : sets size 00044 dMatrix(unsigned _s) : std::vector<double>(_s*_s), rSize(_s) {} 00045 00047 double operator()(unsigned _i, unsigned _j) const 00048 { 00049 return this->operator[](_i*rSize + _j); 00050 } 00051 00053 double & operator()(unsigned _i, unsigned _j) 00054 { 00055 return this->operator[](_i*rSize + _j); 00056 } 00057 00059 void printOn(std::ostream & _os) 00060 { 00061 unsigned index=0; 00062 for (unsigned i=0; i<rSize; i++) 00063 { 00064 for (unsigned j=0; j<rSize; j++) 00065 _os << this->operator[](index++) << " " ; 00066 _os << std::endl; 00067 } 00068 _os << std::endl; 00069 } 00070 00071 private: 00072 unsigned rSize; // row size (== number of columns!) 00073 }; 00074 00075 00082 template <class EOT> 00083 class eoSharing : public eoPerf2Worth<EOT> 00084 { 00085 public: 00086 00087 using eoPerf2Worth<EOT>::value; 00088 00089 00090 /* Ctor requires a distance - cannot have a default distance! */ 00091 eoSharing(double _nicheSize, eoDistance<EOT> & _dist) : eoPerf2Worth<EOT>("Sharing"), 00092 nicheSize(_nicheSize), 00093 dist(_dist) 00094 {} 00095 00098 void operator()(const eoPop<EOT>& _pop) 00099 { 00100 unsigned i, j, 00101 pSize=_pop.size(); 00102 if (pSize <= 1) 00103 throw std::runtime_error("Apptempt to do sharing with population of size 1"); 00104 value().resize(pSize); 00105 std::vector<double> sim(pSize); // to hold the similarities 00106 dMatrix distMatrix(pSize); // to hold the distances 00107 00108 // compute the similarities (wrong name for distMatrix, I know) 00109 distMatrix(0,0)=1; 00110 for (i=1; i<pSize; i++) 00111 { 00112 distMatrix(i,i)=1; 00113 for (j=0; j<i; j++) 00114 { 00115 double d = dist(_pop[i], _pop[j]); 00116 distMatrix(i,j) = 00117 distMatrix(j,i) = ( d>nicheSize ? 0 : 1-(d/nicheSize) ); 00118 } 00119 } 00120 00121 for (i=0; i<pSize; i++) 00122 { 00123 double sum=0.0; 00124 for (j=0; j<pSize; j++) 00125 sum += distMatrix(i,j); 00126 sim[i] = sum; 00127 } 00128 00129 // now set the worthes values 00130 for (i = 0; i < _pop.size(); ++i) 00131 value()[i]=_pop[i].fitness()/sim[i]; 00132 } 00133 // private data of class eoSharing 00134 private: 00135 double nicheSize; 00136 eoDistance<EOT> & dist; // specific distance 00137 }; 00138 00139 00140 00141 #endif