Skip to content

Commit

Permalink
Started some basic UI
Browse files Browse the repository at this point in the history
updated node fireing
simplified nodes ordering, and removed the other list
  • Loading branch information
zelding committed Aug 31, 2018
1 parent 4d3ac8e commit e5376cd
Show file tree
Hide file tree
Showing 8 changed files with 457 additions and 58 deletions.
324 changes: 299 additions & 25 deletions Assets/Scenes/Simulation.unity

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions Assets/Scripts/Entitites/EntityManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace NeatFish.Entities
{
public class EntityManager : MonoBehaviour
{
public double Speed = 0.0;

protected NeuralNet brain;

protected Movement Legs;
Expand Down Expand Up @@ -37,9 +39,13 @@ private void Start()
private void FixedUpdate()
{
if (Legs != null && brain != null) {
double[] output = brain.Activate(new double[] { 1, 2 });
Vector2 asd = Random.insideUnitCircle * Random.Range(-2, 2);

double[] input = new double[2] {asd .x, asd.y };

double[] output = brain.Activate(input);

Legs.Move(new Vector3((float)output[0], (float)output[1], (float)output[3]));
Legs.Move(new Vector3((float)output[0], (float)output[1], (float)output[2]));
}
else {
//Debug.Log("Nolegs");
Expand Down
48 changes: 48 additions & 0 deletions Assets/Scripts/Program/Inspector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using UnityEngine;
using UnityEngine.UI;
using NeatFish.Simulation.NEAT;
using System.Collections.Generic;

public class Inspector : MonoBehaviour {

public NeuralNet Brain;

public GameObject panel;

private Dictionary<uint, Text> NeuronTexts;

private void Start()
{
NeuronTexts = new Dictionary<uint, Text>();

Font ArialFont = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");

foreach (Node n in Brain.Neurons) {
var o = new GameObject("N " + n.Id.ToString() + " " + n.type);

o.transform.localPosition = Vector3.zero;
o.transform.localRotation = Quaternion.identity;

var t = o.AddComponent<Text>();
t.rectTransform.localPosition = new Vector3(n.Position.x * 150, 0, n.Position.y * 50);
t.rectTransform.localRotation = Quaternion.identity;

t.font = ArialFont;
t.material = ArialFont.material;
t.fontSize = 7;
t.alignment = TextAnchor.UpperLeft;
t.text = n.GetValue().ToString();

NeuronTexts.Add(n.Id, t);

o.transform.SetParent(panel.transform);
}
}

private void OnGUI()
{
foreach (Node n in Brain.Neurons) {
NeuronTexts[n.Id].text = n.GetValue().ToString();
}
}
}
11 changes: 11 additions & 0 deletions Assets/Scripts/Program/Inspector.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion Assets/Scripts/Program/Simulation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ public class Simulation : MonoBehaviour {
public GameObject FisheContainer;
public GameObject FishPrototype;

public GameObject Inspector;

[Range(1, 250)]
public uint InitialPopulation = 10;
public uint InitialPopulation = 1;

public Vector3 SpawnBoundaryCenter { get { return spawnBoundaryCenter; } }
public float SpawnBoundaryRaduis { get { return spawnBoundaryRaduis; } }
Expand All @@ -24,6 +26,8 @@ public class Simulation : MonoBehaviour {

protected List<EntityManager> fishManagers;

protected Inspector inspector;

private NodeIDGenerator nodeIDGenerator;
private SimulationManager manager;

Expand All @@ -33,6 +37,8 @@ private void Awake()
throw new System.Exception("No fishcontainer was assigned");
}

inspector = Inspector.GetComponent<Inspector>();
inspector.enabled = false;
}

// Use this for initialization
Expand All @@ -53,6 +59,8 @@ private void Start () {

manager.IsRunning = true;

inspector.Brain = fishManagers[0].Brain;
inspector.enabled = true;
}

// Update is called once per frame
Expand Down
80 changes: 54 additions & 26 deletions Assets/Scripts/Simulation/NEAT/NeuralNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ public class NeuralNet : IMutatable
public List<Node> Neurons { get; protected set; }
public List<Connection> Connections { get; protected set; }

protected List<Node> Network;

protected NodeIDGenerator generator;
protected readonly IRandomSource _rng = RandomDefaults.CreateRandomSource();

Expand All @@ -37,19 +35,21 @@ public NeuralNet(int inputs, int outputs, NodeIDGenerator nodeIDGenerator)

for (int i = 0; i < Inputs; i++) {
var node = new Node(generator.Next, Node.NodeTypes.Input) {
Position = new Vector2(0, i),
Position = new Vector2Int(0, i),
};

Neurons.Add(node);
}

for (int i = 0; i < Outputs; i++) {
var node = new Node(generator.Next, Node.NodeTypes.Output) {
Position = new Vector2(int.MaxValue, i),
Position = new Vector2Int(int.MaxValue, i),
};

Neurons.Add(node);
}

InitializeConnections();
}

public NeuralNet(NeuralNet parent)
Expand Down Expand Up @@ -105,11 +105,13 @@ public double[] Activate(double[] inputs)
throw new System.IndexOutOfRangeException("Input length invalid, should be: " + Inputs.ToString());
}

for(int i = 0; i < Inputs; i++) {
Neurons.Sort(new Node.NodeSorter());

for (int i = 0; i < Inputs; i++) {
Neurons[i].AddValue(inputs[i]);
}

foreach(Node n in Network) {
foreach(Node n in Neurons) {
n.Fire();
}

Expand All @@ -122,47 +124,73 @@ public double[] Activate(double[] inputs)
return output;
}

public void GenerateNetwork()
{
InitializeConnections();

Network = new List<Node>();

for (int l = 0; l < Layers; l++) {
foreach(Node n in Neurons) {
if ( n.Position.x == l ) {
Network.Add(n);
}
}
}
}

/// <summary>
/// Sets up the initial connections for a brand new Net
/// </summary>
protected void InitializeConnections()
{
ConnectionTemplate[] conTmpl = new ConnectionTemplate[ Inputs * Outputs ];

// create templates for all possible connections
for (int i = 0, c = 0; i < Inputs; i++) {
for (int o = 0; o < Outputs; o++) {
conTmpl[c++] = new ConnectionTemplate(generator.Next, i, o);
}
}


// mix them up
SortUtils.Shuffle(conTmpl, _rng);

int connectionCount = (int)NumericsUtils.ProbabilisticRound(conTmpl.Length * 0.05, _rng);
connectionCount = System.Math.Max(1, connectionCount);
// make up a number between the max possible connections and zero
int connectionCount = (int)NumericsUtils.ProbabilisticRound(conTmpl.Length * 0.075, _rng);
connectionCount = System.Math.Max(2, connectionCount);

// create that many actual connections
for(int i = 0; i < connectionCount; i++) {

Node input = Neurons[ i ];
Node output = Neurons[ i + (int)Inputs ];
Node output = Neurons[ i + Inputs ];

Connection con = new Connection(_rng.NextUInt(), input, output, _rng.NextDouble() * 2.0 - 1.0, _rng.NextDouble() * - 5.0);
Connection con = new Connection(_rng.NextUInt(), input, output, _rng.NextDouble() * 2.0 - 1.0, _rng.NextDouble() * -5.0) {
Enabled = true
};

Connections.Add(con);
}
}

/// <summary>
/// returns whether the network is fully connected or not
/// </summary>
/// <returns></returns>
protected bool IsFullyConnected()
{
int maxConnections = 0;
int[] nodelsInLayers = new int[Layers];

for(int i = 0; i < Neurons.Count; i++) {
nodelsInLayers[Neurons[i].Position.x]++;
}

//for each layer the maximum amount of connections is the number in this layer * the number of nodes infront of it
//so lets add the max for each layer together and then we will get the maximum amount of connections in the network
for (int i = 0; i < Layers - 1; i++) {
int nodesInFront = 0;
//for each layer infront of this layer
for (int j = i + 1; j < Layers; j++) {
//add up nodes
nodesInFront += nodelsInLayers[j];
}

maxConnections += nodelsInLayers[i] * nodesInFront;
}

return maxConnections == Neurons.Count;
}

/// <summary>
/// A simple struct to represent a connection before actually creating ther class
/// </summary>
private struct ConnectionTemplate
{
public readonly uint innovationId;
Expand Down
30 changes: 28 additions & 2 deletions Assets/Scripts/Simulation/NEAT/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ public enum NodeTypes { Input, Hidden, Output, Bias };

public readonly NodeTypes type;

public UnityEngine.Vector2 Position;
/// <summary>
/// x: layer
/// y: order in layer
/// </summary>
public UnityEngine.Vector2Int Position;

protected double Value;

Expand Down Expand Up @@ -61,11 +65,14 @@ public void Fire()
c.Output.AddValue(Value * c.Weight + c.Bias);
}
}

PreviousValue = Value;
Value = 0;
}

public double GetValue()
{
return Value;
return PreviousValue;
}

public uint Id
Expand Down Expand Up @@ -106,5 +113,24 @@ public bool IsConnectedWith(Node n)

return false;
}

/// <summary>
/// Used to sort nodes to layers and order in layers
/// </summary>
public class NodeSorter : IComparer<Node>
{
int IComparer<Node>.Compare(Node x, Node y)
{
if ( x.Position.x == y.Position.x ) {
if (x.Position.y == y.Position.y) {
throw new System.Exception("The nodes are at the same place");
}

return x.Position.y.CompareTo(y.Position.y);
}

return x.Position.x.CompareTo(y.Position.x);
}
}
}
}
2 changes: 0 additions & 2 deletions Assets/Scripts/Simulation/SimulationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ public NeuralNet CreateNewBrain(NeuralNet parent = null)
brain = new NeuralNet(2, 3, NodeIDGenerator);
}

brain.GenerateNetwork();

Brains.Add(brain);

return brain;
Expand Down

0 comments on commit e5376cd

Please sign in to comment.