public new bool Contains(IEnumerable <T> collection) { if (Settings.EnableCudafy) { try { int[,] matrix; int first; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( collection.Select(GetInts).Select(item => item.ToArray()).ToArray(), this.Select(GetInts).Select(item => item.ToArray()).ToArray() ); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZeroFirstIndexOfNonPositive(); first = CudafyMatrix.GetFirst(); } return(first < 0); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(collection.All(Contains)); } } return(collection.All(Contains)); }
public IEnumerable <Path> SplitBy(Segment segment) { var list = new StackListQueue <Path>(); StackListQueue <int> indexes; try { int[,] matrix; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( segment.Select(GetInts).Select(item => item.ToArray()).ToArray(), GetRange(1, Count - 2).Select(GetInts).Select(item => item.ToArray()).ToArray() ); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = new StackListQueue <int>(CudafyMatrix.GetIndexes() .Where(index => index >= 0) .Select(index => index + 1)); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); indexes = new StackListQueue <int>(GetRange(1, Count - 2).Intersect(segment).Select(v => IndexOf(v))); } indexes.Sort(); indexes.Prepend(0); indexes.Append(Count - 1); for (int prev = indexes.Dequeue(); indexes.Any(); prev = indexes.Dequeue()) { if (((prev + 1) == indexes[0]) && segment.Contains(this[prev]) && segment.Contains(this[indexes[0]])) { continue; } list.Add(new Path(GetRange(prev, indexes[0] - prev + 1))); } Debug.WriteLineIf(list.Any(), this + " split by " + segment + " is " + string.Join(",", list.Select(item => item.ToString()))); return(list); }
public IEnumerable <T> Distinct() { if (Settings.EnableCudafy) { try { if (Count == 0) { return(new StackListQueue <T>()); } IEnumerable <IEnumerable <int> > list = this.Select(GetInts); int[,] matrix; int[] indexes; lock (CudafySequencies.Semaphore) { int[][] arr = this.Select(GetInts).Select(item => item.ToArray()).ToArray(); CudafySequencies.SetSequencies(arr, arr); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = CudafyMatrix.GetIndexes(); } return(indexes.Where((value, index) => value == index) .Select(index => this[index])); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(this.ToList().Distinct()); } } return(this.ToList().Distinct()); }
public bool IsPlanar(Graph graphArgument) { var enableCudafy = Settings.EnableCudafy; Settings.EnableCudafy = true; if (WorkerLog != null) { WorkerLog("Начало гамма-алгоритма"); } var graph = new Graph(graphArgument); Debug.Assert( graph.Children.All(pair => pair.Value .All(value => graph.Children.ContainsKey(value) && graph.Children[value].Contains(pair.Key))) ); if (WorkerBegin != null) { WorkerBegin(); } // Шаг первый - удаляем все листья и узлы степени 2 if (WorkerLog != null) { WorkerLog("Удаляем все листья и узлы степени 2"); } // листья представляют собой дерево и нарисовать его плоскую укладку тривиально. graph.RemoveAllTrees(); // Замечание. Если на ребра планарного графа нанести произвольное число вершин степени 2, // то он останется планарным; равным образом, если на ребра непланарного графа // нанести вершины степени 2, то он планарным не станет. graph.RemoveIntermedians(); // Шаг второй - граф нужно укладывать отдельно по компонентам связности. if (WorkerLog != null) { WorkerLog("Находим ВСЕ пути в графе длины не более размера графа + 1"); } Dictionary <int, PathDictionary> cachedAllGraphPaths = graph.GetAllGraphPaths(); var queue = new StackListQueue <Context> { graph.GetAllSubGraphs().Select(subgraph => new Context { SubGraphQueue = new StackListQueue <Graph> { subgraph }, CachedSubGraphPathsQueue = new StackListQueue <Dictionary <int, PathDictionary> > { Graph.GetSubgraphPaths(subgraph.Vertices, cachedAllGraphPaths) }, }) }; Debug.WriteLine("start "); foreach (Context context in queue) { while (context.SubGraphQueue.Any()) { Graph subGraph = context.SubGraphQueue.Dequeue(); if (WorkerLog != null) { WorkerLog("Проверка связанной компоненты " + subGraph); } Dictionary <int, PathDictionary> cachedSubGraphPaths = context.CachedSubGraphPathsQueue.Dequeue(); // На вход подаются графы, обладающие следующими свойствами: // граф связный; // граф имеет хотя бы один цикл; // граф не имеет мостиков, т. е. ребер, после удаления которых // граф распадается на две компонеты связности. if (WorkerLog != null) { WorkerLog( "Находим мосты после удаления которых граф распадается на несколько компонет связности"); } var vertices = new StackListQueue <Vertex>(subGraph.Vertices); var bridges = new StackListQueue <Vertex>(); for (int i = 0; i < vertices.Count; i++) { Vertex dequeue = vertices.Dequeue(); IEnumerable <Graph> subsubgraphs = subGraph.GetSubgraph(vertices).GetAllSubGraphs(); if (subsubgraphs.Count() > 1) { bridges.Add(dequeue); } vertices.Enqueue(dequeue); } Debug.Assert(bridges.Count != vertices.Count); if (bridges.Any()) { // Если в графе есть мосты, то их нужно разрезать, провести отдельно плоскую укладку // каждой компоненты связности, а затем соединить их мостами. // Здесь может возникнуть трудность: в процессе укладки концевые вершины моста могут // оказаться внутри плоского графа. Нарисуем одну компоненту связности, // и будем присоединять к ней другие последовательно. // Каждую новую компоненту связности будем рисовать в той грани, в которой лежит // концевая вершина соответствующего моста. Так как граф связности мостами компонент // связности является деревом, мы сумеем получить плоскую укладку. if (WorkerLog != null) { WorkerLog( "В графе есть мосты, их нужно разрезать, провести отдельно плоскую укладку, а затем соединить их мостами."); } if (WorkerLog != null) { WorkerLog("Мосты: " + string.Join(",", bridges)); } IEnumerable <Vertex> exceptBridges = vertices.Except(bridges); IEnumerable <Graph> subsubgraphs = subGraph.GetSubgraph(exceptBridges).GetAllSubGraphs(); Debug.WriteLine("subsubgraphs = " + subsubgraphs.Count()); context.SubGraphQueue.Enqueue( subsubgraphs.Select(subgraph => subGraph.GetSubgraph(subgraph.Vertices.Union(bridges)))); context.CachedSubGraphPathsQueue.Enqueue( subsubgraphs.Select( subgraph => Graph.GetSubgraphPaths(subgraph.Vertices.Union(bridges), cachedSubGraphPaths))); continue; } if (WorkerLog != null) { WorkerLog("Находим ЛЮБОЙ МАКСИМАЛЬНОЙ ДЛИНЫ простой цикл в графе"); } Circle circle = null; for (int i = cachedSubGraphPaths.Keys.Max(); i > 3; i--) { foreach (var pair in cachedSubGraphPaths.Where(pair => pair.Key == i)) { foreach ( var key in subGraph.Vertices.Select(vertex => new KeyValuePair <Vertex, Vertex>(vertex, vertex)) ) { if (pair.Value.ContainsKey(key) && pair.Value[key].Any()) { foreach (Path path in pair.Value[key]) { circle = new Circle(path.GetRange(0, path.Count - 1)); if (Circle.IsSimple(circle)) { break; } circle = null; } if (circle != null) { break; } } if (circle != null) { break; } } if (circle != null) { break; } } if (circle != null) { break; } } if (circle == null && !context.Edges.Any()) { // граф — дерево и нарисовать его плоскую укладку тривиально. // Поскольку мы ещё не начинали рисовать, то значит всё проверено continue; } // Инициализация алгоритма производится так: выбираем любой простой цикл; // и получаем две грани: Γ1 — внешнюю и Γ2 — внутреннюю if (circle != null && !context.Edges.Any()) { context.Edges.Add(new Edge(circle)); } if (circle != null) { context.Edges.Add(new Edge(circle)); context.Builded.Add(context.Edges.Last()); } // Если циклов нет, то надо проверить, что данное дерево // можно вписать в уже построенный граф Debug.WriteLine("SubGraph " + subGraph); Debug.WriteLine("builded " + context.Builded); Debug.WriteLine("edges:" + string.Join(Environment.NewLine, context.Edges.Select(e => e.ToString()))); //// Каждый сегмент S относительно уже построенного графа G′ представляет собой одно из двух: //// ребро, оба конца которого принадлежат G′, но само оно не принадлежит G′; //// связную компоненту графа G – G′, дополненную всеми ребрами графа G, //// один из концов которых принадлежит связной компоненте, //// а второй из графа G′. VertexSortedCollection buildedVertices = context.Builded.Vertices; Dictionary <int, PathDictionary> fromTo = Graph.GetFromToPaths(buildedVertices, buildedVertices, cachedSubGraphPaths); var paths = new PathCollection(fromTo .SelectMany(pair => pair.Value) .SelectMany(pair => pair.Value) .Where(Path.IsNoVertix) .Where(Path.IsNoCircle) ); Debug.WriteLine("paths " + paths); //var secondGraph = new Graph(subGraph.Except(context.Builded)); //if (secondGraph.Any()) //{ // IEnumerable<Graph> collection = secondGraph.GetAllSubGraphs(); // context.SubGraphQueue.Enqueue(collection); // context.CachedSubGraphPathsQueue.Enqueue( // collection.Select(subgraph => Graph.GetSubgraphPaths(subgraph.Vertices, cachedSubGraphPaths))); //} paths.ReplaceAll(paths.Distinct()); Debug.WriteLine("paths " + paths); paths.RemoveAll(context.Builded.Contains); Debug.WriteLine("paths " + paths); Debug.WriteLine("builded " + context.Builded); Debug.WriteLine("edges:" + string.Join(Environment.NewLine, context.Edges.Select(e => e.ToString()))); while (paths.Any()) { paths.RemoveAll(context.Builded.Contains); Debug.WriteLine("paths " + paths); if (!paths.Any()) { continue; } if (Settings.EnableCudafy) { try { while (paths.Any(Path.IsLong)) { // Находим для всех путей их перечечения с уже построенным графом // Разбиваем пути в найденных точках пересечения с уже построенным графом // Если точек пересечения не найдено, то выходим из цикла int[,] matrix; int[] indexes; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( paths.Select( path => path.GetRange(1, path.Count - 2) .Select(vertex => vertex.Id) .ToArray()) .ToArray(), context.Builded.Vertices.Select( vertex => new StackListQueue <int>(vertex.Id).ToArray()) .ToArray() ); CudafySequencies.Execute("CountIntersections"); // подсчитываем число пересечений matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfNonZero(); // находим индексы ненулевых элементов в строках indexes = CudafyMatrix.GetIndexes(); } Dictionary <int, int> dictionary = indexes.Select( (value, index) => new KeyValuePair <int, int>(index, value)) .Where(pair => pair.Value >= 0) .ToDictionary(pair => pair.Key, pair => pair.Value); if (!dictionary.Any()) { break; } Debug.Assert(dictionary.All(pair => pair.Key >= 0)); Debug.Assert(dictionary.All(pair => pair.Value >= 0)); Debug.Assert(dictionary.All(pair => pair.Key < paths.Count)); Debug.Assert(dictionary.All(pair => pair.Value < context.Builded.Vertices.Count)); var dictionary2 = new StackListQueue <KeyValuePair <Path, Vertex> >( dictionary.Select( pair => new KeyValuePair <Path, Vertex>(new Path(paths[pair.Key]), new Vertex(context.Builded.Vertices[pair.Value]))) ); var list = new StackListQueue <int>(dictionary.Select(pair => pair.Key).Distinct()); list.Sort(); Debug.Assert(dictionary2.All(pair => pair.Key.Count > 1)); for (int i = list.Count; i-- > 0;) { paths.RemoveAt(list[i]); } paths.AddRangeExcept( new PathCollection( dictionary2.SelectMany(pair => pair.Key.SplitBy(pair.Value) .Where(Path.IsNoVertix) .Where(Path.IsNoCircle)) .Distinct())); paths.ReplaceAll(paths.Distinct()); paths.RemoveAll(context.Builded.Contains); } } catch (Exception ex) { if (WorkerLog != null) { WorkerLog(ex.ToString()); } paths.ReplaceAll( paths.SelectMany(context.Builded.Split) .Where(Path.IsNoVertix) .Where(Path.IsNoCircle) ); paths.ReplaceAll(paths.Distinct()); paths.RemoveAll(context.Builded.Contains); } }
/// <summary> /// Разбиение пути в точках перечечения пути с графом на отдельные подпути /// </summary> /// <param name="path"></param> /// <returns></returns> public IEnumerable <Path> Split(Path path) { Debug.Assert(Count >= 2); var list = new StackListQueue <Path>(); StackListQueue <int> indexes; if (Settings.EnableCudafy) { try { int[,] matrix; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( Vertices.Select(path.GetInts).Select(item => item.ToArray()).ToArray(), path.GetRange(1, Count - 2).Select(path.GetInts).Select(item => item.ToArray()).ToArray() ); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = new StackListQueue <int>(CudafyMatrix.GetIndexes() .Where(index => index >= 0) .Select(index => index + 1)); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); indexes = new StackListQueue <int>( path.GetRange(1, Count - 2) .Intersect(Vertices) .Select(v => path.IndexOf(v))); } } else { indexes = new StackListQueue <int>( path.GetRange(1, Count - 2) .Intersect(Vertices) .Select(v => path.IndexOf(v))); } indexes.Sort(); indexes.Prepend(0); indexes.Append(Count - 1); Dictionary <Vertex, VertexSortedCollection> children = Children; for (int prev = indexes.Dequeue(); indexes.Any(); prev = indexes.Dequeue()) { if (((prev + 1) == indexes[0]) && children.ContainsKey(path[prev]) && children[path[prev]].Contains(path[indexes[0]])) { continue; } list.Add(new Path(path.GetRange(prev, indexes[0] - prev + 1))); } Debug.WriteLineIf(list.Any(), path + " split by " + this + " is " + string.Join(",", list.Select(item => item.ToString()))); return(list); }
public BooleanVector GetVector(Circle circle) { Debug.Assert(circle.Any()); int count = circle.Count; var collection = new SegmentCollection(); for (int i = 0; i < count; i++) { collection.Add(new Segment(circle[i], circle[(i + 1) % count])); } Debug.Assert(collection.All(Contains)); List <int> indexes; if (Settings.EnableCudafy) { try { IEnumerable <IEnumerable <int> > list1 = collection.Select(GetInts); IEnumerable <IEnumerable <int> > list2 = this.Select(GetInts); int[,] matrix; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( list1.Select(item => item.ToArray()).ToArray(), list2.Select(item => item.ToArray()).ToArray() ); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = CudafyMatrix.GetIndexes().ToList(); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); indexes = collection.Select(segment => IndexOf(segment)).ToList(); } } else { indexes = collection.Select(segment => IndexOf(segment)).ToList(); } indexes.Sort(); var booleanVector = new BooleanVector(); if (indexes[0] > 0) { booleanVector.AddRange(Enumerable.Repeat(false, indexes[0])); } booleanVector.Add(true); for (int i = 1; i < indexes.Count; i++) { if (indexes[i] - indexes[i - 1] > 1) { booleanVector.AddRange(Enumerable.Repeat(false, indexes[i] - indexes[i - 1] - 1)); } booleanVector.Add(true); } return(booleanVector); }
public int Compare(StackListQueue <T> x, StackListQueue <T> y) { int[][] list1 = x.Select(x.GetInts).Select(i => i.ToArray()).ToArray(); int[][] list2 = y.Select(x.GetInts).Select(i => i.ToArray()).ToArray(); int value = list1.Length - list2.Length; if (value != 0) { return(value); } var list11 = new StackListQueue <StackListQueue <int> >(list1.Select(i => new StackListQueue <int>(i.Length))); var list22 = new StackListQueue <StackListQueue <int> >(list2.Select(i => new StackListQueue <int>(i.Length))); try { int[,] matrix; int first; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies(list11.Select(i => i.ToArray()).ToArray(), list22.Select(i => i.ToArray()).ToArray()); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRangeSelectFirstIndexOfNonNegative(); first = CudafyMatrix.GetFirst(); } if (first >= 0) { return(matrix[first, first]); } } catch (Exception exception) { value = list11.Select((c, i) => c[0] - list22[i][0]).FirstOrDefault(compare => compare != 0); if (value != 0) { return(value); } } try { int[,] matrix; int first; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies(list1, list2); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRangeSelectFirstIndexOfNonNegative(); first = CudafyMatrix.GetFirst(); } return((first < 0) ? 0 : matrix[first, first]); } catch (Exception exception) { return (list1.Select((t, i) => t.Select((item, j) => item - list2[i][j]) .FirstOrDefault(compare => compare != 0)) .FirstOrDefault(compare => compare != 0)); } }
public new IEnumerable <Path> Distinct() { if (Count == 0) { return(new MyLibrary.Collections.StackListQueue <Path>()); } if (Settings.EnableCudafy) { try { var list = new StackListQueue <StackListQueue <int> >( this.Select(path => new StackListQueue <int>(path.Select(vertex => vertex.Id)))); int[][] arr = list.Select(item => item.ToArray()).ToArray(); Debug.Assert(Count == arr.Length); int[,] matrix; int[] indexes; lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies(arr, arr); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } Debug.Assert(matrix.GetLength(0) == arr.Length); Debug.Assert(matrix.GetLength(1) == arr.Length); lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = CudafyMatrix.GetIndexes(); } Debug.Assert(indexes.GetLength(0) == arr.Length); IEnumerable <Path> paths1 = indexes.Where((value, index) => value == index) .Select(this.ElementAt); var list1 = new StackListQueue <StackListQueue <int> >( paths1.Select(path => new StackListQueue <int>(path.Select(vertex => vertex.Id)))); var list2 = new StackListQueue <StackListQueue <int> >( paths1.Select(path => new StackListQueue <int>(path.GetReverse().Select(vertex => vertex.Id)))); lock (CudafySequencies.Semaphore) { CudafySequencies.SetSequencies( list1.Select(item => item.ToArray()).ToArray(), list2.Select(item => item.ToArray()).ToArray() ); CudafySequencies.Execute("Compare"); matrix = CudafySequencies.GetMatrix(); } Debug.Assert(matrix.GetLength(0) == paths1.Count()); Debug.Assert(matrix.GetLength(1) == paths1.Count()); lock (CudafyMatrix.Semaphore) { CudafyMatrix.SetMatrix(matrix); CudafyMatrix.ExecuteRepeatZeroIndexOfZero(); indexes = CudafyMatrix.GetIndexes(); } Debug.Assert(indexes.GetLength(0) == paths1.Count()); return (new PathCollection( paths1.Where((value, index) => indexes[index] == -1 || indexes[index] >= index))); } catch (Exception ex) { return(new PathCollection(base.Distinct())); } } { return(new PathCollection(base.Distinct())); } }