-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSightseeingProblemDomain.java
More file actions
575 lines (487 loc) · 18.5 KB
/
Copy pathSightseeingProblemDomain.java
File metadata and controls
575 lines (487 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package com.aim.project.ssp;
import com.aim.project.ssp.heuristics.crossover.OX;
import com.aim.project.ssp.heuristics.crossover.PMX;
import com.aim.project.ssp.heuristics.localsearch.DavissHillClimbing;
import com.aim.project.ssp.heuristics.localsearch.NextDescent;
import com.aim.project.ssp.heuristics.localsearch.TwoOptSwap;
import com.aim.project.ssp.heuristics.mutation.AdjacentSwap;
import com.aim.project.ssp.heuristics.mutation.InversionMutation;
import com.aim.project.ssp.heuristics.mutation.Reinsertion;
import com.aim.project.ssp.instance.InitialisationMode;
import com.aim.project.ssp.instance.Location;
import com.aim.project.ssp.instance.reader.SSPInstanceReader;
import com.aim.project.ssp.interfaces.*;
import AbstractClasses.ProblemDomain;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents the Sightseeing Problem Domain.
* It handles the application of various heuristics and manages solutions.
* It implements methods from the ProblemDomain and Visualisable interfaces.
*
* @author : Sushant Nepal
* @since : 17/03/2025
*/
public class SightseeingProblemDomain extends ProblemDomain implements Visualisable, InLabPracticalExamInterface {
/** Instance representing the problem domain */
public SSPInstanceInterface m_oInstance;
/** Array of heuristics used for generating solutions */
private final HeuristicInterface[] heuristics;
/** Array of solutions */
public SSPSolutionInterface[] solutions;
/**
* Constructor initializes the heuristics and memory size for storing solutions.
*
* @param seed Random number generator seed
*/
public SightseeingProblemDomain(long seed) {
super(seed);
// Initialize heuristics array
heuristics = new HeuristicInterface[]{
new AdjacentSwap(rng),
new DavissHillClimbing(rng),
new NextDescent(rng),
new OX(rng),
new Reinsertion(rng),
new InversionMutation(rng),
new TwoOptSwap(rng),
new PMX(rng)
};
// Set memory size for storing solutions - Current (Best), Candidate, Crossover (for Crossover heuristics)
setMemorySize(3);
}
/**
* Applies a heuristic to a single solution and stores the result.
*
* @param hIndex Index of the heuristic to apply
* @param currentIndex Index of the current solution
* @param candidateIndex Index where the resulting solution will be stored
* @return The objective function value of the resulting solution
*/
@Override
public double applyHeuristic(int hIndex, int currentIndex, int candidateIndex) {
// Get the heuristic to apply using the heuristic ID
HeuristicInterface heuristic = heuristics[hIndex];
// Get the source solutions
SSPSolutionInterface sourceSolution = solutions[currentIndex].clone();
// To store the objective value
double objectiveValue = sourceSolution.getObjectiveFunctionValue();
//System.out.println(sourceSolution.getSolutionRepresentation());
// Only if the heuristic isn't of Crossover type
if (!(heuristic instanceof OX)) {
// Apply the heuristic to the source solution and store the result in the destination solution
objectiveValue = heuristic.apply(sourceSolution, depthOfSearch, intensityOfMutation);
}
// Deep copy of the source solution to avoid reference issues
SSPSolutionInterface candidateSolution = sourceSolution.clone();
// Store the modified source solution in the memory array at the destination index
solutions[candidateIndex] = candidateSolution;
// Return the objective function value of the resulting solution
return objectiveValue;
}
/**
* Applies a heuristic involving two parent solutions and stores the result.
* This method allows for crossover heuristics to be used alongside the regular heuristic
*
* @param hIndex Index of the heuristic to apply
* @param parent1Index Index of the first parent solution
* @param parent2Index Index of the second parent solution
* @param candidateIndex Index where the resulting solution will be stored
* @return The objective function value of the resulting solution
*/
@Override
public double applyHeuristic(int hIndex, int parent1Index, int parent2Index, int candidateIndex) {
// Get the heuristic to apply using the heuristic ID
HeuristicInterface heuristic = heuristics[hIndex];
// Get the parent solutions from the solution array
SSPSolutionInterface parent1 = solutions[parent1Index].clone();
SSPSolutionInterface parent2 = solutions[parent2Index].clone();
// Get the candidate solution object
SSPSolutionInterface candidateSolution = solutions[candidateIndex].clone();
// Check if the heuristic is a Order Crossover type
if (heuristic instanceof OX oxHeuristic) {
// Apply OX with parent1 and parent2 to generate a child solution
double objectiveValue = oxHeuristic.apply(parent1, parent2, candidateSolution, depthOfSearch, intensityOfMutation);
// Store the resulting candidate solution at the candidate index
solutions[candidateIndex] = candidateSolution;
// Return the objective function value of the resulting solution
return objectiveValue;
}
// Check if the heuristic is an instance of PMX
else if (heuristic instanceof PMX pmxHeuristic) {
// Apply PMX with parent1 and parent2 to generate a child solution
double objectiveValue = pmxHeuristic.apply(parent1, parent2, candidateSolution, depthOfSearch, intensityOfMutation);
// Store the resulting candidate solution at the candidate index
solutions[candidateIndex] = candidateSolution;
// Return the objective function value of the resulting solution
return objectiveValue;
} else {
// If the heuristic is not OX
return applyHeuristic(hIndex, parent1Index, candidateIndex);
}
}
/**
* Converts the best solution into a string representation.
*
* @return String representation of the best solution
*/
@Override
public String bestSolutionToString() {
return solutions[0].getSolutionRepresentation().toString();
}
/**
* Compares two solutions based on their representations.
*
* @param iIndex1 Index of the first solution
* @param iIndex2 Index of the second solution
* @return true if the solutions are identical, false otherwise
*/
@Override
public boolean compareSolutions(int iIndex1, int iIndex2) {
// Get the solutions at the specified indices
SSPSolutionInterface solution1 = solutions[iIndex1];
SSPSolutionInterface solution2 = solutions[iIndex2];
// Get the solution representations (assuming it returns an array or similar structure)
int[] solutionRep1 = solution1.getSolutionRepresentation().getSolutionRepresentation();
int[] solutionRep2 = solution2.getSolutionRepresentation().getSolutionRepresentation();
// Compare the two solution representations
if (solutionRep1.length != solutionRep2.length) {
return false; // If lengths differ, solutions are not identical
}
// Compare element by element
for (int i = 0; i < solutionRep1.length; i++) {
if (solutionRep1[i] != solutionRep2[i]) {
return false; // If any element is different, solutions are not identical
}
}
// If no differences were found, the solutions are identical
return true;
}
/**
* Copies a solution from one index to another.
*
* @param a Index of the source solution
* @param b Index of the destination solution
*/
@Override
public void copySolution(int a, int b) {
// Get the solution to copy from the source index
SSPSolutionInterface sourceSolution = solutions[a];
// Create a new instance of the solution, ensuring it's a copy
SSPSolutionInterface destinationSolution = sourceSolution.clone();
// Assign the copied solution to the destination index
solutions[b] = destinationSolution;
}
/**
* Retrieves the objective function value of the best solution.
*
* @return Objective function value of the best solution
*/
@Override
public double getBestSolutionValue() {
return solutions[0].getObjectiveFunctionValue();
}
/**
* Retrieves the objective function value of a specific solution.
*
* @param index Index of the solution
* @return Objective function value of the solution
*/
@Override
public double getFunctionValue(int index) {
return solutions[index].getObjectiveFunctionValue();
}
/**
* Retrieves all heuristics of a specified type.
*
* @param type The type of heuristics to retrieve
* @return An array of heuristic IDs that match the specified type
*/
@Override
public int[] getHeuristicsOfType(HeuristicType type) {
// List to store heuristic IDs that match the type
List<Integer> matchingHeuristics = new ArrayList<>();
// Loop through all heuristics and check their type
for (int i = 0; i < heuristics.length; i++) {
HeuristicInterface heuristic = heuristics[i];
// Check if the heuristic type matches the specified type
if (heuristic.getType() == type) {
matchingHeuristics.add(i); // Add the heuristic ID (index) to the list
}
}
// If no matching heuristics were found, return null
if (matchingHeuristics.isEmpty()) {
return null;
}
// Convert the list of matching heuristic IDs to an array and return
int[] result = new int[matchingHeuristics.size()];
for (int i = 0; i < matchingHeuristics.size(); i++) {
result[i] = matchingHeuristics.get(i);
}
return result;
}
/**
* Retrieves all heuristics that use the depth of search parameter.
*
* @return An array of heuristic IDs that use depth of search
*/
@Override
public int[] getHeuristicsThatUseDepthOfSearch() {
// List to store heuristic IDs that match the type
List<Integer> matchingHeuristics = new ArrayList<>();
// Loop through all heuristics and check their type
for (int i = 0; i < heuristics.length; i++) {
HeuristicInterface heuristic = heuristics[i];
// Check if the heuristic uses dos
if (heuristic.usesDepthOfSearch()) {
matchingHeuristics.add(i); // Add the heuristic ID (index) to the list
}
}
// If no matching heuristics were found, return null
if (matchingHeuristics.isEmpty()) {
return null;
}
// Convert the list of matching heuristic IDs to an array and return
int[] result = new int[matchingHeuristics.size()];
for (int i = 0; i < matchingHeuristics.size(); i++) {
result[i] = matchingHeuristics.get(i);
}
return result;
}
/**
* Retrieves all heuristics that use the intensity of mutation parameter.
*
* @return An array of heuristic IDs that use intensity of mutation
*/
@Override
public int[] getHeuristicsThatUseIntensityOfMutation() {
// List to store heuristic IDs that match the type
List<Integer> matchingHeuristics = new ArrayList<>();
// Loop through all heuristics and check their type
for (int i = 0; i < heuristics.length; i++) {
HeuristicInterface heuristic = heuristics[i];
// Check if the heuristic uses iom
if (heuristic.usesIntensityOfMutation()) {
matchingHeuristics.add(i); // Add the heuristic ID (index) to the list
}
}
// If no matching heuristics were found, return null
if (matchingHeuristics.isEmpty()) {
return null;
}
// Convert the list of matching heuristic IDs to an array and return
int[] result = new int[matchingHeuristics.size()];
for (int i = 0; i < matchingHeuristics.size(); i++) {
result[i] = matchingHeuristics.get(i);
}
return result;
}
/**
* Retrieves the total number of heuristics available in the problem domain.
*
* @return The number of heuristics
*/
@Override
public int getNumberOfHeuristics() {
return 8;
}
/**
* Retrieves the number of instances available in the problem domain.
*
* @return The number of instances
*/
@Override
public int getNumberOfInstances() {
return 7;
}
/**
* Initializes a solution at a specified index.
*
* @param index The index of the solution to initialize
* @throws IllegalArgumentException if the index is out of bounds
*/
@Override
public void initialiseSolution(int index) {
// Bound Checking
if (index < 0 || index >= solutions.length) {
throw new IllegalArgumentException("Index out of bounds");
}
// Creating new Solution - Initialising Randomly
SSPSolutionInterface newSolution = m_oInstance.createSolution(InitialisationMode.RANDOM);
// Adding Solution to Solutions array
solutions[index] = newSolution;
}
/**
* Loads an instance by its ID and sets up the problem domain accordingly.
*
* @param instanceId The ID of the instance to load
* @throws IllegalArgumentException if the instanceId is invalid
*/
@Override
public void loadInstance(int instanceId) {
// Mapping instanceId to filenames
Path instancePath = getPath(instanceId);
// Creating an instance reader
SSPInstanceReader reader = new SSPInstanceReader();
// Reading the instance and creating it
m_oInstance = reader.readSSPInstance(instancePath, this.rng);
// Creating the objective function using the instance
SSPObjectiveFunction objectiveFunction = new SSPObjectiveFunction(m_oInstance);
// Setting the objective function value for each heuristic
for (HeuristicInterface heuristic : heuristics) {
heuristic.setObjectiveFunction(objectiveFunction);
}
// Initialising solutions
initialiseSolution(0);
initialiseSolution(1); // For crossover
initialiseSolution(2);
}
/**
* Returns the file path for the given instance ID.
*
* @param instanceId The ID of the instance
* @return The path to the instance file
* @throws IllegalArgumentException if the instanceId is invalid
*/
private static Path getPath(int instanceId) {
return switch (instanceId) {
case 0 -> Path.of("instances/ssp/carparks-40.ssp");
case 1 -> Path.of("instances/ssp/chatgpt-instance-100.ssp");
case 2 -> Path.of("instances/ssp/clustered.ssp");
case 3 -> Path.of("instances/ssp/grid.ssp");
case 4 -> Path.of("instances/ssp/libraries-15.ssp");
case 5 -> Path.of("instances/ssp/square.ssp");
case 6 -> Path.of("instances/ssp/tramstops-85.ssp");
default -> throw new IllegalArgumentException("Invalid instance ID");
};
}
/**
* Sets the memory size for storing SSP solutions.
*
* @param size the number of solution slots to allocate
*/
@Override
public void setMemorySize(int size) {
solutions = new SSPSolutionInterface[size];
}
/**
* Converts a solution at a specific index to its string representation.
*
* @param index the index of the solution in memory
* @return string representation of the solution
*/
@Override
public String solutionToString(int index) {
return solutions[index].toString();
}
/**
* Returns the name of the problem domain.
*
* @return a string representing the domain name
*/
@Override
public String toString() {
return "psysn2 SSP Domain";
}
/**
* Returns the currently loaded SSP instance.
*
* @return the loaded instance of the problem
*/
@Override
public SSPInstanceInterface getLoadedInstance() {
return m_oInstance;
}
/**
* Retrieves the best solution route as an array of ordered {@link Location} objects,
* starting from the hotel, followed by the sightseeing locations (in the order
* determined by the solution), and ending at the airport.
*
* @return an array of Locations in the order they are visited
*/
@Override
public Location[] getRouteOrderedByLocations() {
// Gets the solution representation
int[] solutionRepresentation = solutions[0].getSolutionRepresentation().getSolutionRepresentation();
// Create an array to store the ordered route
Location[] orderedRoute = new Location[solutionRepresentation.length];
// Set the first location as the hotel
orderedRoute[0] = m_oInstance.getHotelLocation();
int i = 1;
// Add all sightseeing locations in the order given by the solution
for (Location location : m_oInstance.getSolutionAsListOfLocations(solutions[0])) {
orderedRoute[i] = location;
i++;
}
// Set the last location as the airport
orderedRoute[orderedRoute.length - 1] = m_oInstance.getAirportLocation();
return orderedRoute;
}
/**
* Prints the best solution found so far in the following format:
* (h_x,h_y) - (l_x0,l_y0) - ... - (l_x{n-1},l_y{n-1}) - (a_x,a_y)
* Where:
* <ul>
* <li><code>h</code> is the hotel location</li>
* <li><code>a</code> is the airport location</li>
* <li><code>l_xi</code> and <code>l_yi</code> are coordinates of sightseeing locations</li>
* </ul>
*/
@Override
public void printBestSolutionFound() {
StringBuilder sb = new StringBuilder();
// Start with hotel
Location hotel = m_oInstance.getHotelLocation();
sb.append("(").append(hotel.getX()).append(",").append(hotel.getY()).append(")");
// Add sightseeing locations
int[] initialSolutionRepresentation = solutions[0].getSolutionRepresentation().getSolutionRepresentation();
for (int index : initialSolutionRepresentation) {
Location loc = m_oInstance.getSightseeingLocation(index);
sb.append(" - (").append(loc.getX()).append(",").append(loc.getY()).append(")");
}
// End with airport
Location airport = m_oInstance.getAirportLocation();
sb.append(" - (").append(airport.getX()).append(",").append(airport.getY()).append(")");
System.out.println("Best Solution:");
System.out.println(sb);
}
/**
* Prints the objective function value of the best solution found.
*/
@Override
public void printObjectiveValueOfTheSolutionFound() {
System.out.println("Best Value: " + solutions[0].getObjectiveFunctionValue());
}
/**
* Prints the initial solution in the same format as the best solution:
* (h_x,h_y) - (l_x0,l_y0) - ... - (l_x{n-1},l_y{n-1}) - (a_x,a_y)
* Useful for comparing how far the optimisation has improved from the starting point.
*/
@Override
public void printInitialSolution() {
StringBuilder sb = new StringBuilder();
// Start with hotel
Location hotel = m_oInstance.getHotelLocation();
sb.append("(").append(hotel.getX()).append(",").append(hotel.getY()).append(")");
// Add sightseeing locations
int[] initialSolutionRepresentation = solutions[0].getSolutionRepresentation().getSolutionRepresentation();
for (int index : initialSolutionRepresentation) {
Location loc = m_oInstance.getSightseeingLocation(index);
sb.append(" - (").append(loc.getX()).append(",").append(loc.getY()).append(")");
}
// End with airport
Location airport = m_oInstance.getAirportLocation();
sb.append(" - (").append(airport.getX()).append(",").append(airport.getY()).append(")");
System.out.println("Initial Solution:");
System.out.println(sb);
}
/**
* Prints the objective value of the initial solution.
* This can be compared with the value of the best solution to measure improvement.
*/
@Override
public void printObjectiveValueOfTheInitialSolution() {
System.out.println("Initial Value: " + solutions[0].getObjectiveFunctionValue());
}
}