public void LinkNextNode(NeuralNode next) { var link = new NeuralLink(this, next, 1.0); this.nextLayer.Add(link); next.prevLayer.Add(link); }
// Update is called once per frame void Update() { if (timePerStop > 0) { if (!stopped && Time.time > timeOfLastStopOrGo + timeBetweenStop) { stopped = true; timeOfLastStopOrGo = Time.time; nav.SetDestination(transform.position); } else if (stopped && Time.time > timeOfLastStopOrGo + timePerStop) { stopped = false; timeOfLastStopOrGo = Time.time; nav.SetDestination(destination); } } if (Time.time >= nextConfoundingTime) { foreach (KeyValuePair <NeuralNode, List <int> > kvp in towersToConfound) { NeuralNode node = kvp.Key; int[] nonzeroIndices = node.GetNonzeroIndices(); if (nonzeroIndices != null && nonzeroIndices.Length > 0) { float numCallsToConfound = intendedConfoundingTime / Time.deltaTime; int numConfoundings = (int)(nonzeroIndices.Length / numCallsToConfound); for (int i = 0; i < numConfoundings; i++) { List <int> preconfoundedIndices = node.GetConfoundedIndices(); int index = nonzeroIndices [Random.Range(0, nonzeroIndices.Length)]; if (!kvp.Value.Contains(index) && !preconfoundedIndices.Contains(index)) { if (index == -1) { node.b = ConfoundB(node.b); } else { ConfoundWeights(node.weights, index); } kvp.Value.Add(index); node.AddToConfoundedIndices(index); } } } } nextConfoundingTime = Time.time + confoundInterval; } Vector3 rangeSize = rangeIndicator.localScale; float rangeScale = rangeSize.x; if (rangeSize.x > 7 * 2 * range) { rangeScale = 0f; } Vector3 newRangeScale = new Vector3(rangeScale + Time.deltaTime * rangeSpeed, 0, rangeScale + Time.deltaTime * rangeSpeed); rangeIndicator.localScale = newRangeScale; }
public static bool AnyCircular(NeuralNode Node) { List<NeuralNode> Nodes = AllChildren(Node); foreach (NeuralNode n in Nodes) if (IsCircular(n)) return true; return IsCircular(Node); }
// Node Creation --- private GraphicNode CreateGNode(NeuralNode n) { if (n == null) { return(null); } GUIStyle style = new GUIStyle(); if (n.nodeOrder == NeuralNetwork.inputNodeOrder) { style = inStyle; } else if (n.nodeOrder == NeuralNetwork.outputNodeOrder) { style = outStyle; } else { style = hlStyle; } GraphicNode gnode = new GraphicNode(n, new Vector2(0, 0), nodeScale.x, nodeScale.y, style); gNodes.Add(gnode); return(gnode); }
public void Init(int[] structure) { Func <double, double> func = (double x) => { return(1 / (1 + System.Math.Exp(-x))); }; // Creating layer structure nodeLayers = new NeuralNode[structure.Length][]; for (var i = 0; i < structure.Length; i++) { var layerCount = structure[i]; nodeLayers[i] = new NeuralNode[layerCount]; for (var j = 0; j < layerCount; j++) { nodeLayers[i][j] = new NeuralNode(func); } } // Linking nodes in adjacent layers for (var i = 0; i < nodeLayers.Length - 1; i++) { var currentLayer = nodeLayers[i]; var nextLayer = nodeLayers[i + 1]; foreach (var node in currentLayer) { foreach (var nextNode in nextLayer) { node.LinkNextNode(nextNode); } } } }
public override NeuralNode Clone() { GrayscaleNode res = (GrayscaleNode)NeuralNode.create(NodeType.GRAYSCALE); res.SetWeights(actualWeights, this.b); res.SetNonzeroIndices(); return(res); }
protected virtual void Awake(){ targetsInRange = new List<Unit> (); node = NeuralNode.create (NeuralNode.NodeType.FULLCOLOR); targetsSeen = 0; SetRange (this.range); transform.Find ("Range").gameObject.GetComponent<MeshRenderer> ().enabled = false; this.aimPoint = Instantiate (aimPoint); }
public override NeuralNode Clone() { ColorNode res = (ColorNode)NeuralNode.create(NodeType.FULLCOLOR); res.SetWeights(actualWeights, this.b); res.SetNonzeroIndices(); return(res); }
public NeuralLayer(int numInputs, int numNodes) { numIn = numInputs; layer = new System.Collections.Generic.List <NeuralNode>(numInputs); for (int i = 0; i < numNodes; i++) { layer[i] = new NeuralNode(numInputs); } }
public override NeuralNode Clone() { ColorHistNode res = (ColorHistNode)NeuralNode.create(NodeType.COLORHIST); res.SetWeights(actualWeights, this.b); res.SetNonzeroIndices(); res.totalNegativeWeights = this.totalNegativeWeights; res.totalPositiveWeights = this.totalPositiveWeights; return(res); }
public void train() { if (castle.canPurchase(getPrice())) { // Start training! NeuralNode node = NeuralNode.create(neuralNodeType); cFire.node = node; float noise = getNoise(); for (int i = 1; i <= TOTAL_ENEMY_UNITS; i++) { for (int j = 0; j < getQuantityOfEnemy(i); j++) { Unit unit = uGen.MakeUnit(true, ENEMY_INDICES[i - 1], farOff, noise, true); if (unit is UnitAnimated) { UnitAnimated ua = (UnitAnimated)unit; Texture2D[] texes = ua.textures; int texIdx = j % texes.Length; ua.setTexture(texes[texIdx]); } node.AddToTrainingSet(unit, isEnemyTarget(i)); unit.DestroyMe(); } } for (int i = 1; i <= TOTAL_ALLY_UNITS; i++) { for (int j = 0; j < getQuantityOfAlly(i); j++) { Unit unit = uGen.MakeUnit(false, ALLY_INDICES[i - 1], farOff, noise, true); if (unit is UnitAnimated) { UnitAnimated ua = (UnitAnimated)unit; Texture2D[] texes = ua.textures; int texIdx = j % texes.Length; ua.setTexture(texes[texIdx]); } node.AddToTrainingSet(unit, isAllyTarget(i)); unit.DestroyMe(); } } node.LearnUnits(); castle.makePurchase(getPrice()); Time.timeScale = previousTimeScale; // Close window GetComponent <Canvas> ().enabled = false; Camera.main.GetComponent <BuildingPlacement> ().placeableBuildingOld.SetSelected(true); } }
private bool IsInClosedNodes(NeuralNode n, List <NeuralNode> list) { for (int i = 0; i < list.Count; ++i) { if (list[i] == n) { return(true); } } return(false); }
private GraphicNode GetGNodeByNeuralNode(NeuralNode n) { foreach (GraphicNode gn in gNodes) { if (gn.node == n) { return(gn); } } return(null); }
private void GenerateNode() { if (network == null) { return; } NeuralNode node = new NeuralNode(network, order, BiasValue); network.AddNode(node); netWin.UpdateGraphics(); }
public NodeLink(NeuralNode Child, NeuralNode Parent, double Weight) { if (Child.Affinity == NeuralNodeAffinity.Prediction) throw new Exception("A Prediction node cannot be linked as a child"); if (Parent.Affinity == NeuralNodeAffinity.Static) throw new Exception("A static node cannot be linked as a parent"); if (Parent.Affinity == NeuralNodeAffinity.Reference) throw new Exception("A reference node cannot be linked as a parent"); this.Child = Child; this.Parent = Parent; this.WEIGHT = Weight; }
public override double Render(double[] Data, NeuralNode Node) { double d = 0; foreach (NodeLink n in Node.Children) { n.Child.Render(Data); d += n.WEIGHT * n.Child.MEAN; } return d; }
private static void DecompileHelper(NeuralNode Node, List<NeuralNode> Nodes) { foreach (NodeLink n in Node.Children) { if (!Nodes.Contains(n.Child)) { Nodes.Add(n.Child); DecompileHelper(n.Child, Nodes); } } }
protected void OnTriggerEnter(Collider co) { if (co.tag == "Turret" && co is BoxCollider) { CannonFire cf = co.gameObject.GetComponent <CannonFire> (); if (cf != null) { NeuralNode node = cf.GetNode(); if (node != null) { towersToConfound [node] = new List <int> (); } } } }
protected virtual void OnTriggerExit(Collider co) { if (co.tag == "Turret" && co is BoxCollider) { CannonFire cf = co.gameObject.GetComponent <CannonFire> (); if (cf != null) { NeuralNode node = cf.GetNode(); if (node != null) { List <int> confoundedIndices = towersToConfound [node]; node.ResetWeights(confoundedIndices); node.RemoveFromEnemiesToInform(this); node.InformEnemies(confoundedIndices); } } } } //OnTriggerExit()
protected override MutationData MutateNode(NeuralNode node, NeuralNode ancestorNode) { MutationData data = new MutationData(); node.bias = (ancestorNode.bias + Random.Range(0.0f, 1.0f)) / 2; for (int i = 0; i < node.weights.Length; i++) { float mutation = Random.Range(0.0f, 1.0f); float ancestorWeight = ancestorNode.weights[i]; node.weights[i] = (ancestorWeight + mutation) / 2; data.mutationRate += mutation; data.affectedWeights++; } return(data); }
protected override MutationData MutateNode(NeuralNode node, NeuralNode ancestorNode) { MutationData data = new MutationData(); node.bias = (ancestorNode.bias + Random.Range(-mutationRate, mutationRate)); node.bias = Mathf.Clamp01(node.bias); for (int i = 0; i < node.weights.Length; i++) { float ancestorWeight = ancestorNode.weights[i]; float mutation = Random.Range(-mutationRate, mutationRate); node.weights[i] = Mathf.Clamp01(ancestorWeight + mutation); data.mutationRate += mutation; data.affectedWeights++; } return(data); }
public static NeuralNode create(NodeType nodeType) { NeuralNode res = null; if (nodeType == NodeType.FULLCOLOR) { res = ScriptableObject.CreateInstance <ColorNode> (); } else if (nodeType == NodeType.COLORHIST) { res = ScriptableObject.CreateInstance <ColorHistNode> (); } else if (nodeType == NodeType.GRAYSCALE) { res = ScriptableObject.CreateInstance <GrayscaleNode> (); } // else if (nodeType == NodeType.CONVOLVED) { // res = ScriptableObject.CreateInstance<ConvolvedNode> (); // }else if (nodeType == NodeType.COMBINATION) { // res = ScriptableObject.CreateInstance<CombinationNode> (); // } return(res); }
public void Init(NeuralNode node) { this.node = node; }
public override void LearnUnits() { //I should probably make this a float array. //I'm not sure what kind of memory restrictions we're looking at. //This list of arrays is going to be reclaimed after the method finishes, as is the trainingSet List <double[]> features = new List <double[]> (); int featureLength = -1; //Gets the relevant data out of the training set foreach (PhantomUnit u in trainingSet) { Texture tex = u.tex; if (tex is Texture2D) { Texture2D tex2D = (Texture2D)tex; Color[] pixels = tex2D.GetPixels(); if (featureLength == -1) { featureLength = pixels.Length * 3; unitWidth = tex2D.width; unitHeight = tex2D.height; } //I don't actually check that the width and height are correct, just that width*height is correct. I'm going to assume it'll work out. if (pixels.Length * 3 == featureLength) { //This is really IMPORTANT. //The last spot in unit features is reserved for the unit identity (0 for Enemy, 1 for Ally) //Don't iterate over unitFeatures or its full length. double[] unitFeatures = new double[featureLength + 1]; //Assigns the pixel values for each of the colors in the pattern {r,g,b,r,g,b,...) for (int i = 0; i < pixels.Length; i++) { Color c = pixels [i]; unitFeatures [3 * i] = c.r; unitFeatures [3 * i + 1] = c.g; unitFeatures [3 * i + 2] = c.b; } unitFeatures [featureLength] = u.identity; features.Add(unitFeatures); } else { Debug.Log("Unit has incorrect dimensions to be analyzed: " + u.ToString()); } } else if (tex is RenderTexture) { RenderTexture texRend = (RenderTexture)tex; Debug.Log("This is a RenderTexture"); //I don't have the code to get the pixels for this yet } else { Debug.Log("I'm not sure what Texture this is or what to do with it."); } } //for weights = new double[featureLength]; b = 0; for (int it = 0; it < iters; it++) { itersUsed = it + 1; int misses = 0; //Shuffles the feature list NeuralNode.Shuffle(features); foreach (double[] fs in features) { int trueIdentity = (int)Mathf.Round((float)fs [featureLength]); int f = (int)Unit.ALLY_IDENTITY; if (calculateZ(fs) < 0) { f = (int)Unit.ENEMY_IDENTITY; } misses += Mathf.Abs(f - trueIdentity); for (int i = 0; i < featureLength; i++) { weights [i] = weights [i] + learningRate * fs[i] * (trueIdentity - f); } b = b + learningRate * (trueIdentity - f); } //for each of the feature arrays if (misses == 0) { break; } } //for iterations actualWeights = new double[weights.Length]; System.Array.Copy(weights, actualWeights, weights.Length); actualB = b; SetNonzeroIndices(); //Notice that I am clearing out the training set here. //Keeping the references is not necessary and will just take up space. //Being able to get rid of them is sort of the point of making a model. foreach (PhantomUnit u in trainingSet) { Destroy(u); } trainingSet.Clear(); isAILearned = true; }
public void RevertIndices(NeuralNode node, List <int> indicesReverted) { List <int> indicesIveConfounded = towersToConfound[node]; indicesIveConfounded.RemoveAll(i => indicesReverted.Contains(i)); }
void OnGUI() { if (isSelected) { //Debug.Log ("Selected"); // GUI.Button(new Rect(Screen.width /2, Screen.height / 20, 100, 30), bName); if (!isShowingRange) { // Transform t = transform.parent; // Debug.Log (t.name); // Transform rng = t.Find ("Range"); // rng.gameObject.GetComponent<MeshRenderer> ().enabled = true; transform.parent.Find("Turret").Find("Range").gameObject.GetComponent <MeshRenderer> ().enabled = true; isShowingRange = true; } // Add nodes to UI CannonFireAOE cnfire = transform.parent.Find("Turret").GetComponent <CannonFireAOE>(); NeuralNode n = cnfire.GetNode(); Texture2D a = n.getAllyTexture(); Texture2D e = n.getEnemyTexture(); Texture2D c = n.GetTargetTex(); Texture2D f = n.getFeatureTexture(); Sprite sa = Sprite.Create(a, new Rect(0, 0, a.width, a.height), new Vector2(0.5f, 0.5f)); Sprite se = Sprite.Create(e, new Rect(0, 0, e.width, e.height), new Vector2(0.5f, 0.5f)); Sprite sc = Sprite.Create(c, new Rect(0, 0, c.width, c.height), new Vector2(0.5f, 0.5f)); Sprite sf = Sprite.Create(f, new Rect(0, 0, f.width, f.height), new Vector2(0.5f, 0.5f)); nodeMan.setAllySprite(sa); nodeMan.setEnemySprite(se); nodeMan.setTargetSprite(sc); nodeMan.setFeatureSprite(sf); nodeMan.setB(n.b); nodeMan.setZ(n.lastZ); nodeMan.numEneInRange = cnfire.numEnemiesInRange; nodeMan.numAllyInRange = cnfire.numAlliesInRange; // Place tower picture and name GameObject.Find("UIManager").GetComponent <InfoManager>().setTowerName(bName); Sprite icon = null; string sellPrice = ""; if (bName == "Basic Tower") { //Debug.Log("Basic Tower Selected"); icon = Resources.Load <Sprite>("Sprites/BasicTower"); sellPrice = "$140"; } else if (bName == "Radial Tower") { //Debug.Log("Radial Tower Selected"); icon = Resources.Load <Sprite>("Sprites/RadialTower"); sellPrice = "$210"; } else if (bName == "Sniper Tower") { //Debug.Log("Sniper Tower Selected"); icon = Resources.Load <Sprite>("Sprites/SniperTower"); sellPrice = "$350"; } else if (bName == "Machine Tower") { //Debug.Log("Machine Tower Selected"); icon = Resources.Load <Sprite>("Sprites/MachineTower"); sellPrice = "$350"; } else if (bName == "Splash Tower") { //Debug.Log("Splash Tower Selected"); icon = Resources.Load <Sprite>("Sprites/SplashTower"); sellPrice = "$525"; } else { icon = Resources.Load <Sprite>("Sprites/black"); sellPrice = ""; } //Debug.Log(sellPrice); GameObject.Find("UIManager").GetComponent <InfoManager>().setTowerImage(icon); GameObject.Find("UIManager").GetComponent <InfoManager>().setTowerPrice(sellPrice); } else if (isShowingRange) { transform.parent.Find("Turret").Find("Range").gameObject.GetComponent <MeshRenderer> ().enabled = false; isShowingRange = false; // Remove nodes from UI // I'm not so sure we want to do that. We may as well let the player casually look at the masks and z. // nodeMan.resetAll(); GameObject.Find("UIManager").GetComponent <InfoManager>().resetAll(); } }
public static bool IsCircular(NeuralNode Node) { return AllChildren(Node).Contains(Node); }
public static List<NeuralNode> AllChildren(NeuralNode Node) { List<NeuralNode> nodes = new List<NeuralNode>(); DecompileHelper(Node, nodes); return nodes; }
protected virtual MutationData MutateNode(NeuralNode node, NeuralNode ancestorNode) { return(null); }
public NodeLink(NeuralNode Child, NeuralNode Parent) : this(Child, Parent, 0) { }
public GraphicNode(NeuralNode n, Vector2 p, float w, float h, GUIStyle s) { rect = new Rect(p.x, p.y, w, h); style = s; node = n; }
public abstract double Render(double[] Data, NeuralNode Node);
public NeuralLink(NeuralNode prevNode, NeuralNode nextNode, double weight = 1) { this.prevNode = prevNode; this.nextNode = nextNode; this.Weight = rand.NextDouble() - 0.5; }