-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
203 lines (177 loc) · 8.4 KB
/
Copy pathMain.java
File metadata and controls
203 lines (177 loc) · 8.4 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
import IA.Gasolina.GasolinaBoard;
import IA.Gasolina.GasolinaGoalTest;
import IA.Gasolina.GasolinaHeuristicFunction;
import IA.Gasolina.GasolinaSuccessorFunction;
import IA.Gasolina.CentrosDistribucion;
import IA.Gasolina.Gasolineras;
import IA.Gasolina.GasolinaSuccessorFunctionSA;
import aima.search.framework.GraphSearch;
import aima.search.framework.Problem;
import aima.search.framework.Search;
import aima.search.framework.SearchAgent;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.ArrayList;
import java.util.Random;
import aima.search.informed.SimulatedAnnealingSearch;
import aima.search.informed.HillClimbingSearch;
public class Main {
public static void main(String[] args) throws Exception{
// verificar arguments
if (args.length != 4 && args.length != 5) {
System.out.println("Error: es requereixen 4 o 5 arguments.");
System.out.println("Exemple d'ús: java -cp .:AIMA.jar:Gasolina.jar Main {inicialitzacio} {algorisme} {num_execucions} {limit} [seed]");
System.out.println("inicialitzacio: 0=random, 1=greedy1, 2=greedy2, 3=buida");
System.out.println("algorisme: 0=hill climbing, 1=simulated annealing");
System.out.println("limit: límit d'iteracions per a la funció successora (-1 per a sense límit)");
return;
}
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int NUMERO_EJECUCIONES = Integer.parseInt(args[2]);
int limit = Integer.parseInt(args[3]); // ahora es obligatorio
Integer seedFija = null;
if (args.length == 5) {
seedFija = Integer.parseInt(args[4]);
}
// inicialitzar el problema
int ngas = 100;
int ncen = 10, mult = 1;
//System.out.println("Camions: " + board.getNCamions() + ", Gasolineres: " + board.getNGasolineras());
//System.out.println("Executant " + NUMERO_EJECUCIONES + " vegades per trobar el millor resultat...\n");
String inicialitzacio;
if (a == 0) {
inicialitzacio = "random";
}
else if (a == 1) {
inicialitzacio = "greedy1";
}
else if (a == 2){
inicialitzacio = "greedy2";
}
else {
inicialitzacio = "buida";
}
// Variables para almacenar el mejor resultado
GasolinaBoard mejorResultado = null;
double mejorBeneficio = Double.NEGATIVE_INFINITY;
int mejorEjecucion = -1;
List<Object> mejoresAcciones = null;
Properties mejorInstrumentacion = null;
// Ejecutar el algoritmo múltiples veces
for (int ejecucion = 1; ejecucion <= NUMERO_EJECUCIONES; ejecucion++) {
int seed1, seed2;
if (seedFija != null) {
// Usar la seed fija para todas las iteraciones
seed1 = seedFija;
seed2 = seedFija;
} else {
// Generar seeds aleatorias para cada iteración
Random myRandom = new Random();
seed1 = myRandom.nextInt(1234);
seed2 = myRandom.nextInt(1234);
}
//GasolinaBoard board = new GasolinaBoard(new CentrosDistribucion(ncen, mult, 1234), new Gasolineras(ngas, 1234));
GasolinaBoard board = new GasolinaBoard(new CentrosDistribucion(ncen, mult, seed1), new Gasolineras(ngas, seed2));
System.out.println("=== Execució " + ejecucion + " ===");
// Generar estado inicial para esta ejecución
GasolinaBoard initial;
if (a == 0) { // generar estat inicial aleatori
initial = board.solIniRandom();
}
else if (a == 1) { // generar estat inicial greedy 1
initial = board.solIniGreedy();
}
else if (a == 2){ // greedy 2
initial = board.solIniGreedy2();
}
else { // sol ini "buida"
initial = board;
}
GasolinaBoard resultado = null;
List<Object> acciones = null;
Properties instrumentacion = null;
long startTime = System.nanoTime();
if (b == 0) { // hill climbing
Problem p = new Problem(initial,
new GasolinaSuccessorFunction(limit),
new GasolinaGoalTest(),
new GasolinaHeuristicFunction());
HillClimbingSearch alg = new HillClimbingSearch();
SearchAgent agent = new SearchAgent(p, alg);
resultado = (GasolinaBoard) alg.getGoalState();
acciones = agent.getActions();
instrumentacion = agent.getInstrumentation();
}
else { // simulated annealing
Problem p = new Problem(initial,
new GasolinaSuccessorFunctionSA(),
new GasolinaGoalTest(),
new GasolinaHeuristicFunction());
// SA: param: nº max d'iteracions, temp ini, k, lambda
int maxIt = 100000;
int tempIni = 1000;
int k = 1000;
double lambda = 0.001;
SimulatedAnnealingSearch alg = new SimulatedAnnealingSearch(maxIt, tempIni, k, lambda);
SearchAgent agent = new SearchAgent(p, alg);
resultado = (GasolinaBoard) alg.getGoalState();
acciones = agent.getActions();
instrumentacion = agent.getInstrumentation();
}
// imprimir temps d'execucio
long elapsedNs = System.nanoTime() - startTime;
double elapsedMs = elapsedNs / 1_000_000.0;
System.out.println("Temps execució (ms): " + Math.round(elapsedMs));
// Evaluar si este resultado es mejor que el anterior
double beneficioActual = resultado.getBeneficiAvui();
System.out.println("Benefici: " + Math.round(beneficioActual) + ", km: " + resultado.getKm());
if (beneficioActual > mejorBeneficio) {
mejorBeneficio = beneficioActual;
mejorResultado = resultado;
mejorEjecucion = ejecucion;
mejoresAcciones = acciones;
mejorInstrumentacion = instrumentacion;
System.out.println("*** NOU MILLOR RESULTAT! ***");
}
System.out.println();
}
System.out.println("Accions del millor resultat:");
printActions(mejoresAcciones);
System.out.println();
// Mostrar el mejor resultado encontrado
System.out.println("===============================================");
System.out.println("MILLOR RESULTAT TROBAT:");
System.out.println("Execució: " + mejorEjecucion + " de " + NUMERO_EJECUCIONES);
printInstrumentation(mejorInstrumentacion);
System.out.println("Final benefit: " + Math.round(mejorResultado.getBeneficiAvui()) + ", km: " + mejorResultado.getKm());
System.out.println();
// informacio sobre l'execucio
String algoritmo = (b == 0) ? "HC" : "SA";
System.out.println("Fet amb " + algoritmo + " i inicialització " + inicialitzacio+", amb "+ngas+" gasolineres, "+ncen+" centres i multiplicitat "+mult);
//mejorResultado.printEstatComplet();
}
private static void printInstrumentation(Properties properties) {
Iterator keys = properties.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
String property = properties.getProperty(key);
System.out.println(key + " : " + property);
}
}
private static void printActions(List actions) {
if (actions == null || actions.isEmpty()) {
System.out.println("No actions to print (local search doesn't track action sequence)");
return;
}
for (int i = 0; i < actions.size(); i++) {
Object action = actions.get(i);
if (action instanceof String) {
System.out.println(action);
} else {
System.out.println("Action " + i + ": " + action.getClass().getSimpleName());
}
}
}
}