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");
00023 std::string filePath = *((std::string*) sptr.get());
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
00057 FitnessP fitness (new FitnessMin);
00058
00059
00060 Permutation::Permutation* perm = (Permutation::Permutation*) individual->getGenotype().get();
00061
00062
00063
00064 int fitnessV = 0;
00065
00066 for(uint i = 0; i < perm->variables.size() - 1; i++){
00067
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 }