Пример #1
0
        }                                                  //выбранный текущий город (для построения дороги)

        public void AddCity(string name, float x, float y) //добавить город
        {
            City city = new GenericGraph.City(name);

            city.Pos = new PointF(x, y);
            MainGraph.AddVertex(city);
        }
Пример #2
0
 private void TsDelete_Click(object sender, EventArgs e)
 {
     Path = null;
     MainGraph.RemoveNode(NodeContext);
     ContextNode.Close();
     NodeContext = null;
 }
Пример #3
0
        private void ProcessStatic()
        {
            PointPairList solution = new PointPairList();

            solution.Add(new PointPair(curX, V));

            for (int i = 0; (i < N) && (curX < maxX); i++)
            {
                V     = Method(V, curX, H);
                curX += H;
                solution.Add(new PointPair(curX, V));
            }

            // Draw points
            GraphPane pane = MainGraph.GraphPane;

            if (ReloadCheckBox.Checked)
            {
                pane.CurveList.Clear();
            }

            pane.AddCurve("Решение c постоянным шагом",
                          solution,
                          Color.FromArgb(random.Next() % 256,
                                         random.Next() % 256,
                                         random.Next() % 256),
                          SymbolType.None);

            MainGraph.AxisChange();
            MainGraph.Refresh();
        }
Пример #4
0
        /// <summary>
        /// Создание нового экземлпяра графа на основе указанного списка смежности.
        /// </summary>
        /// <param name="list">Исходный список смежности.</param>
        /// <returns>Новый экземпляр графа.</returns>
        public static MainGraph GenerateGraph(AdjacencyList list, int medCount, int villCount)
        {
            if (list == null)
            {
                return(null);
            }
            AdjacencyList.PrintGraph(list);
            MainGraph graph = new MainGraph();

            for (int i = 0; i < villCount; i++)
            {
                graph.AddVertex(new DataVertex());
            }
            for (int i = villCount; i < list.VertexCount; i++)
            {
                graph.AddVertex(new DataVertex(VertexColor.Unmarked, VertexType.Unmarket, Utility.Rand.Next(999) + 1));
            }
            for (int i = 0; i < list.VertexCount; i++)
            {
                foreach (int j in list.GetAdjacent(i))
                {
                    if (list.IsDirected || !list.IsDirected && j > i)
                    {
                        var source = graph.Vertices.ElementAt(i);
                        var target = graph.Vertices.ElementAt(j);

                        graph.AddEdge(new DataEdge(source, target, Utility.Rand.Next(9) + 1));
                    }
                }
            }

            return(graph);
        }
 private void ContextNode_Closed(object sender, ToolStripDropDownClosedEventArgs e)
 {
     if (!MainGraph.Contains(TsTbName.Text))
     {
         NodeContext.Name = TsTbName.Text;
     }
 }
        public MainGraph Generate()
        {
            var list = new AdjacencyList(vertexCount);
            int size = vertexClinic + vertexAmbulator;

            MainGraph graph = new MainGraph();

            for (int i = 0; i < vertexVillage; i++)
            {
                graph.AddVertex(new DataVertex(VertexColor.GroupeVillage, VertexType.GroupeVillage, Utility.Rand.Next(50, 10000)));
            }
            for (int i = vertexVillage; i < vertexVillage + vertexClinic; i++)
            {
                graph.AddVertex(new DataVertex(VertexColor.GroupeClinic, VertexType.GroupeClinic, Utility.Rand.Next(10, 9999) + Math.Round(Utility.Rand.NextDouble(), 3)));
            }
            for (int i = vertexVillage + vertexClinic; i < vertexVillage + vertexClinic + vertexAmbulator; i++)
            {
                graph.AddVertex(new DataVertex(VertexColor.GroupeMedic, VertexType.GroupeMedic, Utility.Rand.Next(10, 9999) + Math.Round(Utility.Rand.NextDouble(), 3)));
            }

            for (int v = 0; v < vertexVillage; v++)
            {
                for (int c = vertexVillage; c < vertexCount; c++)
                {
                    var source = graph.Vertices.ElementAt(v);
                    var target = graph.Vertices.ElementAt(c);
                    graph.AddEdge(new DataEdge(source, target,
                                               Utility.Rand.Next(1, 9999) + Math.Round(Utility.Rand.NextDouble(), 3)));
                }
            }


            return(graph);
        }
Пример #7
0
        public void AddRoad(int length, City c1, City c2) //добавить дорогу
        {
            Road road = new GenericGraph.Road(length);

            road.Connections[0] = c1;
            road.Connections[1] = c2;
            MainGraph.AddEdge(road, c1, c2);
        }
        public MatrixRoadDialog(Window owner, Cost cost, ProblemData problemData, MainGraph graph)
        {
            Owner = owner;
            InitializeComponent();


            DataContext = new Content(Matrix, cost, problemData, graph);
        }
Пример #9
0
 private void TsLinkDelete_Click(object sender, EventArgs e)
 {
     Path = null;
     MainGraph.RemoveLink(LinkContext);
     if (ToolDoubleLink)
     {
         MainGraph.RemoveLink(LinkContext.To.Links.Find((el) => { return(el.To == LinkContext.From); }));
     }
 }
Пример #10
0
        private void DrawIntegral()
        {
            PointPairList pairListHit   = new PointPairList();
            PointPairList pairListNoHit = new PointPairList();

            double function_result;
            double d = FindMaximum();
            double c = FindMinimum();
            double x;
            double y;

            for (uint i = 0; i < N; ++i)
            {
                x = a + random.NextDouble() * (b - a);
                y = c + random.NextDouble() * (d - c);

                function_result = Function(x);

                if (0 > function_result)
                {
                    if (0 > y && function_result <= y)
                    {
                        pairListHit.Add(new PointPair(x, y));
                    }
                    else
                    {
                        pairListNoHit.Add(new PointPair(x, y));
                    }
                }
                else
                {
                    if (0 <= y && function_result >= y)
                    {
                        pairListHit.Add(new PointPair(x, y));
                    }
                    else
                    {
                        pairListNoHit.Add(new PointPair(x, y));
                    }
                }
            }


            LineItem hitCurve = pane.AddCurve("Hit", pairListHit, Color.Green, SymbolType.Plus);

            hitCurve.Line.IsVisible = false;

            LineItem noHitCurve = pane.AddCurve("Not hit", pairListNoHit, Color.Red, SymbolType.Circle);

            noHitCurve.Line.IsVisible = false;

            MainGraph.Hide();
            MainGraph.AxisChange();
            MainGraph.Show();
        }
Пример #11
0
 private void BtnAddEdge_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         Edge newEdge = new Edge(MainGraphName + _MainGraph.EdgeCollection.Count().ToString(), SelectedStartPoint, SelectedEndPoint);
         MainGraph.AddEdge(newEdge);
         NotifyPropertyChanged("MainGraph");
         TaskAnswer = GraphUtils.IsDirectedTree(MainGraph);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Ошибка добавления");
     }
 }
Пример #12
0
        private int CountPoint()
        {
            int       count = 0;
            MainGraph graph = graphArea.LogicCore.Graph as MainGraph;

            foreach (var vertex in graph.Vertices)
            {
                if (vertex.Type != VertexType.GroupeVillage)
                {
                    count++;
                }
            }

            return(count);
        }
Пример #13
0
        public void ExplorePieceDfs(Node conNode, Edge edge, List <Edge> piece)
        {
            piece.Add(edge);
            VisitedEdges.Add(edge);
            Node otherNode = edge.OtherNode(conNode);

            if (SubGraph.Nodes.Contains(otherNode))
            {
                return;
            }
            foreach (Edge source in MainGraph.GetEdges(otherNode).Where(e => !VisitedEdges.Contains(e)))
            {
                ExplorePieceDfs(otherNode, source, piece);
            }
        }
Пример #14
0
        /// <summary>
        /// Создание нового экземлпяра списка смежности на основе указанного графа.
        /// </summary>
        /// <param name="graph">Исходный граф.</param>
        /// <returns>Новый экземпляр графа, задаваемого списком смежности.</returns>
        public static AdjacencyList GenerateList(MainGraph graph)
        {
            var list = new AdjacencyList(graph.VertexCount);

            var vertices = graph.Vertices.ToList();

            foreach (var edge in graph.Edges)
            {
                int source = vertices.IndexOf(edge.Source);
                int target = vertices.IndexOf(edge.Target);
                list.AddEdge(source, target);
            }
            PrintGraph(list);
            return(list);
        }
Пример #15
0
        private void DrawFunction()
        {
            PointPairList pairList = new PointPairList();
            PointPair     pair     = new PointPair();

            for (double x = a; x < b; x += (b - a) / N)
            {
                pair.X = x;
                pair.Y = Function(x);

                pairList.Add(pair);
            }

            pane.AddCurve("Function", pairList, Color.Black, SymbolType.None);

            MainGraph.Hide();
            MainGraph.AxisChange();
            MainGraph.Show();
        }
Пример #16
0
        public MainForm()
        {
            try
            {
                InitializeComponent();
                MsgBox  = new WinFormMessageBox();
                FDialog = new WinFormFileDialog();
                MainUI  = new LapseStudioUI(Platform.Windows, this, MsgBox, FDialog);

                WinFormFileDialog.InitOpenFolderDialog(this);
                AddFileToolButton.Image   = Timelapse_UI.Properties.Resources.Add32;
                CalculateToolButton.Image = Timelapse_UI.Properties.Resources.Calculate32;
                MetadataToolButton.Image  = Timelapse_UI.Properties.Resources.Reload32;
                ProcessToolButton.Image   = Timelapse_UI.Properties.Resources.Save32;
                CancelToolButton.Image    = Timelapse_UI.Properties.Resources.Cancel32;

                MainUI.MainGraph = new BrightnessGraph(MainGraph.Width, MainGraph.Height);
                MainGraph.Init(MainUI.MainGraph);
                MainUI.InitBaseUI();
            }
            catch (Exception ex) { Error.Report("Init", ex); }
        }
Пример #17
0
        public MainWindow()
            : base(Gtk.WindowType.Toplevel)
        {
            try
            {
                this.Build();
                MainUI = new LapseStudioUI(Platform.Unix, this, MsgBox, new GtkFileDialog());

                FileTree.CursorChanged += FileTree_CursorChanged;
                List <Pixbuf> iconlist = new List <Pixbuf>();
                if (File.Exists("Icons/Icon16.png"))
                {
                    iconlist.Add(new Pixbuf("Icons/Icon16.png"));
                }
                if (File.Exists("Icons/Icon32.png"))
                {
                    iconlist.Add(new Pixbuf("Icons/Icon32.png"));
                }
                if (File.Exists("Icons/Icon64.png"))
                {
                    iconlist.Add(new Pixbuf("Icons/Icon64.png"));
                }
                if (File.Exists("Icons/Icon128.png"))
                {
                    iconlist.Add(new Pixbuf("Icons/Icon128.png"));
                }
                if (File.Exists("Icons/Icon256.png"))
                {
                    iconlist.Add(new Pixbuf("Icons/Icon256.png"));
                }
                this.IconList = iconlist.ToArray();

                MainUI.MainGraph = new BrightnessGraph(MainGraph.Allocation.Width, MainGraph.Allocation.Height);
                MainGraph.Init(MainUI.MainGraph);
                MainUI.InitBaseUI();
            }
            catch (Exception ex) { Error.Report("Init", ex); MainUI.Quit(ClosingReason.Error); }
        }
Пример #18
0
        public int MST(List <Root> roots)
        {
            PriorityQueue Q;
            int           mstCount = 0;

            // Foreach seed vertex
            foreach (var r in roots)
            {
                // Reset PriorityQueue
                Q = null;
                Q = new PriorityQueue(MainGraph.Vertices);

                // Set source Cost to 0
                int src_index = Q.IndexOf(r.RootVertex);
                Q[src_index].Cost    = 0;
                Q[src_index].Visited = true;
                MainGraph.UpdateVisited(Q[src_index]);
                // Move to top
                Q.Exchange(0, src_index);

                Vertex p, next;
                // While Q is not empty
                while (Q.Size > 0)
                {
                    // poll
                    p = Q.Poll();

                    // If we get null we are disconnected
                    if (p == null)
                    {
                        break;
                    }

                    // for neighbors
                    for (int i = 0; i < p.Neighbors.Count; ++i)
                    {
                        // No more neighbors
                        if (p.Neighbors[i].ID == 0)
                        {
                            break;
                        }

                        // edge weight
                        float dist = p.Neighbors[i].Weight;

                        // Get neighbor index and vertex from Q
                        int neighborNode = p.Neighbors[i].Node2;
                        next = Q.GetVertex(neighborNode);

                        // Update visited and cost
                        if (next != null)
                        {
                            next.Cost    = dist;
                            next.Visited = true;
                            MainGraph.UpdateVisited(next);
                            Q.Reweight(next, p);
                        }
                        else
                        {
                            next         = MainGraph.GetVertexWithID(neighborNode);
                            next.Visited = true;
                            MainGraph.UpdateVisited(next);
                        }
                    }
                } // End whle

                // Check if all have been visited yet
                if (MainGraph.GetVisited())
                {
                    ++mstCount;
                }
            } // Foreach root
            return(mstCount);
        }
Пример #19
0
        void ReleaseDesignerOutlets()
        {
            if (AlignXButton != null)
            {
                AlignXButton.Dispose();
                AlignXButton = null;
            }

            if (BrightnessSlider != null)
            {
                BrightnessSlider.Dispose();
                BrightnessSlider = null;
            }

            if (BrightnessToolItem != null)
            {
                BrightnessToolItem.Dispose();
                BrightnessToolItem = null;
            }

            if (CancelToolItem != null)
            {
                CancelToolItem.Dispose();
                CancelToolItem = null;
            }

            if (EditThumbsButton != null)
            {
                EditThumbsButton.Dispose();
                EditThumbsButton = null;
            }

            if (FrameSelectedLabel != null)
            {
                FrameSelectedLabel.Dispose();
                FrameSelectedLabel = null;
            }

            if (FrameSelectSlider != null)
            {
                FrameSelectSlider.Dispose();
                FrameSelectSlider = null;
            }

            if (GraphResetButton != null)
            {
                GraphResetButton.Dispose();
                GraphResetButton = null;
            }

            if (MainGraph != null)
            {
                MainGraph.Dispose();
                MainGraph = null;
            }

            if (MainProgressBar != null)
            {
                MainProgressBar.Dispose();
                MainProgressBar = null;
            }

            if (MainTable != null)
            {
                MainTable.Dispose();
                MainTable = null;
            }

            if (MainTabView != null)
            {
                MainTabView.Dispose();
                MainTabView = null;
            }

            if (MetadataToolItem != null)
            {
                MetadataToolItem.Dispose();
                MetadataToolItem = null;
            }

            if (OpenFileToolItem != null)
            {
                OpenFileToolItem.Dispose();
                OpenFileToolItem = null;
            }

            if (ProcessToolItem != null)
            {
                ProcessToolItem.Dispose();
                ProcessToolItem = null;
            }

            if (Statuslabel != null)
            {
                Statuslabel.Dispose();
                Statuslabel = null;
            }

            if (TabChangeButton != null)
            {
                TabChangeButton.Dispose();
                TabChangeButton = null;
            }

            if (ThumbEditView != null)
            {
                ThumbEditView.Dispose();
                ThumbEditView = null;
            }

            if (ThumbViewGraph != null)
            {
                ThumbViewGraph.Dispose();
                ThumbViewGraph = null;
            }

            if (ThumbViewList != null)
            {
                ThumbViewList.Dispose();
                ThumbViewList = null;
            }

            if (YToEndButton != null)
            {
                YToEndButton.Dispose();
                YToEndButton = null;
            }

            if (YToStartButton != null)
            {
                YToStartButton.Dispose();
                YToStartButton = null;
            }
        }
Пример #20
0
        public static int Answer(Cost cost, Chromosome chromosome, ProblemData problemData, MainGraph graph)
        {
            if (chromosome == null || chromosome.fitness == double.MaxValue)
            {
                return(0);
            }
            List <int> array = new List <int>();

            for (int i = 0; i < chromosome.SizeChromosome; i++)
            {
                if (cost.unmarketVertex[i] * chromosome.chromosomeArray[i] != 0)
                {
                    array.Add(cost.unmarketVertex[i]);
                }
            }

            if (array.Count == 1)
            {
                graph.Vertices.ElementAt(array.First()).Color = VertexColor.GroupeClinic;
            }
            else if (array.Count % 2 == 1 && array.Count != 1)
            {
                int    i = (array.Count / 2);
                double a = Math.Abs(array[i + 1] - array[i]);
                double b = Math.Abs(array[i - 1] - array[i]);
                if (a > b)
                {
                    graph.Vertices.ElementAt(array[i]).Color = VertexColor.GroupeClinic;
                }
                else
                {
                    graph.Vertices.ElementAt(array[i]).Color = VertexColor.GroupeMedic;
                }
            }
            for (int i = 0, j = array.Count - 1; i < array.Count / 2; i++, j--)
            {
                if (graph.Vertices.ElementAt(array[i]).vertexCost < graph.Vertices.ElementAt(array[j]).vertexCost)
                {
                    graph.Vertices.ElementAt(array[i]).Color = VertexColor.GroupeMedic;
                    graph.Vertices.ElementAt(array[j]).Color = VertexColor.GroupeClinic;
                }
                else
                {
                    graph.Vertices.ElementAt(array[i]).Color = VertexColor.GroupeClinic;
                    graph.Vertices.ElementAt(array[j]).Color = VertexColor.GroupeMedic;
                }
            }
            return(1);
        }
Пример #21
0
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            Link l        = null;
            bool KeyShift = Control.ModifierKeys == Keys.Shift;
            bool KeyCtrl  = Control.ModifierKeys == Keys.Control;

            Node ClickNode = SearchNodes(MouseGetPos());

            if (ClickNode == null)
            {
                l = SearchLinks(MouseGetPos());
            }
            if (ClickNode != null)                 // ЕСЛИ КЛИКНУЛИ НА ВЕРШИНУ
            {
                if (e.Button == MouseButtons.Left) //ЛЕВЫЙ КЛИК НА ВЕРШИНУ
                {
                    if (KeyShift && KeyCtrl)
                    {
                    }
                    else if (KeyShift)
                    {
                        NodeForLink = ClickNode;
                    }
                    else if (KeyCtrl)
                    {
                        if (MainGraph.Nodes.Count >= Max)
                        {
                            return;
                        }
                        Node n = new Node("N" + NextNodeName++, MouseGetPos());
                        MainGraph.Add(n);
                        if (!ToolDoubleLink)
                        {
                            ClickNode.Link(n);
                        }
                        else
                        {
                            ClickNode.LinkTwo(n);
                        }
                        CurrentNode = n;
                    }
                    else
                    {
                        CurrentNode = ClickNode;
                    }
                }
                else if (e.Button == MouseButtons.Right) //ПРАВЫЙ КЛИК НА ВЕРШИНУ
                {
                    NodeContext           = ClickNode;
                    this.ContextMenuStrip = ContextNode;
                }
            }
            else if (l != null) //КЛИК НА ЛИНКА
            {
                if (e.Button == MouseButtons.Right)
                {
                    LinkContext      = l;
                    ContextMenuStrip = ContexLink;
                }
            }
            else  //КЛИК В НИКУДА
            {
                if (e.Button == MouseButtons.Left)
                {
                    if (KeyCtrl)
                    {
                        if (MainGraph.Nodes.Count >= Max)
                        {
                            return;
                        }
                        MainGraph.Add(new Node("N" + NextNodeName++, MouseGetPos()));
                    }
                }
                else if (e.Button == MouseButtons.Right)
                {
                    NodeContext           = null;
                    this.ContextMenuStrip = null;
                }
            }
        }
Пример #22
0
 public Content(ContentControl contentControl, Cost cost, ProblemData problemData, MainGraph graph)
 {
     this.contentControl = contentControl;
     PrintMatrix(cost, problemData, graph);
 }
Пример #23
0
        void PrintMatrix(Cost cost, ProblemData problemData, MainGraph graph)
        {
            var grid = new Grid();

            for (int i = 0; i < cost.costEdgeArray[0].Length + 1; i++)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition());
                grid.RowDefinitions.Add(new RowDefinition());
            }

            for (int i = 0; i < cost.costEdgeArray.Length + 1; i++)
            {
                for (int j = 0; j < cost.costEdgeArray[0].Length + 1; j++)
                {
                    TextBox textBox = new TextBox();
                    textBox.BorderBrush     = Brushes.Gray;
                    textBox.BorderThickness = new Thickness(1);
                    textBox.IsReadOnly      = true;
                    Grid.SetRow(textBox, i);
                    Grid.SetColumn(textBox, j);


                    if (i == 0 && j == 0)
                    {
                        textBox.Background = Brushes.LightGray;
                        textBox.Text       = "";
                    }
                    else if (i == 0)
                    {
                        if (cost.costEdgeArray[0][j - 1].roadKm == 0)
                        {
                            continue;
                            //textBox.Background = Brushes.Gray;
                        }
                        else
                        {
                            textBox.Background = Brushes.AliceBlue;
                        }
                        textBox.Text = (j).ToString();
                    }
                    else if (j == 0)
                    {
                        int iVertex = cost.unmarketVertex[i - 1];
                        var vertex  = graph.Vertices.ToList().ElementAt(iVertex);
                        if (iVertex + 1 == vertex.ID)
                        {
                            if (vertex.Color == VertexColor.GroupeClinic)
                            {
                                textBox.Background = Brushes.Green;
                            }
                            else if (vertex.Color == VertexColor.GroupeMedic)
                            {
                                textBox.Background = Brushes.Orange;
                            }
                            else if (vertex.Color == VertexColor.Unmarked)
                            {
                                textBox.Background = Brushes.LightGray;
                            }
                        }
                        textBox.Text = (iVertex + 1).ToString() + ": " + cost.costVertexArray[i - 1].ToString();
                    }
                    else if ((i != 0 && j != 0) || j != 0 || i != 0)
                    {
                        if (cost.costEdgeArray[i - 1][j - 1].roadKm == 0)
                        {
                            continue;
                        }

                        textBox.Background = Brushes.White;
                        textBox.Text       = (cost.costEdgeArray[i - 1][j - 1].roadKm * problemData.RoadCost).ToString();
                    }
                    grid.Children.Add(textBox);
                }
            }
            contentControl.Content = grid;
        }
Пример #24
0
        private void ProcessExact()
        {
            PointPairList solution = new PointPairList();

            double startI = V;
            double startX = curX;

            List <List <double> > table = new List <List <double> >();
            List <double>         row   = new List <double>(11);

            solution.Add(new PointPair(startX, startI));

            table.Add(new List <double>()
            {
                0, H, startX, startI
            });

            for (int i = 0; (i < N) && (startX < maxX); i++)
            {
                row.Clear();

                startI  = Method(startI, startX, H);
                startX += H;
                solution.Add(new PointPair(startX, startI));

                row.Add(i + 1);
                row.Add(H);
                row.Add(startX);
                row.Add(startI);

                table.Add(new List <double>(row));
            }

            // Fill table
            DataGridViewRowCollection rows = ExactTable.Rows;

            rows.Clear();

            for (int i = 0; i < table.Count; ++i)
            {
                rows.Add();

                for (int j = 0; j < table[i].Count; ++j)
                {
                    rows[i].Cells[j].Value = table[i][j];
                }
            }

            // Fill last dot
            DataGridViewRowCollection lastDotRow = LastDotTable.Rows;

            lastDotRow.Clear();

            if (0 < table.Count)
            {
                lastDotRow.Add();

                for (int i = 0; i < lastDotRow[0].Cells.Count; ++i)
                {
                    lastDotRow[0].Cells[i].Value = rows[rows.Count - 1].Cells[i].Value;
                }
            }

            // Draw points
            GraphPane pane = MainGraph.GraphPane;

            if (ReloadCheckBox.Checked)
            {
                pane.CurveList.Clear();
            }

            pane.AddCurve("Точное решение",
                          solution,
                          Color.FromArgb(random.Next() % 256,
                                         random.Next() % 256,
                                         random.Next() % 256),
                          SymbolType.None);

            MainGraph.AxisChange();
            MainGraph.Refresh();
        }
Пример #25
0
        private void ProcessDynamic()
        {
            PointPairList solutionWithHalfStep = new PointPairList();

            List <List <double> > table = new List <List <double> >();
            List <double>         row   = new List <double>(11);
            List <double>         Slist = new List <double>();
            List <double>         Xlist = new List <double>();

            double Hprev = H;
            double Vstep = V;
            double Vhalf;
            double Vprev;
            double S;

            uint C1      = 0u;
            uint C2      = 0u;
            uint totalC1 = 0u;
            uint totalC2 = 0u;

            // step #0
            table.Add(new List <double>()
            {
                0, 0, curX, Vstep, Vstep, 0, 0, 0, 0
            });
            solutionWithHalfStep.Add(new PointPair(curX, Vstep));

            // using control
            for (uint i = 1u; (i <= N);)
            {
                // Save previous result
                Vprev = Vstep;
                Hprev = H;

                Vstep = Method(Vprev, curX, H);
                Vhalf = Method(Vprev, curX, H * 0.5);
                Vhalf = Method(Vhalf, curX + (H * 0.5), H * 0.5);

                S = (Vhalf - Vstep) / (Math.Pow(2.0, 4.0) - 1.0);

                if (Math.Abs(S) > eps)
                {
                    H    *= 0.5;
                    Vstep = Vprev;
                    C1++;

                    continue;
                }
                else
                {
                    curX += H;

                    if (Math.Abs(S) <= (eps / Math.Pow(2.0, 5.0)))
                    {
                        H *= 2.0;
                        C2++;
                    }
                }

                Slist.Add(S);
                Xlist.Add(curX);

                // fill the graph
                solutionWithHalfStep.Add(new PointPair(curX, Vhalf));

                // Create table
                row.Clear();

                // index
                row.Add(i);

                // current step
                row.Add(Hprev);

                // x value
                row.Add(curX);

                // v value with step
                row.Add(Vstep);

                // v value with half step
                row.Add(Vhalf);

                // difference between them
                row.Add(Vstep - Vhalf);

                // S
                row.Add(S);

                // number of step doubles
                row.Add(C1);

                //number of step divisions in half
                row.Add(C2);

                // store row
                table.Add(new List <double>(row));

                if (curX >= maxX)
                {
                    break;
                }

                // Update fields
                i++;
                totalC1 += C1;
                totalC2 += C2;
                C1       = 0u;
                C2       = 0u;
            }

            // Draw points
            GraphPane pane = MainGraph.GraphPane;

            if (ReloadCheckBox.Checked)
            {
                pane.CurveList.Clear();
            }

            pane.AddCurve("Решение с половинным шагом",
                          solutionWithHalfStep,
                          Color.FromArgb(random.Next() % 256,
                                         random.Next() % 256,
                                         random.Next() % 256),
                          SymbolType.None);

            MainGraph.AxisChange();
            MainGraph.Refresh();

            // Fill table
            DataGridViewRowCollection rows = MainTable.Rows;

            rows.Clear();

            for (int i = 0; i < table.Count; ++i)
            {
                rows.Add();

                for (int j = 0; j < table[i].Count; ++j)
                {
                    rows[i].Cells[j].Value = table[i][j];
                }
            }

            // Fill last dot
            DataGridViewRowCollection lastDotRow = LastDotTable.Rows;

            lastDotRow.Clear();

            if (0 < table.Count)
            {
                lastDotRow.Add();

                for (int i = 0; i < lastDotRow[0].Cells.Count; ++i)
                {
                    lastDotRow[0].Cells[i].Value = rows[rows.Count - 1].Cells[i].Value;
                }
            }

            if ((0 == Slist.Count) || (0 == Xlist.Count))
            {
                return;
            }

            // Fill reference
            double minS  = Math.Abs(Slist[0]);
            double maxS  = Math.Abs(Slist[0]);
            double maxSx = Xlist[0];
            double minSx = Xlist[0];

            for (int i = 1; i < Slist.Count; ++i)
            {
                if (Math.Abs(Slist[i]) > maxS)
                {
                    maxS  = Math.Abs(Slist[i]);
                    maxSx = Xlist[i];
                }

                if (Math.Abs(Slist[i]) < minS)
                {
                    minS  = Math.Abs(Slist[i]);
                    minSx = Xlist[i];
                }
            }

            minSLabel.Text = "min |S| = " + minS.ToString() + "\nв точке x = " + minSx.ToString();
            maxSLabel.Text = "max |S| = " + maxS.ToString() + "\nв точке x = " + maxSx.ToString();
            IncLabel.Text  = "Ув. шага = " + totalC2.ToString();
            DecLabel.Text  = "Ум. шага = " + totalC1.ToString();
        }
Пример #26
0
        public override int GeneticAlgorithm(MainGraph graph, ProblemData problemData)
        {
            algorithmInfo = new AlgorithmInfo();
            adjacencyList = AdjacencyList.GenerateList(graph);
            cost          = Cost.GanerateCostArray(graph, problemData); problem = problemData;

            var crossover = GeneticMethod.ChosenCrossoverMethod(crossoverMethod, CrossoverProbability, dotCrossover);
            var mutation  = GeneticMethod.ChosenMutationMethod(mutationMethod, MutationProbability, dotMutation);
            var selection = GeneticMethod.ChosenSelectionMethod(selectionMethod, CountTour, CountSelected);
            ReductionForClassicGA reduction = new ReductionForClassicGA();

            Chromosome bestChromosome  = null;
            Population startPopulation = new Population(PopulationSize, cost);
            var        population      = startPopulation;
            int        stepGA          = 0;

            double          MediumFitness   = Solution.MediumFitnessPopulation(population);
            RandomSelection randomSelection = new RandomSelection();

            FitnessCalculation(population.populationList);
            stopwatch = new Stopwatch();
            stopwatch.Start();
            while (stepGA < IterateSize)
            {
                List <Chromosome> midPopulation    = selection.Selection(population);
                List <Chromosome> parentPopulation = randomSelection.Selection(midPopulation, selection.indexSelectChrom);
                List <Chromosome> childList        = crossover.Crossover(parentPopulation);
                if (childList.Count == 0)
                {
                    continue;
                }
                mutation.Mutation(childList);
                FitnessCalculation(childList);


                reduction.Reduction(childList, randomSelection.indexTwoParant, population.populationList);

                double tempMediumFitness = Solution.MediumFitnessPopulation(population);
                double absFitness        = Math.Abs(tempMediumFitness - MediumFitness);
                MediumFitness = tempMediumFitness;
                if (absFitness >= 0 && absFitness <= 1)
                {
                    bestChromosome = population.BestChromosome();
                    var worstChromosome = population.WorstChromosome();
                    if (bestChromosome.fitness - worstChromosome.fitness <= 1 && bestChromosome.fitness - worstChromosome.fitness >= 0)
                    {
                        if (Solution.isAnswerTrue(bestChromosome, cost, problemData))
                        {
                            stopwatch.Stop();

                            algorithmInfo.Time   = stopwatch.Elapsed;
                            algorithmInfo.BestFx = bestChromosome.fitness;
                            algorithmInfo.Steps  = stepGA;
                            break;
                        }
                    }
                }
                stepGA++;
            }
            stopwatch.Stop();
            if (stepGA == IterateSize)
            {
                bool answer = false;
                bestChromosome = population.BestChromosome();
                while (population.populationList.Count != 0)
                {
                    if (Solution.isAnswerTrue(bestChromosome, cost, problemData))
                    {
                        algorithmInfo.Time   = stopwatch.Elapsed;
                        algorithmInfo.BestFx = bestChromosome.fitness;
                        algorithmInfo.Steps  = stepGA;
                        answer = true;
                        break;
                    }
                    else
                    {
                        population.populationList.Remove(bestChromosome);
                        if (population.populationList.Count == 0)
                        {
                            break;
                        }
                        bestChromosome = population.BestChromosome();
                    }
                }
                if (!answer)
                {
                    bestChromosome = null;
                }
            }

            return(Solution.Answer(cost, bestChromosome, problemData, graph));
        }
 /// <summary>
 /// Абстрактный метод генетического алгоритма
 /// </summary>
 /// <param name="graph"></param>
 /// <param name="problemData">Параметры задачи</param>
 public abstract int GeneticAlgorithm(MainGraph graph, ProblemData problemData);
Пример #28
0
        /// <summary>
        /// Реализация генетического алгоритма "CHC".
        /// </summary>
        /// <param name="graph">Граф.</param>
        /// <param name="problemData">Параметры задачи.</param>
        public override int GeneticAlgorithm(MainGraph graph, ProblemData problemData)
        {
            algorithmInfo = new AlgorithmInfo();
            // Инициализация основных структур.
            adjacencyList = AdjacencyList.GenerateList(graph);
            cost          = Cost.GanerateCostArray(graph, problemData);
            problem       = problemData;

            Population   startPopulation = new Population(PopulationSize, cost);
            Population   population      = startPopulation;
            HUXCrossover crossover       = new HUXCrossover(population.SizeChromosome / 4, CrossoverProbability);

            Chromosome bestChromosome = null;
            int        stepGA         = 0;

            stopwatch = new Stopwatch();
            stopwatch.Start();
            while (stepGA < IterateSize)
            {
                FitnessCalculation(population.populationList);

                List <Chromosome> childList = crossover.Crossover(population.populationList);


                if (crossover.Distanse == 0)
                {
                    CatacliysmicMutation(population);
                    crossover.Distanse = population.SizeChromosome / 4;
                    stepGA++;
                    continue;
                }
                if (childList.Count == 0)
                {
                    crossover.Distanse--;
                    stepGA++;
                    continue;
                }

                FitnessCalculation(childList);

                List <Chromosome> newPopulation = EliteReductionForCHC.Reduction(population.populationList, childList, PopulationSize);

                population.populationList = newPopulation;

                stepGA++;
            }
            stopwatch.Stop();
            if (stepGA == IterateSize)
            {
                bool answer = false;
                bestChromosome = population.BestChromosome();
                while (population.populationList.Count != 0)
                {
                    if (population.populationList.Count == 0)
                    {
                        break;
                    }

                    if (Solution.isAnswerTrue(bestChromosome, cost, problemData))
                    {
                        algorithmInfo.Time   = stopwatch.Elapsed;
                        algorithmInfo.BestFx = bestChromosome.fitness;
                        algorithmInfo.Steps  = stepGA;

                        answer = true;
                        break;
                    }
                    else
                    {
                        population.populationList.Remove(bestChromosome);
                        if (population.populationList.Count == 0)
                        {
                            break;
                        }
                        bestChromosome = population.BestChromosome();
                    }
                }
                if (!answer)
                {
                    bestChromosome = null;
                }
            }



            return(Solution.Answer(cost, bestChromosome, problemData, graph));
        }
Пример #29
0
        /// <summary>
        /// Реализация генетического алгоритма "Genitor".
        /// </summary>
        /// <param name="graph">Граф.</param>
        /// <param name="problemData">Параметры задачи</param>
        public override int GeneticAlgorithm(MainGraph graph, ProblemData problemData)
        {
            this.algorithmInfo = new AlgorithmInfo();
            // Инициализация основных структур.
            adjacencyList = AdjacencyList.GenerateList(graph);
            cost          = Cost.GanerateCostArray(graph, problemData); ProblemData problem = problemData;

            var        crossover      = GeneticMethod.ChosenCrossoverMethod(crossoverMethod, 100, dotCrossover);
            var        mutation       = GeneticMethod.ChosenMutationMethod(mutationMethod, MutationProbability, dotMutation);
            var        selection      = GeneticMethod.ChosenSelectionMethod(selectionMethod, CountTour, CountSelected);
            Chromosome bestChromosome = null;
            double     MediumFitness  = 0;


            Population startPopulation = new Population(PopulationSize, cost);

            var population = startPopulation;

            int stepGA = 0;

            // вычесление пригодности хромосом.
            for (int i = 0; i < PopulationSize; i++)
            {
                population.populationList[i].fitness = Fitness.FunctionTrue(cost, problemData, population.populationList[i]);
            }
            RandomSelection randomSelection = new RandomSelection();

            MediumFitness = Solution.MediumFitnessPopulation(population);
            stopwatch     = new Stopwatch();
            stopwatch.Start();
            while (stepGA < IterateSize)
            {
                List <Chromosome> midPopulation    = selection.Selection(population);
                List <Chromosome> parentPopulation = randomSelection.Selection(midPopulation);
                Chromosome        child            = crossover.Crossover(parentPopulation[0], parentPopulation[1]);

                if (mutation != null)
                {
                    mutation.Mutation(child);
                }
                // вычесление ранга хромосомы.

                //population.Sort();
                Ranking2(population);
                // пригодность потомка
                child.fitness = Fitness.FunctionTrue(cost, problemData, child);
                // поиск самой худщей хромосомы
                Chromosome bedChrom = null;

                bedChrom = population.populationList.First();


                // замена худшей хромосомы на потомка
                int index = population.populationList.IndexOf(bedChrom);
                population.populationList.Insert(index, child);
                population.populationList.RemoveAt(index + 1);

                double tempMediumFitness = Solution.MediumFitnessPopulation(population);
                double absFitness        = Math.Abs(tempMediumFitness - MediumFitness);
                MediumFitness = tempMediumFitness;
                if (absFitness >= 0 && absFitness <= 1)
                {
                    bestChromosome = population.BestChromosome();
                    var worstChromosome = population.WorstChromosome();
                    if (bestChromosome.fitness - worstChromosome.fitness <= 1 && bestChromosome.fitness - worstChromosome.fitness >= 0)
                    {
                        if (Solution.isAnswerTrue(bestChromosome, cost, problemData))
                        {
                            stopwatch.Stop();

                            algorithmInfo.Time   = stopwatch.Elapsed;
                            algorithmInfo.BestFx = bestChromosome.fitness;
                            algorithmInfo.Steps  = stepGA;

                            break;
                        }
                    }
                }


                stepGA++;
            }
            stopwatch.Stop();

            if (stepGA == IterateSize)
            {
                bool answer = false;
                bestChromosome = population.BestChromosome();
                while (population.populationList.Count != 0)
                {
                    if (Solution.isAnswerTrue(bestChromosome, cost, problemData))
                    {
                        algorithmInfo.Time   = stopwatch.Elapsed;
                        algorithmInfo.BestFx = bestChromosome.fitness;
                        algorithmInfo.Steps  = stepGA;
                        answer = true;
                        break;
                    }
                    else
                    {
                        population.populationList.Remove(bestChromosome);
                        if (population.populationList.Count == 0)
                        {
                            break;
                        }
                        bestChromosome = population.BestChromosome();
                    }
                }
                if (!answer)
                {
                    bestChromosome = null;
                }
            }

            return(Solution.Answer(cost, bestChromosome, problemData, graph));
        }