1   import interfaces.Controller;
2   import interfaces.AbstractRobot;
3   
4   /**
5   * this class implements a neural net with a 3-1 topology plus bias.
6   * the three inputs are light sensors 0->2.
7   * output of <0.4 corresponds to turn left, 0.4<x<0.6 go forwards, >0.6 turn right.
8   * This was the first neural net that was written, and it was generated using real world
9   * values (similar to GBN2b). The training regime was a bit lax though - the threshhold was set to 0.1,
10  * so it would not be surprising if this net performs a little unexpectedly in some conditions.
11  *
12  * @author Graeme Bell
13  * @see GBN2b
14  */
15  
16  public class GBNN2 extends Controller {
17  
18  AbstractRobot r;
19  boolean initcalled;
20  boolean running=false;
21  
22  private int[] sensors={Controller.SENSOR_TYPE_LIGHT,Controller.SENSOR_TYPE_LIGHT,Controller.SENSOR_TYPE_LIGHT};
23  
24  // this looks rubbish - but it will compile to run extremely fast 
25  // this is because the weights will be inlined and the inputs/outputs
26  // won't need dereferencing or array overhead.
27  
28  float input0;
29  float input1;
30  float input2;
31  
32  // bias input is assumed to be +1
33  
34  float output0;
35  
36  // weights
37  final float weight00 = -4.1f;
38  final float weight10 = 1.16f;
39  final float weight20 = 3.69f;
40  final float weightb0 = -0.94f;
41  
42      public void run(){
43  
44          running=true;
45              
46          while (running){
47          
48                  // get input
49                                                          
50                  input0=r.getSensor1()/100.0f;
51                  input1=r.getSensor2()/100.0f;
52                  input2=r.getSensor3()/100.0f;
53  
54                  //Sigmoidal activation function 1.0/1.0+exp(excitation)
55  
56                  output0 = 1.0f/(1.0f+(float)(Math.exp(  weight00*input0+
57                              weight10*input1+
58                              weight20*input2+
59                              weightb0)));
60  
61                  //decide what to do.
62  
63                  if (output0<0.4) {r.right();}
64                  if (output0<0.6 && output0>=0.4) {r.forward();}
65                  if (output0>=0.6) {r.left();}
66                  
67                  
68                  try{Thread.sleep(500);}catch(Exception e){}
69           }
70  
71      }
72  
73      public void initController(AbstractRobot r) {
74  
75          this.r=r;
76          initcalled=true;
77      }
78      
79      public int[] getSensors(){
80      
81          return sensors;
82      }
83      
84      public void halt(){
85      
86          running=false;
87          r.stopMoving();
88      }
89      
90      public AbstractRobot getRobot(){
91      
92          return r;
93      }
94  }   
95