// Permanet Generation
        public override void PermanentGeneration(Dictionary<GenerationParam, object> genParam)
        {
            if (ERModel.permanentStatus)
            {
                lock (syncLock)
                {
                    if (ERModel.permanentStatus)
                    {
                        double probability = (Double)genParam[GenerationParam.P];
                        int numberOfVertices = (Int32)genParam[GenerationParam.Vertices];
                        container.Size = numberOfVertices;

                        FillValuesByProbability(probability);

                        permanentContainer = container;

                        ERModel.permanentStatus = false;
                    }
                    else
                    {

                        container = permanentContainer;
                    }
                }
            }
            else
            {
                container = permanentContainer;
            }
        }
 public ERContainer(ERContainer cotainer)
 {
     this.size = cotainer.Size;
     this.neighbourship = cotainer.neighbourship;
     this.Edjes = new List<KeyValuePair<int,int>>(cotainer.Edjes);
     this.NoEdjes = new List<KeyValuePair<int,int>>(cotainer.NoEdjes);
     this.degrees = new List<int>( cotainer.degrees);
 }
        public void ERCycles3Test()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            long actualValue = analyzer.GetCycles3();
            long expectedValue = (long)goldResult.Results[0].Result[AnalyseOptions.Cycles3];
            Assert.AreEqual(actualValue, expectedValue);
        }
 public CyclesCounterSingleThreaded(ERContainer container)
 {
     _container = container;
     _verticesCount = _container.Size;
     _marked = new bool[_verticesCount];
     for (int i = 0; i < _verticesCount; ++i)
     {
         unmark(i);
     }
     _stack = new Stack<int>();
     _path = new Stack<int>();
 }
        public void ERClusteringCoefficientTest()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            SortedDictionary<double, int> actualValue = analyzer.GetClusteringCoefficient();
            SortedDictionary<double, int> expectedValue = goldResult.Results[0].Coefficient;
            Assert.IsTrue(compare(actualValue, expectedValue));
        }
        public void ERAveragePathTest()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            double actualValue = analyzer.GetAveragePath();
            double expectedValue = goldResult.Results[0].Result[AnalyseOptions.AveragePath];
            Assert.AreEqual(actualValue, expectedValue);
        }
        private void constructGraph(string modelName)
        {
            try
            {
                XMLResultStorage resultStorage = new XMLResultStorage("");
                goldResult = resultStorage.LoadXML(goldenOutPath.Text);
            }
            catch (Exception e)
            {
                MessageBox.Show(this, "Unable load XML file", e.Message);
            }

            switch (modelName)
            {
                case "Barabasi-Albert":
                    BAContainer baContainer = new BAContainer();
                    baContainer.SetMatrix(inputMatrixPath.Text);
                    BAModelTest(baContainer);
                    break;
                case "ERModel":
                    ERContainer erContainer = new ERContainer();
                    erContainer.SetMatrix(inputMatrixPath.Text);
                    ERModelTest(erContainer);
                    break;
                case "Watts-Strogatz":
                    WSContainer wsContainer = new WSContainer();
                    wsContainer.SetMatrix(inputMatrixPath.Text);
                    WSModelTest(wsContainer);
                    break;
                default:
                    Console.WriteLine("Default case");
                    break;
            }
        }
 internal void CopyMotifs(ERContainer other)
 {
     other.Motifs4Order = new SortedDictionary<int, List<int>>(this.Motifs4Order);
     foreach (var item in this.Motifs4Order)
     {
         other.Motifs4Order[item.Key] = new List<int>(item.Value);
     }
 }
        public void Update4OrderMotifs(ERContainer transformation, KeyValuePair<int, int> edjes1, KeyValuePair<int, int> edjes2, int index1, int index2)
        {
            var motif = transformation.Motifs4Order[index1][index2];
            var empty1 = false;
            var empty2 = false;
            if (transformation.Motifs4Order.ContainsKey(motif))
            {
                transformation.Motifs4Order.Remove(motif);
            }

            var list = new List<int>();
            var list1 = new List<int>();
            foreach (var dic in transformation.Motifs4Order)
            {
                if (dic.Value.Contains(motif))
                {
                    if (dic.Value.Count <= 1)
                    {
                        list.Add(dic.Key);
                    }
                    else
                    {
                        transformation.Motifs4Order[dic.Key].Remove(motif);
                    }
                }

                if (dic.Value.Contains(index1))
                {
                    if (dic.Value.Count <= 1)
                    {
                        list1.Add(dic.Key);
                    }
                    else
                    {
                        transformation.Motifs4Order[dic.Key].Remove(index1);
                    }
                }
            }

            foreach (var key in list)
            {
                transformation.Motifs4Order.Remove(key);
            }

            foreach (var key in list1)
            {
                transformation.Motifs4Order.Remove(key);
            }

            if (transformation.Motifs4Order.ContainsKey(index1))
            {
                transformation.Motifs4Order.Remove(index1);
            }

            transformation.Motifs4Order.Add(transformation.MotifsEdjes.Count - 1, new List<int>());
            transformation.Motifs4Order.Add(transformation.MotifsEdjes.Count - 2, new List<int>());

            for (int i = 0; i < transformation.MotifsEdjes.Count; i++)
            {
                var edjes = transformation.MotifsEdjes[i];
                if (!edjes.Equals(new KeyValuePair<int, int>()))
                {
                    if (edjes1.Key != edjes.Value && edjes1.Key != edjes.Key
                              && edjes1.Value != edjes.Key && edjes1.Value != edjes.Value)
                    {
                        if (!((AreNeighbours(edjes1.Key, edjes.Key) && AreNeighbours(edjes1.Key, edjes.Value))
                            || (AreNeighbours(edjes1.Value, edjes.Key) && AreNeighbours(edjes1.Value, edjes.Value))
                            || (AreNeighbours(edjes1.Key, edjes.Key) && AreNeighbours(edjes1.Value, edjes.Key))
                            || (AreNeighbours(edjes1.Value, edjes.Value) && AreNeighbours(edjes1.Key, edjes.Value))))
                        {
                            empty1 = true;
                            transformation.Motifs4Order[transformation.MotifsEdjes.Count - 1].Add(i);
                        }
                    }

                    if (edjes2.Key != edjes.Value && edjes2.Key != edjes.Key
                            && edjes2.Value != edjes.Key && edjes2.Value != edjes.Value)
                    {
                        if (!((AreNeighbours(edjes2.Key, edjes.Key) && AreNeighbours(edjes2.Key, edjes.Value))
                            || (AreNeighbours(edjes2.Value, edjes.Key) && AreNeighbours(edjes2.Value, edjes.Value))
                            || (AreNeighbours(edjes2.Key, edjes.Key) && AreNeighbours(edjes2.Value, edjes.Key))
                            || (AreNeighbours(edjes2.Value, edjes.Value) && AreNeighbours(edjes2.Key, edjes.Value))))
                        {
                            transformation.Motifs4Order[transformation.MotifsEdjes.Count - 2].Add(i);
                            empty2 = true;
                        }
                    }
                }
            }
            if (!empty1)
            {
                transformation.Motifs4Order.Remove(transformation.MotifsEdjes.Count - 1);
            }

            if (!empty2)
            {
                transformation.Motifs4Order.Remove(transformation.MotifsEdjes.Count - 2);
            }
        }
        private ERContainer TransformKeppingDistriburtion(ERContainer tranformation, Random random, out int triangle)
        {
            var removeedjesIndex1 = random.Next(0, tranformation.Motifs4Order.Count - 1);
            var removeedjesIndex2 = 0;
            try
            {
               removeedjesIndex2 = random.Next(0, tranformation.Motifs4Order.ElementAt(removeedjesIndex1).Value.Count - 1);
            }
            catch (Exception ex)
            {
                Console.WriteLine(removeedjesIndex1);
                Console.WriteLine(tranformation.Motifs4Order.ElementAt(removeedjesIndex1).Value.Count);
            }

            var removeEdjes1 = tranformation.Motifs4Order.ElementAt(removeedjesIndex1).Key;
            var removeEdjes2 = tranformation.Motifs4Order.ElementAt(removeedjesIndex1).Value[removeedjesIndex2];

            var removeedjeVertix1 = tranformation.MotifsEdjes[removeEdjes1].Key;
            var removeedjeVertix2 = tranformation.MotifsEdjes[removeEdjes1].Value;
            var removeedjeVertix3 = tranformation.MotifsEdjes[removeEdjes2].Key; ;
            var removeedjeVertix4 = tranformation.MotifsEdjes[removeEdjes2].Value;

            int addtriangle1 = 0;
            int addtriangle2 = 0;

            //Remove edje
            tranformation.Neighbourship[removeedjeVertix1].Remove(removeedjeVertix2);
            tranformation.Neighbourship[removeedjeVertix2].Remove(removeedjeVertix1);
            tranformation.Neighbourship[removeedjeVertix3].Remove(removeedjeVertix4);
            tranformation.Neighbourship[removeedjeVertix4].Remove(removeedjeVertix3);
            tranformation.MotifsEdjes[removeEdjes1] = new KeyValuePair<int, int>();
            tranformation.MotifsEdjes[removeEdjes2] = new KeyValuePair<int, int>();

            //Count remove triangle
            int removetriangle = CountTriangle(removeedjeVertix1,
               removeedjeVertix2, tranformation) + CountTriangle(removeedjeVertix3,removeedjeVertix4, tranformation);

            //add edje
            if (tranformation.Neighbourship[removeedjeVertix1].Contains(removeedjeVertix3) || tranformation.Neighbourship[removeedjeVertix2].Contains(removeedjeVertix4))
            {
                tranformation.Neighbourship[removeedjeVertix1].Add(removeedjeVertix4);
                tranformation.Neighbourship[removeedjeVertix4].Add(removeedjeVertix1);
                tranformation.MotifsEdjes.Add(new KeyValuePair<int, int>(removeedjeVertix1, removeedjeVertix4));
                addtriangle1 = CountTriangle(removeedjeVertix1,
               removeedjeVertix4, tranformation);
                tranformation.Neighbourship[removeedjeVertix2].Add(removeedjeVertix3);
                tranformation.Neighbourship[removeedjeVertix3].Add(removeedjeVertix2);
                tranformation.MotifsEdjes.Add(new KeyValuePair<int, int>(removeedjeVertix2, removeedjeVertix3));
                addtriangle2 = CountTriangle(removeedjeVertix2,
              removeedjeVertix3, tranformation);
                container.Update4OrderMotifs(tranformation, new KeyValuePair<int, int>(removeedjeVertix2, removeedjeVertix3), new KeyValuePair<int, int>(removeedjeVertix1, removeedjeVertix4), removeEdjes1, removeedjesIndex2);
            }

            else
            {
                tranformation.Neighbourship[removeedjeVertix1].Add(removeedjeVertix3);
                tranformation.Neighbourship[removeedjeVertix3].Add(removeedjeVertix1);
                tranformation.MotifsEdjes.Add(new KeyValuePair<int, int>(removeedjeVertix1, removeedjeVertix3));
                addtriangle1 = CountTriangle(removeedjeVertix1,
              removeedjeVertix3, tranformation);
                tranformation.Neighbourship[removeedjeVertix2].Add(removeedjeVertix4);
                tranformation.Neighbourship[removeedjeVertix4].Add(removeedjeVertix2);
                tranformation.MotifsEdjes.Add(new KeyValuePair<int, int>(removeedjeVertix2, removeedjeVertix4));
                addtriangle2 = CountTriangle(removeedjeVertix2,
              removeedjeVertix4, tranformation);
                container.Update4OrderMotifs(tranformation, new KeyValuePair<int, int>(removeedjeVertix2, removeedjeVertix4), new KeyValuePair<int, int>(removeedjeVertix1, removeedjeVertix3), removeEdjes1, removeedjesIndex2);
            }

            // Count Add triangle
            int addtriangle = addtriangle1 + addtriangle2;

            triangle = addtriangle - removetriangle;

            return tranformation;
        }
 public PivotsCyclesCounter(IThreadEventHandler handler, ERContainer container, 
     int pivot, int cycleLength)
 {
     _handler = handler;
     _container = container;
     _pivot = pivot;
     _cycleLength = cycleLength;
 }
        public void ERMinPathDistTest()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            SortedDictionary<int, int> actualValue = analyzer.GetMinPathDist();
            SortedDictionary<int, int> expectedValue = goldResult.Results[0].DistanceBetweenVertices;
            Assert.IsTrue(compare(actualValue, expectedValue));
        }
        private int CountTriangle(int i, int j,ERContainer container)
        {
            var list = container.Neighbourship[j];

            int count = 0;
            for (int t = 0; t < list.Count; t++)
            {
                if (list[t] != i)
                {
                    if (container.Neighbourship[list[t]].Contains(i))
                        count++;
                }
            }

            return count;
        }
        private SortedDictionary<int, int> CountDegreeDestributionE(ERContainer mContainer)
        {
            SortedDictionary<int, int> degreeDistribution = new SortedDictionary<int, int>();
            int avg = 0;

            for (int i = 0; i < mContainer.Size; ++i)
            {
                int n = mContainer.Neighbourship[i].Count;
                avg += n;
                if (degreeDistribution.ContainsKey(n))
                {
                    degreeDistribution[n]++;
                }
                else
                {
                    degreeDistribution.Add(n, 1);
                }
            }

            return degreeDistribution;
        }
 // Конструктор, получающий контейнер графа.
 public ERAnalyzer(ERContainer c)
 {
     log.Info("Creating ERAnalizer object.");
     container = c;
 }
        private static int CountTringlei(int i, int size,ERContainer container)
        {
            var  nodes = new NodeTrigle[size];
            for (int j = 0; j < size; j++)
                nodes[j] = new NodeTrigle();

            int count = 0;
            nodes[i].lenght = 0;
            nodes[i].ancestor = 0;
            var  q = new Queue<int>();
            q.Enqueue(i);
            int u;

            while (q.Count != 0)
            {
                u = q.Dequeue();
                var  l = container.Neighbourship[u];
                for (int j = 0; j < l.Count; ++j)
                    if (nodes[l[j]].lenght == -1)
                    {
                        nodes[l[j]].lenght = nodes[u].lenght + 1;
                        nodes[l[j]].ancestor = u;
                        q.Enqueue(l[j]);
                    }
                    else
                    {
                        if (nodes[u].lenght == 1 && nodes[l[j]].lenght == 1)
                        {
                            ++count;
                        }
                    }
            }

            return count /= 2;
        }
        public override SortedDictionary<int, double> GetTrianglesTrajectory(double constant, BigInteger stepcount,bool keepdistribution)
        {
            log.Info("Getting triangle trajectory.");

            var stepscount = stepcount;
            var tarctory = new SortedDictionary<int, double>();
            int time = 0;
            int currentcounttriangle = GetCyclesForTringle(container);

            tarctory.Add(time, currentcounttriangle);
            if (keepdistribution)
                container.Get4Motifs();

            var currentContainer = container.Copy();

            var tempContainer = new ERContainer();
            var random = new Random();
            while (time != stepcount)
            {
                try
                {
                    time++;
                    var count = 0;

                    tempContainer = keepdistribution? TransformKeppingDistriburtion(currentContainer, random, out count) : Transformations(currentContainer, random,keepdistribution,out count);

                    if (currentcounttriangle < (-count))
                    {
                        Console.WriteLine("f**k");
                    }
                    var counttriangle = currentcounttriangle + count;

                    var delta = counttriangle - currentcounttriangle;

                    if (delta > 0)
                    {
                        tarctory.Add(time, counttriangle);
                        currentContainer = tempContainer.Copy();
                        currentcounttriangle = counttriangle;
                    }
                    else
                    {
                        if (new Random().NextDouble() < CalculatePropability(delta, constant))
                        {
                            tarctory.Add(time, counttriangle);
                            currentContainer = tempContainer.Copy();
                            currentcounttriangle = counttriangle;
                        }
                        else
                        {
                            tarctory.Add(time, currentcounttriangle);
                        }

                        Console.WriteLine(time);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(String.Format("Error occurred in step {0} ,Error message {1} ", stepcount, ex.InnerException));
                }

            }

            // very freak code

            bool trace = false;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["Tracing"].Value == "yes")
                trace = true;

            if (trace)
            {
                TraceContainer(config.AppSettings.Settings["TracingDirectory"].Value,
                    currentContainer,
                    constant);
            }

            // end of freak code

            return tarctory;
        }
 public CyclesParallelCounter(ERContainer container)
 {
     _container = container;
     _verticesCount = _container.Size;
     _counters = new PivotsCyclesCounter[_verticesCount];
 }
        public void ERCyclesTest()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            SortedDictionary<int, long> actualValue = analyzer.GetCycles(4, 6);
            SortedDictionary<int, long> expectedValue = goldResult.Results[0].Cycles;
            Assert.IsTrue(compare(actualValue, expectedValue));
        }
        public void EREigenValueTest()
        {
            XMLResultStorage resultStorage = new XMLResultStorage("");
            ResultAssembly goldResult = resultStorage.LoadXML("EROutput.xml");
            ERContainer container = new ERContainer();
            container.SetMatrix("ERInput.txt");
            AbstarctGraphAnalyzer analyzer = new ERAnalyzer(container);

            ArrayList actualValue = analyzer.GetEigenValues();
            ArrayList expectedValue = goldResult.Results[0].EigenVector;
            Assert.IsTrue(compare(actualValue, expectedValue));
        }
 // Конструктор по умолчанию, в котором создается пустой контейнер графа.
 public ERGenerator()
 {
     container = new ERContainer();
 }
        // very freak method
        private void TraceContainer(string tracingDirectory, ERContainer cont, double mu)
        {
            string dir = tracingDirectory + "TrajectoryResults\\";
            string filePath = dir + mu.ToString() + "_dump.txt";

            if (System.IO.File.Exists(filePath))
                filePath = dir + mu.ToString() + "_1_dump.txt";

            System.IO.Directory.CreateDirectory(dir);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
            {
                bool[,] matrix = cont.GetMatrix();
                for (int i = 0; i < matrix.GetLength(0); ++i)
                {
                    for (int j = 0; j < matrix.GetLength(1); ++j)
                    {
                        if (matrix[i, j])
                        {
                            file.Write(1 + " ");
                        }
                        else
                        {
                            file.Write(0 + " ");
                        }
                    }
                    file.WriteLine("");
                }
            }
        }
        private ERContainer Transformations(ERContainer trcontainer,Random random, bool keepdistribution,out int  triangle)
        {
            var tranformation = trcontainer.Copy();

            triangle = 0;

            try
            {

                var removeedje = random.Next(0, tranformation.Edjes.Count - 1);

                var removeedjeVertix1 = tranformation.Edjes[removeedje].Key;
                var removeedjeVertix2 = tranformation.Edjes[removeedje].Value;

                var addEdje = random.Next(0, tranformation.NoEdjes.Count - 1);

                var addEdjeVertix1 = tranformation.NoEdjes[addEdje].Key;
                var addEdjeVertix2 = tranformation.NoEdjes[addEdje].Value;

                //Remove edje
                tranformation.Neighbourship[removeedjeVertix1].Remove(removeedjeVertix2);
                tranformation.Neighbourship[removeedjeVertix2].Remove(removeedjeVertix1);

                tranformation.NoEdjes.Add(tranformation.Edjes[removeedje]);
                tranformation.Edjes.RemoveAt(removeedje);

                //Count remove triangle
                int removetriangle = CountTriangle(removeedjeVertix1,
                   removeedjeVertix2, tranformation);

                //add edje
                tranformation.Neighbourship[addEdjeVertix1].Add(addEdjeVertix2);
                tranformation.Neighbourship[addEdjeVertix2].Add(addEdjeVertix1);

                tranformation.Edjes.Add(tranformation.NoEdjes[addEdje]);
                tranformation.NoEdjes.RemoveAt(addEdje);

                // Count Add triangle

                int addtriangle = CountTriangle(addEdjeVertix1,
                   addEdjeVertix2, tranformation);

                triangle = addtriangle - removetriangle;
            }

            catch (Exception ex)
            {
                log.Error("Error according when transforms edges");
            }

            return tranformation;
        }
        private int GetCyclesForTringle(ERContainer container)
        {
            // log.Info("Getting count of cycles - order 3.");

            int count = 0;
            for (int i = 0; i < container.Size; ++i)
            {
                count += CountTringlei(i, container.Size, container);
                //List<int> nbs = container.Neighbourship[i];
                //for (int j = 0; j < nbs.Count; ++j)
                //{
                //    List<int> tmp = container.Neighbourship[nbs[j]];
                //    count += nbs.Intersect(tmp).Count();
                //}
            }

            return count / 3;
        }
        private void ERModelTest(ERContainer container)
        {
            //XMLResultStorage resultStorage = new XMLResultStorage("");
            //goldResult = resultStorage.LoadXML(goldenOutPath.Text);
            ERAnalyzer analyzer = new ERAnalyzer(container);

            //test tDegreeDistribution
            testDegreeDistribution(0, analyzer);

            //test AveragePath
            testAveragePath(1, analyzer);

            //test ClusteringCoefficient
            testClusteringCoefficient(2, analyzer);

            //test EigenValue
            testEigenValue(3, analyzer);

            //test Cycles of order 3
            testCycles3(4, analyzer);

            // test diameter
            testDiameter(5, analyzer);

            // test cycle of order 4
            testCycles4(6, analyzer);

            // test motive
            // testMotiv(7, analyzer);

            // test distance between vertexes
            testDistanceBetweenVertices(7, analyzer);

            // test distance between eigen values
            testDistancesBetweenEigenValues(8, analyzer);

            // test order of max full subgraph
            testFullSubgraphs(9, analyzer);

            // testCycles(11, analyzer);
        }