-
Notifications
You must be signed in to change notification settings - Fork 0
/
Agent.cpp
353 lines (289 loc) · 12.1 KB
/
Agent.cpp
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
//
// Created by Marco Matarese on 18/06/2019.
//
#include "Agent.h"
#include <limits>
#include <list>
#include <time.h>
#include <fstream>
#include <string>
/**
* Initialize this->codeToAction:
* - all take(n) actions with n=0, ..., noBlocks-1
* - all stack(n,m) actions with n,m=0, ..., noBlocks-1
* - all putOnTable(n) actions with n=0, ..., noBlocks-1.
*/
void Agent::initCodeToAction() {
int indx = 0,
*args = new int[2];
for(int i = 0; i < this->perceivedEnv->getNoBlocks(); i++) {
args[0] = i;
this->codeToAction.insert(std::pair<int, Action>(indx, Action("take", args)));
this->actionToCode.insert(std::pair<Action, int>(Action("take", args), indx));
indx++;
}
for(int i = 0; i < this->perceivedEnv->getNoBlocks(); i++) {
args[0] = i;
for(int j = 0; j < this->perceivedEnv->getNoBlocks(); j++) {
if(i != j) {
args[1] = j;
this->codeToAction.insert(std::pair<int, Action>(indx, Action("stack", args)));
this->actionToCode.insert(std::pair<Action, int>(Action("stack", args), indx));
indx++;
}
}
}
for(int i = 0; i < this->perceivedEnv->getNoBlocks(); i++) {
args[0] = i;
this->codeToAction.insert(std::pair<int, Action>(indx, Action("putOnTable", args)));
this->actionToCode.insert(std::pair<Action, int>(Action("putOnTable", args), indx));
indx++;
}
}
/**
*
*/
void Agent::initCodeToStates() {
this->codeToStates.insert(std::pair<int, std::set<Predicate>>(0, this->perceivedEnv->getCurrState()));
this->statesToCode.insert(std::pair<std::set<Predicate>, int>(this->perceivedEnv->getCurrState(), 0));
}
/**
* Initialize this->QMatrix.
*/
void Agent::initializeQMatrix() {
int nextIndx;
for(int i = 0; i < this->QMatrixNoRows; i++)
for(int j = 0; j < this->QMatrixNoCols; j++)
this->QMatrix[i][j] = 0;
}
/**
* Realloc this->QMatrix adding a new row.
* Update this->QMatrixNoRows.
* Update this->perceivedEnv->noStates.
*/
void Agent::addRowToQMatrix() {
int currNoRows = this->QMatrixNoRows;
// reallocation
this->QMatrix = (float**) realloc(this->QMatrix, (currNoRows + 1) * sizeof(float *));
this->QMatrix[currNoRows] = (float *) malloc(this->noActions * sizeof(float));
for(int i = 0; i < this->noActions; i++)
this->QMatrix[currNoRows][i] = 0;
// updates
this->QMatrixNoRows++;
this->perceivedEnv->setNoStates(this->QMatrixNoRows);
}
/**
* Print the QMatrix on std output.
*/
void Agent::printQMatrix() {
for(int i = 0; i < this->QMatrixNoRows; i++) {
for (int j = 0; j < this->QMatrixNoCols; j++)
std::cout << this->QMatrix[i][j] << " ";
std::cout << std::endl;
}
}
/**
* Compute the policy based on this->QMatrix values.
*/
void Agent::calculatePolicy() {
int noConfigs = this->perceivedEnv->getNoStates(),
noActions = this->noActions,
currMaxIndx = 0;
float currMax;
std::set<Predicate> currConf;
Action currAction,
bestActionPerConf;
for(int i = 0; i < noConfigs; i++) {
currMax = -9999999;
currConf = this->codeToStates.at(i);
for(int j = 0; j < noActions; j++) {
currAction = this->codeToAction.at(j);
if (this->QMatrix[i][j] != 0.0 && this->QMatrix[i][j] > currMax) {
currMax = this->QMatrix[i][j];
currMaxIndx = j;
}
}
bestActionPerConf = this->codeToAction.at(currMaxIndx);
this->policy.insert(std::pair<std::set<Predicate>, Action>(currConf, bestActionPerConf));
}
}
/**
* Show the current policy.
*/
void Agent::showPolicy() {
std::cout << "BEST POLICY:" << std::endl;
for(auto x : this->policy) {
std::cout << "In state: ";
for(auto y : x.first)
std::cout << y << " ";
std::cout << std::endl << " Do: " << x.second << std::endl;
}
}
/**
* Choose an action from all possible action in current state. Whit probability epsilon, choose the best action
* based on Q value, with probability 1-epsilon another action.
* @param epsilon the probability to do the best action
* @return the chosen action
*/
Action Agent::chooseAction(float epsilon) {
std::list<Action> possibleActions = std::list<Action>();
std::list<Action>::iterator it = possibleActions.begin();
Action action,
bestAction;
bool precondsSatisfied;
float currMax = -999999;
int rowIndx = this->statesToCode[this->perceivedEnv->getCurrState()],
colIndx = 0,
prob = rand() % 100 + 1,
indx = 0;
// collect possible actions in current state
for(int i = 0; i < noActions; i++) {
action = this->codeToAction.at(i);
precondsSatisfied = this->perceivedEnv->currStateSatisfyPrecondsOf(action);
if(precondsSatisfied) {
it = possibleActions.insert(it, action);
colIndx = this->getActionToCode(action);
if (colIndx == -1)
std::cout << "ERROR: code to action " << action << " not found!" << std::endl;
else {
if (this->QMatrix[rowIndx][colIndx] > currMax) {
currMax = this->QMatrix[rowIndx][colIndx];
bestAction = this->codeToAction.at(colIndx);
}
}
}
}
if(prob < (epsilon * 100) && possibleActions.size() > 0) { // if prob < epsilon, then do another action
indx = rand() % possibleActions.size();
return *it;
}
return bestAction; // prob >= epsilon
}
/**
*
* @param currState
* @param action
* @return
*/
int Agent::calculateReward(Action action) {
if(this->perceivedEnv->isCurrStateAFinalState()) {
if(this->perceivedEnv->isCurrStateTheAcceptingState()) {
return ACCEPTING_STATE_REWARD;
}
else return REJECTING_STATE_REWARD;
}
return ONE_STEP_REWARD;
}
/**
* (1) Check if preconditions are satisfied.
* (2) If satisfied, perform the action's effects (predicates to add and del).
* @param action the action to do
* @return true if action is performed, false otherwise
*/
bool Agent::doAction(Action action) {
std::set<Predicate> currState = this->perceivedEnv->getCurrState();
std::set<Predicate>::iterator it;
Predicate pred;
int *args = new int[2];
bool preconditionsSatisfied = this->perceivedEnv->currStateSatisfyPrecondsOf(action);
if (preconditionsSatisfied) {
// delete predicates
for (Predicate pred : *(action.getPostconditionsToDel())) {
this->perceivedEnv->removeToCurrState(pred);
}
// add predicates
for (Predicate pred : *(action.getPostconditionsToAdd())) {
this->perceivedEnv->addToCurrState(pred);
}
// non-automatic action effects: they depends on world's current configuration...
if(action.getName() == "take") {
args[0] = action.getArg(0);
// if handling block was on another block
if(! (pred = this->perceivedEnv->findPredWithPartialInfoInCurrState("on", 0, args[0])).isEmptyPredicate()) {
args[1] = pred.getSecondArg(); // the other block
this->perceivedEnv->removeToCurrState(Predicate("on", args)); // remove on(handling_b,other_b)
args[0] = pred.getSecondArg(); //
this->perceivedEnv->addToCurrState(Predicate("clear", args)); // remove clear(other_b)
}
// else if handling block was on table
else if((it = this->perceivedEnv->getCurrState().find(Predicate("onTable", args))) !=
this->perceivedEnv->getCurrState().end()) {
this->perceivedEnv->removeToCurrState(Predicate("onTable", args)); // remove onTable(handling_b)
}
}
}
else {
std::cout << "Precondition to action " << action.getName();
for(int i = 0; i < action.getNoArgs(); i++)
std::cout << " " << action.getArg(i) << " ";
std::cout << "unsatisfied." << std::endl;
return false;
}
return true;
}
/**
* Q learning with a non-well-know environment.
* @param noEpochs
*/
void Agent::doQLearning(int noEpochs) {
Action action;
int actionCode = 0,
currStateCode = 0,
prevStateCode = 0,
run,
noVictories = 0;
float epsilon = 0.2,
reward = 0,
max_a = 0,
alfa = 0.8,
gamma = 0.9,
cumulativeRewards;
std::set<Predicate> prevState,
currState;
std::map<std::set<Predicate>, int>::iterator it;
std::ofstream outFile;
//outFile.open("cumulativeRewards.txt");
// for each epochs
for(int i = 0; i < noEpochs; i++) {
this->perceivedEnv->initCurrState(); // init world's config
run = 0;
cumulativeRewards = 0;
// until a final state is reached
while(! this->perceivedEnv->isCurrStateAFinalState()) {
action = this->chooseAction(epsilon); // choose an action
prevState = this->perceivedEnv->getCurrState(); // collect actual state
if(this->doAction(action)) { // do the chosen action
currState = this->perceivedEnv->getCurrState(); // collect resulting state
reward = calculateReward(action); // calculate reward
cumulativeRewards += reward;
if(reward == ACCEPTING_STATE_REWARD) noVictories++;
actionCode = this->getActionToCode(action); // retrieve Q col index
prevStateCode = this->statesToCode[prevState]; // retrieve Q row index (prev)
// check whether I already visited currState or not
if (this->statesToCode.find(currState) != this->statesToCode.end())
currStateCode = this->statesToCode[currState]; // retrieve Q row index (curr)
else {
this->codeToStates.insert(std::pair<int, std::set<Predicate>>(this->QMatrixNoRows, currState));
this->statesToCode.insert(std::pair<std::set<Predicate>, int>(currState, this->QMatrixNoRows));
currStateCode = this->QMatrixNoRows;
this->addRowToQMatrix(); // add row to Q, update system's params
}
// retrieve best action in resulting state based on Q values
max_a = -1;
for (int i = 0; i < this->noActions; i++)
if (this->QMatrix[currStateCode][i] > max_a)
max_a = this->QMatrix[currStateCode][i];
// Q(s,a) = Q(s,a) + alfa * (r + gamma * max_a'(Q(s',a) - Q(s,a))
this->QMatrix[prevStateCode][actionCode] = this->QMatrix[prevStateCode][actionCode] +
alfa * (reward + gamma * max_a -
this->QMatrix[prevStateCode][actionCode]);
}
run++;
}
std::cout << "Epoch: " << i << " Runs: " << run << std::endl;
//outFile << cumulativeRewards << std::endl;
}
std::cout << "Percentage of vinctory: " << (noVictories*100)/noEpochs << std::endl;
std::cout << "Tot epochs: " << noEpochs << " victory runs: " << noVictories << std::endl;
//outFile.close();
}