-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReactiveTemplate.java
More file actions
executable file
·257 lines (224 loc) · 7.72 KB
/
ReactiveTemplate.java
File metadata and controls
executable file
·257 lines (224 loc) · 7.72 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
package template;
import com.sun.istack.internal.NotNull;
import logist.agent.Agent;
import logist.behavior.ReactiveBehavior;
import logist.plan.Action;
import logist.plan.Action.Move;
import logist.plan.Action.Pickup;
import logist.simulation.Vehicle;
import logist.task.Task;
import logist.task.TaskDistribution;
import logist.topology.Topology;
import logist.topology.Topology.City;
import java.util.LinkedList;
import java.util.List;
public class ReactiveTemplate implements ReactiveBehavior
{
private final LinkedList<State> stateList = new LinkedList<>(); // All possible states
private List<City> cityList; // All reachable cities
private City tempBestAction; // temp best action corresponding to an iteration of maxQ
private int counter = 0;
@Override
public void setup(Topology topology, TaskDistribution td, Agent agent)
{
// Reads the discount factor from the agents.xml file.
// If the property is not present it defaults to 0.95
Double discount = agent.readProperty("discount-factor", Double.class,
0.95);
this.initState(topology);
this.valueIteration(td, agent, discount);
System.out.println("All possible states: ");
stateList.forEach(System.out::println);
System.out.println("Number of iterations: " + counter);
}
@Override
public Action act(Vehicle vehicle, Task availableTask)
{
Action action = null;
State currentState;
if (availableTask == null)
{
currentState = new State(vehicle.getCurrentCity(), vehicle.getCurrentCity());
State completeState = lookUpState(currentState);
if (completeState != null)
{
action = new Move(completeState.getBestAction());
} else {System.out.println("ERROR: No corresponding state found!");}
} else
{
currentState = new State(vehicle.getCurrentCity(), availableTask.deliveryCity);
State completeState = lookUpState(currentState);
if (completeState != null)
{
City bestAction = completeState.getBestAction();
if (availableTask.deliveryCity.equals(bestAction)) {
action = new Pickup(availableTask);
}
else
{
action = new Move(completeState.getBestAction());
}
} else {System.out.println("ERROR: No corresponding state found!");}
}
return action;
}
/**
* initialize all possible states and reachable cities.
*
* @param t topology
*/
private void initState(Topology t)
{
cityList = t.cities();
for (City from : t)
{
for (City to : t)
{
stateList.add(new State(from, to));
}
}
}
/**
* Markov decision process, Compute best policy.
*
* @param td TaskDistribution
* @param agent agent which travels and deliver tasks
* @param discountFactor discount the future state reward
*/
private void valueIteration(TaskDistribution td, Agent agent, double discountFactor)
{
City currentCity;
City taskDest;
List<City> neighbourList;
List<City> newList;
do
{
for (State s : stateList)
{
currentCity = s.getFrom();
taskDest = s.getTo();
neighbourList = s.getFrom().neighbors();
if (!currentCity.hasNeighbor(taskDest) && !currentCity.equals(taskDest))
{
newList = new LinkedList<>(neighbourList);
newList.add(taskDest);
}
else
{
newList = new LinkedList<>(neighbourList);
}
double maxQ;
maxQ = computeMaxQ(currentCity, taskDest, newList, td, agent, discountFactor);
s.updateBestReward(maxQ, tempBestAction);
}
counter++;
} while (!converge(0.00001));
}
/**
* Compute maxQ for a given state.
*
* @param currentCity current city
* @param taskDestCity task destination city
* @param reachableCity reachable city list after legal moves performed by the agent
* @param td task distribution
* @param agent agent
* @param discountFactor discount factor of the future reward
*
* @return Q(s)
*/
private double computeMaxQ(City currentCity, City taskDestCity, List<City> reachableCity, TaskDistribution td,
Agent agent, double discountFactor)
{
double maxQ = - Double.MAX_VALUE;
for (City nextCity : reachableCity)
{
double sum = 0;
double cost;
for (City nextPossibleTaskDest : cityList)
{
State futureState = new State(nextCity, nextPossibleTaskDest);
if (!nextPossibleTaskDest.equals(nextCity))
{
sum += discountFactor * td.probability(nextCity, nextPossibleTaskDest) * getBestValue(futureState);
} else
{
sum += discountFactor * td.probability(nextCity, null) * getBestValue(futureState);
}
}
//Add reward if the package is taken.
if (taskDestCity.equals(nextCity))
{
sum += td.reward(currentCity, taskDestCity);
}
//Subtract the cost of the trip
List<Vehicle> vehicles = agent.vehicles();
cost = currentCity.distanceTo(nextCity) * vehicles.get(0).costPerKm();
sum -= cost;
if (sum > maxQ)
{
maxQ = sum;
tempBestAction = nextCity;
}
}
return maxQ;
}
/**
* Get the bestValue V(s) stored in the stateList
*
* @param s State
*
* @return V(s) of a given state
*/
private double getBestValue(State s)
{
for (State state : stateList)
{
if (state.equals(s))
{
return state.getBestReward();
}
}
return 0;
}
/**
* Check whether the results after n iteration is good enough, difference between the previous iteration and current
* iteration is smaller than epsilon
*
* @param epsilon max difference between pre maxQ and current maxQ after n iterations
*
* @return true if diff is smaller than epsilon
*/
private boolean converge(double epsilon)
{
double maxDiff = - Double.MAX_VALUE;
double diff;
for (State s : stateList)
{
diff = Math.abs(s.getBestReward() - s.getPre_bestReward());
if (diff > maxDiff)
{
maxDiff = diff;
}
}
return maxDiff < epsilon;
}
/**
* Find the corresponding state in the precomputed stateList
*
* @param DesiredState state to be searched
*
* @return complete state
*/
@NotNull private State lookUpState(State DesiredState)
{
for (State state : stateList)
{
if (DesiredState.equals(state))
{
return state;
}
}
System.out.println("ERROR: No state found!");
return null;
}
}