Example #1
0
        public void FindMinWay_Common_3Returned()
        {
            //arrange
            Graph graph = new Graph();

            graph.AddNode(1);
            graph.AddNode(2);
            graph.AddNode(3);
            graph.AddNode(4);
            graph.AddNode(5);

            graph.AddEdge(1, 3, 3);
            graph.AddEdge(1, 2, 7);
            graph.AddEdge(1, 4, 5);

            graph.AddEdge(2, 4, 4);
            graph.AddEdge(2, 5, 8);

            graph.AddEdge(3, 1, 3);

            graph.AddEdge(4, 1, 5);
            graph.AddEdge(4, 5, 6);

            graph.AddEdge(5, 2, 8);

            //act
            int expected = GraphAlgorithm.FindMinWay(graph);
            int actual   = 3;

            //assert
            Assert.AreEqual(expected, actual);
        }
Example #2
0
        public FetchItemServiceResponse<Graph<UserDto>> DetectRolesInGraph(Graph<UserDto> graph)
        {
            FetchItemServiceResponse<Graph<UserDto>> response = new FetchItemServiceResponse<Graph<UserDto>>();

            try
            {
                if (graph.Communities.Count == 0)
                {
                    throw new Exception("You have to find communities first!");
                }

                GraphAlgorithm<UserDto> algorithms = new GraphAlgorithm<UserDto>(graph);
                HashSet<ShortestPathSet<UserDto>> shortestPaths = algorithms.GetAllShortestPathsInGraph(graph.Nodes);

                //setting closeness centrality
                algorithms.SetClosenessCentralityForEachNode(shortestPaths);

                //setting closeness centrality for community
                algorithms.SetClosenessCentralityForEachNodeInCommunity(shortestPaths);

                //community closeness centrality mean and standart deviation
                algorithms.SetMeanClosenessCentralityForEachCommunity();
                algorithms.SetStandartDeviationForClosenessCentralityForEachCommunity();

                //cPaths for nCBC measure
                HashSet<ShortestPathSet<UserDto>> cPaths = algorithms.CPaths(shortestPaths);

                //setting nCBC for each node
                algorithms.SetNCBCForEachNode(cPaths);

                //setting DSCount for each node
                algorithms.SetDSCountForEachNode(cPaths);

                GraphRoleDetection<UserDto> roleDetection = new GraphRoleDetection<UserDto>(graph, algorithms);
                roleDetection.ExtractOutsiders();
                roleDetection.ExtractLeaders();
                roleDetection.ExtractOutermosts();

                //sorting nodes by their mediacy score
                HashSet<Node<UserDto>> sortedNodes = algorithms.OrderNodesByMediacyScore();
                roleDetection.ExtractMediators(sortedNodes);

                response.Succeeded = true;
                response.Item = graph;
            }
            catch (Exception e)
            {
                response.Succeeded = false;
                throw new Exception(e.Message);
            }

            return response;
        }
Example #3
0
        public void FindMinWay_Empty_Exception()
        {
            //arrange
            Graph graph = new Graph();

            string expected = "EmptyGraph";

            //act
            Exception exception = Assert.ThrowsException <Exception>(() => GraphAlgorithm.FindMinWay(graph));
            string    actual    = exception.Message;

            //assert
            Assert.AreEqual(expected, actual);
        }
        public void RunApp_Test()
        {
            Graph <UserDto>              graph         = new Graph <UserDto>();
            GraphAlgorithm <UserDto>     algorithms    = new GraphAlgorithm <UserDto>(graph);
            GraphRoleDetection <UserDto> roleDetection = new GraphRoleDetection <UserDto>(graph, algorithms);


            HashSet <Edge <UserDto> > edges;

            using (IUnitOfWork uow = UnitOfWorkFactory.CreateUnitOfWork())
            {
                edges = uow.GraphRepo.ExtractEdgesFromConversation();
            }
            foreach (Edge <UserDto> edge in edges)
            {
                graph.CreateGraph(edge);
            }


            graph.GetEdgesCount();
            HashSet <ShortestPathSet <UserDto> > shortestPaths = algorithms.GetAllShortestPathsInGraph(graph.Nodes);

            //setting closeness centrality
            algorithms.SetClosenessCentralityForEachNode(shortestPaths);

            //setting closeness centrality for community
            algorithms.SetClosenessCentralityForEachNodeInCommunity(shortestPaths);

            //community closeness centrality mean and standart deviation
            algorithms.SetMeanClosenessCentralityForEachCommunity();
            algorithms.SetStandartDeviationForClosenessCentralityForEachCommunity();

            //cPaths for nCBC measure
            HashSet <ShortestPathSet <UserDto> > cPaths = algorithms.CPaths(shortestPaths);

            //setting nCBC for each node
            algorithms.SetNCBCForEachNode(cPaths);

            //setting DSCount for each node
            algorithms.SetDSCountForEachNode(cPaths);

            roleDetection.ExtractOutsiders();
            roleDetection.ExtractLeaders();
            roleDetection.ExtractOutermosts();

            //sorting nodes by their mediacy score
            HashSet <Node <UserDto> > sortedNodes = algorithms.OrderNodesByMediacyScore();

            roleDetection.ExtractMediators(sortedNodes);
        }
Example #5
0
 private void MenuAlgorithmStartStop_Click(object sender, EventArgs e)
 {
     _SelectedMenuItem = sender as ToolStripMenuItem;
     if (_SelectedMenuItem != null)
     {
         if (_SelectedMenuItem.Name.Contains("Dijkstra"))
         {
             _Algorithm = new DijkstraAlgorithm(_Graph);
         }
         else if (_SelectedMenuItem.Name.Contains("BFS"))
         {
             _Algorithm = new BreathFirstSearchAlgorithm(_Graph);
         }
     }
     StartAlogorithm();
 }
Example #6
0
        public void FindMinWay_1Edge_EdgeWeightReturned()
        {
            //arrange
            Graph graph = new Graph();

            graph.AddNode(1);
            graph.AddNode(2);

            graph.AddEdge(1, 2, 7);

            //act
            int expected = GraphAlgorithm.FindMinWay(graph);
            int actual   = 7;

            //assert
            Assert.AreEqual(expected, actual);
        }
Example #7
0
 private void Timer_Tick(object sender, EventArgs e) // időzített esemény
 {
     if (_Algorithm != null)                         // ha van algoritmus
     {
         if (!_Algorithm.Running)                    // és még nem fut
         {
             _Algorithm.Start();                     // akkor elindítjuk
             if (_Algorithm.Running)                 // ha sikerült elindítani
             {
                 _ListAlgorithmResults.Items.Insert(0, _Algorithm.Status);
                 // a listára felvesszük az algoritmus státuszát
                 _StatusLabel.Text = "Algorithm running...";
             }
             else // ha nem sikerült elindítani
             {
                 _ListAlgorithmResults.Items.Insert(0, "Algorithm finished.");
                 _SelectedMenuItem.Text = "Start";
                 _StatusLabel.Text      = "Algorithm stopped.";
                 _Timer.Interval        = 3000;
                 _Timer.Stop(); // leállítjuk az időzítőt
                 _Algorithm = null;
             }
             DrawGraph();
         }
         else // ha már fut
         {
             _Algorithm.Step(); // léptetjük
             _ListAlgorithmResults.Items.Insert(0, _Algorithm.Status);
             if (!_Algorithm.Running) // ha befejeződött
             {
                 _ListAlgorithmResults.Items.Insert(0, "Algorithm finished.");
                 _SelectedMenuItem.Text = "Start";
                 _StatusLabel.Text      = "Algorithm stopped.";
                 _Timer.Interval        = 3000;
                 _Timer.Stop();
                 //nem rajzolom ki a gráfot, hogy az algoritmus futásának eredménye megmaradjon.
                 _ButtonRedrawGraph.Visible = true;
             }
             else
             {
                 DrawGraph();
             }
         }
     }
 }
Example #8
0
        public void FindMinWay_NonEdged_Exception()
        {
            //arrange
            Graph graph = new Graph();

            graph.AddNode(1);
            graph.AddNode(2);
            graph.AddNode(3);
            graph.AddNode(4);
            graph.AddNode(5);

            string expected = "NonEdgedGraph";

            //act
            Exception exception = Assert.ThrowsException <Exception>(() => GraphAlgorithm.FindMinWay(graph));
            string    actual    = exception.Message;

            //assert

            Assert.AreEqual(expected, actual);
        }
Example #9
0
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            // amikor lenyomjuk az egérgombot
            switch (e.Button)
            {
            case MouseButtons.Left:               // ha bal gomb, akkor kiválasztás
                _Graph.SelectNode(e.Location);    // megpróbálunk csúcsot kiválasztani
                if (!_Graph.NodeSelected)         // ha ez nem sikerül
                {
                    _Graph.SelectArc(e.Location); // megpróbálunk élet kiválasztani
                }
                else
                {
                    if (_Graph.PreviousNode != null && _AutoStart)
                    {
                        _Timer.Interval   = 10;
                        _Algorithm        = _Algorithm = new DijkstraAlgorithm(_Graph);
                        _SelectedMenuItem = _MenuAlgorithmDijkstraStartStop;
                        StartAlogorithm();
                    }
                }
                break;

            case MouseButtons.Right:     // ha jobb gomb, akkor létrehozás
                _Graph.SelectNode(e.Location);
                if (_Graph.NodeSelected) // ha egy csúcson vagyunk, akkor élet hozunk létre
                {
                    _MouseLocation = e.Location;
                }
                else     // különben új csúcsot hozunk létre
                {
                    _Graph.AddNode(e.Location);
                    _GraphChanged = true;
                }
                break;
            }
            DrawGraph();
        }
Example #10
0
 private void StartAlogorithm()
 {
     if (_SelectedMenuItem != null)
     {
         if (_SelectedMenuItem.Text == "Start")
         {
             _SelectedMenuItem.Text = "Stop";
             _ListAlgorithmResults.Items.Clear();                         // listbox eleminek törlése
             _ListAlgorithmResults.Items.Insert(0, "Algorithm started."); // beszúrás a listbox tetejére
             _Timer.Start();                                              // időzítő indítása
         }
         else
         {
             _SelectedMenuItem.Text = "Start";
             _ListAlgorithmResults.Items.Insert(0, "Algorithm stopped.");
             _Timer.Stop(); // időzítő leállítása
             _Algorithm = null;
         }
     }
     else
     {
         _ListAlgorithmResults.Items.Insert(0, "Error! No Menu selected, but the algorithm is begin to start.");
     }
 }
Example #11
0
    void SimulationFlow() // tato funkcia zavola objekty so scenky, prepoji ich umelo, zavola algoritmus na zrusenie uzlov, prepoji zoznamy dllconectorov a spusti simulaciu
    {
        foreach (GUICircuitComponent[] network in _listOfNetworks)
        {
            int numOfBatteries = 0;
            foreach (GUICircuitComponent component in network)
            {
                if (component.GetType() == GameObject.Find("Accumulator").GetComponent <GUICircuitComponent>().GetType())
                {
                    numOfBatteries++;
                }
            }

            if ((numOfBatteries < 2) && (network.Length > 1))
            {
                Circuit newSimulation = new Circuit();
                simList.Add(newSimulation);
                foreach (GUICircuitComponent component in network)
                {
                    component.SetSimulationProp(newSimulation);
                }

                GraphAlgorithm           algorithm = new GraphAlgorithm();
                ConnectionsOfComponent[] dllconnectionsOfComponents = algorithm.Untangle(network);

                //Debug.Log(dllconnectionsOfComponents.Length);
                _countOfMadeConnections = 0;

                List <Circuit.Lead[]> alreadyConnected = new List <Circuit.Lead[]>();

                for (int i = 0; i < dllconnectionsOfComponents.Length; i++)
                {
                    for (int a = 0; a < dllconnectionsOfComponents[i].dllconnections.Length; a++)
                    {
                        for (int b = 0; b < dllconnectionsOfComponents[i].dllconnections[a].connectedDllconnectors.Length; b++)
                        {
                            if (dllconnectionsOfComponents[i].dllconnections[a].dllconector != dllconnectionsOfComponents[i].dllconnections[a].connectedDllconnectors[b])
                            {
                                Boolean alreadyThere = false;
                                foreach (Circuit.Lead[] pair in alreadyConnected)
                                {
                                    if ((pair[0] == dllconnectionsOfComponents[i].dllconnections[a].connectedDllconnectors[b]) && (pair[1] == dllconnectionsOfComponents[i].dllconnections[a].dllconector))
                                    {
                                        alreadyThere = true;
                                    }
                                }

                                if (alreadyThere == false)
                                {
                                    Circuit.Lead[] newPair = new Circuit.Lead[2];
                                    newPair[0] = dllconnectionsOfComponents[i].dllconnections[a].dllconector;
                                    newPair[1] = dllconnectionsOfComponents[i].dllconnections[a].connectedDllconnectors[b];
                                    alreadyConnected.Add(newPair);
                                    //Debug.Log("Komponent cislo: " + i + " konektor ku ktoremu sa pripaja: " + a + " pripajany konektor: " + b + " cislo conections: " + _countOfMadeConnections);
                                    newSimulation.Connect(dllconnectionsOfComponents[i].dllconnections[a].dllconector, dllconnectionsOfComponents[i].dllconnections[a].connectedDllconnectors[b]);
                                    _countOfMadeConnections += 1;
                                }
                            }
                        }
                    }
                }

                Debug.Log("Simulation complete with " + _countOfMadeConnections + " connections");
                Debug.Log("Sim Elements count " + newSimulation.elements.Count);
            }
        }
        _listOfNetworks.Clear();
    }
Example #12
0
    public override void InstantiateSafeStart()
    {
        // First init common stuff
        base.InstantiateSafeStart();

        // >>> Grab variable data from settings
        string teachingMode   = graphSettings.TeachingMode;
        int    difficulty     = graphSettings.Difficulty;
        float  algorithmSpeed = graphSettings.AlgorithmSpeed;


        string graphTask      = graphSettings.GraphTask; //..
        string graphStructure = graphSettings.GraphStructure;
        string edgeType       = graphSettings.EdgeType;
        string edgeBuildMode  = graphSettings.EdgeBuildMode;

        int[] graphSetup = graphSettings.GraphSetup();

        // Extra
        bool shortestPathOneToAll = graphSettings.ShortestPathOneToAll;

        // Only works for Demo as for now,
        if (shortestPathOneToAll && graphSettings.IsUserTest())
        {
            shortestPathOneToAll = false;
        }

        // >>> Init Algorithm
        graphAlgorithm = (GraphAlgorithm)GrabAlgorithmFromObj();
        graphAlgorithm.InitGraphAlgorithm(this, graphStructure, algorithmSpeed, shortestPathOneToAll);

        // >>> Init Graph manager
        bool isShortestPath = graphTask == UtilGraph.SHORTEST_PATH;
        int  minEdge        = graphSettings.MinEdgeCost;
        int  maxEdge        = graphSettings.MaxEdgeCost;

        graphManager = ActivateDeactivateGraphComponents(graphSettings.GraphStructure);
        graphManager.InitGraphManager(algorithmName, graphStructure, edgeType, isShortestPath, graphSettings.RNGDict(), listVisual, minEdge, maxEdge);

        // Graph setup (rows/colums - tree depth/nTree - random?)
        graphManager.InitGraph(graphSetup);

        // Create graph based on init variables
        graphManager.CreateGraph(edgeBuildMode);

        // >>> Init position manager
        posManager.InitPositionManager(isShortestPath);

        // >>> Support
        blackboard.ChangeText(0, algorithmName);

        bool includeLineNr = Settings.PseudocodeLineNr;
        bool inDetailStep  = Settings.PseudocodeStep;

        // Prepare difficulty level related stuff for user test (copied from sort)
        pseudoCodeViewer.InitPseudoCodeViewer(graphAlgorithm, includeLineNr, inDetailStep);
        if (graphSettings.TeachingMode == Util.USER_TEST)
        {
            if (difficulty <= Util.PSEUDO_CODE_MAX_DIFFICULTY)
            {
                // Pseudocode
                pseudoCodeViewer.PseudoCodeSetup();
                // Fix pseudocode for graph
                pseudoCodeViewer.ChangeSizeOfPseudocode(pseudocodeChangeSizeStartPos);
            }

            if (difficulty <= UtilGraph.LIST_VISUAL_MAX_DIFFICULTY)
            {
                // List visual
                string listType = graphAlgorithm.GetListType();
                listVisual.InitListVisual(listType, algorithmSpeed);
                //AddToCheckList(UtilGraph.LIST_VISUAL);
            }
        }
        else
        {
            // >>> Demo
            // Pseudocode
            pseudoCodeViewer.PseudoCodeSetup();

            // Fix pseudocode for graph
            pseudoCodeViewer.ChangeSizeOfPseudocode(pseudocodeChangeSizeStartPos);

            // List visual
            listVisual.InitListVisual(graphAlgorithm.GetListType(), algorithmSpeed);
        }

        // Hide menu
        StartCoroutine(ActivateTaskObjects(true));

        // Init start pillar
        bool selectNodes = graphSettings.SelectStartEndNodes;

        startPillar.InitStartPillar(teachingMode, selectNodes, isShortestPath);

        // If user want to select nodes, then start button will become inactive until node(s) have been chosen
        if (selectNodes)
        {
            // Start node
            chosenNodes           = 0;
            numberOfNodesToChoose = 1;

            // End node
            if (isShortestPath)
            {
                numberOfNodesToChoose++;
            }

            // Init pointer with start task
            pointer.InitPointer(UtilGraph.SELECT_NODE, numberOfNodesToChoose);

            // Start check list
            activeChecklist     = START_UP_CHECK;
            checkListModeActive = true;
        }
        else
        {
            StartCoroutine(SetAutomaticallyImportantNodes(isShortestPath));
        }
    }
Example #13
0
        // TODO: алгоритм запускается в отдельном потоке, надо предусмотреть блокировку формы
        private void InitializeAlgorithmButtons()
        {
            var algorithms = GraphAlgorithmFactory.CreateAllGraphAlgorithms();
            var i          = 1;

            foreach (var algorithm in algorithms)
            {
                algorithm.Performed += result =>
                {
                    if (!string.IsNullOrWhiteSpace(result.StringResult))
                    {
                        MessageBox.Show(result.StringResult,
                                        GetStringResource("ResultMessageBoxTitle"));
                    }
                    else if (result.Number.HasValue)
                    {
                        MessageBox.Show(result.Number.ToString(),
                                        GetStringResource("ResultMessageBoxTitle"));
                    }

                    if (result.Edges != null)
                    {
                        if (result.IsSequential)
                        {
                            ColorizedEdgesAnimation(result.Edges, Brushes.Blue);
                        }
                        else
                        {
                            ColorizeEdges(result.Edges, Brushes.Blue);
                        }
                    }
                    if (result.Vertices != null)
                    {
                        ColorizeVertices(result.Vertices, Brushes.Red);
                    }
                    Dispatcher.Invoke(DispatcherPriority.Normal,
                                      (ThreadStart) delegate { ChangeAction(InterfaceAction.VertexEdit); });
                };
                var button = new Button
                {
                    Style   = FindResource("ToolbarButton") as Style,
                    Content = $"A{i++}",
                    ToolTip = algorithm.Name
                };
                button.Click += (sender, args) =>
                {
                    if (_currentAction == InterfaceAction.PerformAlgorithm && _algorithmVerticesCount == 0)
                    {
                        return;
                    }
                    ColorizeEdges(_graph.Edges, Brushes.Black);
                    ColorizeVertices(_graph.Vertices, Brushes.White);
                    ChangeAction(InterfaceAction.PerformAlgorithm);
                    _algorithmVertices = null;
                    foreach (var parametr in algorithm.RequiredParameters)
                    {
                        if (parametr.Item1 == typeof(Vertex))
                        {
                            _algorithmVerticesCount = parametr.Item2;
                            _algorithmVertices      = new List <Vertex>();
                        }
                    }

                    if (algorithm.RequiredParameters.Length == 1)
                    {
                        var parameters = new GraphAlgorithmParameters(_graph);
                        algorithm.PerformAlgorithmAsync(parameters);
                    }
                    _currentAlgorithm = algorithm;
                };
                Toolbar.Children.Add(button);
            }
        }