-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork.java
More file actions
567 lines (497 loc) · 19.5 KB
/
Copy pathNetwork.java
File metadata and controls
567 lines (497 loc) · 19.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
package NEAT;
import java.util.ArrayList;
import java.util.Random;
/**
* Class that models our neural network.
* @author Chance Simmons and Brandon Townsend
* @version 25 February 2019
*/
public class Network {
/** Identification number for this network. */
private int id;
/** List of the input nodes for this network. */
private ArrayList<Node> inNodes;
/** List of the output nodes for this network. */
private ArrayList<Node> outNodes;
/** List of the hidden nodes for this network. */
private ArrayList<Node> hiddenNodes;
/** List of the links of this network. */
private ArrayList<Link> links;
/** Innovation List */
private static ArrayList<Link> innovationList = new ArrayList<Link>();
/** Bias node of the network */
private Node biasNode;
/**
* Constructor that only takes an identification number and initializes empty list.
* @param id The identification number of the new network.
*/
public Network(int id) {
this(id, new ArrayList<Node>(), new ArrayList<Node>(), new ArrayList<Node>(),
new ArrayList<Link>());
}
/**
* Constructor that builds a network based on passed nodes, but no links between those nodes.
* @param id The identification number of the new network.
* @param in A list of initialized input nodes.
* @param out A list of initialized output nodes.
* @param hid A list of initialized hidden nodes.
*/
public Network(int id, ArrayList<Node> in, ArrayList<Node> out, ArrayList<Node> hid) {
this(id, in, out, hid, new ArrayList<Link>());
}
/**
* Constructor that builds a network based on passed nodes and links.
* @param id The identification number of the new network.
* @param in A list of initialized input nodes.
* @param out A list of initialized output nodes.
* @param hid A list of initialized hidden nodes.
* @param links A list of initialized links.
*/
public Network(int id, ArrayList<Node> in, ArrayList<Node> out, ArrayList<Node> hid,
ArrayList<Link> links) {
this.id = id;
this.inNodes = in;
this.outNodes = out;
this.hiddenNodes = hid;
this.links = links;
}
/**
* Constructor that initializes a network based upon the number of nodes we would like to
* create for our input and output layers.
* @param id The identification number of the new network.
* @param inCount The number of input nodes.
* @param outCount The number of output nodes.
*/
public Network(int id, int inCount, int outCount){
this.inNodes = new ArrayList<Node>();
this.hiddenNodes = new ArrayList<Node>();
this.outNodes = new ArrayList<Node>();
this.links = new ArrayList<Link>();
this.biasNode = new Node(-1, NodeLayer.BIAS);
this.biasNode.setOutput(1);
this.id = id;
this.createNetwork(inCount,outCount);
}
/**
* Copy constructor that is used to clone a network
* @param oldNetwork the network that is being cloned
*/
public Network(Network oldNetwork) {
this.id = oldNetwork.getId();
this.inNodes = new ArrayList<Node>();
this.hiddenNodes = new ArrayList<Node>();
this.outNodes = new ArrayList<Node>();
this.links = new ArrayList<Link>();
this.biasNode = new Node(-1, NodeLayer.BIAS);
this.biasNode.setOutput(1);
for(Node input : oldNetwork.inNodes) {
Node toAdd = new Node(input.getId(), NodeLayer.INPUT, input.getInputSum(),
input.getOutput());
this.addNode(toAdd);
//System.out.printf("\n-> Old Node Mem Address: %s\t New Node Mem Address: %s", input,
// toAdd);
}
for(Node hidden : oldNetwork.hiddenNodes) {
Node toAdd = new Node(hidden.getId(), NodeLayer.HIDDEN, hidden.getInputSum(),
hidden.getOutput());
this.addNode(toAdd);
//System.out.printf("\n-> Old Node Mem Address: %s\t New Node Mem Address: %s", hidden,
// toAdd);
}
for(Node output : oldNetwork.outNodes) {
Node toAdd = new Node(output.getId(), NodeLayer.OUTPUT, output.getInputSum(),
output.getOutput());
this.addNode(toAdd);
//System.out.printf("\n-> Old Node Mem Address: %s\t New Node Mem Address: %s", output,
// toAdd);
}
int inputIndex;
int outputIndex;
Node newInput;
Node newOutput;
// Below is something atrocious, I know. It's the best way I could think about doing it
// though. Sets up links based on the nodes.
for(Link oldLink : oldNetwork.getLinks()) {
Node oldLinkInput = oldLink.getInput();
Node oldLinkOutput = oldLink.getOutput();
if(this.inNodes.contains(oldLinkInput)) {
inputIndex = this.inNodes.indexOf(oldLinkInput);
newInput = this.inNodes.get(inputIndex);
if(this.hiddenNodes.contains(oldLinkOutput)) {
outputIndex = this.hiddenNodes.indexOf(oldLinkOutput);
newOutput = this.hiddenNodes.get(outputIndex);
} else {
outputIndex = this.outNodes.indexOf(oldLinkOutput);
newOutput = this.outNodes.get(outputIndex);
}
} else {
inputIndex = this.hiddenNodes.indexOf(oldLinkInput);
outputIndex = this.outNodes.indexOf(oldLinkOutput);
newInput = this.hiddenNodes.get(inputIndex);
newOutput = this.outNodes.get(outputIndex);
}
Link toAdd = addLink(newInput, newOutput);
toAdd.setWeight(oldLink.getWeight());
toAdd.setEnabled(oldLink.isEnabled());
//System.out.printf("\n\t-> Old Link Mem Address: %s\t New Link Mem Address: %s",
// oldLink, toAdd);
}
}
/**
* Initializes a network by creating and adding nodes to this network's list of nodes.
* @param inCount Number of input nodes.
* @param outCount Number of output nodes.
*/
private void createNetwork(int inCount,int outCount){
// Creates all input layer nodes.
for(int i = 0; i < inCount; i++){
addNode(new Node(this.getNumNodes(), NodeLayer.INPUT));
}
// Creates all output layer nodes.
for(int i = 0; i < outCount; i++){
addNode(new Node(this.getNumNodes(), NodeLayer.OUTPUT));
}
// Fully connects all input layer nodes to all output layer nodes.
for(Node in : this.inNodes) {
for(Node out : this.outNodes) {
this.addLink(in,out);
}
}
}
/**
* Returns the identification number of this network.
* @return The identification number of this network.
*/
public int getId() {
return id;
}
/**
* Returns the links in this network
* @return the links of this network
*/
public ArrayList<Link> getLinks(){
return this.links;
}
/**
* Returns the number of nodes in this network.
* @return The number of nodes in this network.
*/
public int getNumNodes() {
return this.inNodes.size() + this.outNodes.size() + this.hiddenNodes.size();
}
/**
* Returns the number of links in this network.
* @return The number of links in this network.
*/
public int getNumLinks() {
return this.links.size();
}
/**
* Adds a node to the network.
* @param node The node to be added.
* @return True if the node is added, false otherwise.
*/
public boolean addNode(Node node) {
boolean result;
// Adding the node based on what layer it should be added to.
if(node.getLayer() == NodeLayer.INPUT) {
result = this.inNodes.add(node);
} else if(node.getLayer() == NodeLayer.OUTPUT) {
//Negative Innovation for bias node
this.biasNode.getOutgoingLinks().add(new Link(this.biasNode,node,-1));
result = this.outNodes.add(node);
} else {
//Negative Innovation for bias node
this.biasNode.getOutgoingLinks().add(new Link(this.biasNode,node,-1));
result = this.hiddenNodes.add(node);
}
return result;
}
/**
* Removes a node from the network.
* @param node The node to be removed.
* @return True if the node is removed, false otherwise.
*/
public boolean removeNode(Node node) {
boolean result = true;
// Performing check to see if any lists are empty.
if(inNodes.isEmpty() && outNodes.isEmpty() && hiddenNodes.isEmpty()) {
result = false;
System.out.println("Node cannot be removed as all lists are empty.");
} else {
// Checking to see if the node is in any list.
if(inNodes.contains(node)) {
inNodes.remove(node);
} else if(outNodes.contains(node)) {
inNodes.remove(node);
} else if(hiddenNodes.contains(node)) {
hiddenNodes.remove(node);
} else {
result = false;
System.out.println("Node cannot be removed as it is not in any list.");
}
}
return result;
}
/**
* Adds a link to the network.
* @param inNode the input node of the link
* @param outNode the output node of the link
* @return the link that was added
*/
public Link addLink(Node inNode,Node outNode) {
int innovationNum = Network.innovationList.size();
for(int i = 0; i < Network.innovationList.size(); i++){
Link toCheck = Network.innovationList.get(i);
int inputID = toCheck.getInput().getId();
int outputID = toCheck.getOutput().getId();
//If the innovation is identical to one in the overall list, set the new links
// innovation number to that innovation number.
if(inputID == inNode.getId() && outputID == outNode.getId()){
innovationNum = i;
}
}
//If a new innovation was created, add it to the overall list
if(innovationNum == Network.innovationList.size()){
Network.innovationList.add(new Link(inNode,outNode,innovationNum));
}
Link toAdd = new Link(inNode, outNode, innovationNum);
this.links.add(toAdd);
inNode.getOutgoingLinks().add(toAdd);
return toAdd;
}
/**
* Removes a link from the network.
* @param link The link to be removed.
* @return True if the link is removed, false otherwise.
*/
public boolean removeLink(Link link) {
boolean result = true;
// Performing check to see if the list is empty.
if(this.links.isEmpty()) {
result = false;
System.out.println("Link cannot be removed as the list of links is empty.");
} else {
// Checking to see if the link is in the list.
if(this.links.contains(link)) {
this.links.remove(link);
} else {
result = false;
System.out.println("Link cannot be removed as it is not in the list of links.");
}
}
return result;
}
/**
* Effectively destroys this network by removing all of its nodes and links.
* @return True when it has finished removing everything.
*/
public boolean destroy() {
for(Node i : inNodes) {
removeNode(i);
}
for(Node h : hiddenNodes) {
removeNode(h);
}
for(Node o : outNodes) {
removeNode(o);
}
for(Link l : links) {
removeLink(l);
}
return true;
}
/**
* Feeds the input through the network and returns the output.
* @param playerInput the input of the agent
* @return the output from the network
*/
public double[] feedForward(int[] playerInput) {
double[] result = new double[outNodes.size()];
// Setting up input nodes based on what the player inputs.
for(int i = 0; i < playerInput.length; i++) {
Node node = this.inNodes.get(i);
node.setOutput(playerInput[i]);
}
// activating all the nodes.
this.biasNode.activate();
for(Node i : inNodes) {
i.activate();
}
for(Node h : hiddenNodes) {
h.activate();
}
count = 0;
for(Node o : outNodes) {
o.activate();
result[count++] = o.getOutput();
}
return result;
}
/**
* Gets a node that has a certain ID.
* @param id the ID to search for
* @return the node
*/
public Node getNode(int id){
for(Node node: this.inNodes){
if(node.getId() == id){
return node;
}
}
for(Node node:this.hiddenNodes){
if(node.getId() == id){
return node;
}
}
for(Node node:this.outNodes){
if(node.getId() == id){
return node;
}
}
return null;
}
/**
* Checks to see if this genome is compatible with another genome.
* @return the compatibility value
*/
public double compatible(Network network){
double weightSum = 0;
int matchingCount = 0;
int disjointCount = 0;
double weightDiff;
double compatibility;
//Find the number of matching links, as well as the weight difference with the matching links
for(Link link: this.links){
for(Link otherLink:network.getLinks()){
if(link.equals(otherLink)){
matchingCount++;
weightSum += Math.abs(link.getWeight() - otherLink.getWeight());
}
}
}
//Find the disjoint count based off of the max number of links
if(this.links.size() > network.getLinks().size()){
disjointCount = this.getNumLinks() - matchingCount;
}else if(this.links.size() < network.getLinks().size()){
disjointCount = network.getNumLinks() - matchingCount;
}
weightDiff = weightSum / matchingCount;
compatibility = (disjointCount * Constant.DISJOINT_COEFF.getValue()) + (weightDiff *
Constant.WEIGHT_COEFF.getValue());
return compatibility;
}
/**
* Mutation that enables a link in the network
*/
public void linkEnableMutation(){
if(this.links.size() > 0) {
Random geneChooser = new Random();
int geneNum = geneChooser.nextInt(links.size() - 1);
Link toToggle = this.links.get(geneNum);
toToggle.setEnabled(!toToggle.isEnabled());
}
}
/**
* Mutation that enables the first disabled gene that is found.
*/
public void reenableLinkMutation(){
boolean foundLink = false;
for(int i = 0; !foundLink && i < this.links.size(); i++) {
Link link = this.links.get(i);
if(!link.isEnabled()) {
link.setEnabled(true);
foundLink = true;
}
}
}
/**
* Mutation that adjusts a weight of a link
* this.weight = weightGenerator.nextDouble() * 2 - 1;
*/
public void linkWeightMutation(){
Random random = new Random();
for(Link link : this.links) {
double howMuch = Math.random();
// Here we completely change the weight of the link.
if(howMuch < 0.1) {
link.setWeight(Math.random() * 2 - 1);
} else { // Here we make a slight adjustment to the weight. Divide by a large
// number to make it tiny
link.setWeight(link.getWeight() + random.nextGaussian() / 50);
if(link.getWeight() > 1) {
link.setWeight(1);
} else if(link.getWeight() < -1) {
link.setWeight(-1);
}
}
}
}
/**
* A new connection gene is added between two previously unconnected nodes.
*/
public void addLinkMutation() {
boolean found = false;
Random random = new Random();
// Check to see if it's a fully connected network.
if(this.hiddenNodes.isEmpty()) {
found = true;
} else {
int totalPossibleLinks = this.inNodes.size() * this.outNodes.size();
totalPossibleLinks += this.hiddenNodes.size() * (this.inNodes.size() + this.outNodes.size());
// Calculate the difference to see if we can add any links.
if(totalPossibleLinks - this.links.size() == 0) {
found = true;
}
}
ArrayList<Link> allLinks;
if(!found) {
allLinks = new ArrayList<Link>();
for(Node input : this.inNodes) {
for(Node hidden : this.hiddenNodes) {
allLinks.add(new Link(input, hidden, -1));
}
}
for(Node hidden : this.hiddenNodes) {
for(Node output : this.outNodes) {
allLinks.add(new Link(hidden, output, -1));
}
}
int start = this.inNodes.size() * this.outNodes.size();
for(; start < this.links.size(); start++) {
boolean removed = false;
Link actualLink = this.links.get(start);
for(int i = 0; !removed && i < allLinks.size(); i++) {
Link removeLink = allLinks.get(i);
if(actualLink.getInput().equals(removeLink.getInput()) &&
actualLink.getOutput().equals(removeLink.getOutput())) {
allLinks.remove(removeLink);
removed = true;
}
}
}
Link toAdd = allLinks.get(random.nextInt(allLinks.size()));
addLink(toAdd.getInput(), toAdd.getOutput());
}
}
/**
* Mutation that adds a node to the genome/network.
*/
public void addNodeMutation(){
Random random = new Random();
ArrayList<Link> inToOut = new ArrayList<Link>();
for(Link link : this.links) {
if(link.getInput().getLayer() == NodeLayer.INPUT && link.getOutput().getLayer() == NodeLayer.OUTPUT) {
inToOut.add(link);
}
}
Link link = inToOut.get(random.nextInt(inToOut.size()));
link.setEnabled(false);
Node newNode = new Node(this.getNumNodes());
Node oldIn = link.getInput();
Node oldOut = link.getOutput();
this.addNode(newNode);
this.addLink(oldIn,newNode);
this.addLink(newNode,oldOut);
}
}