Ejemplo n.º 1
0
    public static List<GraphModel> GetChartData()
    {
        DataTable dt = new DataTable();
        using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ShoppingDB;User ID=sa;Password=pass123!@#"))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select Name,total=value from CountryDetails order by total desc", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            con.Close();
        }
        List<countrydetails> dataList = new List<countrydetails>();

        List<GraphModel> gmL = new List<GraphModel>();

        foreach (DataRow dtrow in dt.Rows)
        {
            GraphModel gm = new GraphModel();

            gm.label = dtrow[0].ToString();
            gm.value= Convert.ToInt32(dtrow[1]);
            gmL.Add(gm);
        }

        return gmL;
    }
Ejemplo n.º 2
0
 public void Init()
 {
     _graph = new GraphModel();
     _user1 = _graph.CreateNode("user");
     var user2 = _graph.CreateNode("user");
     var tweet = _graph.CreateNode("tweet");
     _graph.CreateEdge(_user1, tweet, "tweeted");
     _graph.CreateEdge(user2, tweet, "retweeted");
     _graph.CreateEdge(_user1, user2, "followed");
     _graph.CreateEdge(_user1, _user1, "followed");
 }
Ejemplo n.º 3
0
        // todo クラス化
        private IGraphModel MakeTrendChartModel(IProject project, ISprintToGraphModel sprintToGraphModel)
        {
            var sx = project.Sprints;

            // todo グラフデータに変換
            // xは日付
            // yはValue
            var gx =
                (from s in sx
                 let g = sprintToGraphModel.Make(s)
                 select g).ToArray();

            // マージする
            var merged =
                new GraphModel
                {
                    Pv = gx.Select(x => x.Pv).Foldl(Enumerable.Empty<IGraphPoint>(), (a, x) => sprintToGraphModel.Merge(a, x)).ToArray(),
                    Ev = gx.Select(x => x.Ev).Foldl(Enumerable.Empty<IGraphPoint>(), (a, x) => sprintToGraphModel.Merge(a, x)).ToArray(),
                    Ac = gx.Select(x => x.Ac).Foldl(Enumerable.Empty<IGraphPoint>(), (a, x) => sprintToGraphModel.Merge(a, x)).ToArray(),
                };
            // 抜けてる日付をorする
            var allDays = merged.Pv.Concat(merged.Ev).Concat(merged.Ac).Select(x => x.Day).Distinct();
            var filledBlank =
                new GraphModel
                {
                    Pv = sprintToGraphModel.ToFillBlank(merged.Pv, allDays).ToArray(),
                    Ev = sprintToGraphModel.ToFillBlank(merged.Ev, allDays).ToArray(),
                    Ac = sprintToGraphModel.ToFillBlank(merged.Ac, allDays).ToArray(),
                };
            // 値を積み上げる
            var stacked =
                new GraphModel
                {
                    Pv = sprintToGraphModel.ToStacked(filledBlank.Pv).ToArray(),
                    Ev = sprintToGraphModel.ToStacked(filledBlank.Ev).ToArray(),
                    Ac = sprintToGraphModel.ToStacked(filledBlank.Ac).ToArray(),
                };
            return stacked;
        }
 public static MacroRefNodeModel CreateMacroRefNode(this IGraphNodeCreationData data, GraphModel macroGraphModel)
 {
     return(data.GraphModel.CreateMacroRefNode(macroGraphModel, data.Position, data.SpawnFlags, data.Guid));
 }
Ejemplo n.º 5
0
 public BaseAlgorithm(GraphModel graphModel)
 {
     this.graphModel = graphModel;
 }
Ejemplo n.º 6
0
 public Benchmarks()
 {
     _g = g
          .ConfigureEnvironment(env => env.UseModel(GraphModel.FromBaseTypes <Vertex, Edge>(lookup => lookup
                                                                                            .IncludeAssembliesOfBaseTypes())));
 }
Ejemplo n.º 7
0
 public GremlinQueryTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
 {
     _g = g
          .ConfigureEnvironment(_ => _
                                .UseModel(GraphModel.FromBaseTypes <Vertex, Edge>()));
 }
Ejemplo n.º 8
0
 public DepthFirstSearchDirectedAlgorithm(GraphModel model)
 {
     _model = model;
 }
        /// <summary>
        /// Classifies text into either positive or negative sentiment
        /// The data files can be downloaded from https://archive.ics.uci.edu/ml/datasets/Sentiment+Labelled+Sentences
        /// </summary>
        /// <param name="dataFilesPath">Path to extracted data files</param>
        public static void SentimentClassification(string dataFilesPath)
        {
            var files          = new[] { "amazon_cells_labelled.txt", "imdb_labelled.txt", "yelp_labelled.txt" };
            var LINE_SEPARATOR = "\n".ToCharArray();
            var SEPARATOR      = "\t".ToCharArray();
            var stringTable    = new StringTableBuilder();
            var sentimentData  = files.SelectMany(f =>
                                                  File.ReadAllText(dataFilesPath + f).Split(LINE_SEPARATOR).
                                                  Where(l => !string.IsNullOrWhiteSpace(l)).Select(l => l.Split(SEPARATOR)).
                                                  Select(s => Tuple.Create(Tokenise(s[0]), s[1][0] == '1' ? "positive" : "negative")).
                                                  Where(d => d.Item1.Any())).Shuffle(0).ToList();
            var splitSentimentData = sentimentData.Split();

            // build training and test classification bag
            var trainingClassificationBag =
                BuildIndexedClassifications(splitSentimentData.Training, stringTable);
            var testClassificationBag =
                BuildIndexedClassifications(splitSentimentData.Test, stringTable);

            // train a bernoulli naive bayes classifier
            var bernoulli = trainingClassificationBag.TrainBernoulliNaiveBayes();

            Console.WriteLine("Bernoulli accuracy: {0:P}",
                              testClassificationBag.Classify(bernoulli.CreateClassifier()).Average(r => r.Score));

            // train a multinomial naive bayes classifier
            var multinomial = trainingClassificationBag.TrainMultinomialNaiveBayes();

            Console.WriteLine("Multinomial accuracy: {0:P}",
                              testClassificationBag.Classify(multinomial.CreateClassifier()).Average(r => r.Score));

            // convert the index lists to vectors and normalise along the way
            var sentimentDataTable = BuildIndexedClassifications(sentimentData, stringTable).
                                     ConvertToTable().Normalise(NormalisationType.Standard);
            var vectoriser        = sentimentDataTable.GetVectoriser();
            var sentimentDataSet  = sentimentDataTable.Split(0);
            var dataTableAnalysis = sentimentDataTable.GetAnalysis();

            using (var lap = BrightWireProvider.CreateLinearAlgebra())
            {
                var graph            = new GraphFactory(lap);
                var trainingData     = graph.CreateDataSource(sentimentDataSet.Training, vectoriser);
                var testData         = graph.CreateDataSource(sentimentDataSet.Test, vectoriser);
                var indexListEncoder = (IIndexListEncoder)trainingData;

                // use a one hot encoding error metric, rmsprop gradient descent and xavier weight initialisation
                var errorMetric = graph.ErrorMetric.OneHotEncoding;
                var propertySet = graph.CurrentPropertySet.Use(graph.GradientDescent.RmsProp).
                                  Use(graph.WeightInitialisation.Xavier);
                var engine = graph.CreateTrainingEngine(trainingData, 0.3f);
                engine.LearningContext.ScheduleLearningRate(5, 0.1f);
                engine.LearningContext.ScheduleLearningRate(11, 1f);
                engine.LearningContext.ScheduleLearningRate(15, 0.3f);

                // train a neural network classifier
                var neuralNetworkWire = graph.Connect(engine).AddFeedForward(512, "layer1")
                                        //.AddBatchNormalisation()
                                        .Add(graph.ReluActivation()).AddDropOut(0.5f).
                                        AddFeedForward(trainingData.OutputSize, "layer2").Add(graph.ReluActivation()).
                                        AddBackpropagation(errorMetric, "first-network");

                // train the network
                Console.WriteLine("Training neural network classifier...");
                const int  TRAINING_ITERATIONS = 10;
                GraphModel bestNetwork         = null;
                engine.Train(TRAINING_ITERATIONS, testData, errorMetric, network => bestNetwork = network);
                if (bestNetwork != null)
                {
                    engine.LoadParametersFrom(bestNetwork.Graph);
                }
                var firstClassifier = graph.CreateEngine(engine.Graph);

                // stop the backpropagation to the first neural network
                engine.LearningContext.EnableNodeUpdates(neuralNetworkWire.Find("layer1"), false);
                engine.LearningContext.EnableNodeUpdates(neuralNetworkWire.Find("layer2"), false);

                // create the bernoulli classifier wire
                var bernoulliClassifier = bernoulli.CreateClassifier();
                var bernoulliWire       = graph.Connect(engine).AddClassifier(bernoulliClassifier,
                                                                              sentimentDataSet.Training, dataTableAnalysis);

                // create the multinomial classifier wire
                var multinomialClassifier = multinomial.CreateClassifier();
                var multinomialWire       = graph.Connect(engine).AddClassifier(multinomialClassifier,
                                                                                sentimentDataSet.Training, dataTableAnalysis);

                // join the bernoulli, multinomial and neural network classification outputs
                var firstNetwork = neuralNetworkWire.Find("first-network");
                var joined       = graph.Join(multinomialWire,
                                              graph.Join(bernoulliWire, graph.Connect(trainingData.OutputSize, firstNetwork)));

                // train an additional classifier on the output of the previous three classifiers
                joined.AddFeedForward(outputSize: 64).Add(graph.ReluActivation()).
                AddDropOut(dropOutPercentage: 0.5f).AddFeedForward(trainingData.OutputSize).
                Add(graph.ReluActivation()).AddBackpropagation(errorMetric);

                // train the network again
                Console.WriteLine("Training stacked neural network classifier...");
                GraphModel bestStackedNetwork = null;
                engine.Train(10, testData, errorMetric, network => bestStackedNetwork = network);
                if (bestStackedNetwork != null)
                {
                    engine.LoadParametersFrom(bestStackedNetwork.Graph);
                }
                Console.WriteLine("Enter some text to test the classifiers...");
                while (true)
                {
                    Console.Write(">");
                    var line = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        break;
                    }
                    var tokens    = Tokenise(line);
                    var indexList = new List <uint>();
                    foreach (var token in tokens)
                    {
                        if (stringTable.TryGetIndex(token, out uint stringIndex))
                        {
                            indexList.Add(stringIndex);
                        }
                    }

                    if (indexList.Any())
                    {
                        var queryTokens = indexList.GroupBy(d => d).
                                          Select(g => Tuple.Create(g.Key, (float)g.Count())).ToList();
                        var vector = new float[trainingData.InputSize];
                        foreach (var token in queryTokens)
                        {
                            vector[token.Item1] = token.Item2;
                        }
                        var indexList2   = IndexList.Create(indexList.ToArray());
                        var encodedInput = indexListEncoder.Encode(indexList2);
                        Console.WriteLine("Bernoulli classification: " +
                                          bernoulliClassifier.Classify(indexList2).First().Label);
                        Console.WriteLine("Multinomial classification: " +
                                          multinomialClassifier.Classify(indexList2).First().Label);
                        var result         = firstClassifier.Execute(encodedInput);
                        var classification = vectoriser.GetOutputLabel(1,
                                                                       (result.Output[0].Data[0] > result.Output[0].Data[1]) ? 0 : 1);
                        Console.WriteLine("Neural network classification: " + classification);
                        var stackedResult         = engine.Execute(encodedInput);
                        var stackedClassification = vectoriser.GetOutputLabel(1,
                                                                              (stackedResult.Output[0].Data[0] > stackedResult.Output[0].Data[1]) ? 0 : 1);
                        Console.WriteLine("Stack classification: " + stackedClassification);
                    }
                    else
                    {
                        Console.WriteLine("Sorry, none of those words have been seen before.");
                    }

                    Console.WriteLine();
                }
            }

            Console.WriteLine();
        }
Ejemplo n.º 10
0
        private GraphModel GraphSetup()
        {
            GraphDB db = new GraphDB();
            var graph = new GraphModel();

            //get all the nodes
            foreach (var node in db.Nodes)
            {
                var dataVertex = new DataVertex() { ID = node.Id, Text = node.label };
                graph.AddVertex(dataVertex);
                nodeList.Add(node.Id,node.label);
            }

            var vlist = graph.Vertices.ToList();

            //add all the edges
            foreach (var node in vlist)
            {
                Dictionary<int,int> edges =  new Dictionary<int, int>();
                foreach (var edge in db.Edges.Where(x => x.FromNode == node.ID))
                {
                    var dataEdge = new DataEdge(node, vlist[vlist.FindIndex(x => x.ID == edge.ToNode)]);
                    graph.AddEdge(dataEdge);
                    edges.Add(edge.ToNode,1);
                }

                vertices.Add(node.ID,edges);

            }

            return graph;
        }
Ejemplo n.º 11
0
 public static InstantiateNodeModel FindInstantiateNodeModel(this GraphModel graph)
 {
     return(graph.NodeModels.OfType <IStackModel>().SelectMany(node => node.NodeModels.OfType <InstantiateNodeModel>()).First());
 }
Ejemplo n.º 12
0
 public GremlinQueryLanguageTest()
 {
     this._model = GraphModel.FromAssembly(Assembly.GetExecutingAssembly(), typeof(Vertex), typeof(Edge), GraphElementNamingStrategy.Simple);
 }
Ejemplo n.º 13
0
        public Gantt()
        {
            InitializeComponent();

            // create the diagram's data model
            var model = new GraphModel <Activity, int>();
            int row   = 1;

            model.NodesSource = new ObservableCollection <Activity>()
            {
                // don't use Key==0
                new Activity()
                {
                    Key = 1, Row = row++, Text = "Start", FromKeys = P(), Length = 0, Start = 0, Critical = true, Category = "Start"
                },
                new Activity()
                {
                    Key = 2, Row = row++, Text = "a", FromKeys = P(1), Length = 4, Start = 0, Critical = true
                },
                new Activity()
                {
                    Key = 3, Row = row++, Text = "b", FromKeys = P(1), Length = 5.33, Start = 0
                },
                new Activity()
                {
                    Key = 4, Row = row++, Text = "c", FromKeys = P(2), Length = 5.17, Start = 4, Critical = true
                },
                new Activity()
                {
                    Key = 5, Row = row++, Text = "d", FromKeys = P(2), Length = 6.33, Start = 4
                },
                new Activity()
                {
                    Key = 6, Row = row++, Text = "e", FromKeys = P(3, 4), Length = 5.17, Start = 9.17, Critical = true
                },
                new Activity()
                {
                    Key = 7, Row = row++, Text = "f", FromKeys = P(5), Length = 4.5, Start = 10.33
                },
                new Activity()
                {
                    Key = 8, Row = row++, Text = "g", FromKeys = P(6), Length = 5.17, Start = 14.34, Critical = true
                },
                new Activity()
                {
                    Key = 9, Row = row++, Text = "Finish", FromKeys = P(7, 8), Length = 0, Start = 19.51, Critical = true, Category = "Finish"
                },
                // add Dates along the top
                new Activity()
                {
                    Key = 9999, Row = 0, Text = "23Jul", Start = 0, Category = "Week"
                },
                new Activity()
                {
                    Key = 9999, Row = 0, Text = "30Jul", Start = 5, Category = "Week"
                },
                new Activity()
                {
                    Key = 9999, Row = 0, Text = "6Aug", Start = 10, Category = "Week"
                },
                new Activity()
                {
                    Key = 9999, Row = 0, Text = "13Aug", Start = 15, Category = "Week"
                },
            };
            myDiagram.Model = model;

            // initialize the converter to know about the Diagram, to support zooming
            var conv = Diagram.FindResource <LengthConverter>(this, "myLengthConverter");

            if (conv != null)
            {
                conv.Diagram = myDiagram;
            }
            // initialize the Diagram.GridPattern based on the spacing
            myDiagram.GridPattern.CellSize = new Size(conv.Space * Gantt.XUnit, Gantt.YUnit);
        }
Ejemplo n.º 14
0
        public void Test_MoveElementsActionForNodes([Values] TestingMode mode)
        {
            var node0        = GraphModel.CreateNode <Type0FakeNodeModel>("Node0", Vector2.zero);
            var node1        = GraphModel.CreateNode <Type0FakeNodeModel>("Node1", Vector2.zero);
            var node2        = GraphModel.CreateNode <Type0FakeNodeModel>("Node2", Vector2.zero);
            var node3        = GraphModel.CreateNode <Type0FakeNodeModel>("Node3", Vector2.zero);
            var newPosition0 = new Vector2(50, -75);
            var newPosition1 = new Vector2(60, 25);
            var newPosition2 = new Vector2(-30, 15);
            var deltaAll     = new Vector2(100, 100);

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(1).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(2).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
                return(new MoveElementsAction(newPosition0, new[] { node0 }, null));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(2).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(2).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
                return(new MoveElementsAction(newPosition1, new[] { node1 }, null));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(newPosition1));
                Assert.That(GetNode(2).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(newPosition1));
                Assert.That(GetNode(2).Position, Is.EqualTo(Vector2.zero));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
                return(new MoveElementsAction(newPosition2, new[] { node2 }, null));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(newPosition1));
                Assert.That(GetNode(2).Position, Is.EqualTo(newPosition2));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0));
                Assert.That(GetNode(1).Position, Is.EqualTo(newPosition1));
                Assert.That(GetNode(2).Position, Is.EqualTo(newPosition2));
                Assert.That(GetNode(3).Position, Is.EqualTo(Vector2.zero));
                return(new MoveElementsAction(deltaAll, new[] { node0, node1, node2, node3 }, null));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(4));
                Assert.That(GetNode(0).Position, Is.EqualTo(newPosition0 + deltaAll));
                Assert.That(GetNode(1).Position, Is.EqualTo(newPosition1 + deltaAll));
                Assert.That(GetNode(2).Position, Is.EqualTo(newPosition2 + deltaAll));
                Assert.That(GetNode(3).Position, Is.EqualTo(deltaAll));
            });
        }
Ejemplo n.º 15
0
 public JsonSupportTest()
 {
     _g = g
          .UseModel(GraphModel.FromBaseTypes <Vertex, Edge>());
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Uses a recurrent LSTM neural network to predict stock price movements
        /// Data can be downloaded from https://raw.githubusercontent.com/plotly/datasets/master/stockdata.csv
        /// </summary>
        static void StockData(string dataFilePath)
        {
            // load and normalise the data
            var dataSet    = new StreamReader(dataFilePath).ParseCSV(',', true);
            var normalised = dataSet.Normalise(NormalisationType.FeatureScale);
            var rows       = normalised.GetNumericRows(dataSet.Columns.Where(c => c.Name != "Date").Select(c => c.Index));

            // build the data table with a window of input data and the prediction as the following value
            var builder = BrightWireProvider.CreateDataTableBuilder();

            builder.AddColumn(ColumnType.Matrix, "Past");
            builder.AddColumn(ColumnType.Vector, "Future");
            const int LAST_X_DAYS = 14;

            for (var i = 0; i < rows.Count - LAST_X_DAYS - 1; i++)
            {
                var inputVector = new List <FloatVector>();
                for (var j = 0; j < LAST_X_DAYS; j++)
                {
                    inputVector.Add(FloatVector.Create(rows[i + j]));
                }
                var input  = FloatMatrix.Create(inputVector.ToArray());
                var target = FloatVector.Create(rows[i + LAST_X_DAYS + 1]);
                builder.Add(input, target);
            }
            var data = builder.Build().Split(trainingPercentage: 0.2);

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

                // create the property set
                graph.CurrentPropertySet
                .Use(graph.GradientDescent.Adam)
                .Use(graph.WeightInitialisation.Xavier);

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

                // build the network
                const int HIDDEN_LAYER_SIZE = 256;
                graph.Connect(engine)
                .AddLstm(HIDDEN_LAYER_SIZE)
                .AddFeedForward(engine.DataSource.OutputSize)
                .Add(graph.TanhActivation())
                .AddBackpropagationThroughTime(errorMetric);

                // train the network and restore the best result
                GraphModel bestNetwork = null;
                engine.Train(50, testData, errorMetric, model => bestNetwork = model);
                if (bestNetwork != null)
                {
                    // execute each row of the test data on an execution engine
                    var executionEngine = graph.CreateEngine(bestNetwork.Graph);
                    var results         = executionEngine.Execute(testData).OrderSequentialOutput();
                    var expectedOutput  = data.Test.GetColumn <FloatVector>(1);

                    var score = results.Select((r, i) => errorMetric.Compute(r.Last(), expectedOutput[i])).Average();
                    Console.WriteLine(score);
                }
            }
        }
Ejemplo n.º 17
0
        public IEnumerator AlignNodesHierarchiesCommandWorks([Values] TestingMode mode)
        {
            var constantA = GraphModel.CreateConstantNode(typeof(int).GenerateTypeHandle(), "constantA", Vector2.zero);
            var binary0   = GraphModel.CreateNode <Type0FakeNodeModel>("Node1", Vector2.one * 200);
            var binary1   = GraphModel.CreateNode <Type0FakeNodeModel>("Node2", Vector2.one * 500);

            GraphModel.CreateEdge(binary0.Input0, constantA.OutputPort);
            GraphModel.CreateEdge(binary1.Input0, binary0.Output0);

            MarkGraphViewStateDirty();
            yield return(null);

            void RefreshModelReferences()
            {
                constantA = GraphModel.NodeModels[0] as IConstantNodeModel;
                binary0   = GraphModel.NodeModels[1] as Type0FakeNodeModel;
                binary1   = GraphModel.NodeModels[2] as Type0FakeNodeModel;

                Assert.IsNotNull(constantA);
                Assert.IsNotNull(binary0);
                Assert.IsNotNull(binary1);
            }

            yield return(TestPrereqCommandPostreq(mode,
                                                  () =>
            {
                RefreshModelReferences();

                Assert.That(binary0.Input0, Is.ConnectedTo(constantA.OutputPort));
                Assert.That(binary1.Input0, Is.ConnectedTo(binary0.Output0));

                var port0UI = binary0.Output0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port0UI);
                var port1UI = binary1.Input0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port1UI);
                Assert.AreNotEqual(GetPortY(port0UI), GetPortY(port1UI));

                var port2UI = constantA.OutputPort.GetUI <Port>(GraphView);
                Assert.IsNotNull(port2UI);
                var port3UI = binary0.Input0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port3UI);
                Assert.AreNotEqual(GetPortY(port2UI), GetPortY(port3UI));
            },
                                                  frame =>
            {
                switch (frame)
                {
                case 0:
                    CommandDispatcher.Dispatch(new AlignNodesCommand(GraphView, true, binary1));
                    return TestPhase.WaitForNextFrame;

                default:
                    return TestPhase.Done;
                }
            },
                                                  () =>
            {
                RefreshModelReferences();

                var port0UI = binary0.Output0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port0UI);
                var port1UI = binary1.Input0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port1UI);
                Assert.AreEqual(GetPortY(port0UI), GetPortY(port1UI));

                var port2UI = constantA.OutputPort.GetUI <Port>(GraphView);
                Assert.IsNotNull(port2UI);
                var port3UI = binary0.Input0.GetUI <Port>(GraphView);
                Assert.IsNotNull(port3UI);
                Assert.AreEqual(GetPortY(port2UI), GetPortY(port3UI));
            }));
        }
        public void NestedIteration_DifferentGroups_DifferentEntitiesAccess([Values] CodeGenMode mode)
        {
            SetupTestGraph(mode, graph =>
            {
                var translationType = typeof(Translation).GenerateTypeHandle(Stencil);
                var scaleType       = typeof(Scale).GenerateTypeHandle(Stencil);

                // query1 - Position
                var query1 = GraphModel.CreateComponentQuery("g1");
                query1.AddComponent(Stencil, translationType, ComponentDefinitionFlags.None);
                var query1Instance = GraphModel.CreateVariableNode(query1, Vector2.zero);

                // query2 - Scale
                var query2 = GraphModel.CreateComponentQuery("g2");
                query2.AddComponent(Stencil, scaleType, ComponentDefinitionFlags.None);
                var query2Instance = GraphModel.CreateVariableNode(query2, Vector2.zero);

                // update query 1
                var update = GraphModel.CreateNode <OnUpdateEntitiesNodeModel>("update", Vector2.zero);
                GraphModel.CreateEdge(update.InstancePort, query1Instance.OutputPort);

                // nested update query 2
                var forAllStack = GraphModel.CreateLoopStack <ForAllEntitiesStackModel>(Vector2.zero);
                var forAllNode  = forAllStack.CreateLoopNode(update, 0) as ForAllEntitiesNodeModel;
                Assert.That(forAllNode, Is.Not.Null);
                GraphModel.CreateEdge(forAllNode.InputPort, query2Instance.OutputPort);
                GraphModel.CreateEdge(forAllStack.InputPort, forAllNode.OutputPort);

                // entity from query 1
                var entity1 = graph.CreateVariableNode(
                    update.FunctionParameterModels.Single(
                        p => p.DataType == typeof(Entity).GenerateTypeHandle(graph.Stencil)),
                    Vector2.zero);

                // entity from query 2
                var entity2 = graph.CreateVariableNode(
                    forAllStack.FunctionParameterModels.Single(
                        p => p.DataType == typeof(Entity).GenerateTypeHandle(graph.Stencil)),
                    Vector2.zero);

                // set a new Translation to entities of query1
                var setTranslation           = forAllStack.CreateStackedNode <SetComponentNodeModel>("set translation");
                setTranslation.ComponentType = typeof(Translation).GenerateTypeHandle(graph.Stencil);
                setTranslation.DefineNode();
                ((FloatConstantModel)setTranslation.InputConstantsById["z"]).value = 10f;
                graph.CreateEdge(setTranslation.EntityPort, entity1.OutputPort);

                // set a new Scale to entities of query2
                var setScale           = forAllStack.CreateStackedNode <SetComponentNodeModel>("set scale");
                setScale.ComponentType = typeof(Scale).GenerateTypeHandle(graph.Stencil);
                setScale.DefineNode();
                ((FloatConstantModel)setScale.InputConstantsById["Value"]).value = 30f;
                graph.CreateEdge(setScale.EntityPort, entity2.OutputPort);
            },
                           (manager, index, entity) =>
            {
                if (index % 2 == 0)
                {
                    manager.AddComponentData(entity, new Translation());
                }
                else
                {
                    manager.AddComponentData(entity, new Scale());
                }
            },
                           (manager, index, entity) =>
            {
                if (manager.HasComponent <Translation>(entity))
                {
                    Assert.That(manager.GetComponentData <Translation>(entity).Value.z, Is.EqualTo(10f));
                }

                if (manager.HasComponent <Scale>(entity))
                {
                    Assert.That(manager.GetComponentData <Scale>(entity).Value, Is.EqualTo(30f));
                }
            }
                           );
        }
 public GraphsonSupportTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
 {
     _g = g
          .ConfigureEnvironment(env => env.UseModel(GraphModel.FromBaseTypes <Vertex, Edge>(lookup => lookup
                                                                                            .IncludeAssembliesOfBaseTypes())));
 }
Ejemplo n.º 20
0
 public BreadthFirstSearchAlgorithm(GraphModel model)
 {
     _model = model;
     _path  = new Dictionary <int, int>();
 }
Ejemplo n.º 21
0
        public void Test_EditPropertyGroupNodeAction_AddRemove([Values] TestingMode mode)
        {
            IConstantNodeModel        constant = GraphModel.CreateConstantNode("toto", typeof(Vector3).GenerateTypeHandle(Stencil), Vector2.zero);
            GetPropertyGroupNodeModel property = GraphModel.CreateGetPropertyGroupNode(Vector2.zero);

            GraphModel.CreateEdge(property.InstancePort, constant.OutputPort);

            Type       type       = typeof(GameObject);
            MemberInfo memberInfo = type.GetMembers()[0];
            var        newMember  = new TypeMember
            {
                Path = new List <string> {
                    memberInfo.Name
                },
                Type = memberInfo.GetUnderlyingType().GenerateTypeHandle(Stencil)
            };


            TestPrereqActionPostreq(mode,
                                    () =>
            {
                property = (GetPropertyGroupNodeModel)GraphModel.NodesByGuid[property.Guid];

                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(1));
                Assert.That(property.GetPortsForMembers().Count(), Is.EqualTo(0));
                Assert.That(property.OutputsByDisplayOrder.Count(), Is.EqualTo(0));
                return(new EditPropertyGroupNodeAction(
                           EditPropertyGroupNodeAction.EditType.Add,
                           property,
                           newMember));
            },
                                    () =>
            {
                property = (GetPropertyGroupNodeModel)GraphModel.NodesByGuid[property.Guid];

                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(1));
                Assert.That(property.GetPortsForMembers().Count(), Is.EqualTo(1));
                Assert.That(property.OutputsByDisplayOrder.Count(), Is.EqualTo(1));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                property = (GetPropertyGroupNodeModel)GraphModel.NodesByGuid[property.Guid];

                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(1));
                Assert.That(property.GetPortsForMembers().Count(), Is.EqualTo(1));
                Assert.That(property.OutputsByDisplayOrder.Count(), Is.EqualTo(1));
                return(new EditPropertyGroupNodeAction(
                           EditPropertyGroupNodeAction.EditType.Remove,
                           property,
                           newMember));
            },
                                    () =>
            {
                property = (GetPropertyGroupNodeModel)GraphModel.NodesByGuid[property.Guid];

                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(1));
                Assert.That(property.GetPortsForMembers().Count(), Is.EqualTo(0));
                Assert.That(property.OutputsByDisplayOrder.Count(), Is.EqualTo(0));
            });
        }
Ejemplo n.º 22
0
        public void Test_BypassNodeAction([Values] TestingMode mode)
        {
            var constantA = GraphModel.CreateConstantNode("constantA", typeof(float).GenerateTypeHandle(Stencil), Vector2.zero);
            var binary0   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);
            var binary1   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);

            GraphModel.CreateEdge(binary0.InputPortA, constantA.OutputPort);
            GraphModel.CreateEdge(binary1.InputPortA, binary0.OutputPort);

            var constantB = GraphModel.CreateConstantNode("constantB", typeof(float).GenerateTypeHandle(Stencil), Vector2.zero);
            var binary2   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);
            var binary3   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);

            GraphModel.CreateEdge(binary2.InputPortA, constantB.OutputPort);
            GraphModel.CreateEdge(binary3.InputPortA, binary2.OutputPort);

            var constantC = GraphModel.CreateConstantNode("constantC", typeof(float).GenerateTypeHandle(Stencil), Vector2.zero);
            var binary4   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);
            var binary5   = GraphModel.CreateBinaryOperatorNode(BinaryOperatorKind.Add, Vector2.zero);

            GraphModel.CreateEdge(binary4.InputPortA, constantC.OutputPort);
            GraphModel.CreateEdge(binary5.InputPortA, binary4.OutputPort);

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(9));
                Assert.That(GetEdgeCount(), Is.EqualTo(6));
                Assert.That(binary0.InputPortA, Is.ConnectedTo(constantA.OutputPort));
                Assert.That(binary1.InputPortA, Is.ConnectedTo(binary0.OutputPort));
                Assert.That(binary2.InputPortA, Is.ConnectedTo(constantB.OutputPort));
                Assert.That(binary3.InputPortA, Is.ConnectedTo(binary2.OutputPort));
                Assert.That(binary4.InputPortA, Is.ConnectedTo(constantC.OutputPort));
                Assert.That(binary5.InputPortA, Is.ConnectedTo(binary4.OutputPort));
                return(new BypassNodeAction(binary0));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(9));
                Assert.That(GetEdgeCount(), Is.EqualTo(5));
                Assert.That(binary1.InputPortA, Is.ConnectedTo(constantA.OutputPort));
                Assert.That(binary2.InputPortA, Is.ConnectedTo(constantB.OutputPort));
                Assert.That(binary3.InputPortA, Is.ConnectedTo(binary2.OutputPort));
                Assert.That(binary4.InputPortA, Is.ConnectedTo(constantC.OutputPort));
                Assert.That(binary5.InputPortA, Is.ConnectedTo(binary4.OutputPort));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(9));
                Assert.That(GetEdgeCount(), Is.EqualTo(5));
                Assert.That(binary1.InputPortA, Is.ConnectedTo(constantA.OutputPort));
                Assert.That(binary2.InputPortA, Is.ConnectedTo(constantB.OutputPort));
                Assert.That(binary3.InputPortA, Is.ConnectedTo(binary2.OutputPort));
                Assert.That(binary4.InputPortA, Is.ConnectedTo(constantC.OutputPort));
                Assert.That(binary5.InputPortA, Is.ConnectedTo(binary4.OutputPort));
                return(new BypassNodeAction(binary2, binary4));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(9));
                Assert.That(GetEdgeCount(), Is.EqualTo(3));
                Assert.That(binary1.InputPortA, Is.ConnectedTo(constantA.OutputPort));
                Assert.That(binary3.InputPortA, Is.ConnectedTo(constantB.OutputPort));
                Assert.That(binary5.InputPortA, Is.ConnectedTo(constantC.OutputPort));
            });
        }
Ejemplo n.º 23
0
 public MyProblemFitness(GraphModel gm)
 {
     graphModel = gm;
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Builds a graph according provided informations.
 /// </summary>
 /// <param name="graphInfo">Informations about the Graph. Format 'AB9'</param>
 public void BuildGraph(string graphInfo)
 {
     graph = GraphBusiness.BuildGraph(graphInfo);
 }
Ejemplo n.º 25
0
        void TestExtractMacro(IEnumerable <IGraphElementModel> toExtract, IO inputs, IO outputs)
        {
            MacroRefNodeModel macroRef = GraphModel.ExtractNodesAsMacro(m_MacroGraphModel, Vector2.zero, toExtract);

            Assert.That(macroRef.Macro, Is.EqualTo(m_MacroGraphModel));

            inputs.Check(m_MacroGraphModel, macroRef.InputVariablePorts.ToList(), ModifierFlags.ReadOnly);
            outputs.Check(m_MacroGraphModel, macroRef.OutputVariablePorts.ToList(), ModifierFlags.WriteOnly);

            CompilationResult compilationResult = GraphModel.Compile(AssemblyType.None, GraphModel.CreateTranslator(), CompilationOptions.Default);

            Assert.That(
                compilationResult.status,
                Is.EqualTo(CompilationStatus.Succeeded));
            Debug.Log(compilationResult.sourceCode[0]);
        }
Ejemplo n.º 26
0
        public void Test_MoveMultipleStackedNodesAction_ToDifferentStack([Values] TestingMode mode)
        {
            var stack0 = GraphModel.CreateStack(string.Empty, Vector2.zero);
            var nodeA  = stack0.CreateStackedNode <Type0FakeNodeModel>("A");
            var nodeB  = stack0.CreateStackedNode <Type0FakeNodeModel>("B");
            var nodeC  = stack0.CreateStackedNode <Type0FakeNodeModel>("C");
            var stack1 = GraphModel.CreateStack(string.Empty, Vector2.zero);
            var nodeD  = stack1.CreateStackedNode <Type0FakeNodeModel>("D");
            var nodeE  = stack1.CreateStackedNode <Type0FakeNodeModel>("E");
            var nodeF  = stack1.CreateStackedNode <Type0FakeNodeModel>("F");

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeA, Has.IndexInStack(0, stack0));
                Assert.That(nodeB, Has.IndexInStack(1, stack0));
                Assert.That(nodeC, Has.IndexInStack(2, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeD, Has.IndexInStack(0, stack1));
                Assert.That(nodeE, Has.IndexInStack(1, stack1));
                Assert.That(nodeF, Has.IndexInStack(2, stack1));
                return(new MoveStackedNodesAction(new [] { nodeA, nodeC }, stack1, 1));
            },
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(1));
                Assert.That(nodeB, Has.IndexInStack(0, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(5));
                Assert.That(nodeD, Has.IndexInStack(0, stack1));
                Assert.That(nodeA, Has.IndexInStack(1, stack1));
                Assert.That(nodeC, Has.IndexInStack(2, stack1));
                Assert.That(nodeE, Has.IndexInStack(3, stack1));
                Assert.That(nodeF, Has.IndexInStack(4, stack1));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(1));
                Assert.That(nodeB, Has.IndexInStack(0, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(5));
                Assert.That(nodeD, Has.IndexInStack(0, stack1));
                Assert.That(nodeA, Has.IndexInStack(1, stack1));
                Assert.That(nodeC, Has.IndexInStack(2, stack1));
                Assert.That(nodeE, Has.IndexInStack(3, stack1));
                Assert.That(nodeF, Has.IndexInStack(4, stack1));
                return(new MoveStackedNodesAction(new [] { nodeF, nodeD }, stack0, 0));
            },
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeF, Has.IndexInStack(0, stack0));
                Assert.That(nodeD, Has.IndexInStack(1, stack0));
                Assert.That(nodeB, Has.IndexInStack(2, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeA, Has.IndexInStack(0, stack1));
                Assert.That(nodeC, Has.IndexInStack(1, stack1));
                Assert.That(nodeE, Has.IndexInStack(2, stack1));
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeF, Has.IndexInStack(0, stack0));
                Assert.That(nodeD, Has.IndexInStack(1, stack0));
                Assert.That(nodeB, Has.IndexInStack(2, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(3));
                Assert.That(nodeA, Has.IndexInStack(0, stack1));
                Assert.That(nodeC, Has.IndexInStack(1, stack1));
                Assert.That(nodeE, Has.IndexInStack(2, stack1));
                return(new MoveStackedNodesAction(new [] { nodeF, nodeC }, stack1, 2));
            },
                                    () =>
            {
                Assert.That(stack0.NodeModels.Count(), Is.EqualTo(2));
                Assert.That(nodeD, Has.IndexInStack(0, stack0));
                Assert.That(nodeB, Has.IndexInStack(1, stack0));
                Assert.That(stack1.NodeModels.Count(), Is.EqualTo(4));
                Assert.That(nodeA, Has.IndexInStack(0, stack1));
                Assert.That(nodeE, Has.IndexInStack(1, stack1));
                Assert.That(nodeF, Has.IndexInStack(2, stack1));
                Assert.That(nodeC, Has.IndexInStack(3, stack1));
            });
        }
Ejemplo n.º 27
0
        public void Test_BypassNodeAction_Throw()
        {
            var constantA = GraphModel.CreateConstantNode("constantA", typeof(float).GenerateTypeHandle(Stencil), Vector2.zero);

            Assert.Throws <InvalidOperationException>(() => m_Store.Dispatch(new BypassNodeAction(constantA)));
        }
Ejemplo n.º 28
0
        public void Test_EmbeddedConstantIsUsedWhenDisconnected([Values] TestingMode mode)
        {
            const float outerValue = 42f;
            const float innerValue = 347f;

            // make sure that we really test values that are not default
            Assume.That(outerValue, Is.Not.EqualTo(default(float)));
            Assume.That(innerValue, Is.Not.EqualTo(default(float)));

            var stencil = GraphModel.Stencil;

            FunctionModel a = GraphModel.CreateFunction("A", Vector2.zero);

            // Debug.Log(...)
            MethodInfo logMethod = typeof(Debug).GetMethod(nameof(Debug.Log), new[] { typeof(object) });

            Assume.That(logMethod, Is.Not.Null);
            FunctionCallNodeModel log = a.CreateStackedNode <FunctionCallNodeModel>("Log", 0, SpawnFlags.Default, n => n.MethodInfo = logMethod);
            var logParameterPort      = log.GetParameterPorts().Single();

            // Math.Abs(...)
            MethodInfo absMethod = typeof(Mathf).GetMethod(nameof(Mathf.Abs), new[] { typeof(float) });

            Assume.That(absMethod, Is.Not.Null);
            FunctionCallNodeModel abs = GraphModel.CreateNode <FunctionCallNodeModel>("Abs", Vector2.zero, SpawnFlags.Default, n => n.MethodInfo = absMethod);
            var absParameterPort      = abs.GetParameterPorts().Single();

            ((FloatConstantModel)abs.InputConstantsById[absParameterPort.UniqueId]).value = innerValue;

            GraphModel.CreateEdge(logParameterPort, abs.OutputPort);

            // float
            IConstantNodeModel outerFloat = GraphModel.CreateConstantNode("float42", typeof(float).GenerateTypeHandle(stencil), Vector2.zero);

            Assume.That(outerFloat, Is.Not.Null);
            ((FloatConstantModel)outerFloat).value = outerValue;

            string innerFloatString = SyntaxFactory.LiteralExpression(
                SyntaxKind.NumericLiteralExpression,
                SyntaxFactory.Literal(innerValue)).ToFullString();
            string outerFloatString = SyntaxFactory.LiteralExpression(
                SyntaxKind.NumericLiteralExpression,
                SyntaxFactory.Literal(outerValue)).ToFullString();

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                // outer float disconnected, check that we use the inner value
                SyntaxNode astRoot = CompileCurrentGraphModel();
                LiteralExpressionSyntax literalInsideLogAbs = GetLiteralInsideLogAbs(astRoot);
                Assert.That(literalInsideLogAbs.ToFullString(), Is.EqualTo(innerFloatString));
                return(new CreateEdgeAction(absParameterPort, outerFloat.OutputPort));
            },
                                    () =>
            {
                // outer float connected, check that we use the outer value
                SyntaxNode astRoot = CompileCurrentGraphModel();
                LiteralExpressionSyntax literalInsideLogAbs = GetLiteralInsideLogAbs(astRoot);
                Assert.That(literalInsideLogAbs.ToFullString(), Is.EqualTo(outerFloatString));
            });
        }
 public static MacroRefNodeModel CreateMacroRefNode(this IGraphModel graphModel, GraphModel macroGraphModel,
                                                    Vector2 position, SpawnFlags spawnFlags = SpawnFlags.Default, GUID?guid = null)
 {
     return(graphModel.CreateNode <MacroRefNodeModel>(graphModel.AssetModel.Name, position, spawnFlags, n => n.GraphAssetModel = (GraphAssetModel)macroGraphModel.AssetModel, guid));
 }
Ejemplo n.º 30
0
        public IEnumerator HighlightIsAppliedToVariables()
        {
            var actions = RunTestFor <VariableNodeModel, TokenNode>(TypeHandle.Int,
                                                                    (m, p) => (VariableNodeModel)GraphModel.CreateVariableNode(m, p));

            while (actions.MoveNext())
            {
                yield return(null);
            }
        }
Ejemplo n.º 31
0
        public GraphViewModel()
        {
            var graph = new GraphModel();

            Host = graph.Picture;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Process data to create the lines
        /// </summary>
        /// <param name="graphData"></param>
        private void ProcessData(GraphModel graphData)
        {
            if (graphData?.result == null || graphData.result.Length <= 0)
            {
                return;
            }
            var dateTimeList = graphData.result.Select(item => item.getDateTime()).ToList();

            var temperatureList = graphData.result.Select(item => item.getTemperature()).Where(item => item.HasValue)
                                  .ToList();

            if (temperatureList != null && temperatureList.Count > 0)
            {
                var line = CreateLine("Temperature", temperatureList, dateTimeList);
                _model.Series.Add(line);
            }

            var humidityList = graphData.result.Select(item => item.getHumidity()).Where(item => item.HasValue)
                               .ToList();

            if (humidityList != null && humidityList.Count > 0)
            {
                var line = CreateLine("Humidity", humidityList, dateTimeList);
                _model.Series.Add(line);
            }

            var setPointList = graphData.result.Select(item => item.getSetPoint()).Where(item => item.HasValue)
                               .ToList();

            if (setPointList != null && setPointList.Count > 0)
            {
                var line = CreateLine("SetPoint", setPointList, dateTimeList);
                _model.Series.Add(line);
            }

            var barometerList = graphData.result.Select(item => item.getBarometer()).Where(item => item.HasValue)
                                .ToList();

            if (barometerList != null && barometerList.Count > 0)
            {
                var line = CreateLine("Barometer", barometerList, dateTimeList);
                _model.Series.Add(line);
            }

            var percentageList = graphData.result.Select(item => item.getValue()).Where(item => item.HasValue).ToList();

            if (percentageList != null && percentageList.Count > 0)
            {
                var line = CreateLine("Percentage", percentageList, dateTimeList);
                _model.Series.Add(line);
            }

            var secondValueList = graphData.result.Select(item => item.getSecondValue()).Where(item => item.HasValue)
                                  .ToList();

            if (secondValueList != null && secondValueList.Count > 0)
            {
                var line = CreateLine("Second Percentage", secondValueList, dateTimeList);
                _model.Series.Add(line);
            }

            var PercentageMinList = graphData.result.Select(item => item.getValueMin()).Where(item => item.HasValue).ToList();

            if (PercentageMinList != null && PercentageMinList.Count > 0)
            {
                var line = CreateLine("Min Percentage", PercentageMinList, dateTimeList);
                _model.Series.Add(line);
            }

            var PercentageMaxList = graphData.result.Select(item => item.getValueMax()).Where(item => item.HasValue).ToList();

            if (PercentageMaxList != null && PercentageMaxList.Count > 0)
            {
                var line = CreateLine("Max Percentage", PercentageMaxList, dateTimeList);
                _model.Series.Add(line);
            }

            var PercentageAvgList = graphData.result.Select(item => item.getValueAvg()).Where(item => item.HasValue).ToList();

            if (PercentageAvgList != null && PercentageAvgList.Count > 0)
            {
                var line = CreateLine("Avg Percentage", PercentageAvgList, dateTimeList);
                _model.Series.Add(line);
            }

            var powerDeliveryList = graphData.result.Select(item => item.getPowerDelivery())
                                    .Where(item => item.HasValue).ToList();

            if (powerDeliveryList != null && powerDeliveryList.Count > 0)
            {
                var line = CreateLine("Power Delivery", powerDeliveryList, dateTimeList);
                _model.Series.Add(line);
            }

            var powerUsageList = graphData.result.Select(item => item.getPowerUsage()).Where(item => item.HasValue)
                                 .ToList();

            if (powerUsageList != null && powerUsageList.Count > 0)
            {
                var line = CreateLine("Power Usage", powerUsageList, dateTimeList);
                _model.Series.Add(line);
            }

            var counterList = graphData.result.Select(item => item.getCounter()).Where(item => item.HasValue).ToList();

            if (counterList != null && counterList.Count > 0)
            {
                var line = CreateLine("Counter", counterList, dateTimeList);
                _model.Series.Add(line);
            }

            var speedList = graphData.result.Select(item => item.getSpeed()).Where(item => item.HasValue).ToList();

            if (speedList != null && speedList.Count > 0)
            {
                var line = CreateLine("Speed", speedList, dateTimeList);
                _model.Series.Add(line);
            }

            var directionList = graphData.result.Select(item => item.getDirection()).Where(item => item.HasValue)
                                .ToList();

            if (directionList != null && directionList.Count > 0)
            {
                var line = CreateLine("Direction", directionList, dateTimeList);
                _model.Series.Add(line);
            }

            var sunPowerList = graphData.result.Select(item => item.getSunPower()).Where(item => item.HasValue)
                               .ToList();

            if (sunPowerList != null && sunPowerList.Count > 0)
            {
                var line = CreateLine("SunPower", sunPowerList, dateTimeList);
                _model.Series.Add(line);
            }

            var usageList = graphData.result.Select(item => item.getUsage()).Where(item => item.HasValue).ToList();

            if (usageList != null && usageList.Count > 0)
            {
                var line = CreateLine("Usage", usageList, dateTimeList);
                _model.Series.Add(line);
            }

            var rainList = graphData.result.Select(item => item.getRain()).Where(item => item.HasValue).ToList();

            if (rainList != null && rainList.Count > 0)
            {
                var line = CreateLine("Rain", rainList, dateTimeList);
                _model.Series.Add(line);
            }

            var co2List = graphData.result.Select(item => item.getCo2()).Where(item => item.HasValue).ToList();

            if (co2List != null && co2List.Count > 0)
            {
                var line = CreateLine("Co2", co2List, dateTimeList);
                _model.Series.Add(line);
            }

            var co2MinList = graphData.result.Select(item => item.getCo2Min()).Where(item => item.HasValue).ToList();

            if (co2MinList != null && co2MinList.Count > 0)
            {
                var line = CreateLine("Min Co2", co2MinList, dateTimeList);
                _model.Series.Add(line);
            }

            var co2MaxList = graphData.result.Select(item => item.getCo2Max()).Where(item => item.HasValue).ToList();

            if (co2MaxList != null && co2MaxList.Count > 0)
            {
                var line = CreateLine("Max Co2", co2MaxList, dateTimeList);
                _model.Series.Add(line);
            }

            var luxList = graphData.result.Select(item => item.getLux()).Where(item => item.HasValue).ToList();

            if (luxList != null && luxList.Count > 0)
            {
                var line = CreateLine("Lux", luxList, dateTimeList);
                _model.Series.Add(line);
            }

            var luxMinList = graphData.result.Select(item => item.getLuxMin()).Where(item => item.HasValue).ToList();

            if (luxMinList != null && luxMinList.Count > 0)
            {
                var line = CreateLine("Min Lux", luxMinList, dateTimeList);
                _model.Series.Add(line);
            }

            var luxMaxList = graphData.result.Select(item => item.getLuxMax()).Where(item => item.HasValue).ToList();

            if (luxMaxList != null && luxMaxList.Count > 0)
            {
                var line = CreateLine("Max Lux", luxMaxList, dateTimeList);
                _model.Series.Add(line);
            }

            var luxAvgList = graphData.result.Select(item => item.getLuxAvg()).Where(item => item.HasValue).ToList();

            if (luxAvgList != null && luxAvgList.Count > 0)
            {
                var line = CreateLine("Avg Lux", luxAvgList, dateTimeList);
                _model.Series.Add(line);
            }

            MapTemperatureLines(graphData, dateTimeList);
        }
Ejemplo n.º 33
0
        public void Test_UpdateRankAction([Values] TestingMode mode)
        {
            TypeHandle intType      = typeof(int).GenerateTypeHandle(Stencil);
            TypeHandle intArrayType = intType.MakeVsArrayType(Stencil);
            VariableDeclarationModel declaration = GraphModel.CreateGraphVariableDeclaration("decl0", typeof(int).GenerateTypeHandle(Stencil), true);

            GraphModel.CreateVariableNode(declaration, Vector2.zero);
            GraphModel.CreateVariableNode(declaration, Vector2.zero);

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(0));

                Assert.That(declaration.DataType.IsVsArrayType(Stencil), Is.False);
                Assert.That(((ConstantNodeModel)declaration.InitializationModel).Type, Is.EqualTo(typeof(int)));

                foreach (var variableNodeModel in GraphModel.NodeModels.OfType <VariableNodeModel>())
                {
                    Assert.That(variableNodeModel.OutputPort.DataType, Is.EqualTo(intType));
                }
                return(new UpdateTypeRankAction(declaration, true));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(0));

                Assert.That(declaration.DataType.IsVsArrayType(Stencil), Is.True);
                Assert.That(((ConstantNodeModel)declaration.InitializationModel), Is.Null, "Array type have no initialization values");

                foreach (var variableNodeModel in GraphModel.NodeModels.OfType <VariableNodeModel>())
                {
                    Assert.That(variableNodeModel.OutputPort.DataType, Is.EqualTo(intArrayType));
                }
            });

            TestPrereqActionPostreq(mode,
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(0));
                Assert.That(declaration.DataType.IsVsArrayType(Stencil), Is.True);
                Assert.That(((ConstantNodeModel)declaration.InitializationModel), Is.Null, "Array type have no initialization values");
                foreach (var variableNodeModel in GraphModel.NodeModels.OfType <VariableNodeModel>())
                {
                    Assert.That(variableNodeModel.OutputPort.DataType, Is.EqualTo(intArrayType));
                }
                return(new UpdateTypeRankAction(declaration, false));
            },
                                    () =>
            {
                Assert.That(GetNodeCount(), Is.EqualTo(2));
                Assert.That(GetEdgeCount(), Is.EqualTo(0));
                Assert.That(declaration.DataType.IsVsArrayType(Stencil), Is.False);
                Assert.That(((ConstantNodeModel)declaration.InitializationModel), Is.Not.Null);
                foreach (var variableNodeModel in GraphModel.NodeModels.OfType <VariableNodeModel>())
                {
                    Assert.That(variableNodeModel.OutputPort.DataType, Is.EqualTo(intType));
                }
            });
        }
Ejemplo n.º 34
0
        public void OnEventTest([Values] CodeGenMode mode)
        {
            SetupTestGraphMultipleFrames(mode, g =>
            {
                ComponentQueryDeclarationModel query = GraphModel.CreateComponentQuery("g1");
                TypeHandle positionType = typeof(Translation).GenerateTypeHandle(Stencil);
                query.AddComponent(Stencil, positionType, ComponentDefinitionFlags.None);
                IVariableModel queryInstance = GraphModel.CreateVariableNode(query, Vector2.zero);

                TypeHandle eventTypeHandle = typeof(UnitTestEvent).GenerateTypeHandle(Stencil);

                OnEventNodeModel onUpdateModel = GraphModel.CreateNode <OnEventNodeModel>("update", Vector2.zero, SpawnFlags.Default, n => n.EventTypeHandle = eventTypeHandle);

                GraphModel.CreateEdge(onUpdateModel.InstancePort, queryInstance.OutputPort);

                SetPropertyGroupNodeModel set = onUpdateModel.CreateStackedNode <SetPropertyGroupNodeModel>("set", 0);
                var member = new TypeMember(TypeHandle.Float, new List <string> {
                    nameof(Translation.Value), nameof(Translation.Value.x)
                });
                set.AddMember(member);

                IVariableModel posComponent = GraphModel.CreateVariableNode(onUpdateModel.FunctionParameterModels.Single(p => p.DataType == positionType), Vector2.zero);
                GraphModel.CreateEdge(set.InstancePort, posComponent.OutputPort);

                ((FloatConstantModel)set.InputConstantsById[member.GetId()]).value = 2f;
            },

                                         // Add translation to even entities
                                         EachEntity((manager, i, e) =>
            {
                if (e.Index % 2 == 0)
                {
                    manager.AddComponent(e, typeof(Translation));
                }
            }),

                                         // Send event on these
                                         EachEntity(del: (manager, i, e) =>
            {
                if (e.Index % 2 == 0)
                {
                    Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(0f));
                }
                else
                {
                    Assert.IsFalse(manager.HasComponent <Translation>(e));
                }

                // Add event on all entities
                manager.AddBuffer <UnitTestEvent>(e).Add(new UnitTestEvent());
            }),

                                         // Event handler should set t.x to 2
                                         EachEntity((manager, i, e) =>
            {
                if (e.Index % 2 == 0)
                {
                    Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(2f));
                }
            }),

                                         // Reset translation
                                         EachEntity((manager, i, e) =>
            {
                if (e.Index % 2 == 0)
                {
                    var t     = manager.GetComponentData <Translation>(e);
                    t.Value.x = 0;
                    manager.SetComponentData(e, t);
                }
            }),

                                         // As we send events manually, the event system is not running and won't cleanup events.
                                         // Event handler should set t.x to 2 again
                                         EachEntity((manager, i, e) =>
            {
                if (e.Index % 2 == 0)
                {
                    Assert.That(manager.GetComponentData <Translation>(e).Value.x, Is.EqualTo(2f));
                }
            })
                                         );
        }