1 import java
.lang
.Runtime
;
2 import java
.util
.Observable
;
3 import java
.io
.IOException
;
5 class Environment
extends Observable
{
7 public final int NumOfAnts
;
8 public final int MaxNumOfTours
;
11 public int MinTourLength
;
12 public int MinTourIteration
;
15 public static Graph graph
;
19 Environment(int MaxNumOfTours
, int GuiSize
, Graph graph
) {
20 this(MaxNumOfTours
, GuiSize
, graph
.NumOfCities
, graph
);
23 Environment(int MaxNumOfTours
, int GuiSize
, int NumOfAnts
, Graph graph
) {
25 this.MaxNumOfTours
= MaxNumOfTours
;
27 this.MinTour
= new int[graph
.NumOfCities
];
28 this.MinTourLength
= graph
.getINFINITY();
29 this.MinTourIteration
= 0;
31 this.NumOfAnts
= NumOfAnts
;
32 this.ants
= new Ant
[NumOfAnts
];
33 Environment
.graph
= graph
;
35 for (int i
= 0; i
< NumOfAnts
; i
++)
36 ants
[i
] = new Ant(graph
);
38 av
= new AntView(graph
.NumOfCities
, GuiSize
);
41 /* add a shutdown hook to print out the last best solution */
42 Runtime
.getRuntime().addShutdownHook(new EnvironmentShutdownHook(this));
44 /* run the garbage collector after all the initialization is done */
49 protected void finalize() {
55 while (! terminateCondition(i
++)) {
57 graph
.pheromoneUpdate(ants
);
60 * updatePheromoneTrails(); */
64 protected void constructSolutions() {
66 /* clear ants memory and ..
67 * assign an initial random city to ant */
68 for (Ant ant
: ants
) {
70 ant
.pickInitialRandomCity();
73 /* let each ant construct a complete tour
74 * start a 1 since every ant already has an initial city */
75 for (int step
= 1; step
< graph
.NumOfCities
; step
++) {
77 ant
.neighbourListASDecisionRule(step
);
80 /* compute tour length of each ant */
81 for (Ant ant
: ants
) {
82 ant
.computeTourLength();
87 protected void updateStatistics(int iteration
) {
88 for (Ant ant
: ants
) {
89 if (ant
.TourLength
< MinTourLength
) {
90 MinTourLength
= ant
.TourLength
;
91 MinTourIteration
= iteration
;
92 for (int i
= 0; i
< graph
.NumOfCities
; i
++) {
93 MinTour
[i
] = ant
.Tour
[i
];
96 this.notifyObservers(MinTour
);
99 /* since we are already at it.. run the garbage collector */
103 protected Boolean
terminateCondition(int iteration
) {
104 /* 1) solution within predefined distance
105 * 2) max number of tour constructions or algorithm iterations
107 * 4) algorithm stagnation behaviour */
108 if (iteration
>= MaxNumOfTours
) {
116 public String
toString() {
117 StringBuilder result
= new StringBuilder();
118 result
.append("Shortest tour at iteration " +
124 for (int t
: MinTour
) {
125 if (graph
.ids
[t
] != null)
126 result
.append(graph
.ids
[t
] + "\t");
128 result
.append(t
+ "\t");
130 if (graph
.ids
[0] != null)
131 result
.append(graph
.ids
[MinTour
[0]]);
133 result
.append(MinTour
[0]);
134 return result
.toString();