public void InitialiseNetwork()
        {
            //Clear all the nodes
            foreach (Node Node in Nodes)
            {
                Node.ClearValue();
            }


            //Check if we have 'shortcuts' to the input and output nodes
            if (InputNodes.Count == 0 || OutputNodes.Count == 0)
            {
                InputNodes.Clear();
                OutputNodes.Clear();

                foreach (Node Node in Nodes)
                {
                    switch (Node.Type)
                    {
                    case eNeuralNodeType.eInput:
                        InputNodes.Add(Node);
                        break;

                    case eNeuralNodeType.eOutput:
                        OutputNodes.Add(Node);
                        break;
                    }
                }
            }
        }
 public MultilayerPerceptron(int nInputs, int nHidden, int nOutputs)
 {
     for (int i = 0; i < nOutputs; ++i)
     {
         OutputNodes.Add(new Node());
     }
     for (int i = 0; i < nHidden; ++i)
     {
         var node = new Node();
         foreach (var hiddenNode in HiddenNodes)
         {
             node.Connectors.Add(new Connector()
             {
                 Weight = 1, Node = hiddenNode
             });
         }
     }
     for (int i = 0; i < nInputs; ++i)
     {
         var node = new Node();
         foreach (var output in OutputNodes)
         {
             node.Connectors.Add(new Connector()
             {
                 Weight = 1, Node = output
             });
         }
         InputNodes.Add(node);
     }
 }
Example #3
0
 protected void AddOutputNode(BaseOutputNode node)
 {
     node.OnConnected  += OnNodeConnected;
     node.OnDisconnect += OnNodeDisconnected;
     OutputNodes.Add(node);
     OnNodeAdded?.Invoke(this, node);
 }
Example #4
0
        public virtual void TryAndProcess()
        {
            int c = Nodes.Count;

            for (int i = 0; i < c; i++)
            {
                Node n = Nodes[i];

                if (OutputNodes.Contains(n.Id))
                {
                    continue;
                }
                if (InputNodes.Contains(n.Id))
                {
                    continue;
                }

                n.TryAndProcess();
            }

            c = InputNodes.Count;

            for (int i = 0; i < c; i++)
            {
                Node n;
                if (NodeLookup.TryGetValue(InputNodes[i], out n))
                {
                    InputNode inp = (InputNode)n;
                    inp.TryAndProcess();
                }
            }
        }
Example #5
0
 protected override void CreateNodes(ref Blocks.BlockBase root)
 {
     this.Interpolate = true;
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "input1", "in1"));
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "input2", "in2"));
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "select", "sel"));
     OutputNodes.Add(new Blocks.BlockOutputNode(ref root, "output", "out"));
 }
 protected override void CreateNodes(ref Blocks.BlockBase root)
 {
     InputNodes = new List <Blocks.BlockInputNode>();
     foreach (var item in _inputs)
     {
         InputNodes.Add(new Blocks.BlockInputNode(ref root, item, item));
     }
     OutputNodes.Add(new Blocks.BlockOutputNode(ref root, "output", "out"));
 }
        public void ClearNetwork()
        {
            //clear the vector of pointers to the input nodes
            InputNodes.Clear();
            OutputNodes.Clear();

            //delete all nodes from the network and clear the
            //vector
            Nodes.Clear();
        }
        public void AddNode(int plLayer, eNeuralNodeType peType)
        {
            Node       oNode;
            Connection oConnection;
            int        lNodeIndex;

            //create node
            oNode          = new Node(peType, plLayer);
            oNode.Treshold = 0;
            oNode.Id       = Nodes.Count;
            Nodes.Add(oNode);

            switch (peType)
            {
            case eNeuralNodeType.eInput:
            {
                InputNodes.Add(oNode);
                break;
            }

            case eNeuralNodeType.eOutput:
            {
                OutputNodes.Add(oNode);
                break;
            }
            }

            lNodeIndex = Nodes.Count - 1;

            //create connections to all nodes in previous layer
            for (int lIndex = 0; lIndex < (int)Nodes.Count; lIndex++)
            {
                if (Nodes[lIndex].lLayer == plLayer - 1)
                {
                    oConnection = new Connection(lIndex, lNodeIndex);

                    oConnection.fWeight = 0;

                    oNode.Connections.Add(oConnection);
                }
            }

            //create connections to all nodes in next layer
            foreach (Node Node in Nodes)
            {
                if (Node.lLayer == plLayer + 1)
                {
                    oConnection = new Connection(lNodeIndex, Node.Id);

                    oConnection.fWeight = 0;

                    Node.Connections.Add(oConnection);
                }
            }
        }
Example #9
0
        /// <summary>
        /// this is used in GraphInstances
        /// To resize proportionate to new size
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public virtual void ResizeWith(int width, int height)
        {
            this.width  = width;
            this.height = height;

            int c = Nodes.Count;

            for (int i = 0; i < c; i++)
            {
                Node n = Nodes[i];

                if (OutputNodes.Contains(n.Id))
                {
                    continue;
                }
                if (InputNodes.Contains(n.Id))
                {
                    continue;
                }

                if (n is BitmapNode)
                {
                    BitmapNode bn = (BitmapNode)n;
                    bn.TryAndProcess();
                }
                else
                {
                    Point osize;

                    if (OriginSizes.TryGetValue(n.Id, out osize))
                    {
                        float wratio = width / (float)osize.X;
                        float hratio = height / (float)osize.Y;

                        int fwidth  = (int)Math.Min(4096, Math.Max(16, Math.Round(osize.X * wratio)));
                        int fheight = (int)Math.Min(4096, Math.Max(16, Math.Round(osize.Y * hratio)));

                        n.Width  = fwidth;
                        n.Height = fheight;
                    }
                }
            }

            c = InputNodes.Count;

            for (int i = 0; i < c; i++)
            {
                Node n;
                if (NodeLookup.TryGetValue(InputNodes[i], out n))
                {
                    InputNode inp = (InputNode)n;
                    inp.TryAndProcess();
                }
            }
        }
Example #10
0
        private void N_OnOutputAddedToNode(Node n, NodeOutput inp)
        {
            UINodePoint outpoint = new UINodePoint(this, Graph);

            outpoint.Output            = inp;
            outpoint.VerticalAlignment = VerticalAlignment.Center;
            OutputNodes.Add(outpoint);
            OutputStack.Children.Add(outpoint);
            outpoint.UpdateColor();

            ResizeHeight();
        }
Example #11
0
        private void N_OnOutputRemovedFromNode(Node n, NodeOutput inp)
        {
            var uinp = OutputNodes.Find(m => m.Output == inp);

            if (uinp != null)
            {
                OutputStack.Children.Remove(uinp);
                OutputNodes.Remove(uinp);
            }

            ResizeHeight();
        }
Example #12
0
        public override Task ProcessRequest(IRequestContext context)
        {
            if (Disabled)
            {
                context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Least connected load balancer '{Name}' is disabled");

                return(Task.Run(() =>
                {
                    context.Outgoing.StatusCode = 503;
                    context.Outgoing.ReasonPhrase = "Balancer " + Name + " is disabled";
                    context.Outgoing.SendHeaders(context);
                }));
            }

            var output = OutputNodes
                         .Where(o => !o.Disabled && o.Node != null)
                         .OrderBy(o => o.ConnectionCount)
                         .FirstOrDefault();

            if (output == null)
            {
                context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Least connected load balancer '{Name}' has no enabled outputs");

                return(Task.Run(() =>
                {
                    context.Outgoing.StatusCode = 503;
                    context.Outgoing.ReasonPhrase = "Balancer " + Name + " has no enabled outputs";
                    context.Outgoing.SendHeaders(context);
                }));
            }

            context.Log?.Log(LogType.Step, LogLevel.Standard, () => $"Least connected load balancer '{Name}' routing request to '{output.Name}'");

            output.IncrementConnectionCount();
            var trafficAnalyticInfo = output.TrafficAnalytics.BeginRequest();

            var task = output.Node.ProcessRequest(context);

            if (task == null)
            {
                output.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                return(null);
            }

            return(task.ContinueWith(t =>
            {
                output.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                output.DecrementConnectionCount();
            }));
        }
Example #13
0
        private void N_OnOutputRemovedFromNode(Node n, NodeOutput inp, NodeOutput previous = null)
        {
            var uinp = OutputNodes.Find(m => m.Output == inp);

            if (uinp != null)
            {
                //whoops forgot to dispose
                //on the uinodepoint to remove previous connects
                //etc
                uinp.Dispose();
                OutputStack.Children.Remove(uinp);
                OutputNodes.Remove(uinp);
            }
        }
Example #14
0
        /// <summary>
        /// This is used in GraphInstanceNodes
        /// We only save the final buffers connected to the outputs,
        /// and release all other buffers to save video card memory
        /// since it is all in video memory and shader based
        /// we do not have to transfer data to the video card
        /// so it will be relatively fast still to update
        /// when we have to recreate the textures
        /// </summary>
        public virtual void ReleaseIntermediateBuffers()
        {
            foreach (Node n in Nodes)
            {
                if (OutputNodes.Contains(n.Id))
                {
                    continue;
                }

                if (n.Buffer != null)
                {
                    n.Buffer.Release();
                }
            }
        }
Example #15
0
 public void RemoveNode(INode node)
 {
     if (node is BaseOutputNode)
     {
         var sp = spOutputNodes.Children.OfType <StackPanel>().Where(x => x.Name == "nodeContainer" && x.Tag == node).FirstOrDefault();
         spOutputNodes.RemoveChild(sp);
         OutputNodes.RemoveAll(x => x.Node == node);
     }
     else if (node is InputNode)
     {
         var sp = spInputNodes.Children.OfType <StackPanel>().Where(x => x.Name == "nodeContainer" && x.Tag == node).FirstOrDefault();
         spInputNodes.RemoveChild(sp);
         InputNodes.RemoveAll(x => x.Node == node);
     }
 }
Example #16
0
        protected void RemoveNode(BaseNode node)
        {
            node.Disconnect();
            node.OnConnected  -= OnNodeConnected;
            node.OnDisconnect -= OnNodeDisconnected;
            if (node is BaseOutputNode)
            {
                OutputNodes.Remove((BaseOutputNode)node);
            }
            else
            {
                InputNodes.Remove((BaseInputNode)node);
            }

            OnNodeRemoved?.Invoke(this, node);
        }
        public FirstLevelEquipment(int number, Point stackLocation) : base(
                "АПП",
                "First Level Equipment " + number,
                new Point(stackLocation.X, number * (verticalOffset) + stackLocation.Y))
        {
            Height          = 370;
            inputEquipments = new List <IndividualEquipment>();
            CreateInputNodes();
            OutputNodes.Add(new Point(Location.X + Width, Location.Y + Height / 2));
            int numberIE = 0;

            foreach (Point inputNode in inputNodes)
            {
                inputEquipments.Add(new IndividualEquipment(false, numberIE, number, GetStackLocationIE(number, stackLocation)));
                arrows.Add(new BigArrow(inputEquipments[numberIE++].OutputNodes[0], inputNode));
            }
        }
Example #18
0
 private void Module_OnNodeAdded(object sender, INode node)
 {
     if (node is BaseOutputNode)
     {
         if (!OutputNodes.Any(x => x.Node == node))
         {
             AddNode(node);
         }
     }
     else if (node is BaseInputNode)
     {
         if (!InputNodes.Any(x => x.Node == node))
         {
             AddNode(node);
         }
     }
 }
Example #19
0
        private void N_OnOutputAddedToNode(Node n, NodeOutput inp, NodeOutput previous = null)
        {
            UINodePoint outpoint = new UINodePoint(this, Graph);

            outpoint.Output            = inp;
            outpoint.VerticalAlignment = VerticalAlignment.Center;
            OutputNodes.Add(outpoint);
            OutputStack.Children.Add(outpoint);
            outpoint.UpdateColor();

            if (previous != null)
            {
                foreach (var cinp in inp.To)
                {
                    LoadConnection(cinp.Node.Id);
                }
            }
        }
Example #20
0
        public virtual void Remove(Node n)
        {
            if (n is OutputNode)
            {
                OutputNodes.Remove(n.Id);
            }
            else if (n is InputNode)
            {
                InputNodes.Remove(n.Id);
            }

            NodeLookup.Remove(n.Id);
            if (Nodes.Remove(n))
            {
                n.OnUpdate -= N_OnUpdate;
            }
            n.Dispose();
        }
Example #21
0
 public IndividualEquipment(bool small, int equipmentNumber, int signalNumber, Point stackLocation) : base(
         "АИП",
         "Individual Equipment " + equipmentNumber,
         new Point(stackLocation.X, equipmentNumber * (verticalOffset) + stackLocation.Y))
 {
     this.small   = small;
     inputNumbers = new List <SchemaLablel>();
     inputNodes.Add(new Point(Location.X, Location.Y));
     inputNodes.Add(new Point(Location.X, Location.Y + Height));
     OutputNodes.Add(new Point(Location.X + Width, Location.Y + Height / 2));
     foreach (Point inputNode in inputNodes)
     {
         bool isFirst = (inputNodes.IndexOf(inputNode) == 0);
         arrows.Add(new BigArrow(new Point(inputNode.X + inputArrowOffset, inputNode.Y), inputNode));
         inputNumbers.Add(new SchemaLablel(
                              Convert.ToString(GetInputNumberValue(equipmentNumber, signalNumber, isFirst)),
                              "Input " + (GetInputNumberValue(equipmentNumber, signalNumber, isFirst)),
                              new Point(inputNode.X + inputNumberOffsetX, inputNode.Y + inputNumberOffsetY)));
     }
 }
        private void BindNodesCountToForm(frmMain form)
        {
            form.OnInputNodesValueChanged += (newValue) =>
            {
                if (newValue > InputNodes.Count)
                {
                    for (int i = newValue - InputNodes.Count; i > 0; i--)
                    {
                        var inNode = new InputNode(this, "Schema", "DataLocation");
                        AddInputNode(inNode);
                    }
                }
                else if (newValue < InputNodes.Count)
                {
                    for (int i = InputNodes.Count - newValue; i > 0; i--)
                    {
                        RemoveNode(InputNodes.Last());
                    }
                }
            };

            form.OnOutputNodesValueChanged += (newValue) =>
            {
                if (newValue > OutputNodes.Count)
                {
                    for (int i = newValue - OutputNodes.Count; i > 0; i--)
                    {
                        var outNode = new OutputNode(this, "Schema", "DataLocation");
                        outNode.State = new ModuleState();
                        AddOutputNode(outNode);
                    }
                }
                else if (newValue < OutputNodes.Count)
                {
                    for (int i = OutputNodes.Count - newValue; i > 0; i--)
                    {
                        RemoveNode(OutputNodes.Last());
                    }
                }
            };
        }
Example #23
0
        public virtual bool Add(Node n)
        {
            if (NodeLookup.ContainsKey(n.Id))
            {
                return(false);
            }

            if (n is OutputNode)
            {
                OutputNodes.Add(n.Id);
            }
            else if (n is InputNode)
            {
                InputNodes.Add(n.Id);
            }

            NodeLookup[n.Id] = n;
            Nodes.Add(n);

            n.OnUpdate += N_OnUpdate;

            return(true);
        }
Example #24
0
 protected override void CreateNodes(ref Blocks.BlockBase root)
 {
     this.Frequencies = new string[] { "10", "20" };
     this.Length      = this.SampleRate = 22100;
     OutputNodes.Add(new Blocks.BlockOutputNode(ref root, "output", "out"));
 }
Example #25
0
        public override Task ProcessRequest(IRequestContext context)
        {
            if (Disabled)
            {
                context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Sticky session load balancer '{Name}' is disabled by configuration");

                return(Task.Run(() =>
                {
                    context.Outgoing.StatusCode = 503;
                    context.Outgoing.ReasonPhrase = "Balancer " + Name + " is disabled";
                    context.Outgoing.SendHeaders(context);
                }));
            }

            if (string.IsNullOrEmpty(SessionCookie))
            {
                context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Sticky session load balancer '{Name}' has no cookie name configured");

                return(Task.Run(() =>
                {
                    context.Outgoing.StatusCode = 503;
                    context.Outgoing.ReasonPhrase = "Balancer " + Name + " has no session cookie configured";
                    context.Outgoing.SendHeaders(context);
                }));
            }

            var cookies   = context.Incoming.GetCookies();
            var sessionId = cookies.ContainsKey(SessionCookie) ? cookies[SessionCookie] : null;
            TrafficAnalyticInfo trafficAnalyticInfo;

            if (string.IsNullOrEmpty(sessionId))
            {
                context.Log?.Log(LogType.Logic, LogLevel.Detailed, () => $"No session cookie in incoming request");

                var output = OutputNodes
                             .Where(o => !o.Disabled && o.Node != null)
                             .OrderBy(o => o.ConnectionCount)
                             .ThenBy(o => o.SessionCount)
                             .FirstOrDefault();

                if (output == null)
                {
                    context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Sticky session load balancer '{Name}' has no enabled outputs");

                    return(Task.Run(() =>
                    {
                        context.Outgoing.StatusCode = 503;
                        context.Outgoing.ReasonPhrase = "Balancer " + Name + " has no enabled outputs";
                        context.Outgoing.SendHeaders(context);
                    }));
                }

                trafficAnalyticInfo = output.TrafficAnalytics.BeginRequest();
                output.IncrementConnectionCount();

                context.Outgoing.OnSendHeaders.Add(ctx =>
                {
                    context.Log?.Log(LogType.Logic, LogLevel.Detailed, () => $"Sticky session load balancer '{Name}' looking for a Set-Cookie header in the response");

                    if (ctx.Outgoing.Headers.TryGetValue("Set-Cookie", out var setCookieHeaders))
                    {
                        var setSession = setCookieHeaders.FirstOrDefault(c => c.StartsWith(SessionCookie + "="));
                        if (setSession != null)
                        {
                            context.Log?.Log(LogType.Logic, LogLevel.Detailed, () => $"A session cookie was found, this caller will be sticky to output '{output.Name}'");

                            var start = SessionCookie.Length + 1;
                            var end   = setSession.IndexOf(';', start);
                            if (end < 0)
                            {
                                end = setSession.Length;
                            }
                            sessionId = setSession.Substring(start, end - start);

                            output.IncrementSessionCount();
                            lock (_sessionNodes) _sessionNodes[sessionId] = output;
                            lock (_sessionExpiry) _sessionExpiry.Add(new Tuple <string, DateTime>(sessionId, DateTime.UtcNow + SessionDuration));
                        }
                    }
                });

                context.Log?.Log(LogType.Step, LogLevel.Standard, () => $"Sticky session load balancer '{Name}' routing request to '{output.Name}'");

                var task = output.Node.ProcessRequest(context);

                if (task == null)
                {
                    output.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                    return(null);
                }

                return(task.ContinueWith(t =>
                {
                    output.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                    output.DecrementConnectionCount();
                }));
            }

            NodeOutput sessionOutput;
            bool       hasSession;

            lock (_sessionNodes) hasSession = _sessionNodes.TryGetValue(sessionId, out sessionOutput);

            if (!hasSession)
            {
                context.Log?.Log(LogType.Logic, LogLevel.Standard, () => $"No session found for session id {sessionId}");

                sessionOutput = OutputNodes
                                .Where(o => !o.Disabled && o.Node != null)
                                .OrderBy(o => o.ConnectionCount)
                                .ThenBy(o => o.SessionCount)
                                .FirstOrDefault();

                if (sessionOutput == null)
                {
                    context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"Sticky session load balancer '{Name}' has no enabled outputs");

                    return(Task.Run(() =>
                    {
                        context.Outgoing.StatusCode = 503;
                        context.Outgoing.ReasonPhrase = "Balancer " + Name + " has no enabled outputs";
                        context.Outgoing.SendHeaders(context);
                    }));
                }

                context.Log?.Log(LogType.Logic, LogLevel.Standard, () => $"Sticking this session to least connected output '{sessionOutput.Name}'");

                sessionOutput.IncrementSessionCount();
                lock (_sessionNodes) _sessionNodes[sessionId] = sessionOutput;
                lock (_sessionExpiry) _sessionExpiry.Add(new Tuple <string, DateTime>(sessionId, DateTime.UtcNow + SessionDuration));
            }

            if (sessionOutput.Disabled)
            {
                context.Log?.Log(LogType.Logic, LogLevel.Important, () => $"The sticky output '{sessionOutput.Name}' for load balancer '{Name}' for session id {sessionId} is disabled");

                return(Task.Run(() =>
                {
                    context.Outgoing.StatusCode = 503;
                    context.Outgoing.ReasonPhrase = "Balancer " + Name + " sticky output is down";
                    context.Outgoing.SendHeaders(context);
                }));
            }

            context.Log?.Log(LogType.Step, LogLevel.Standard, () => $"Sticky session load balancer '{Name}' routing request to '{sessionOutput.Name}'");

            trafficAnalyticInfo = sessionOutput.TrafficAnalytics.BeginRequest();
            sessionOutput.IncrementConnectionCount();

            var sessionTask = sessionOutput.Node.ProcessRequest(context);

            if (sessionTask == null)
            {
                sessionOutput.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                return(null);
            }

            return(sessionTask.ContinueWith(t =>
            {
                sessionOutput.TrafficAnalytics.EndRequest(trafficAnalyticInfo);
                sessionOutput.DecrementConnectionCount();
            }));
        }
Example #26
0
        public void AddNode(INode node)
        {
            string colorName = "";

            switch (node.GetNodeType())
            {
            case INodeType.LINE:
                colorName = ConfigurationManager
                            .ConnectionStrings["LineColor"]
                            .ConnectionString;
                break;

            case INodeType.HOOK:
                colorName = ConfigurationManager
                            .ConnectionStrings["HookColor"]
                            .ConnectionString;
                break;

            default:
                colorName = "Fuchsia";
                logger.Warn("No color assigned for input node type");
                // Logger.Log(Severity.WARN, LogCategory.CONTROL, "No color assigned for input node type");
                break;
            }



            var innerContainer = new StackPanel();

            innerContainer.Name              = "nodeContainer";
            innerContainer.Tag               = node;
            innerContainer.Orientation       = Orientation.Vertical;
            innerContainer.VerticalAlignment = VerticalAlignment.Top;


            var label = new Label();

            label.Padding           = new Thickness(0);
            label.Content           = node.GetDisplayName();
            label.VerticalAlignment = VerticalAlignment.Bottom;

            innerContainer.Children.Add(label);

            var circleControl = CreateNodeVisual(colorName);

            circleControl.VerticalAlignment = VerticalAlignment.Top;

            innerContainer.Children.Add(circleControl);


            if (node is BaseOutputNode)
            {
                innerContainer.HorizontalAlignment = HorizontalAlignment.Left;
                label.HorizontalAlignment          = HorizontalAlignment.Left;
                circleControl.HorizontalAlignment  = HorizontalAlignment.Left;

                OutputNodes.Add(new RenderNode(this, circleControl, node));
                spOutputNodes.Children.Add(innerContainer);
            }
            else if (node is InputNode)
            {
                innerContainer.HorizontalAlignment = HorizontalAlignment.Right;
                label.HorizontalAlignment          = HorizontalAlignment.Right;
                circleControl.HorizontalAlignment  = HorizontalAlignment.Right;

                InputNodes.Add(new RenderNode(this, circleControl, node));
                spInputNodes.Children.Add(innerContainer);
            }
        }
Example #27
0
 protected override void CreateNodes(ref Blocks.BlockBase root)
 {
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "actual", "tx", "transmitted bitstream"));
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "actual", "rx", "received bitstream"));
     OutputNodes.Add(new Blocks.BlockOutputNode(ref root, "ber", "ber", "scalar value representing ber"));
 }
Example #28
0
 protected override void CreateNodes(ref Blocks.BlockBase root)
 {
     Operation = LineCodingOps.Encode; LineCoding = LineCodings.None;
     InputNodes.Add(new Blocks.BlockInputNode(ref root, "instream", "in"));
     OutputNodes.Add(new Blocks.BlockOutputNode(ref root, "outstream", "out"));
 }
Example #29
0
        public bool[] Propagate(int[] inputs)
        {
            var inputNodes = InputNodes;

            if (inputs.Length != inputNodes.Count)
            {
                throw new Exception("Number of inputs does not match number of genome inputs");
            }

            var connectionsToPropagate = ConnectionGenes.Values.Where(cg => cg.IsEnabled).ToList();

            if (connectionsToPropagate.Count == 0)
            {
                return(OutputNodes.Select(x => x.Value > 0).ToArray());
            }

            foreach (var node in NodeGenes.Values)
            {
                node.Value   = 0;
                node.IsReady = false;
            }

            for (int i = 0; i < inputs.Length; i++)
            {
                inputNodes[i].Value   = inputs[i];
                inputNodes[i].IsReady = true;
            }


            while (connectionsToPropagate.Count != 0)
            {
                var propagatedConnections = new List <ConnectionGene>();

                foreach (var connectionGene in connectionsToPropagate)
                {
                    var previouesNode = NodeGenes[connectionGene.PreviousNodeId];
                    if (!previouesNode.IsReady)
                    {
                        continue;
                    }
                    var nextNode = NodeGenes[connectionGene.NextNodeId];

                    nextNode.Value += previouesNode.Value * connectionGene.Weight;
                    propagatedConnections.Add(connectionGene);

                    if (!connectionsToPropagate.Any(cg => cg.NextNodeId == connectionGene.NextNodeId && cg != connectionGene))
                    {
                        nextNode.Value   = ActivationFunctions.Sigmoid.Count(nextNode.Value);
                        nextNode.IsReady = true;
                    }
                }

                // No changes in propagation; Input values cannot be passed further
                if (propagatedConnections.Count == 0)
                {
                    break;
                }

                foreach (var propagatedConnectionGene in propagatedConnections)
                {
                    connectionsToPropagate.Remove(propagatedConnectionGene);
                }
            }

            return(OutputNodes.Select(x => x.Value > 0).ToArray());
        }
 public override string ToString()
 {
     return(string.Format("{0} Inputs, {1} Outputs which {2} of them are BiasNodes, Total {3} Connections.",
                          InputNodes.Count, OutputNodes.Count, OutputNodes.Count(c => c is BiasNode), Connections.Count));
 }