-
Notifications
You must be signed in to change notification settings - Fork 0
/
Player.java
executable file
·375 lines (335 loc) · 13 KB
/
Player.java
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
// Run with and java Main verbose > player2server < server2player
import java.util.*;
import java.lang.Integer;
class Player {
private static final int N = 5;
private static final int M = 9;
private static final double SHOOT_THRESHOLD = 0.75;
Map<Integer, HMM> models = new HashMap<>(); // Species number mapping to HMM model.
int[][] observationsPerBird;
HMM[] shootModels;
int[] likeliestLastState;
Map<Integer, MoveScore> bird2MoveScore;
List<ArrayList<HMM>> speciesModels; // speciesModels[species][modelNumber]
public Player() {
}
/**
* Shoot!
*
* This is the function where you start your work.
*
* You will receive a variable pState, which contains information about all
* birds, both dead and alive. Each bird contains all past moves.
*
* The state also contains the scores for all players and the number of
* time steps elapsed since the last time this function was called.
*
* @param pState the GameState object with observations etc
* @param pDue time before which we must have returned
* @return the prediction of a bird we want to shoot at, or cDontShoot to pass
*/
public Action shoot(GameState pState, Deadline pDue) {
/*
* Here you should write your clever algorithms to get the best action.
* This skeleton never shoots.
*/
// Shoot after 40 timesteps. Train one hmm per round and bird.
// Calculate the probability of being at each state x for each hmm at time t.
// Then for t+1, get the probability of each observation by taking
// the probability of each state times the probability of transitioning to each other
// state, times the probability of emitting the observation.
// if it is after 40 timesteps
if(pState.getBird(0).getSeqLength() < 40)
return cDontShoot;
// create 1 model per bird in game and train it on the current data
//likeliestLastState = new int[shootModels.length];
shootModels = new HMM[pState.getNumBirds()];
int lastState;
double[][] stateVector;
double[][] emissionVector;
MoveScore moveScore;
outerloop:
for(int i = 0; i < pState.getNumBirds(); i++) {
shootModels[i] = new HMM();
shootModels[i].randomizeParamsNormal(N, M, 0.1); // TODO: check if this initialization is optimal for shooting. Uniform pi?
shootModels[i].A = HMM.identityMatrix(N);
// shootModels[i].pi = new double[][]{{0.2, 0.2, 0.2, 0.2, 0.2}};
int[] O = new int[pState.getBird(i).getSeqLength()];
for(int j = 0; j < pState.getBird(i).getSeqLength(); j++) {
int nextMove = pState.getBird(i).getObservation(j);
if(nextMove == -1) break outerloop; // if the bird is dead, we don't care about any more of its observations
O[j] = pState.getBird(i).getObservation(j);
}
shootModels[i].fit(O);
// for each model, calculate most likely state for bird with viterbi
shootModels[i].fillDelta(O);
// Get last column of delta as vector.
stateVector = HMM.extractColumn(shootModels[i].delta, shootModels[i].delta[0].length - 1);
// Normalize the vector
stateVector = HMM.transpose(stateVector);
HMM.normalize(stateVector);
// multiply that vector with A to get state probabilities at next timestep.
stateVector = HMM.matrixMul(stateVector, shootModels[i].A);
// multiply the state probabilities at next timestep with B to get observation probabilities
emissionVector = HMM.matrixMul(stateVector, shootModels[i].B);
// Shoot on the first emission probability that is over 0.75.
double emissionProb;
double maxProb = 0;
int move = -1;
for(int j = 0; j < emissionVector[0].length; j++) {
emissionProb = emissionVector[0][j];
if(emissionProb > SHOOT_THRESHOLD){
System.err.println("shot");
return new Action(i, j);
}
}
}
return cDontShoot;
}
private MaxScoreObj max(MaxScoreObj[] maxScores) {
MaxScoreObj maxScore = maxScores[0];
MaxScoreObj newMaxScore;
for(int i = 1; i < maxScores.length; i++) {
newMaxScore = maxScores[i];
if(newMaxScore.compareTo(maxScore) > 0) {
maxScore = newMaxScore;
}
}
return maxScore;
}
private int[][] getObservations(GameState pState) {
int[][] res = new int[pState.getNumBirds()][pState.getRound() + 1];
for(int i = 0; i < pState.getNumBirds(); i++) {
Bird bird = pState.getBird(i);
int[] O = new int[bird.getSeqLength()];
for (int j = 0; j < bird.getSeqLength(); j++) {
O[j] = bird.getObservation(j);
}
res[i] = O;
}
return res;
}
public MaxScoreObj createMaxScoreObj(double[][] scores, int birdNo) {
HMM.DoubleInt res;
int rightMove = -1;
int species = -1;
double maxScore = Double.NEGATIVE_INFINITY;
double storkScore;
for(int i = 0; i < scores.length; i++) {
for(Integer j : models.keySet()) {
if(scores[i][j] > maxScore) {
maxScore = scores[i][j];
rightMove = i;
species = j;
}
}
}
if(models.containsKey(Constants.SPECIES_BLACK_STORK)) {
storkScore = scores[rightMove][Constants.SPECIES_BLACK_STORK];
}else {
storkScore = Double.NaN;
}
return new MaxScoreObj(maxScore, storkScore, rightMove, birdNo, species);
}
private class MaxScoreObj implements Comparable<MaxScoreObj> {
private double maxScore;
private double storkScore;
private int move;
private int birdNo;
private int species;
@Override
public int compareTo(MaxScoreObj o) {
if(Double.isNaN(this.maxScore))
return -1;
return Double.compare(this.maxScore, o.getMaxScore());
}
public MaxScoreObj(double d1, double d2, int moveNo, int birdNo, int species) {
maxScore = d1;
storkScore = d2;
move = moveNo;
this.birdNo = birdNo;
this.species = species;
}
public int getBirdNo() {
return birdNo;
}
public void setBirdNo(int birdNo) {
this.birdNo = birdNo;
}
public int getMove() {
return move;
}
public double getMaxScore() {
return maxScore;
}
public double getStorkScore() {
return storkScore;
}
public String toString() {
return String.format("move %d has maxProb %f and storkProb %f", move, maxScore, storkScore);
}
public int getSpecies() {
return species;
}
}
private int[] addToArray(int[] a, int b) {
int[] res = new int[a.length + 1];
int i;
for(i = 0; i < a.length; i++) {
res[i] = a[i];
}
res[i] = b;
return res;
}
/**
* @param pState the GameState object with observations etc
* @param pDue time before which we must have returned
* @return a vector with guesses for all the birds
*/
public int[] guess(GameState pState, Deadline pDue) {
/*
* Here you should write your clever algorithms to guess the species of
* each bird. This skeleton makes no guesses, better safe than sorry!
*/
int[] lGuess = new int[pState.getNumBirds()];
if(pState.getRound() == 0){
for(int i = 0; i < lGuess.length; i++){
lGuess[i] = Constants.SPECIES_PIGEON;
}
return lGuess;
}
double logP;
int speciesGuess;
// for each bird in pState,
for(int i = 0; i < pState.getNumBirds(); i++){
// get the observation sequence of that bird
int[] O = new int[pState.getBird(i).getSeqLength()];
for(int j = 0; j < pState.getBird(i).getSeqLength(); j++){
int newObs = pState.getBird(i).getObservation(j);
if(newObs == -1)
break;
O[j] = newObs;
}
// for each HMM in speciesModels[][], do a logP score.
speciesGuess = -1;
double maxLogP = Double.NEGATIVE_INFINITY;
for(int j = 0; j < speciesModels.size(); j++){ // j is the species
for(int k = 0; k < speciesModels.get(j).size(); k++) { // k is not interesting for the guessing
speciesModels.get(j).get(k).fillAlpha(O);
logP = speciesModels.get(j).get(k).computeLogP();
// is this log p greater than the greatest logP?
if(logP > maxLogP) {
maxLogP = logP;
speciesGuess = j;
}
}
}
// The highest score will get its species guessed
lGuess[i] = speciesGuess;
}
return lGuess;
}
private int[] cutIfDead(int[] O) {
for(int j = 0; j < O.length; j++){
if(O[j] == -1) {
O = Arrays.copyOfRange(O, 0, j);
break;
}
}
return O;
}
/**
* If you hit the bird you were trying to shoot, you will be notified
* through this function.
*
* @param pState the GameState object with observations etc
* @param pBird the bird you hit
* @param pDue time before which we must have returned
*/
public void hit(GameState pState, int pBird, Deadline pDue) {
System.err.println("HIT BIRD!!!");
}
/**
* If you made any guesses, you will find out the true species of those
* birds through this function.
*
* @param pState the GameState object with observations etc
* @param pSpecies the vector with species
* @param pDue time before which we must have returned
*/
public void reveal(GameState pState, int[] pSpecies, Deadline pDue) {
if(pState.getRound() == 0){
speciesModels = new ArrayList<>();
// add an empty list for each species
for(int i = 0; i < Constants.COUNT_SPECIES; i++){
speciesModels.add(new ArrayList<>());
}
}
for(int i = 0; i < pSpecies.length; i++) {
System.err.printf("correct answer for guess %d: %d\n", i, pSpecies[i]);
}
// For each bird in pSpecies
for(int i = 0; i < pSpecies.length; i++) {
// generate a new model
HMM model;
// train the model on the observation data from this round
if(pState.getBird(i).isAlive()) {
int[] O = new int[pState.getBird(i).getSeqLength()];
for (int j = 0; j < pState.getBird(i).getSeqLength(); j++) {
O[j] = pState.getBird(i).getObservation(j);
}
model = new HMM();
model.initializeParamsGuess(N, M, 0.01);
model.fit(O);
speciesModels.get(pSpecies[i]).add(model);
}// TODO: should we have an else for broken observation sequences due to dead bird?
else{
int lastMove = 0;
int j = 0;
while(pState.getBird(i).wasAlive(j)){
j++;
}
if(j < 10){
return;
}
int[] O = new int[j];
for(int k = 0; k < O.length; k++) {
O[k] = pState.getBird(i).getObservation(k);
}
model = new HMM();
model.initializeParamsGuess(N, M, 0.0001);
model.fit(O);
speciesModels.get(pSpecies[i]).add(model);
}
// add the model to speciesModels.get(species)
System.err.printf("pSpecies[i]: %d\n", pSpecies[i]);
}
}
public List<Integer> uniqueSpecies(int[] pSpecies) {
HashMap<Integer, Boolean> hm = new HashMap<>();
for(int i = 0; i < pSpecies.length; i++) {
hm.putIfAbsent(pSpecies[i], true);
}
List<Integer> unique = new ArrayList<Integer>();
for(Integer key : hm.keySet()) {
unique.add(key);
}
Collections.sort(unique);
return unique;
}
public static final Action cDontShoot = new Action(-1, -1);
private class MoveScore {
int move;
double score;
public MoveScore(int move, double score) {
this.move = move;
this.score = score;
}
public double getScore() {
return score;
}
public int getMove() {
return move;
}
}
}