Filename: "main_code.cpp" // Author: John M. McCullock // Date: Jan, 25, 2007 // Boltzmann Machine Example: Travelling Salesman Problem // Based on C code by Karsten Kutza #include "globals.h" #include "cBoltzmann.h" void initialize(cBoltzmann &Net); bool ValidTour(cBoltzmann &Net); void showResults(cBoltzmann &Net); void Anneal(cBoltzmann &Net); int main() { //Microsoft's memory leak detection tool. _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // Number of cities, Inital temperature, Gamma value. cBoltzmann Net(8, 100, 6); srand((unsigned)time(0)); initialize(Net); Net.CalcWeights(); Net.SetRandom(); //Randomly set output nodes to either On or Off. do { Net.ReduceHeat(); showResults(Net); Net.setTemperature(Net.getTemperature() * static_cast(0.99)); }while(! ValidTour(Net)); return 0; } void initialize(cBoltzmann &Net) { float x1, x2, y1, y2; float Alpha1, Alpha2; int nCities = Net.getCities(); for(int n1 = 0; n1 < nCities; n1++) { for (int n2 = 0; n2 < nCities; n2++) { Alpha1 = ((float) n1 / nCities) * 2 * static_cast(PI); Alpha2 = ((float) n2 / nCities) * 2 * static_cast(PI); x1 = cos(Alpha1); y1 = sin(Alpha1); x2 = cos(Alpha2); y2 = sin(Alpha2); Net.setDistance(n1, n2, sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))); } // n2 } // n1 printf("Temperature Valid Length Tour\n\n"); return; } bool ValidTour(cBoltzmann &Net) { int Cities, Stops; int nCities = Net.getCities(); for(int i = 0; i < nCities; i++) { Cities = 0; Stops = 0; for(int j = 0; j < nCities; j++) { if(Net.getOutput(i * nCities + j)){ if(++Cities > 1){ return false; } } if(Net.getOutput(j * nCities + i)){ if(++Stops > 1){ return false; } } } // j if ((Cities != 1) || (Stops != 1)){ return false; } } // i return true; } void showResults(cBoltzmann &Net) { int nCities = Net.getCities(); if (ValidTour(Net)){ printf("\nTemperature Valid Length Tour\n"); printf("%11.4f\tyes\t%6.3f\t", Net.getTemperature(), Net.LengthOfTour()); }else{ printf("%11.4f\tno\t\t", Net.getTemperature()); } for(int i = 0; i < nCities; i++) { for(int j = 0; j < nCities; j++) { if(Net.getOutput(i * nCities + j)){ printf("%d", j); } } // j if(i != nCities - 1){ } } // i printf("\n"); return; }