// установка значений всех виджетов и полей значениями по-умолчанию public void Default() { imageTsPath = imageGraph = null; iterator = null; tspImg.Source = null; graph = new Digraph(); tsPath = new Digraph.Path(graph); tspPathTxtBox.Text = ""; ExitTraceTsp(); traceTspBttn.IsEnabled = false; }
/// <summary> /// Отрисовка дерева ветвлений /// </summary> /// <param name="tree">дерево ветвления</param> /// <returns>битовое изображение</returns> public static Bitmap Drawing(BranchAndBound.TreeBranch tree) { if (tree == null || tree.Root == null) throw new Exception("Невозможно отрисовать дерево ветвлений. Дерево пусто."); uint no = 0; var current = tree.Root; string script = "graph G { nrankdir = LR node [style=\"filled\", fillcolor=\"gray\"] node" + no + "[label = " + "\"" + (float.IsPositiveInfinity(current.LowerBound) ? "Inf" : current.LowerBound.ToString()) + "\"] ", scriptMain = ""; var dictionaryBranch = new Dictionary<BranchAndBound.Branch, uint>(); dictionaryBranch.Add(current, no++); var queue = new Queue<BranchAndBound.Branch>(); for(;;) { if (current.Left != null) { dictionaryBranch.Add(current.Left, no++); queue.Enqueue(current.Left); scriptMain = "node" + dictionaryBranch[current.Left] + "[label = " + "\"" + (float.IsPositiveInfinity(current.Left.LowerBound) ? "Inf" : current.Left.LowerBound.ToString()) + "\n" + (current.Left.BranchingEdge.Begin < 0 || current.Left.BranchingEdge.End < 0 ? "/(" : "(") + (Math.Abs(current.Left.BranchingEdge.Begin) + 1) + ", " + (Math.Abs(current.Left.BranchingEdge.End) + 1) + ")\"] " + scriptMain; } if (current.Right != null) { dictionaryBranch.Add(current.Right, no++); queue.Enqueue(current.Right); scriptMain = "node" + dictionaryBranch[current.Right] + "[label = " + "\"" + (float.IsPositiveInfinity(current.Right.LowerBound) ? "Inf" : current.Right.LowerBound.ToString()) + "\n" + (current.Right.BranchingEdge.Begin < 0 || current.Right.BranchingEdge.End < 0 ? "/(" : "(") + (Math.Abs(current.Right.BranchingEdge.Begin) + 1) + ", " + (Math.Abs(current.Right.BranchingEdge.End) + 1) + ")\"] " + scriptMain; } if (queue.Count == 0) break; current = queue.Dequeue(); scriptMain += "node" + dictionaryBranch[current.Parent] + " -- " + "node" + dictionaryBranch[current] + " "; } if (!string.IsNullOrEmpty(scriptMain)) script += scriptMain; script += "}"; return RenderingOnGraphviz(script); }
// задание графа private void EnterGraph(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(inputGraphTxtBox.Text)) { MessageBox.Show("Пустое текстовое поле.", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } var lines = inputGraphTxtBox.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length > 30) { MessageBox.Show("Недопустимый размер матрицы смежности. Максимальный рамзер - 30.", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } var matrix = new Digraph.AdjacencyMatrix(lines.Length); for (int i = 0; i < lines.Length; i++) { var values = lines[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (values.Length != lines.Length) { MessageBox.Show("Матрица смежности должна быть квадратной.", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } for (int j = 0; j < lines.Length; j++) { float c; if (!float.TryParse(values[j], out c)) { if (values[j].CompareTo("*") == 0) matrix[i, j] = float.PositiveInfinity; else { MessageBox.Show("Матрица смежности содержит недопустимые символы.", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } } else if (c < 0) { MessageBox.Show("Матрица смежности содержит отрицательные элементы", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } else if (i == j) { MessageBox.Show("Матрица смежности должна описывать полный граф.", "Предупреждение!", MessageBoxButton.OK, MessageBoxImage.Warning); Default(); return; } else matrix[i, j] = c; } } // изменение матрицы графа graph.Adjacency = matrix; // новый метод ветвей и границ для трассировки iterator = new BranchAndBound(graph); try { // визуализация и установка изображения графа imageGraph = Painter.Drawing(graph); tspImg.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(imageGraph.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } catch (Exception exc) { MessageBox.Show(exc.Message, "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error); return; } // обнуление информации о маршруте tspPathTxtBox.Text = ""; // обнувление возможности трассировки traceTspBttn.IsEnabled = false; ExitTraceTsp(); }