Esempio n. 1
0
        public override bool Equals(object obj)
        {
            var circle = obj as Circle;
            if (circle == null) return false;
            if (Count != circle.Count) return false;
            if (Count == 0) return true;

            var list1 = new SortedStackListQueue<Vertex>(this) {Comparer = VertexComparer};
            var list2 = new SortedStackListQueue<Vertex>(circle) {Comparer = VertexComparer};
            if (!list1.Equals(list2)) return false;

            int index = circle.IndexOf(this[0]);
            var circle1 = new Circle(circle);
            circle1.Rotate(index);
            if (this.SequenceEqual(circle1)) return true;
            circle1.Rotate();
            circle1.Reverse();
            return this.SequenceEqual(circle1);
        }
Esempio n. 2
0
        public override bool Equals(object obj)
        {
            var edge = obj as Edge;

            if (obj == null)
            {
                return(false);
            }
            if (Count != edge.Count())
            {
                return(false);
            }
            if (Count == 0)
            {
                return(true);
            }

            var list1 = new SortedStackListQueue <Vertex>(this)
            {
                Comparer = VertexComparer
            };
            var list2 = new SortedStackListQueue <Vertex>(edge)
            {
                Comparer = VertexComparer
            };

            if (!list1.Equals(list2))
            {
                return(false);
            }

            int index = edge.IndexOf(this[0]);
            var edge1 = new Edge(edge);

            edge1.Rotate(index);
            if (this.SequenceEqual(edge1))
            {
                return(true);
            }
            edge1.Rotate();
            edge1.Reverse();
            return(this.SequenceEqual(edge1));
        }
Esempio n. 3
0
        public int Compare(Graph x, Graph y)
        {
            int value = x.Count - y.Count;

            if (value != 0)
            {
                return(value);
            }
            int count = x.Count;

            if (count == 0)
            {
                return(0);
            }
            List <int> l1 = x.SelectMany(s => s.Select(v => v.Id)).ToList();
            List <int> l2 = y.SelectMany(s => s.Select(v => v.Id)).ToList();

            l1.Sort();
            l2.Sort();
            value = l1.Select((i, j) => i - l2[j]).FirstOrDefault(v => v != 0);
            if (value != 0)
            {
                return(value);
            }
            var list1 = new SortedStackListQueue <Segment>(x)
            {
                Comparer = SegmentComparer
            };
            var list2 = new SortedStackListQueue <Segment>(y)
            {
                Comparer = SegmentComparer
            };

            if (!list1.IsSorted(list1))
            {
                list1.Sort(SegmentComparer);
            }
            if (!list2.IsSorted(list2))
            {
                list2.Sort(SegmentComparer);
            }
            return
                (list1.Select((s, i) => SegmentComparer.Compare(s, list2[i])).FirstOrDefault(compare => compare != 0));

            //try
            //{
            //    int[,] matrix;
            //    int[] array;
            //    int first;

            //    var compare1 = new int[count, count];
            //    var compare2 = new int[count, count];

            //    var stackListQueue1 = new StackListQueue<StackListQueue<int>>(x.Select(x.GetInts));
            //    {
            //        var stackListQueue = new StackListQueue<StackListQueue<int>>(stackListQueue1)
            //        {
            //            stackListQueue1.Select(p => p.GetReverse())
            //        };
            //        lock (CudafySequencies.Semaphore)
            //        {
            //            int[][] arrayOfArray = stackListQueue.Select(i=>i.ToArray()).ToArray();
            //            CudafySequencies.SetSequencies(arrayOfArray, arrayOfArray);
            //            CudafySequencies.Execute("Compare");
            //            matrix = CudafySequencies.GetMatrix();
            //        }
            //        stackListQueue1 =
            //            new StackListQueue<StackListQueue<int>>(
            //                stackListQueue1.Select((p, i) => matrix[i, i + count] <= 0 ? p : stackListQueue[i + count]));
            //        lock (CudafySequencies.Semaphore)
            //        {
            //            int[][] arrayOfArray = stackListQueue1.Select(i => i.ToArray()).ToArray();
            //            CudafySequencies.SetSequencies(arrayOfArray, arrayOfArray);
            //            CudafySequencies.Execute("Compare");
            //            compare1 = CudafySequencies.GetMatrix();
            //        }
            //        lock (CudafyArray.Semaphore)
            //        {
            //            CudafyArray.SetArray(Enumerable.Range(0, count).ToArray());
            //            CudafyArray.SetCompare(compare1);
            //            CudafyArray.OddEvenSort();
            //            array = CudafyArray.GetArray();
            //        }
            //        stackListQueue1 =
            //            new StackListQueue<StackListQueue<int>>(array.Select(i => stackListQueue1.ElementAt(i)));
            //    }

            //    var stackListQueue2 = new StackListQueue<StackListQueue<int>>(x.Select(x.GetInts));
            //    {
            //        var stackListQueue = new StackListQueue<StackListQueue<int>>(stackListQueue2)
            //        {
            //            stackListQueue2.Select(p => p.GetReverse())
            //        };
            //        lock (CudafySequencies.Semaphore)
            //        {
            //            int[][] arrayOfArray = stackListQueue.Select(i => i.ToArray()).ToArray();
            //            CudafySequencies.SetSequencies(arrayOfArray, arrayOfArray);
            //            CudafySequencies.Execute("Compare");
            //            matrix = CudafySequencies.GetMatrix();
            //        }
            //        stackListQueue2 =
            //            new StackListQueue<StackListQueue<int>>(
            //                stackListQueue2.Select((p, i) => matrix[i, i + count] <= 0 ? p : stackListQueue[i + count]));
            //        lock (CudafySequencies.Semaphore)
            //        {
            //            int[][] arrayOfArray = stackListQueue2.Select(i => i.ToArray()).ToArray();
            //            CudafySequencies.SetSequencies(arrayOfArray, arrayOfArray);
            //            CudafySequencies.Execute("Compare");
            //            compare2 = CudafySequencies.GetMatrix();
            //        }

            //        lock (CudafyArray.Semaphore)
            //        {
            //            CudafyArray.SetArray(Enumerable.Range(0, count).ToArray());
            //            CudafyArray.SetCompare(compare2);
            //            CudafyArray.OddEvenSort();
            //            array = CudafyArray.GetArray();
            //        }
            //        stackListQueue2 =
            //            new StackListQueue<StackListQueue<int>>(array.Select(i => stackListQueue2.ElementAt(i)));
            //    }

            //    lock (CudafySequencies.Semaphore)
            //    {
            //        CudafySequencies.SetSequencies(stackListQueue1.Select(i => i.ToArray()).ToArray(),
            //            stackListQueue2.Select(i => i.ToArray()).ToArray());
            //        CudafySequencies.Execute("Compare");
            //        matrix = CudafySequencies.GetMatrix();
            //    }
            //    lock (CudafyMatrix.Semaphore)
            //    {
            //        CudafyMatrix.SetMatrix(matrix);
            //        CudafyMatrix.ExecuteRangeSelectFirstIndexOfNonZero();
            //        first = CudafyMatrix.GetFirst();
            //    }
            //    return (first < 0) ? 0 : matrix[first, first];
            //}
            //catch (Exception exception)
            //{
            //    var list1 = new StackListQueue<Segment>(x);
            //    var list2 = new StackListQueue<Segment>(y);
            //    if (!list1.IsSorted(list1)) list1.Sort(SegmentComparer);
            //    if (!list2.IsSorted(list2)) list2.Sort(SegmentComparer);
            //    return
            //        list1.Select((s, i) => SegmentComparer.Compare(s, list2[i])).FirstOrDefault(compare => compare != 0);
            //}
        }
Esempio n. 4
0
        public bool Execute(ILinearMiniMax <T> minimax, ref IEnumerable <Vector <T> > optimalVectors,
                            ref IEnumerable <T> optimalValues, ITrace trace)
        {
            // Реализуем алгоритм только для случая наращивания базиса по одной переменной
            Debug.Assert(H == 1);

            Debug.Assert(minimax.A.Rows == minimax.R.Count());
            Debug.Assert(minimax.A.Rows == minimax.B.Count());
            Debug.Assert(minimax.A.Columns == minimax.C.Count());

            // Количество переменных
            int n = minimax.C.Count;

            AppendLineCallback appendLineCallback = trace != null ? trace.AppendLineCallback : null;
            ProgressCallback   progressCallback   = trace != null ? trace.ProgressCallback : null;
            CompliteCallback   compliteCallback   = trace != null ? trace.CompliteCallback : null;

            if (progressCallback != null)
            {
                progressCallback(0, minimax.C.Count);
            }
            // Исходным выбранным частичным планом считается тот, базис которого пуст
            var list =
                new StackListQueue <BooleanMultiPlan>(new[] { true, false }
                                                      .SelectMany(value => Enumerable.Range(0, n).Select(
                                                                      index => new BooleanMultiPlan(new BooleanVector(value),
                                                                                                    new Vector <int>(index), minimax))
                                                                  .Where(item => item.ArgBound.All(x => x >= 0.0))));

            for (int k = 1;; k++)
            {
                if (appendLineCallback != null)
                {
                    appendLineCallback(string.Format("Количество подмножеств = {0}", list.Count));
                }
                if (progressCallback != null)
                {
                    progressCallback(k, minimax.C.Count);
                }
                // Удаляем подмножества с заведомо недопустимыми значениями
                if (appendLineCallback != null)
                {
                    appendLineCallback("Удаляем подмножества с заведомо недопустимыми значениями");
                }
                Debug.WriteLine("Удаляем подмножества с заведомо недопустимыми значениями");
                list.RemoveAll(item => item.ArgBound.Any(x => x < 0));
                if (appendLineCallback != null)
                {
                    appendLineCallback(string.Format("Количество подмножеств = {0}", list.Count));
                }
                Debug.WriteLine("Количество подмножеств = {0}", list.Count);

                if (list.Count == 0)
                {
                    return(false);
                }

                for (;;)
                {
                    double maxMin = list.Max(item => item.FuncMin);
                    double minMax = list.Min(item => item.FuncMax);

                    if (appendLineCallback != null)
                    {
                        appendLineCallback(string.Format("maxMin = {0} minMax = {1}", maxMin, minMax));
                    }
                    Debug.WriteLine("maxMin = {0} minMax = {1}", maxMin, minMax);

                    if (maxMin <= minMax)
                    {
                        break;
                    }

                    // Удаляем варианты подмножеств, для которых существует более лучшая оценка целевой функции
                    if (appendLineCallback != null)
                    {
                        appendLineCallback(
                            "Удаляем варианты подмножеств, для которых существует более лучшая оценка целевой функции");
                    }

                    switch (minimax.Target)
                    {
                    case Target.Maximum:
                        list.RemoveAll(item => item.FuncMax < maxMin);
                        break;

                    case Target.Minimum:
                        list.RemoveAll(item => item.FuncMin > minMax);
                        break;
                    }

                    if (appendLineCallback != null)
                    {
                        appendLineCallback(string.Format("Количество подмножеств = {0}", list.Count));
                    }
                    Debug.WriteLine("Количество подмножеств = {0}", list.Count);
                }

                if (k == n)
                {
                    break;
                }

                // Генерируем все возможные соседние планы, связанные с введением в базис H переменных
                // и вычисляем их оценки
                if (appendLineCallback != null)
                {
                    appendLineCallback(
                        string.Format(
                            "Генерируем все возможные соседние планы, связанные с введением в базис {0} переменных",
                            H));
                }
                Debug.WriteLine(
                    "Генерируем все возможные соседние планы, связанные с введением в базис {0} переменных", H);
                var next = new SortedStackListQueue <BooleanMultiPlan>(new[] { true, false }
                                                                       .SelectMany(value => list.Select(
                                                                                       element => new BooleanMultiPlan(new BooleanVector(element.Vector)
                {
                    value
                },
                                                                                                                       new Vector <int>(element.Indeces)
                {
                    (element.Indeces.Last() + 1) % n
                }, minimax))
                                                                                   .Where(item => item.ArgBound.All(x => x >= 0.0))))
                {
                    Comparer = new BooleanMultiPlanComparer()
                };
                if (appendLineCallback != null)
                {
                    appendLineCallback("Удаляем дупликаты");
                }
                Debug.WriteLine("Удаляем дупликаты");
                list = new StackListQueue <BooleanMultiPlan>(next.Distinct());
                Debug.WriteLine("Количество подмножеств = {0}", list.Count);
            }

            // Завершаем алгоритм и возвращаем найденное решение
            optimalVectors =
                new StackListQueue <Vector <T> >(
                    list.Select(item =>
                                new Vector <T>(
                                    Enumerable.Range(0, n)
                                    .Select(index =>
                                            item.Vector[item.Indeces.IndexOf(index)] ? (T)(dynamic)1 : default(T)))));
            optimalValues =
                new StackListQueue <T>(list.Select(item => (T)(dynamic)(item.FuncMin)));
            Debug.Assert(list.All(item => item.FuncMin <= item.FuncMax));
            if (compliteCallback != null)
            {
                compliteCallback();
            }
            return(true);
        }