• Main Page
  • Modules
  • Classes
  • Files
  • File List

D:/Projekt/ECF_trunk/examples/GATSP/TSPEvalOp.cpp

00001 #include <cmath>
00002 #include <iostream>
00003 #include <string>
00004 #include <fstream>
00005 #include <ecf/ECF.h>
00006 #include "TSPEvalOp.h"
00007 
00008 
00009 void TSPEvalOp::registerParameters(StateP state)
00010 {
00011     state->getRegistry()->registerEntry("tsp.infile", (voidP) (new std::string), ECF::STRING);
00012 }
00013 
00014 
00015 bool TSPEvalOp::initialize(StateP state)
00016 {
00017     if(!state->getRegistry()->isModified("tsp.infile")) {
00018         state->getLogger()->log(1, "Error: no input file defined for TSP! (parameter 'tsp.infile'");
00019         return false;
00020     }
00021 
00022     voidP sptr = state->getRegistry()->getEntry("tsp.infile"); // get parameter value
00023     std::string filePath = *((std::string*) sptr.get()); // convert from voidP to user defined type
00024 
00025     std::ifstream iFile(filePath.c_str());
00026     std::string line;
00027     if(!iFile.is_open()) {
00028         state->getLogger()->log(1, "Error: can't open input file " + filePath);
00029         return false;
00030     }
00031 
00032     do {
00033         getline(iFile,line);
00034     }while(line.find("DIMENSION",0) == std::string::npos);
00035 
00036     std::stringstream ss(line.substr(line.find(":") + 1));
00037     ss >> dimension;
00038 
00039     do {
00040         getline(iFile,line);
00041     }while(line.find("EDGE_WEIGHT_SECTION",0) == std::string::npos);
00042 
00043     weights.resize(dimension);
00044     for(int i = 0; i < dimension; i++) {
00045         weights[i].resize(dimension);
00046         for(int j = 0; j < dimension; j++) {
00047                 iFile >> weights[i][j];
00048         }
00049     }
00050     return true;
00051 }
00052 
00053 
00054 FitnessP TSPEvalOp::evaluate(IndividualP individual)
00055 {
00056     // minimize travel distance, so use FitnessMin
00057     FitnessP fitness (new FitnessMin);
00058 
00059     // get Permutation genotype from the individual
00060     Permutation::Permutation* perm = (Permutation::Permutation*) individual->getGenotype().get();
00061     // (you can also use boost smart pointers:)
00062     //PermutationP perm = boost::static_pointer_cast<Permutation::Permutation> (individual->getGenotype());
00063 
00064     int fitnessV = 0;
00065     // genotype Permutation keeps a vector of indexes named 'variables'
00066     for(uint i = 0; i < perm->variables.size() - 1; i++){
00067         // the length of each route is the sum of distances (weights) between each city in a route
00068         fitnessV += weights[perm->variables[i]][perm->variables[i + 1]];
00069     }
00070     fitnessV += weights[perm->variables[0]][perm->variables[dimension - 1]];
00071     
00072 
00073     fitness->setValue(fitnessV);
00074     return fitness;
00075 }

Generated on Thu Oct 6 2011 13:41:02 for ECF by  doxygen 1.7.1