Click here to Skip to main content
Click here to Skip to main content

Genetic Algorithms and the Traveling Salesman Problem using C# and ATL COM

By , 24 Nov 2002
 

Sample Image

Introduction

This project is about an application used by the Traveling Salesman, given a finite number of 'cities'(I have choosen cities from 1 to a finite number) along with the distance of travel (distance between two cities is randomly choosen) between each pair of them, The aim is to find the cheapest distance of visiting all the cities and returning to the starting point. Using GA we can get an optimal solution to solve this problem.

This is only an example to look at calling COM Components and accessing SAFEARRAY in C#. I don't know many things about genetic algorithm and please don't take take this code as demonstrating a problem to solve using only genetic algorithms (GA). This is just one approach. The C++ code for GA I got from the Internet.

Background (optional)

Disclaimer: I am not a GA and C# expert. I have reused C++ code to make it into a COM component and my goal was to show some visualisation effects using new kid on the block C#. It's only an example of GA coding.Any comments and criticism you have are most welcome.

Using the code

The main TSP component is written using COM via ATL, and the client application using C#. The TSP GA application will provide the following operations:

  • Set number of cities.
  • Set Population size for each generation.
  • Set Generation Size.
  • Set Cross Over Percentage.
  • Set Mutation rate.
  • Start TSPGA Algorithm.
  • Gets best Distance for each generation.
  • Gets overall best distance for all generations.
  • Gets overall best path traversed.
  • Gets Worst distance.

Design

COM Server

Find below the IDL file for details of methods exposed from interface:

interface ITSPGAAlgorithm : IDispatch
{
   [propput, id(1), helpstring("property SetPopulationSize")] 
                    HRESULT SetPopulationSize([in] short newVal);
   [propput, id(2), helpstring("property GetPopulationSize")] 
                    HRESULT GetPopulationSize([in] short* newVal);
   [propget, id(3), helpstring("property GenerationSize")] 
                    HRESULT GenerationSize([out, retval] short *pVal);
   [propput, id(3), helpstring("property GenerationSize")] 
                    HRESULT GenerationSize([in] short newVal);
   [propget, id(4), helpstring("property Mutate")]
                    HRESULT Mutate([out, retval] double *pVal);
   [propput, id(4), helpstring("property Mutate")]
                    HRESULT Mutate([in] double newVal);
   [propget, id(5), helpstring("property CitySize")]
                    HRESULT CitySize([out, retval] short *pVal);
   [propput, id(5), helpstring("property CitySize")]
                    HRESULT CitySize([in] short newVal);
   [id(6), helpstring("method SetCrossOverRate")] 
                    HRESULT SetCrossOverRate([in] short nCrossOverPercentage);
   [id(7), helpstring("method StartGAForTSP")]
                    HRESULT StartGAForTSP();
   [id(8), helpstring("method GetAllBestDistancesByGenerations")] 
                    HRESULT GetAllBestDistancesByGenerations([out,retval] 
                                                             VARIANT*pAllDistances);
   [id(9), helpstring("method GetBestPathForTSP")] 
                    HRESULT GetBestPathForTSP([out, retval] VARIANT* pPath);
   [propget, id(10), helpstring("property BestOverAll")] 
                    HRESULT BestOverAll([out, retval] short *pVal);
   [propget, id(11), helpstring("property WorstOverAll")] 
                    HRESULT WorstOverAll([out, retval] short *pVal);
};

Starting TSPGA

This is the main piece of code responsible for evolving generations, reproducing solution, mutations etc.

STDMETHODIMP CTSPGAAlgorithm::StartGAForTSP()
{
   // TODO: Add your implementation code here
   pGen = new ga(POP_SIZE,GEN_STOP,PROB_MUT,PROB_CROSS,CITY_COUNT);
   pGen->evolve();

   return S_OK;
}

Returning Distances to client

Use SAFEARRAY to fill the array of distances as a VARIANT pointer as below.

STDMETHODIMP CTSPGAAlgorithm::GetAllBestDistancesByGenerations(VARIANT *pAllDistances)
{
          // TODO: Add your implementation code here
          VariantInit(pAllDistances);
          pAllDistances->vt = VT_ARRAY | VT_I2 ;
          SAFEARRAY * psa;
          SAFEARRAYBOUND bounds = {GEN_STOP,0};
          psa = SafeArrayCreate(VT_I2,1,&bounds);
          int * pDist = NULL;
          pGen->GetDistanceByGen(&pDist);
          short *pDest = (short*)CoTaskMemAlloc(sizeof(short) * GEN_STOP);
          SafeArrayAccessData(psa,reinterpret_cast<void **>(&pDest));
          for(int i = 0 ; i < GEN_STOP ; i++)
                   pDest[i] = pDist[i];
          SafeArrayUnaccessData(psa);
          pAllDistances->parray = psa;

          return S_OK;
}

C# Client

I’m a not an expert in C# programming. It took quite a bit of time to put in all my browsing experience to find one really good article for XY Plot graph, so here is the link http://www.c-sharpcorner.com/Code/2002/Aug/XYPlotControl.asp. This is a nice user control to use in C# which adds nice visual effects to the travelling salesman problem.

Register TSPGAATL.dll using regsvr32

To access this component from C#, from the VisualStudio.NET IDE click on the 'Project' menu. Click 'Add Refernces', and a tabbed dialog should appear. Select the 'COM' tab and browse for 'TSPGAATL.dll', and add it. Now C# knows everything about our COM component.

Find below my code for accessing the COM component from C# and accessing the SAFEARRAY from a method.

// Create the COM component
TSPGAATLLib.ITSPGAAlgorithm comTSPGA = new TSPGAATLLib.TSPGAAlgorithmClass();

// Set All the properties 
comTSPGA.CitySize = System.Convert.ToInt16(this.textBox1.Text);
comTSPGA.SetPopulationSize = System.Convert.ToInt16(this.textBox2.Text);
comTSPGA.GenerationSize = System.Convert.ToInt16(this.textBox3.Text);
comTSPGA.SetCrossOverRate(System.Convert.ToInt16(this.textBox4.Text));
comTSPGA.Mutate = System.Convert.ToDouble(this.textBox5.Text);

// Start the GA TSP Engine 
comTSPGA.StartGAForTSP();

//Reset the User Control Graph 
xyGraphControl1.Reset();
xyGraphControl1.XTickValue = 20;
xyGraphControl1.YTickValue = 20;
xyGraphControl1.XOrigin = 1;
xyGraphControl1.YOrigin = 100;
xyGraphControl1.LabelX = "Generation";
xyGraphControl1.LabelY = "Distance";
 
//TSP gets diifferent best routes he can traverse
//C# handles Variant wrapped safearrays the following way...
//We fill Array with all Generations(say 1000)
//Make sure we convert to respective datatypes(C# complier returns good build errors)

System.Array distAll =(System.Array)comTSPGA.GetAllBestDistancesByGenerations();
for(int i = 0;i < distAll.Length;i++ )  
{
   //Write it to a file..
   distFile += distAll.GetValue(i) + "\n";                   
   //Display the Graph here by extracting the value stored in System.Array variable
   //Add the Distance points for each generation
   xyGraphControl1.AddPoint(System.Convert.ToInt64(i), 
                            System.Convert.ToInt64(distAll.GetValue(i)));            
}
FileStream fs = new FileStream(@"c:\dist.txt" , FileMode.OpenOrCreate, FileAccess.Write); 
StreamWriter m_streamWriter = new StreamWriter(fs); 
// Write to the file using StreamWriter class 
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : "); 
m_streamWriter.Write(distFile);
m_streamWriter.Flush();

//Now help out TS(Travelling SalesMan)and give him this best route.
String outPut = "";
System.Array bestRoute =(System.Array) comTSPGA.GetBestPathForTSP();
for(int i = 0;i < bestRoute.Length;i++ )
{
  outPut += bestRoute.GetValue(i) + "-->";    
}
//Display it in Text Box
this.textBox6.Text = outPut + bestRoute.GetValue(0);
//the best overall ranking distance
this.label9.Text = System.Convert.ToString(comTSPGA.BestOverAll);
//the worst overall ranking system

this.label11.Text = System.Convert.ToString(comTSPGA.WorstOverAll);
xyGraphControl1.Invalidate();

Points of Interest

Accessing SAFEARRAY from C# took some time for me but the way C# handling any kind of datatype is excellent. Initially I was resisting my self to move to C# from my good old Win32, MFC and ATL controls.

C# is a good language to consider.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Kalyan S Dontharaju
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralNeed Source Code for timetable problem using genetic Algorithmmemberumar ahmad28 Mar '10 - 21:15 
Please Can any one provide me the source code of Time table scheduling problem in C# or C++
QuestionHow can i implement GA for Lab Time Table generatormemberEiRy12 Oct '09 - 5:20 
I'm stuck on how to represent the data in code to do the genetic algorithm. I mean how to represent the data (teacher, class etc) in code (11011 etc). Then how genetic algorithm work with the represented data? Confused | :confused: Can you anyone help me..
Generalgenetic algorithm for sotware testingmemberavkshanthi4 Jun '08 - 17:50 
hello,
 
i want to develop program for "genetic algorithm for software testing"
can u help me. i will pay many for this
 
avk
Questionfacility layout problem solved by GAmembertak seong5 Sep '07 - 18:27 
does anyone know how to use GA to solve FLP??
can let me know where can i find more about it??
i need the source code to solve FLP
AnswerRe: facility layout problem solved by GAmemberGAbirkan29 Sep '07 - 0:44 
go fo google scholar; u r gonna find plenty of design articles; if can't reach to certain articles, let me know..
QuestionGAmemberssann7 Feb '07 - 2:23 
hi,
i am interesting in develop an scheduling school timetable system. can u help me in that using the genetic algorithm. i m developing it in vb.net. ths.
QuestionHow can i implement GA for School Time Table Managementmemberasmysee1 May '06 - 19:11 
hello,
 
thanks for your artical, i am working on School TimeTable Management. I have to implement that using Genetic Algorithm, i have done it. But i am unable to add more constrants when ever we required. And i feel it is a little bit slow. Could u help me on this, i am developing this in C# 2005.
AnswerRe: How can i implement GA for School Time Table Managementmembersuryavas23 Oct '06 - 20:09 
Smile | :) Hi,
 
I am interested in develope School Time table. pls tell that procedures to develope in genetic algorithm
 

AnswerRe: How can i implement GA for School Time Table Managementmemberyashucharabuddi6 Mar '07 - 3:53 
Hi..I am developing a timetable generating system..Can u please send me the code at yashu.rani@gmail.com
AnswerRe: How can i implement GA for School Time Table ManagementmemberbirkanGA8 Aug '07 - 4:05 
This response might be a bit late, but I have come across many applications of Tabu Search algorithm performing quite fast and efficient with time tabling. Genetic algorithms, mainly evolutionary algorithms, are rather slow but they perform much better when in space is larger. Moreover, you might like to have multiple objectives while working with GA that they can handle easly.
 
By the way I like this graphical representation. Good job!
AnswerRe: How can i implement GA for School Time Table Managementmemberbrar322 Dec '09 - 13:24 
can anbody plz send me the code for timetaling problem. i m in deep trouble. plz someone help me out. i can pay for the code. I got resubmission in my dissertation and if i didnt pass this time i will fail Msc. plz help me
 
amardeep
Generaltsp and vehicle routing problemmembershahida@kevin17 Jan '06 - 16:22 
hello sir..
i'm a student and have some problem in here..
i wanna to develop a simple vehicle routing problem using C#.Net..
my problem is like this:
eg:
 
from:[comboBox1]--> list name of places (read from database)
 
to:[comboBox2]-->list name of places(read from database)
 
listbox1-->contains items that chosed from combobox2(means more than one choices)
 
let say from-->A
to: B,C,D,E(all this items is add in listbox)
then we want the system to detect which is the nearest wheither from A-B or A-C or A-D or A-E(detect by it's distance which we read from databases)....
then give the first result,let say C is the nearest node to A,so choose C
next the system will detect from C to B,D and E....
this go on the same way as above until all the node has been arrange...
 
sir,do u have any idea about this problem and can u help me???
 
thousands of thanks....

 
kevin
Generalproblem when building the projectmemberdaftarfree26 Jan '05 - 19:28 
Hi all,
I downloaded the projects, and try to run it.
 
However, I can't build the library with the following error..
Creating library ReleaseUMinDependency/TSPGAATL.lib and object ReleaseUMinDependency/TSPGAATL.exp
LIBCMT.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
ReleaseUMinDependency/TSPGAATL.dll : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
 
I try to run the demo project as well, however, I got the error
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in GraphicsControlTest.exe
Additional information: The specified module could not be found.
 
Anyone can help?
 
Thanks in advance,
Generalsource code neededmemberManyproblem13 Jan '05 - 23:21 
Hi,
 
I hope to use this Travelling salesman problem to differentiate the performance between 3 EAs algorithm ( Genetic Algorithm, Evolutionary Strategies, and Evolutionary Programming )
 
Do anyone have the source code related to this problem?
or
Do you have any suggestion on how to solve this. I'm willing to pay if someone can help me to solve this.
 
Thanks.
GeneralObjective Function and constraintsmemberRamya Narayanaswamy22 Apr '04 - 8:49 
Hello All,
I am trying to write a genetic algorithm for the generalised assignement problem. I have a genetic algorithm code running for the multi dimensional kanpsack problem. I need to change the objective function and the constraints and i am not able to figure in which header or source file i need to change the objective function and the constraints. I am using the source code from the GALibrary. Some one kindly help me out.
Thanks
 
Ramya Narayanaswamy
GeneralGreat Ideamemberantoine@orchus-tech14 Mar '04 - 7:33 
Hi
 
This is a great idea. COngratulations on offering our community something else than round buttons heheheee
But, personnally, I'm not verse in COM, so to have an article that explains in finer details the workings of
your code would be very nice Smile | :)
 
Thanks!
 
Antoine
 
This by our hands that dream,
"I shall find a way or make one!"
GeneralRe: Great IdeamemberKalyan S Dontharaju18 Mar '04 - 9:31 
Thanx..GeneticAlgorithm (GA) is a huge topic and mainly used to solve or attempt to solve combinatorial problems (where they are easy to state but many of them are very difficult to solve..one such example is Travelling Salesmen problem) and as a beginner i suggest to get know all the terms and practical applications where GA is used..I used to have some good links to GA resources....I'll have to find them ..If you want detail COM descriptions..i tried interface functions names defined in IDL to be more friedly....may be i attempted to be atleast..Smile | :)
 
Kalyan
GeneralRe: Great Ideamembersuryavas23 Oct '06 - 20:24 
pls Cry | :(( sent me that GE resoure links
 
h

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 25 Nov 2002
Article Copyright 2002 by Kalyan S Dontharaju
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid