void _Create(GraphFactory graph, int inputSize, float[] memory, string memoryId)
        {
            _inputSize = inputSize;
            int hiddenLayerSize = memory.Length;

            _memory = new MemoryFeeder(memory, null, memoryId);
            _state  = new MemoryFeeder(new float[memory.Length]);
            _input  = new FlowThrough();
            var Wf    = graph.Connect(inputSize, _input).AddFeedForward(hiddenLayerSize, "Wf");
            var Wi    = graph.Connect(inputSize, _input).AddFeedForward(hiddenLayerSize, "Wi");
            var Wo    = graph.Connect(inputSize, _input).AddFeedForward(hiddenLayerSize, "Wo");
            var Wc    = graph.Connect(inputSize, _input).AddFeedForward(hiddenLayerSize, "Wc");
            var Uf    = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Uf");
            var Ui    = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Ui");
            var Uo    = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Uo");
            var Uc    = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Uc");
            var Ft    = graph.Add(Wf, Uf).Add(graph.SigmoidActivation("Ft"));
            var It    = graph.Add(Wi, Ui).Add(graph.SigmoidActivation("It"));
            var Ot    = graph.Add(Wo, Uo).Add(graph.SigmoidActivation("Ot"));
            var ftCt1 = graph.Multiply(hiddenLayerSize, Ft.LastNode, _state);
            var Ct    = graph.Add(ftCt1, graph.Multiply(It, graph.Add(Wc, Uc).Add(graph.TanhActivation()))).
                        AddForwardAction(_state.SetMemoryAction);

            _output = graph.Multiply(Ot, Ct.Add(graph.TanhActivation())).
                      AddForwardAction(_memory.SetMemoryAction)
                      //.Add(new HookErrorSignal(context => {
                      //    if (_lastBackpropagation != null) {
                      //        foreach (var item in _lastBackpropagation)
                      //            context.AppendErrorSignal(item.Value, item.Key);
                      //        _lastBackpropagation = null;
                      //    }
                      //}))
                      .LastNode;
            _start = new OneToMany(SubNodes, bp => _lastBackpropagation = bp);
        }
        public void TestRecurrent()
        {
            var data        = BinaryIntegers.Addition(100, false).Split(0);
            var graph       = new GraphFactory(_lap);
            var errorMetric = graph.ErrorMetric.BinaryClassification;

            graph.CurrentPropertySet.Use(graph.GradientDescent.Adam).Use(
                graph.GaussianWeightInitialisation(false, 0.1f, GaussianVarianceCalibration.SquareRoot2N));

            // create the engine
            var trainingData = graph.CreateDataSource(data.Training);
            var testData     = trainingData.CloneWith(data.Test);
            var engine       = graph.CreateTrainingEngine(trainingData, learningRate: 0.01f, batchSize: 16);

            // build the network
            const int HIDDEN_LAYER_SIZE = 32, TRAINING_ITERATIONS = 5;
            var       memory  = new float[HIDDEN_LAYER_SIZE];
            var       network = graph.Connect(engine).AddSimpleRecurrent(graph.ReluActivation(), memory).
                                AddFeedForward(engine.DataSource.OutputSize).Add(graph.ReluActivation()).
                                AddBackpropagationThroughTime(errorMetric);

            // train the network for twenty iterations, saving the model on each improvement
            Models.ExecutionGraph bestGraph = null;
            engine.Train(TRAINING_ITERATIONS, testData, errorMetric, bn => bestGraph = bn.Graph);

            // export the graph and verify it against some unseen integers on the best model
            var executionEngine = graph.CreateEngine(bestGraph ?? engine.Graph);
            var testData2       = graph.CreateDataSource(BinaryIntegers.Addition(8, true));
            var results         = executionEngine.Execute(testData2);
        }
        public override void ReadFrom(GraphFactory factory, BinaryReader reader)
        {
            var inputSize = reader.ReadInt32();
            var memoryId  = reader.ReadString();
            var memory    = FloatVector.ReadFrom(reader);

            if (_memory == null)
            {
                _Create(factory, inputSize, memory.Data, memoryId);
            }
            else
            {
                _memory.Data = memory;
            }
            var Wf = (FeedForward)_input.FindByName("Wf");
            var Wi = (FeedForward)_input.FindByName("Wi");
            var Wo = (FeedForward)_input.FindByName("Wo");
            var Wc = (FeedForward)_input.FindByName("Wc");
            var Uf = (FeedForward)_memory.FindByName("Uf");
            var Ui = (FeedForward)_memory.FindByName("Ui");
            var Uo = (FeedForward)_memory.FindByName("Uo");
            var Uc = (FeedForward)_memory.FindByName("Uc");

            Wf.ReadFrom(factory, reader);
            Wi.ReadFrom(factory, reader);
            Wo.ReadFrom(factory, reader);
            Wc.ReadFrom(factory, reader);
            Uf.ReadFrom(factory, reader);
            Ui.ReadFrom(factory, reader);
            Uo.ReadFrom(factory, reader);
            Uc.ReadFrom(factory, reader);
        }
Esempio n. 4
0
            protected override void OnCacheLoaded()
            {
                var graphDataColor = new GraphData <int>("Fietsdiefstallen per kleur?", "Diefstallen", "Kleur", new List <int>());
                GraphFactory <int> graphFactory = new GraphFactory <int>();
                PlotModel          plotModel    = graphFactory.createGraph(GraphType.Pie, new GraphEffect(), graphDataColor);

                var colorParts = getPieSeries();

                colorParts.Slices.AddRange(Cache.Take(8).Select(color => new PieSlice(color.Color, color.Count)));
                var restCount = Cache.GetRange(8, Cache.Count - 8).Sum(color => color.Count);

                colorParts.Slices.Add(new PieSlice("Overig", restCount));

                plotModel.Series.Add(colorParts);
                var plotView2 = new PlotView
                {
                    BackgroundColor = Color.White,
                    Model           = plotModel
                };

                Padding = new Thickness(0, 0, 0, 0);
                Content = new PlotView
                {
                    BackgroundColor = Color.White,
                    Model           = plotModel
                };
            }
Esempio n. 5
0
 public LifecycleManagingDatabase(Config config, GraphFactory dbFactory, GraphDatabaseFacadeFactory.Dependencies dependencies)
 {
     this._config       = config;
     this._dbFactory    = dbFactory;
     this._dependencies = new AvailabiltyGuardCapturingDependencies(this.setAvailabilityGuard, dependencies);
     this._log          = dependencies.UserLogProvider().getLog(this.GetType());
 }
Esempio n. 6
0
            protected override void OnCacheLoaded()
            {
                var graphDataBrand = new GraphData <int>("Fietsdiefstallen per merk?", "Diefstallen", "Merk", new List <int>());
                GraphFactory <int> graphFactory = new GraphFactory <int>();
                PlotModel          plotModel    = graphFactory.createGraph(GraphType.Pie, new GraphEffect(), graphDataBrand);

                var brandParts = getPieSeries();

                brandParts.Slices.AddRange(Cache.Take(8).Select(brandItem => new PieSlice(brandItem.Brand, brandItem.Count)));
                var restCount = Cache.GetRange(8, Cache.Count - 8).Sum(brand => brand.Count);

                brandParts.Slices.Add(new PieSlice("Overig", restCount));

                plotModel.Series.Add(brandParts);

                var plotView = new PlotView
                {
                    BackgroundColor = Color.White,
                    Model           = plotModel
                };

                Padding = new Thickness(0, 0, 0, 0);
                Content = new PlotView
                {
                    BackgroundColor = Color.White,
                    Model           = plotModel
                };
            }
Esempio n. 7
0
 public TestRunner()
 {
     Factory = new GraphFactory <int, double>();
     Parser  = new DefaultGraphTextLineParser();
     Files   = new HashSet <string>();
     Graphs  = new Dictionary <string, IGraph <int> >();
 }
        /// <summary>
        /// Creates a node and any other connected nodes from a serialised execution graph
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="graph">Serialised graph</param>
        public static INode CreateFrom(this GraphFactory factory, Models.ExecutionGraph graph)
        {
            // create the input node
            var nodeTable = new Dictionary <string, INode>();
            var ret       = factory.Create(graph.InputNode);

            nodeTable.Add(ret.Id, ret);

            // create the other nodes
            foreach (var node in graph.OtherNodes)
            {
                var n = factory.Create(node);
                if (!nodeTable.ContainsKey(n.Id))
                {
                    nodeTable.Add(n.Id, n);
                }
            }

            // let each node know it has been deserialised and access to the entire graph
            foreach (var item in nodeTable)
            {
                item.Value.OnDeserialise(nodeTable);
            }

            // create the wires between nodes
            foreach (var wire in graph.Wires)
            {
                var from = nodeTable[wire.FromId];
                var to   = nodeTable[wire.ToId];
                from.Output.Add(new WireToNode(to, wire.InputChannel));
            }
            return(ret);
        }
Esempio n. 9
0
 private static void GenerateRandomWithCycle(int i, int j, out Graph g, out Graph h)
 {
     // random graph and a cycle
     g = GraphFactory.GenerateRandom(i, 0.4, 0);
     h = GraphFactory.GenerateCycle(j).Permute(1);
     Export("Random_And_Cycle", g, h);
 }
Esempio n. 10
0
 public void BalanceTwice()
 {
     g    = GraphFactory.UnBalancedFlow();
     algo = new GraphBalancerAlgorithm(g, Traversal.FirstVertex(g), Traversal.FirstVertex(g));
     algo.Balance();
     algo.Balance();
 }
Esempio n. 11
0
        static void ManyToOne()
        {
            var grammar   = new SequenceClassification(dictionarySize: 10, minSize: 5, maxSize: 5, noRepeat: true, isStochastic: false);
            var sequences = grammar.GenerateSequences().Take(1000).ToList();
            var builder   = BrightWireProvider.CreateDataTableBuilder();

            builder.AddColumn(ColumnType.Matrix, "Sequence");
            builder.AddColumn(ColumnType.Vector, "Summary");

            foreach (var sequence in sequences)
            {
                var list    = new List <FloatVector>();
                var charSet = new HashSet <char>();
                foreach (var ch in sequence)
                {
                    charSet.Add(ch);
                    var row = grammar.Encode(charSet.Select(ch2 => (ch2, 1f)));
                    list.Add(row);
                }
                builder.Add(new FloatMatrix {
                    Row = list.ToArray()
                }, list.Last());
            }
            var data = builder.Build().Split(0);

            using (var lap = BrightWireProvider.CreateLinearAlgebra(false)) {
                var graph       = new GraphFactory(lap);
                var errorMetric = graph.ErrorMetric.BinaryClassification;

                // create the property set
                var propertySet = graph.CurrentPropertySet
                                  .Use(graph.GradientDescent.RmsProp)
                                  .Use(graph.WeightInitialisation.Xavier)
                ;

                // create the engine
                var trainingData = graph.CreateDataSource(data.Training);
                var testData     = trainingData.CloneWith(data.Test);
                var engine       = graph.CreateTrainingEngine(trainingData, 0.03f, 8);

                // build the network
                const int HIDDEN_LAYER_SIZE = 128;
                var       memory            = new float[HIDDEN_LAYER_SIZE];
                var       network           = graph.Connect(engine)
                                              .AddLstm(memory)
                                              //.AddSimpleRecurrent(graph.ReluActivation(), memory)
                                              .AddFeedForward(engine.DataSource.OutputSize)
                                              .Add(graph.SigmoidActivation())
                                              .AddBackpropagationThroughTime(errorMetric)
                ;

                engine.Train(10, testData, errorMetric);

                var networkGraph    = engine.Graph;
                var executionEngine = graph.CreateEngine(networkGraph);

                var output = executionEngine.Execute(testData);
                Console.WriteLine(output.Where(o => o.Target != null).Average(o => o.CalculateError(errorMetric)));
            }
        }
Esempio n. 12
0
        public void ConstructorWithNullSink()
        {
            g = GraphFactory.UnBalancedFlow();
            Vertex v = new Vertex();

            new GraphBalancerAlgorithm(g, Traversal.FirstVertex(g), null);
        }
Esempio n. 13
0
        public void ConstructorWithSinkNotPartOfTheGraph()
        {
            g = GraphFactory.UnBalancedFlow();
            Vertex v = new Vertex();

            new GraphBalancerAlgorithm(g, Traversal.FirstVertex(g), v);
        }
Esempio n. 14
0
        public void BalanceUnBalancedFlowGraph()
        {
            g = GraphFactory.UnBalancedFlow();
            IVertex source = null;
            IVertex sink   = null;

            foreach (IVertex v in g.Vertices)
            {
                if (g.InDegree(v) == 0)
                {
                    source = v;
                    continue;
                }
                if (g.OutDegree(v) == 0)
                {
                    sink = v;
                    continue;
                }
            }
            Assert.IsNotNull(source);
            Assert.IsNotNull(sink);

            int vertexCount = g.VerticesCount;
            int edgeCount   = g.EdgesCount;

            algo = new GraphBalancerAlgorithm(g, source, sink);
            algo.DeficientVertexAdded += new VertexEventHandler(algo_DeficientVertexAdded);
            algo.SurplusVertexAdded   += new VertexEventHandler(algo_SurplusVertexAdded);
            algo.Balance();

            VerifyBalanced(vertexCount, edgeCount);
        }
        void _Create(GraphFactory graph, int inputSize, float[] memory, string memoryId)
        {
            int hiddenLayerSize = memory.Length;

            _inputSize = inputSize;

            _memory = new MemoryFeeder(memory, null, memoryId);
            _input  = new FlowThrough();

            var Wx = graph.Connect(inputSize, _input).AddFeedForward(hiddenLayerSize, "Wx").LastNode;

            var Wi = graph.Connect(hiddenLayerSize, Wx).AddFeedForward(hiddenLayerSize, "Wi");
            var Ui = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Ui");

            var Wf = graph.Connect(hiddenLayerSize, Wx).AddFeedForward(hiddenLayerSize, "Wf");
            var Uf = graph.Connect(hiddenLayerSize, _memory).AddFeedForward(hiddenLayerSize, "Uf");

            var It = graph.Add(Wi, Ui).Add(graph.SigmoidActivation());
            var Ft = graph.Add(Wf, Uf).Add(graph.SigmoidActivation());

            _output = graph
                      .Add(graph.Multiply(hiddenLayerSize, Wx, It.LastNode), graph.Multiply(hiddenLayerSize, _memory, Ft.LastNode))
                      .AddForwardAction(_memory.SetMemoryAction)
                      //.Add(new HookErrorSignal(context => {
                      //    if (_lastBackpropagation != null) {
                      //        foreach (var item in _lastBackpropagation)
                      //            context.AppendErrorSignal(item.Value, item.Key);
                      //        _lastBackpropagation = null;
                      //    }
                      //}))
                      .LastNode
            ;
            _start = new OneToMany(SubNodes, bp => _lastBackpropagation = bp);
        }
        public override void ReadFrom(GraphFactory factory, BinaryReader reader)
        {
            var inputSize = reader.ReadInt32();
            var memoryId  = reader.ReadString();
            var memory    = FloatVector.ReadFrom(reader);

            if (_memory == null)
            {
                _Create(factory, inputSize, memory.Data, memoryId);
            }
            else
            {
                _memory.Data = memory;
            }

            var Wx = _input.FindByName("Wx") as INode;
            var Wi = _input.FindByName("Wi") as INode;
            var Wf = _input.FindByName("Wf") as INode;
            var Ui = _memory.FindByName("Ui") as INode;
            var Uf = _memory.FindByName("Uf") as INode;

            Wx.ReadFrom(factory, reader);
            Wi.ReadFrom(factory, reader);
            Wf.ReadFrom(factory, reader);
            Ui.ReadFrom(factory, reader);
            Uf.ReadFrom(factory, reader);
        }
Esempio n. 17
0
        public void TestConverter()
        {
            Exception exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, string.Empty));

            Assert.Equal(CsvConverter.INVALID_CSV_ERROR, exception.Message);

            exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, String.Empty));
            Assert.Equal(CsvConverter.INVALID_CSV_ERROR, exception.Message);

            string csv = "P,C,Q";

            exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, csv));
            Assert.Equal(CsvConverter.FIRST_LINE_ERROR, exception.Message);

            csv       = "Parent,Child,Quantity\nABC,DEF,GHI";
            exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, csv));
            Assert.Equal(string.Format(CsvConverter.INVALID_QUANTITY_ERROR, 1), exception.Message);

            csv       = "Parent,Child,Quantity\nABC,DEF,3\nDEF,4";
            exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, csv));
            Assert.Equal(string.Format(CsvConverter.TOKEN_COUNT_ERROR, 2), exception.Message);

            csv       = "Parent,Child,Quantity\nABCD,DEFG,13";
            exception = Assert.Throws <ArgumentException>(() => GraphFactory.Generate(InputType.CSV, csv));
            Console.WriteLine(exception.Message);
            Assert.Equal("Errors encountered on line 1:\nThe field ParentName must match the regular expression '^[A-Z]{3}$'.\nThe field ChildName must match the regular expression '^[A-Z]{3}$'.\nThe field Quantity must be between 1 and 9.", exception.Message);

            csv = "Parent,Child,Quantity\nABD,DEF,3";
            var c = GraphFactory.Generate(InputType.CSV, csv);

            Assert.NotNull(c);
        }
Esempio n. 18
0
        static (GraphFactory, IDataSource) MakeGraphAndData()
        {
            var graph = new GraphFactory(_cpu);
            var data  = graph.CreateDataSource(And.Get());

            return(graph, data);
        }
Esempio n. 19
0
        public void GetShortestPath_ShouldBeAbleToFindingShortestPath()
        {
            // Note: this method uses AStarSearch class inside.
            // AStarSerach has its own comprehensive tests, so this test is only to ensure that this method exists and
            // returns something meaningful.
            var graph = GraphFactory.CreateRectangularGraph(3,
                                                            3, MovementTypesFixture.GetMovementTypes(), MovementTypesFixture.Ground);
            var start2d        = new Coordinate2D(0, 0, OffsetTypes.OddRowsRight);
            var start          = start2d.To3D();
            var goal2d         = new Coordinate2D(2, 2, OffsetTypes.OddRowsRight);
            var goal           = goal2d.To3D();
            var expectedPath2d = new List <Coordinate2D>
            {
                new Coordinate2D(1, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 1, OffsetTypes.OddRowsRight),
                goal2d
            };
            var expectedShortestPath = Coordinate2D.To3D(expectedPath2d);

            var shortestPath2d = graph.GetShortestPath(start2d, goal2d, MovementTypesFixture.Walking);
            var shortestPath   = graph.GetShortestPath(start, goal, MovementTypesFixture.Walking);

            Assert.That(shortestPath2d, Is.EqualTo(expectedPath2d));
            Assert.That(shortestPath, Is.EqualTo(expectedShortestPath));
        }
Esempio n. 20
0
 public override void ReadFrom(GraphFactory factory, BinaryReader reader)
 {
     _filterWidth  = reader.ReadInt32();
     _filterHeight = reader.ReadInt32();
     _xStride      = reader.ReadInt32();
     _yStride      = reader.ReadInt32();
 }
Esempio n. 21
0
        public void GetNeighbours_ShouldGetCorrectNeighbors()
        {
            var graph = GraphFactory.CreateRectangularGraph(6, 7, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);

            // Column 2, row 1
            var offsetTarget = new Coordinate2D(2, 1, OffsetTypes.OddRowsRight);
            var cubeTarget   = offsetTarget.To3D();
            var neighbors    = graph.GetNeighbors(cubeTarget, false).ToList();
            // Neighbors for cube coordinates should be:
            // Cube(+1, -1, 0), Cube(+1, 0, -1), Cube(0, +1, -1), Cube(-1, +1, 0), Cube(-1, 0, +1), Cube(0, -1, +1),
            var expectedNeighbors = new List <Coordinate3D>
            {
                new Coordinate3D(2, -2, 0),
                new Coordinate3D(3, -3, 0),
                new Coordinate3D(3, -4, 1),
                new Coordinate3D(2, -4, 2),
                new Coordinate3D(1, -3, 2),
                new Coordinate3D(1, -2, 1)
            };

            Assert.That(neighbors, Is.EqualTo(expectedNeighbors));

            Assert.That(
                graph.GetNeighbors(offsetTarget, false).ToList(),
                Is.EquivalentTo(Coordinate3D.To2D(expectedNeighbors, OffsetTypes.OddRowsRight))
                );
        }
Esempio n. 22
0
        public void GetPassableNeighbors_ShouldExcludeBlockedNeighbors()
        {
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);
            var center2d = new Coordinate2D(1, 1, OffsetTypes.OddRowsRight);
            var center   = center2d.To3D();

            graph.BlockCells(new List <Coordinate2D>
            {
                new Coordinate2D(2, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(1, 2, OffsetTypes.OddRowsRight)
            });

            var expectedPassableNeighbors2d = new List <Coordinate2D>
            {
                new Coordinate2D(1, 0, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(2, 2, OffsetTypes.OddRowsRight),
                new Coordinate2D(0, 1, OffsetTypes.OddRowsRight)
            };
            var expectedPassableNeighbors = Coordinate2D.To3D(expectedPassableNeighbors2d);

            Assert.That(graph.GetPassableNeighbors(center2d), Is.EqualTo(expectedPassableNeighbors2d));
            Assert.That(graph.GetPassableNeighbors(center), Is.EqualTo(expectedPassableNeighbors));
        }
Esempio n. 23
0
 /// <summary>
 /// Called when serialising the node
 /// </summary>
 /// <param name="graph">Graph factory</param>
 /// <param name="description">Node description</param>
 /// <param name="data">Node serialisation data</param>
 protected virtual void _Initalise(GraphFactory graph, string description, byte[] data)
 {
     if (data != null)
     {
         _ReadFrom(data, reader => ReadFrom(graph, reader));
     }
 }
Esempio n. 24
0
        public void ConvertsOffsetCoordinatesToCubeCoordinatesCorrectly()
        {
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);
            var cubeCoordinates = graph.GetAllCellsCoordinates();
            //For odd rows right:
            //Down and right: Y - 1, Z + 1
            //Down and left:  X - 1, Z + 1
            //Right: X + 1, Y - 1;
            var expectedCubeCoordinates = new List <Coordinate3D>
            {
                new Coordinate3D(0, 0, 0),
                // Down right:
                new Coordinate3D(0, -1, 1),
                // Down left:
                new Coordinate3D(-1, -1, 2),
                // Back to top, right from start position:
                new Coordinate3D(1, -1, 0),
                // Down right:
                new Coordinate3D(1, -2, 1),
                // Down left:
                new Coordinate3D(0, -2, 2),
                // Back to top, right from previous top point:
                new Coordinate3D(2, -2, 0),
                // Down right:
                new Coordinate3D(2, -3, 1),
                // Down and left:
                new Coordinate3D(1, -3, 2)
            };

            Assert.That(cubeCoordinates, Is.EqualTo(expectedCubeCoordinates));
        }
Esempio n. 25
0
        public override void ReadFrom(GraphFactory factory, BinaryReader reader)
        {
            var lap = factory?.LinearAlgebraProvider;

            InputSize  = reader.ReadInt32();
            OutputSize = reader.ReadInt32();

            // read the bias parameters
            var bias = FloatVector.ReadFrom(reader);

            if (Bias == null)
            {
                Bias = lap.CreateVector(bias);
            }
            else
            {
                Bias.Data = bias;
            }

            // read the weight parameters
            var weight = FloatMatrix.ReadFrom(reader);

            if (Weight == null)
            {
                Weight = lap.CreateMatrix(weight);
            }
            else
            {
                Weight.Data = weight;
            }
            if (_updater == null)
            {
                _updater = factory?.CreateWeightUpdater(Weight);
            }
        }
Esempio n. 26
0
        void _Create(GraphFactory graph, int inputSize, float[] memory, INode activation, string memoryId)
        {
            _inputSize  = inputSize;
            _activation = activation;
            int hiddenLayerSize = memory.Length;

            _memory = new MemoryFeeder(memory, null, memoryId);
            _input  = new FlowThrough();

            var inputChannel = graph.Connect(inputSize, _input)
                               .AddFeedForward(hiddenLayerSize, "Wh");
            var memoryChannel = graph.Connect(hiddenLayerSize, _memory)
                                .AddFeedForward(hiddenLayerSize, "Uh");

            _output = graph.Add(inputChannel, memoryChannel)
                      .AddBackwardAction(new ConstrainSignal())
                      .Add(activation)
                      .AddForwardAction(_memory.SetMemoryAction)
                      //.Add(new HookErrorSignal(context => {
                      //    if (_lastBackpropagation != null) {
                      //        foreach (var item in _lastBackpropagation)
                      //            context.AppendErrorSignal(item.Value, item.Key);
                      //        _lastBackpropagation = null;
                      //    }
                      //}))
                      .LastNode;
            ;
            _start = new OneToMany(SubNodes, bp => _lastBackpropagation = bp);
        }
Esempio n. 27
0
        // todo: export to explicit Unit Tests
        static void Main(string[] args)
        {
            IGraph <char> g1 =
                new GraphFactory <char>()
                .AddEdge('A', 'B')
                .AddEdge('B', 'C')
                .Create();

            Debug.Assert(g1.IsConnected);
            IGraph <char> g2 =
                new GraphFactory <char>()
                .AddEdge('A', 'B')
                .AddEdge('B', 'C')
                .AddNode('D')
                .Create();

            Debug.Assert(!g2.IsConnected);
            IGraph <char> g3 =
                new GraphFactory <char>()
                .AddEdge('B', 'A')
                .AddEdge('B', 'C')
                .AddEdge('D', 'C')
                .Create();

            Debug.Assert(g3.IsConnected);
        }
Esempio n. 28
0
        public override void ReadFrom(GraphFactory factory, BinaryReader reader)
        {
            var inputSize = reader.ReadInt32();
            var memoryId  = reader.ReadString();
            var memory    = FloatVector.ReadFrom(reader);

            if (_memory == null)
            {
                _Create(factory, inputSize, memory.Data, memoryId);
            }
            else
            {
                _memory.Data = memory;
            }
            var Wh = _input.FindByName("Wh");
            var Wr = _input.FindByName("Wr");
            var Wz = _input.FindByName("Wz");
            var Uh = _memory.FindByName("Uh");
            var Ur = _memory.FindByName("Ur");
            var Uz = _memory.FindByName("Uz");

            Wh.ReadFrom(factory, reader);
            Wr.ReadFrom(factory, reader);
            Wz.ReadFrom(factory, reader);
            Uh.ReadFrom(factory, reader);
            Ur.ReadFrom(factory, reader);
            Uz.ReadFrom(factory, reader);
        }
Esempio n. 29
0
        public void SetManyCellsTerrainType_ShouldSetTerrainTypesToCells()
        {
            var graph = GraphFactory.CreateRectangularGraph(3, 3, MovementTypesFixture.GetMovementTypes(),
                                                            MovementTypesFixture.Ground);

            var coordinateToSet = new Coordinate2D(2, 1, OffsetTypes.OddRowsRight);

            graph.SetCellsTerrainType(coordinateToSet, MovementTypesFixture.Water);
            Assert.That(graph.GetCellState(coordinateToSet).TerrainType, Is.EqualTo(MovementTypesFixture.Water));

            var coordinatesToSet = Coordinate2D.To3D(new List <Coordinate2D>
            {
                new Coordinate2D(0, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(0, 2, OffsetTypes.OddRowsRight)
            });

            graph.SetCellsTerrainType(coordinatesToSet, MovementTypesFixture.Water);
            foreach (var coordinate in coordinatesToSet)
            {
                Assert.That(graph.GetCellState(coordinate).TerrainType, Is.EqualTo(MovementTypesFixture.Water));
            }

            graph.SetCellsTerrainType(new List <Coordinate2D>
            {
                new Coordinate2D(0, 1, OffsetTypes.OddRowsRight),
                new Coordinate2D(0, 2, OffsetTypes.OddRowsRight)
            }, MovementTypesFixture.Air);
            foreach (var coordinate in coordinatesToSet)
            {
                Assert.That(graph.GetCellState(coordinate).TerrainType, Is.EqualTo(MovementTypesFixture.Air));
            }
        }
Esempio n. 30
0
        public override void ReadFrom(GraphFactory factory, BinaryReader reader)
        {
            var isElman     = reader.ReadBoolean();
            var inputSize   = reader.ReadInt32();
            var memoryId    = reader.ReadString();
            var memory      = FloatVector.ReadFrom(reader);
            var activation  = _Hydrate(factory, reader);
            var activation2 = _Hydrate(factory, reader);

            if (_memory == null)
            {
                _Create(factory, isElman, inputSize, memory.Data, activation, activation2, memoryId);
            }
            else
            {
                _memory.Data = memory;
            }

            var Wh = _input.FindByName("Wh");
            var Wy = _input.FindByName("Wy");
            var Uh = _memory.FindByName("Uh");

            Wh.ReadFrom(factory, reader);
            Wy.ReadFrom(factory, reader);
            Uh.ReadFrom(factory, reader);
        }
Esempio n. 31
0
        public void RenderGraph_givenFillColor_generatesImage()
        {
            var colors = new List<Color>
                             {
                                 Color.Blue,
                                 Color.Red,
                                 Color.Green,
                                 Color.White,
                                 Color.Black,
                                 Color.Aqua,
                                 Color.Yellow,
                                 Color.Magenta,
                                 Color.LightYellow,
                                 Color.SkyBlue,
                                 Color.OldLace,
                                 Color.SteelBlue,
                                 Color.DeepSkyBlue,
                                 Color.Gray,
                                 Color.Cornsilk
                             };

            var nodes = new List<Node>();
            var edges = new List<Edge>();

            foreach (var fill in colors)
            {
                Node prior = null;
                foreach (var font in colors)
                {
                    Node n = CreateNode(fill, font);
                    nodes.Add(n);
                    if (prior != null)
                    {
                        Edge e = new Edge(prior, n);
                        edges.Add(e);
                    }

                    prior = n;
                }
            }

            var graphFactory = new GraphFactory();
            var graph = graphFactory.CreateGraph(nodes, edges);

            var renderer = new DotRenderer(graph);
            var image = renderer.RenderImage();
            image.Save("NodeFillColor.png");
        }
Esempio n. 32
0
        public void RenderGraph_givenArrowShape_generatesImage(
            [Values(ArrowShape.Box, ArrowShape.Crow, ArrowShape.Diamond, ArrowShape.Dot, ArrowShape.Inv, ArrowShape.None, ArrowShape.Normal, ArrowShape.Tee, ArrowShape.Vee)]
            ArrowShape arrowHead)
        {
            var edgeStyle = new EdgeStyle();
            edgeStyle.ArrowHead = arrowHead;

            var startStyles
                = new List<ArrowShape>
                      {
                          ArrowShape.Box,
                          ArrowShape.Crow,
                          ArrowShape.Diamond,
                          ArrowShape.Dot,
                          ArrowShape.Inv,
                          ArrowShape.None,
                          ArrowShape.Normal,
                          ArrowShape.Tee,
                          ArrowShape.Vee
                      };

            var starts = new List<Node>();
            var edges = new List<Edge>();
            var finish = new Node("finish", "Finish");

            foreach (var shape in startStyles)
            {
                var n = Enum.GetName(typeof(ArrowShape), shape);
                var s = new Node(n, n);
                edgeStyle.ArrowTail = shape;
                var e = new Edge(s, finish, edgeStyle);

                starts.Add(s);
                edges.Add(e);
            }

            var graphFactory = new GraphFactory();
            var graph = graphFactory.CreateGraph(starts, finish, edges);

            var renderer = new DotRenderer(graph);

            var head = Enum.GetName(typeof(ArrowShape), arrowHead);
            var filename = head + ".png";
            var image = renderer.RenderImage();
            image.Save(filename);
        }
Esempio n. 33
0
        /// <summary>
        /// Envoi un courriel en format HTML
        /// </summary>
        /// <param name="tagFormater">L'objet de conversion des tags initialiser avec un compte</param>
        /// <param name="smtp">La configuration du serveur SMTP</param>
        /// <param name="recipients">La liste des récipients</param>
        /// <param name="subject">Le sujet du courriel</param>
        /// <param name="templateFile">Le modèle à utiliser pour le courriel</param>
        /// <param name="img">L'image du graphique</param>
        public void SendMailHTML(MailTagFormater tagFormater,
                                 SmtpSettings smtp,
                                 string recipients,
                                 string subject,
                                 string templateFile,
                                 VideotronAccount account)
        {
            // Les templates personnalisé sont plus fort que ceux de base (notion d'override)
            // Si le template n'existe pas, on prend le premier de la liste
            if (MailTemplates.FirstOrDefault(p => p.Name == templateFile) == null)
                templateFile = MailTemplates.FirstOrDefault().Name;

            subject = tagFormater.Convert(subject);

            StringBuilder template = new StringBuilder(tagFormater.Convert(MailTemplates.FirstOrDefault(p => p.Name == templateFile).GetContent()));

            SmtpClient client = new SmtpClient(smtp.Host, smtp.Port);
            client.Credentials = new NetworkCredential(smtp.Username, smtp.Password);

            MailMessage message = new MailMessage();

            message.From = new MailAddress(smtp.SenderMail, smtp.Sender, System.Text.Encoding.UTF8);

            foreach (string address in recipients.Split(';'))
                message.To.Add(new MailAddress(address));

            message.Subject = subject;

            switch (MailTemplates.FirstOrDefault(p => p.Name == templateFile).Encoding)
            {
                case MailTemplate.MailTemplateEncodingType.ASCII:
                    message.SubjectEncoding = System.Text.Encoding.ASCII;
                    message.BodyEncoding = System.Text.Encoding.ASCII;
                    break;
                case MailTemplate.MailTemplateEncodingType.ISO8859:
                    message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                    message.BodyEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                    break;
                default:
                    message.SubjectEncoding = System.Text.Encoding.UTF8;
                    message.BodyEncoding = System.Text.Encoding.UTF8;
                    break;
            }

            // Modèle HTML
            if (MailTemplates.FirstOrDefault(p => p.Name == templateFile).IsHTML)
            {
                message.IsBodyHtml = true;
                AlternateView htmlView;

                // Embebbed image
                List<string> embeddedImageFile = new List<string>();
                Match embeddedImage;
                string addedImage;
                do
                {
                    embeddedImage = Regex.Match(template.ToString(), "src=\"(?<src>[^cid]+)\"", RegexOptions.IgnoreCase);

                    if (embeddedImage.Success)
                    {
                        addedImage = System.IO.Path.Combine(MailTemplates.FirstOrDefault(p => p.Name == templateFile).Folder,
                                                            embeddedImage.Groups["src"].Value);
                        if (!File.Exists(addedImage))
                            throw new FileNotFoundException(addedImage);

                        embeddedImageFile.Add(addedImage);
                        template.Replace(String.Format("{0}", embeddedImage.Groups["src"].Value), String.Format("cid:img{0}", embeddedImageFile.Count));
                    }
                }
                while (embeddedImage.Success);

                // Insertion du graphique
                // Il faudrait le mettre dans MailTagFormater, mais c'est compliqué, pas le temps
                List<Tuple<int, int>> graphSize = new List<Tuple<int, int>>();
                Match match = Regex.Match(template.ToString(), @"\[GRAPH(\((?<param>[^\)]*)?\))?\]", RegexOptions.IgnoreCase);
                int graphCount = 0;
                int delta = 0;
                while (match.Success)
                {
                    int width = 430;
                    int height = 230;

                    Match paramMatch = Regex.Match(match.Groups["param"].Value,
                                                   @"(?<method>[a-z]{3,})=(?<param>[^,]+)",
                                                   RegexOptions.IgnoreCase);
                    while (paramMatch.Success)
                    {
                        if (paramMatch.Groups["method"].Value.ToUpper() == "WIDTH")
                            width = Convert.ToInt32(paramMatch.Groups["param"].Value);
                        else if (paramMatch.Groups["method"].Value.ToUpper() == "HEIGHT")
                            height = Convert.ToInt32(paramMatch.Groups["param"].Value);
                        paramMatch = paramMatch.NextMatch();
                    }

                    graphSize.Add(new Tuple<int, int>(width, height));

                    template.Remove(match.Index + delta, match.Length);
                    string newValue = String.Format("<img src=\"cid:graph_{0}\" width=\"{1}\" height=\"{2}\" />",
                                                    graphCount,
                                                    width,
                                                    height);
                    template.Insert(match.Index + delta, newValue);

                    if (match.Length > newValue.Length)
                        delta -= match.Length - newValue.Length;
                    else if (match.Length < newValue.Length)
                        delta += newValue.Length - match.Length;

                    graphCount++;
                    match = match.NextMatch();
                }

                htmlView = AlternateView.CreateAlternateViewFromString(template.ToString(), System.Text.Encoding.UTF8, "text/html");
                for (int i = 0; i < graphSize.Count; i++)
                {
                    System.Drawing.Image img;
                    MemoryStream memoryGraph = new MemoryStream();
                    GraphFactory graphFactory = new GraphFactory();
                    ZedGraphControl graph = graphFactory.Generate(account.Username,
                                                    new Period(account.PeriodStart, account.PeriodEnd),
                                                    graphSize[i].Item1, graphSize[i].Item2);

                    img = graph.GetImage();
                    img.Save(memoryGraph, System.Drawing.Imaging.ImageFormat.Jpeg);
                    memoryGraph.Position = 0;

                    htmlView.LinkedResources.Add(new LinkedResource(memoryGraph,
                                                                    MediaTypeNames.Image.Jpeg) {
                                                 ContentId = String.Format("graph_{0}", i),
                                                 TransferEncoding = TransferEncoding.Base64 });
                }

                for (int i = 0; i < embeddedImageFile.Count; i++)
                {
                    if (Regex.Match(embeddedImageFile[i], "(jpg|jpeg)$", RegexOptions.IgnoreCase).Success)
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Jpeg) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 });
                    else if (Regex.Match(embeddedImageFile[i], "gif$", RegexOptions.IgnoreCase).Success)
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Gif) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 });
                    else if (Regex.Match(embeddedImageFile[i], "tiff$", RegexOptions.IgnoreCase).Success)
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Tiff) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 });
                    else
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i]) { ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64 });
                }

                message.AlternateViews.Add(htmlView);
            }

            // Plain/Text
            else
            {
                message.Body = template.ToString();
            }
            client.Send(message);
            message.Dispose();
        }
Esempio n. 34
0
 private Graph CreateGraph()
 {
     var factory = new GraphFactory();
     return factory.CreateGraph();
 }
Esempio n. 35
0
 /// <summary>
 /// Create a graph to test with
 /// </summary>
 /// <returns>New graph instance</returns>
 private Graph CreateGraph(params object[] content)
 {
     var factory = new GraphFactory();
     return factory.CreateGraph(content);
 }
Esempio n. 36
0
 public void SetUp()
 {
     mFactory = new GraphFactory();
 }