Exemple #1
0
        private bool AssignElements(int[] clusterAssignments, List <Cluster> clusters, List <List <double> > W, ref int _current)
        {
            try
            {
                bool converged = true;
                //Asignar cada elemento a su cluster correspondiente
                for (int i = 0; i < Set.ElementsCount; i++)
                {
                    Element _element = Set[i];
                    int     newC     = ClusterProcessedElement(_element, clusters, W);

                    if (newC != clusterAssignments[i])
                    {
                        converged             = false;
                        clusterAssignments[i] = newC;
                    }

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.UpdateProgressBar(_current++, "Running LAC algorithm...", false);
                    }
                }

                return(converged);
            }
            catch
            {
                return(true);
            }
        }
Exemple #2
0
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null || Structurings == null)
                {
                    throw new NullReferenceException();
                }

                int k = StructuringsCount;
                int _current = 1, _max = k * k;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running BOK algorithm...", true);
                }

                double _bestDistance        = double.MaxValue;
                int    _structuringPosition = 0;

                for (int i = 0; i < StructuringsCount; i++)
                {
                    double _temp = 0;
                    for (int j = 0; j < StructuringsCount; j++)
                    {
                        if (i != j)
                        {
                            _temp += GenericDistances.CalculateDistance(Structurings[i], Structurings[j], Set);
                        }

                        if (IContainerProgressBar != null)
                        {
                            IContainerProgressBar.UpdateProgressBar(_current++, "Running BOK algorithm...", false);
                        }
                    }
                    if (_temp < _bestDistance)
                    {
                        _bestDistance        = _temp;
                        _structuringPosition = i;
                    }
                }
                Structuring = Structurings[_structuringPosition];

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.FinishProgressBar();
                }

                return(Structuring);
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in CSPA algorithm.");
                }
                return(null);
            }
        }
Exemple #3
0
        public override Structuring BuildStructuring()
        {
            try
            {
                int _current = 1;
                int _max     = IterationsCount;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running HCE algorithm...", true);
                }

                int n = StructuringsCount * (StructuringsCount - 1) / 2;

                HeapArrayMax <Pair> _pairs = new HeapArrayMax <Pair>(n);
                for (int i = 0; i < StructuringsCount; i++)
                {
                    for (int j = i + 1; j < StructuringsCount; j++)
                    {
                        Pair _temp = Fitness(Structurings[i], Structurings[j]);

                        _pairs.Add(_temp);
                    }
                }

                for (int i = 0; i < IterationsCount; i++)
                {
                    Pair parents = _pairs.First;
                    _pairs.RemoveFirst();

                    Crossover(parents);

                    //calcular nuevo fitness//////////////***********//////////////
                    _pairs.Add(Fitness(parents.P1, parents.P2));

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.UpdateProgressBar(_current++, "Running HCE algorithm...", false);
                    }
                }

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.FinishProgressBar();
                }

                return(_pairs.First.P2);
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in HCE algorithm.");
                }
                return(null);
            }
        }
        public override Structuring BuildStructuring()
        {
            if (Structurings == null || Set == null || ClusterAlgorithm == null)
            {
                throw new NullReferenceException();
            }

            if (IContainerProgressBar != null)
            {
                IContainerProgressBar.ResetProgressBar(1, 1, true);
                IContainerProgressBar.UpdateProgressBar(0, "Running Simple CoAssociation algorithm with Lifetime...", true);
            }

            ClusterAlgorithm.IContainerProgressBar = IContainerProgressBar;
            ClusterAlgorithm.Set       = Set;
            ClusterAlgorithm.Proximity = new CoAssociationMatrixDiss(Set, Structurings, Name);

            return(ClusterAlgorithm.BuildStructuring());
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                int _current = 1;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, 1, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running Metis algorithm...", true);
                }


                if (ClustersCount <= 0)
                {
                    throw new Exception("La cantidad de clusters debe ser mayor que cero");
                }
                else if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus, Proximity = Proximity
                    };
                    return(Structuring);
                }
                else
                {
                    string filename   = BuildInputFile(ref _current);
                    string parameters = filename + " " + ClustersCount;
                    Utils.ExecuteMetisPackage(Utils.MetisExecutableName, parameters);
                    Structuring = Utils.BuildStructuringFromOutputFile(filename, Set, ClustersCount, Proximity);

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Has Occurred an error in METIS algorithm.");
                }
                return(null);
            }
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, 1, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running WSPA algorithm...", true);
                }

                VerifyPartitions(Structurings);
                List <double[, ]> MatrixsOf_dit = new List <double[, ]>();
                double[,] Max_row = new double[Set.ElementsCount, StructuringsCount];
                List <double[, ]> MatrixsObjectRepresentation = new List <double[, ]>();


                for (int i = 0; i < StructuringsCount; i++)
                {
                    double[,] Matrix = new double[Set.ElementsCount, Structurings[i].ClustersCount];
                    MatrixsOf_dit.Add(Matrix);

                    double[,] MatrixRepresentation = new double[Set.ElementsCount, Structurings[i].ClustersCount];
                    MatrixsObjectRepresentation.Add(MatrixRepresentation);

                    for (int j = 0; j < Set.ElementsCount; j++)
                    {
                        int    k    = 0;
                        double _max = double.MinValue;
                        //Aqui se llena la matrix por fila
                        foreach (var cluster in Structurings[i].Clusters.Values)
                        {
                            Matrix[j, k] = Calculate_dit(Set[j], cluster);

                            if (Matrix[j, k] > _max)
                            {
                                _max = Matrix[j, k];
                            }

                            if (j > 0)
                            {
                                int    _q           = Structurings[i].ClustersCount;
                                double _numerator   = Max_row[j - 1, i] - Matrix[j - 1, k] + 1;
                                double _denominator = _q * Max_row[j - 1, i] + _q - SumRow(Matrix, j - 1);
                                MatrixRepresentation[j - 1, k] = _numerator / _denominator;
                            }

                            k++;
                        }

                        Max_row[j, i] = _max;
                    }

                    //Calcula la ultima fila de la representacion, es decir del ultimo objeto
                    for (int k = 0; k < Structurings[i].ClustersCount; k++)
                    {
                        int    j            = Set.ElementsCount;
                        int    _q           = Structurings[i].ClustersCount;
                        double _numerator   = Max_row[j - 1, i] - Matrix[j - 1, k] + 1;
                        double _denominator = _q * Max_row[j - 1, i] + _q - SumRow(Matrix, j - 1);
                        MatrixRepresentation[j - 1, k] = _numerator / _denominator;
                    }
                }


                double[,] _Similarities = new double[Set.ElementsCount, Set.ElementsCount];
                double m = StructuringsCount;
                for (int i = 0; i < Set.ElementsCount; i++)
                {
                    for (int j = 0; j < Set.ElementsCount; j++)
                    {
                        double _Sij = 0;
                        for (int k = 0; k < MatrixsObjectRepresentation.Count; k++)
                        {
                            double[,] A = MatrixsObjectRepresentation[k];

                            if (i != j)
                            {
                                _Sij += EscalarProduct(A, i, j) / (Norm(A, i) * Norm(A, j));
                            }
                        }
                        _Similarities[i, j] = _Sij / m;
                    }
                }

                SimilarityWSPA _sim = new SimilarityWSPA(_Similarities);

                Metis _metis = new Metis(Set, _sim);
                _metis.IContainerProgressBar = IContainerProgressBar;
                _metis.ClustersCount         = ClustersCount;

                Structuring = _metis.BuildStructuring();

                return(Structuring);
            }
            catch (Exception _ex)
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in WSPA algorithm.\n" + _ex.Message);
                }
                return(null);
            }
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, 1, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running WBPA algorithm...", true);
                }

                WSPA.VerifyPartitions(Structurings);
                List <double[, ]> MatrixsOf_dit = new List <double[, ]>();
                double[,] Max_row = new double[Set.ElementsCount, StructuringsCount];
                List <double[, ]> MatrixsObjectRepresentation = new List <double[, ]>();

                int q_m = StructuringsCount * Structurings[0].ClustersCount;
                double[,] A = new double[Set.ElementsCount, q_m];

                for (int i = 0; i < StructuringsCount; i++)
                {
                    double[,] Matrix = new double[Set.ElementsCount, Structurings[i].ClustersCount];
                    MatrixsOf_dit.Add(Matrix);

                    double[,] MatrixRepresentation = new double[Set.ElementsCount, Structurings[i].ClustersCount];
                    MatrixsObjectRepresentation.Add(MatrixRepresentation);

                    for (int j = 0; j < Set.ElementsCount; j++)
                    {
                        int    k    = 0;
                        double _max = double.MinValue;
                        //Aqui se llena la matrix por fila
                        foreach (var cluster in Structurings[i].Clusters.Values)
                        {
                            Matrix[j, k] = WSPA.Calculate_dit(Set[j], cluster);

                            if (Matrix[j, k] > _max)
                            {
                                _max = Matrix[j, k];
                            }

                            if (j > 0)
                            {
                                int    _q           = Structurings[i].ClustersCount;
                                double _numerator   = Max_row[j - 1, i] - Matrix[j - 1, k] + 1;
                                double _denominator = _q * Max_row[j - 1, i] + _q - WSPA.SumRow(Matrix, j - 1);
                                MatrixRepresentation[j - 1, k] = _numerator / _denominator;
                                A[j - 1, i *_q + k]            = MatrixRepresentation[j - 1, k];
                            }

                            k++;
                        }

                        Max_row[j, i] = _max;
                    }

                    //Calcula la ultima fila de la representacion, es decir del ultimo objeto
                    for (int k = 0; k < Structurings[i].ClustersCount; k++)
                    {
                        int    j            = Set.ElementsCount;
                        int    _q           = Structurings[i].ClustersCount;
                        double _numerator   = Max_row[j - 1, i] - Matrix[j - 1, k] + 1;
                        double _denominator = _q * Max_row[j - 1, i] + _q - WSPA.SumRow(Matrix, j - 1);
                        MatrixRepresentation[j - 1, k] = _numerator / _denominator;
                        A[j - 1, i *_q + k]            = MatrixRepresentation[j - 1, k];
                    }
                }

                int _ElementsCount = Set.ElementsCount;

                for (int i = 0; i < q_m; i++)
                {
                    Element _element = new Element();
                    _element.Name       = "Element cluster - " + i;
                    _element.Index      = i;
                    _element.Attributes = Set.Attributes;

                    Set.Elements.Insert(0, _element);
                }
                //Actualizar los indices de los elementos originales
                for (int i = q_m; i < Set.ElementsCount; i++)
                {
                    Set[i].Index = i;
                }

                SimilarityWBPA _sim = new SimilarityWBPA(A, _ElementsCount, Structurings[0].ClustersCount, StructuringsCount);

                Metis _metis = new Metis(Set, _sim);
                _metis.IContainerProgressBar = IContainerProgressBar;
                _metis.ClustersCount         = ClustersCount;

                Structuring _StructTemp = _metis.BuildStructuring();



                Dictionary <string, Cluster> dic_clusters = new Dictionary <string, Cluster>();
                foreach (var cluster in _StructTemp.Clusters.Values)
                {
                    for (int i = 0; i < cluster.ElementsCount; i++)
                    {
                        if (cluster.Elements[i].Index < q_m)
                        {
                            cluster.Elements.RemoveAt(i);
                            i--;
                        }
                    }
                    if (cluster.ElementsCount > 0)
                    {
                        dic_clusters.Add(cluster.Name, cluster);
                    }
                }

                Structuring = new Partition()
                {
                    Clusters = dic_clusters
                };

                //Borrar los elementos annadidos en el conjunto
                for (int i = 0; i < q_m; i++)
                {
                    Set.Elements.RemoveAt(0);
                }

                //Actualizar los indices de los elementos que estan en el SET, que eran los originales
                for (int i = 0; i < Set.ElementsCount; i++)
                {
                    Set[i].Index = i;
                }

                return(Structuring);
            }
            catch (Exception _ex)
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in WBPA algorithm.\n" + _ex.Message);
                }
                return(null);
            }
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null || Structurings == null)
                {
                    throw new NullReferenceException();
                }

                int _current = 1, _maxpb = Set.ElementsCount * Structurings.Count;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _maxpb, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running HGPA algorithm...", true);
                }

                if (ClustersCount <= 0)
                {
                    throw new Exception("La cantidad de clusters debe ser mayor que cero");
                }
                else if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus
                    };

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }
                else
                {
                    #region Algorithm
                    //Construir un conjunto de elementos donde ahora cada elemento es un label,
                    //o lo que es lo mismo una hyperedge. Este seria el meta-grafo
                    Set hyperedgeSet = new Set("HyperEdge Set");

                    int dimH = 0;
                    foreach (Structuring s in Structurings)
                    {
                        dimH += s.ClustersCount;
                    }

                    byte[,] metagraph = new byte[Set.ElementsCount, dimH];

                    //Ahora por cada label annadir un nuevo elemento al conjunto, recordar que cada label
                    //seria cada hyperedges, lo que ahora cada hyperedges estaria representada por la clase Element
                    //pero la lista de Values seria el vector binario o mejor dicho los elementos que pertenecen
                    //a la hyperedges.
                    //La matriz metagraph es la representacion en vectores binarios del conjunto hyperedges.

                    // Ojo esto ya  ///////Es mejor representar cada hyperedges de esta forma es decir con los elementos que pertenecen
                    // no se hace   ///////a dicha hyperedges ya que si se representa por el vector binario entonces necesitariamos mucha memoria.
                    int index = 0;
                    foreach (Structuring structuring in Structurings)
                    {
                        foreach (Cluster cluster in structuring.Clusters.Values)
                        {
                            Element element = new Element();
                            element.Index = index;
                            element.Name  = "hyperedge-" + index;
                            foreach (Element temp in cluster.Elements)
                            {
                                metagraph[temp.Index, index] = 1;

                                if (IContainerProgressBar != null)
                                {
                                    IContainerProgressBar.UpdateProgressBar(_current++, "Running HGPA algorithm...", false);
                                }
                            }

                            hyperedgeSet.AddElement(element);
                            index++;
                        }
                    }

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.UpdateProgressBar(_maxpb, "Running HGPA algorithm...", true);
                    }

                    Similarity _sim = new BinaryJaccardMeasure(metagraph);

                    ClusterAlgorithm ca = new Metis(hyperedgeSet, _sim);

                    ca.ClustersCount = ClustersCount;
                    ca.BuildStructuring();

                    Partition metaClusters = (Partition)ca.Structuring;

                    //Asignar cada elemento original a su metacluster correspondiente

                    //double[] va a tener dimension igual a la cantidad de elementos iniciales y en cada posicion va a estar un numero entre 0 y 1
                    List <double[]> _meta_hyperedges = new List <double[]>();
                    foreach (Cluster _c in metaClusters.Clusters.Values)
                    {
                        double[] _meta_hyperedge = new double[metagraph.GetLength(0)];
                        foreach (Element _e in _c.Elements)
                        {
                            //_e.Index es la columna de la matrix metgraph, que dicha columna representa a ese elemento
                            for (int row = 0; row < metagraph.GetLength(0); row++)
                            {
                                _meta_hyperedge[row] += metagraph[row, _e.Index];
                            }
                        }

                        //LLevar cada posicion a un valor enre 0 y 1
                        for (int i = 0; i < _meta_hyperedge.Length; i++)
                        {
                            _meta_hyperedge[i] = _meta_hyperedge[i] / _c.ElementsCount;
                        }

                        _meta_hyperedges.Add(_meta_hyperedge);
                    }

                    //Construir la particion final
                    Dictionary <string, Cluster> _dic_clusters = new Dictionary <string, Cluster>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        Element _e = Set[i];

                        double _max            = -1;
                        int    _meta_hyperedge = -1;
                        for (int j = 0; j < _meta_hyperedges.Count; j++)
                        {
                            if (_meta_hyperedges[j][_e.Index] > _max)
                            {
                                _max            = _meta_hyperedges[j][_e.Index];
                                _meta_hyperedge = j;
                            }
                        }

                        string _nameOfCluster = "C-" + _meta_hyperedge;
                        if (_dic_clusters.ContainsKey(_nameOfCluster))
                        {
                            _dic_clusters[_nameOfCluster].AddElement(_e);
                        }
                        else
                        {
                            Cluster c = new Cluster(_nameOfCluster);
                            c.AddElement(_e);
                            _dic_clusters.Add(_nameOfCluster, c);
                        }
                    }


                    Structuring = new Partition()
                    {
                        Clusters = _dic_clusters
                    };

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);

                    #endregion
                }
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in MCLA algorithm.");
                }
                return(null);
            }
        }
Exemple #9
0
        /// <summary>
        /// Simulated Annealing, minimize the function.
        /// </summary>
        /// <param name="initial">Initial Solution.</param>
        /// <param name="Temp0">Initial Temperature. (Temp0=1000)</param>
        /// <param name="alpha">Update K. (alpha less than 1, alpha=.99)</param>
        /// <param name="K0">Iterations Count each step (100).</param>
        /// <param name="rho">Update K. (rho=1.05)</param>
        /// <param name="A">Acceptations Count each step. (A=10)</param>
        /// <param name="Frz">Final Temperature. (Frz=.5)</param>
        /// <param name="iterationsCount">Iterations Count. (iterationsCount=1000)</param>
        /// <param name="Neighbor">Delegate to calculate an Neighbor.</param>
        /// <param name="parametersNeighbor">Neighbor's parameters.</param>
        /// <param name="EvaluateSolution">Function to evaluate.</param>
        /// <param name="parametersEvaluateSolution">EvaluateSolution's parameters.</param>ref int aMaxCluster
        /// <param name="aMaxCluster">aMaxCluster the parameter to create new cluster in OneMoveElement.</param>
        /// <returns>Best Solution.</returns>
        public static string[] RunSAOMNewNeighbor(Set Set, string[] initial_sol, List <string[]> partitions, double Temp0, double alpha, double K0, double rho, double A, double Frz, double iterationsCount, IContainerProgressBar IContainerProgressBar, int _current, GenericDistances aGenericDistance, ref int aMaxCluster)
        {
            string[] _result = initial_sol;
            string[] _best   = _result;
            double   Temp    = Temp0;
            double   K       = K0;

            double old_evaluation = 0;

            double k         = 0;
            double a         = 0;
            double iteration = 0;

            while (iteration < iterationsCount && A / K < Frz)
            {
                k = 0;
                a = 0;
                while (k < K && a < A)
                {
                    old_evaluation = DelegateImplementations.S(Set, _best, partitions, aGenericDistance);


                    string[] nextSolution = DelegateImplementations.MeetJoinClusters(Set, _result, ref aMaxCluster);

                    double new_evaluation = DelegateImplementations.S(Set, nextSolution, partitions, aGenericDistance);

                    double diff = new_evaluation - old_evaluation;

                    if (diff < 0)
                    {
                        _best   = nextSolution;
                        _result = nextSolution;
                        a++;
                    }
                    else
                    {
                        double r = new Random(Environment.TickCount).NextDouble();

                        if (r < Math.Exp(-diff / Temp))
                        {
                            _result = nextSolution;
                            a++;
                        }
                        else
                        {
                            aMaxCluster = _result.Distinct <string>().Count();
                        }
                    }
                    k++;
                }

                //Update
                Temp = alpha * Temp;
                K    = rho * K;

                iteration++;

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.UpdateProgressBar(_current++, "Running SAOMNewNeighbor algorithm...", false);
                }
            }

            return(_best);
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null || Structurings == null)
                {
                    throw new NullReferenceException();
                }

                int _max = Set.ElementsCount * Structurings.Count;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running HGPA algorithm...", true);
                }

                if (ClustersCount <= 0)
                {
                    throw new Exception("La cantidad de clusters debe ser mayor que cero");
                }
                else if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus
                    };

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }
                else
                {
                    UBfactor = 5;

                    string filename = BuildInputFile();

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.UpdateProgressBar(_max, "Running HGPA algorithm...", true);
                    }

                    string parameters = filename + " " + ClustersCount + " " + UBfactor;
                    Utils.ExecuteMetisPackage(Utils.HMetisExecutableName, parameters);
                    Structuring = Utils.BuildStructuringFromOutputFile(filename, Set, ClustersCount, null);

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in CSPA algorithm.");
                }
                return(null);
            }
        }
        private List <MeasureOutput> RunMethod(List <PartitionInfo> _partitionsInfo, List <Measure> _measures, Structuring _realpartition, List <MeasureOutput> _measuresOutput, List <MeasureInfo> _MeasuresChecked)
        {
            try
            {
                int _current = 1;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _partitionsInfo.Count * _measures.Count + _measures.Count, false);
                }

                for (int i = 0; i < _partitionsInfo.Count; i++)
                {
                    double[] _values = new double[_measures.Count];
                    //Evaluar cada Medida según la partición correspondiente
                    for (int k = 0; k < _measures.Count; k++)
                    {
                        if (IContainerProgressBar != null)
                        {
                            IContainerProgressBar.UpdateProgressBar(_current++, "Computing Measure " + _measures[k].Name + " in Partition " + _partitionsInfo[i].AlgorithmName, false);
                        }

                        Measure _measureTemp = _measures[k];
                        _measureTemp.Set               = Enviroment.Set;
                        _measureTemp.Structuring       = _partitionsInfo[i].Partition;
                        _measureTemp.RealPartition     = _realpartition;
                        _measureTemp.ObjetiveAttribute = Att_objetive;

                        _values[k] = _measureTemp.EvaluatePartition();

                        _values[k] = Math.Round(_values[k], 4);
                    }

                    _measuresOutput.Add(new MeasureOutput()
                    {
                        AlgorithmName = _partitionsInfo[i].AlgorithmName,
                        Measures      = _MeasuresChecked,
                        Partition     = _partitionsInfo[i].Partition,
                        Values        = _values
                    });
                }

                {
                    //Evaluar la particion real, para poder comparar los valores de las demas particiones con respecto a los valores de la real
                    double[] _valuesRealPartition = new double[_measures.Count];
                    //Evaluar cada Medida según la partición correspondiente
                    for (int k = 0; k < _measures.Count; k++)
                    {
                        if (IContainerProgressBar != null)
                        {
                            IContainerProgressBar.UpdateProgressBar(_current++, "Computing Measure " + _measures[k].Name + " in Real Partition", false);
                        }

                        Measure _measureTemp = _measures[k];
                        _measureTemp.Set               = Enviroment.Set;
                        _measureTemp.Structuring       = _realpartition;
                        _measureTemp.RealPartition     = _realpartition;
                        _measureTemp.ObjetiveAttribute = Att_objetive;

                        _valuesRealPartition[k] = _measureTemp.EvaluatePartition();

                        _valuesRealPartition[k] = Math.Round(_valuesRealPartition[k], 4);
                    }

                    _measuresOutput.Add(new MeasureOutput()
                    {
                        AlgorithmName = "Real Partition",
                        Measures      = _MeasuresChecked,
                        Partition     = _realpartition,
                        Values        = _valuesRealPartition
                    });
                }
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.FinishProgressBar();
                }

                return(_measuresOutput);
            }
            catch (Exception ex)
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in Measures");
                }

                return(null);
            }
        }
Exemple #12
0
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null)
                {
                    throw new NullReferenceException();
                }

                int _current = 1;
                int _max     = IterationsCount * (Set.ElementsCount * 4);
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running LAC algorithm...", true);
                }

                //////BORRAR////////////////////////////
                //Verificar que todos los atributos sean de tipo Numerico
                foreach (var attr in Set.Attributes.Values)
                {
                    if (attr.AttributeType != AttributeType.Numeric)
                    {
                        throw new Exception("The LAC algorithm run only with numerics Sets.");
                    }
                }

                if (ClustersCount > Set.ElementsCount)
                {
                    ClustersCount = Set.ElementsCount;
                }

                if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus, Proximity = Proximity
                    };
                    return(Structuring);
                }
                else
                {
                    List <Cluster>        clusters = new List <Cluster>();
                    List <List <double> > W        = new List <List <double> >();

                    //Seleccionar los centroides aleatorios
                    Random r     = new Random(Seed);
                    int    index = 0;

                    #region K centroids y W
                    for (int i = Set.ElementsCount - 1, j = 0; i >= 0; i--, j++)
                    {
                        index = r.Next(0, i + 1);

                        List <Element> l = new List <Element>();
                        l.Add(Set[index]);
                        clusters.Add(new Cluster("C-" + j, l)
                        {
                            Centroid = Set[index]
                        });

                        List <double> wi = new List <double>();
                        for (int m = 0; m < Set.Attributes.ValuesCount; m++)
                        {
                            wi.Add(1.0 / Math.Sqrt(Set.Attributes.ValuesCount));
                        }

                        W.Add(wi);

                        //Element temp = Set[index];
                        //Set[index] = Set[i];
                        //Set[i] = temp;
                        Set.Swap(index, i);


                        if (clusters.Count == ClustersCount)
                        {
                            break;
                        }
                    }
                    #endregion

                    bool  converged          = false;
                    int   numIterations      = 0;
                    int[] clusterAssignments = new int[Set.ElementsCount];

                    while (!converged && numIterations < IterationsCount)
                    {
                        numIterations++;
                        converged = true;

                        //PASO 3::
                        //Asignar cada elemento a su cluster correspondiente(lo unico que se utiliza son los centroides)
                        //No tienen porque estar llenos los clusters
                        AssignElements(clusterAssignments, clusters, W, ref _current);

                        foreach (var item in clusters)
                        {
                            item.Elements.Clear();
                        }

                        //Lleno cada cluster segun la asignacion
                        for (int j = 0; j < clusterAssignments.Length; j++)
                        {
                            while (clusters.Count <= clusterAssignments[j])
                            {
                                clusters.Add(new Cluster("C-" + j));
                            }
                            clusters[clusterAssignments[j]].AddElement(Set[j]);

                            if (IContainerProgressBar != null)
                            {
                                IContainerProgressBar.UpdateProgressBar(_current++, "Running LAC algorithm...", false);
                            }
                        }

                        //PASO 4::
                        //Computar los nuevos pesos
                        for (int j = 0; j < W.Count; j++)
                        {
                            for (int i = 0; i < W[j].Count; i++)
                            {
                                double Xji = CalculateXji(i, clusters[j]);

                                double wji = CalculateWji(Xji, Set.Attributes.ValuesCount, clusters[j]);

                                W[j][i] = wji;
                            }
                        }

                        //PASO 5::
                        //Asignar nuevamente cada elemento a su cluster correspondiente
                        converged = AssignElements(clusterAssignments, clusters, W, ref _current);

                        foreach (var item in clusters)
                        {
                            item.Elements.Clear();
                        }

                        for (int j = 0; j < clusterAssignments.Length; j++)
                        {
                            while (clusters.Count <= clusterAssignments[j])
                            {
                                clusters.Add(new Cluster("C-" + j));
                            }
                            clusters[clusterAssignments[j]].AddElement(Set[j]);

                            if (IContainerProgressBar != null)
                            {
                                IContainerProgressBar.UpdateProgressBar(_current++, "Running LAC algorithm...", false);
                            }
                        }

                        //PASO 6::
                        //Computar los nuevos centroides
                        for (int i = 0; i < clusters.Count; i++)
                        {
                            clusters[i].UpdateCentroid();
                        }
                    }


                    //Crear Dictionary<string,Cluster> para poder construir la particion
                    Dictionary <string, Cluster> dic_clusters = new Dictionary <string, Cluster>();
                    for (int i = 0; i < clusters.Count; i++)
                    {
                        List <double> _ws = new List <double>();
                        clusters[i].Name    = "C-" + i;
                        clusters[i].Weights = _ws;
                        dic_clusters.Add(clusters[i].Name, clusters[i]);

                        for (int j = 0; j < Set.Attributes.ValuesCount; j++)
                        {
                            _ws.Add((double)W[i][j]);
                        }
                    }

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    Structuring = new WeightedPartition()
                    {
                        Clusters = dic_clusters, Proximity = Proximity
                    };
                    return(Structuring);
                }
            }
            catch (Exception _ex)
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in LAC algorithm.\n" + _ex.Message);
                }
                return(null);
            }
        }
Exemple #13
0
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null)
                {
                    throw new NullReferenceException();
                }

                IterationsCount = 100;

                int _current = 1;
                int _max     = IterationsCount * (Set.ElementsCount * 2);
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running K-Means algorithm...", false);
                }

                if (ClustersCount > Set.ElementsCount)
                {
                    ClustersCount = Set.ElementsCount;
                }

                if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus, Proximity = Proximity
                    };
                    return(Structuring);
                }
                else
                {
                    List <Cluster> clusters = new List <Cluster>();

                    //Seleccionar los centroides aleatorios
                    Random r     = new Random(Seed + Environment.TickCount);
                    int    index = 0;

                    for (int i = Set.ElementsCount - 1, j = 0; i >= 0; i--, j++)
                    {
                        index = r.Next(0, i + 1);

                        List <Element> l = new List <Element>();
                        l.Add(Set[index]);
                        clusters.Add(new Cluster("C-" + j, l)
                        {
                            Centroid = Set[index]
                        });

                        //Element temp = Set[index];
                        //Set[index] = Set[i];
                        //Set[i] = temp;
                        Set.Swap(index, i);


                        if (clusters.Count == ClustersCount)
                        {
                            break;
                        }
                    }

                    //Algoritmo
                    bool  converged          = false;
                    int   emptyClustersCount = 0;
                    int   numIterations      = 0;
                    int[] clusterAssignments = new int[Set.ElementsCount];

                    while (!converged && numIterations < IterationsCount)
                    {
                        converged          = true;
                        emptyClustersCount = 0;
                        numIterations++;

                        //colocar en cada centroide el elemento mas similar
                        for (int i = 0; i < Set.ElementsCount; i++)
                        {
                            Element toCluster = Set[i];
                            int     newC      = ClusterProcessedElement(toCluster, clusters);

                            if (newC != clusterAssignments[i])
                            {
                                converged             = false;
                                clusterAssignments[i] = newC;
                            }


                            if (IContainerProgressBar != null)
                            {
                                IContainerProgressBar.UpdateProgressBar(_current++, "Running K-Means algorithm...", false);
                            }
                        }

                        foreach (var item in clusters)
                        {
                            item.Elements.Clear();
                        }

                        for (int j = 0; j < clusterAssignments.Length; j++)
                        {
                            while (clusters.Count <= clusterAssignments[j])
                            {
                                clusters.Add(new Cluster("C-" + j));
                            }
                            clusters[clusterAssignments[j]].AddElement(Set[j]);


                            if (IContainerProgressBar != null)
                            {
                                IContainerProgressBar.UpdateProgressBar(_current++, "Running K-Means algorithm...", false);
                            }
                        }

                        List <Cluster> lc = new List <Cluster>();
                        foreach (var item in clusters)
                        {
                            if (item.ElementsCount == 0)
                            {
                                emptyClustersCount++;
                                lc.Add(item);
                            }
                            else
                            {
                                item.UpdateCentroid();
                            }
                        }
                        foreach (var item in lc)
                        {
                            clusters.Remove(item);
                        }

                        if (emptyClustersCount > 0)
                        {
                            ClustersCount -= emptyClustersCount;
                        }
                    }

                    //Crear Dictionary<string,Cluster> para poder construir la particion
                    Dictionary <string, Cluster> dic_clusters = new Dictionary <string, Cluster>();
                    for (int i = 0; i < clusters.Count; i++)
                    {
                        clusters[i].Name = "C-" + i;
                        dic_clusters.Add(clusters[i].Name, clusters[i]);
                    }


                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }


                    Structuring = new Partition()
                    {
                        Clusters = dic_clusters, Proximity = Proximity
                    };
                    return(Structuring);
                }
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in K-Means algorithm.");
                }
                return(null);
            }
        }
Exemple #14
0
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null || Structurings == null)
                {
                    throw new NullReferenceException();
                }

                int _current = 1, _max = IterationsCount;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(0, "Running Simulated Annealing MeetJoinClusters algorithm...", true);
                }

                int random_pos = new Random(Environment.TickCount).Next(0, StructuringsCount);
                //EuclideanDistance _eu = new EuclideanDistance();
                //_eu.AttributesToCalculateProximity = Set.Attributes.Values;
                //KMeans _kmeans = new KMeans(Set, _eu);
                //_kmeans.ClustersCount =3;
                //_kmeans.Seed = Environment.TickCount;
                //_kmeans.IterationsCount = 100;

                //Structuring initial = Structurings[random_pos];

                BOK bok = new BOK(Set, Structurings)
                {
                    GenericDistances = new MirkinDistance()
                };
                Structuring initial = UseBOK ? bok.BuildStructuring() : Structurings[0];

                string[] initial_sol = new string[Set.ElementsCount];
                for (int i = 0; i < Set.ElementsCount; i++)
                {
                    initial_sol[i] = initial.Elements[Set[i]][0];
                }

                int _maxCluster = initial.ClustersCount;

                List <string[]> labels_List = new List <string[]>();
                //Convertir todas las particiones a arreglo de string, donde en cada posicion
                //esta la etiqueta del cluster al que pertenece el elemento j
                for (int i = 0; i < Structurings.Count; i++)
                {
                    string[] _temp = new string[Set.ElementsCount];
                    labels_List.Add(_temp);
                    for (int j = 0; j < Set.ElementsCount; j++)
                    {
                        _temp[j] = Structurings[i].Elements[Set[j]][0];
                    }
                }

                string[] _result_labels = SA <string[]> .RunSAOMNewNeighbor(Set, initial_sol, labels_List, Temperature, .99, 50, 1.05, 10, .5, IterationsCount, IContainerProgressBar, _current, GenericDistances, ref _maxCluster);

                Dictionary <string, Cluster> dic_clusters = new Dictionary <string, Cluster>();
                for (int i = 0; i < Set.ElementsCount; i++)
                {
                    if (dic_clusters.ContainsKey(_result_labels[i]))
                    {
                        dic_clusters[_result_labels[i]].AddElement(Set[i]);
                    }
                    else
                    {
                        Cluster c = new Cluster(_result_labels[i]);
                        c.AddElement(Set[i]);
                        dic_clusters.Add(c.Name, c);
                    }
                }

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.FinishProgressBar();
                }

                Structuring = new Partition()
                {
                    Clusters = dic_clusters
                };
                return(Structuring);
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in Simulated Annealing MeetJoinClusters algorithm.");
                }
                return(null);
            }
        }
        private string BuildInputFile()
        {
            int _current = 1;

            Random r          = new Random(Environment.TickCount);
            string folderpath = Utils.ExesFolderPath;
            string filename   = "inputhypergraph" + Utils.GetUniqueID + ".config";
            string filepath   = folderpath + Path.DirectorySeparatorChar + filename;

            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }

            FileStream   fs = new FileStream(filepath, FileMode.CreateNew, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);

            //Calcular el numero de Hyperedges
            int hedges = 0;

            foreach (Structuring s in Structurings)
            {
                hedges += s.ClustersCount;
            }

            int vertices = Set.ElementsCount;

            //como los vertices y las hyperedges tienen el mismo peso se omite el parametro "fmt"

            //First Line
            string firsteline = hedges + " " + vertices;

            sw.WriteLine(firsteline);

            // |E|h - lines, where |E|h is the amount of hyperedges

            foreach (Structuring structuring in Structurings)
            {
                foreach (Cluster cluster in structuring.Clusters.Values)
                {
                    StringBuilder line = new StringBuilder();
                    foreach (Element element in cluster.Elements)
                    {
                        line.Append((element.Index + 1).ToString() + " ");

                        if (IContainerProgressBar != null)
                        {
                            IContainerProgressBar.UpdateProgressBar(_current++, "Running HGPA algorithm...", false);
                        }
                    }

                    sw.WriteLine(line);
                }
            }

            sw.Close();
            fs.Close();


            return(filename);
        }
Exemple #16
0
        /// <summary>
        /// Simulated Annealing, minimize the function.
        /// </summary>
        /// <param name="initial">Initial Solution.</param>
        /// <param name="Temp0">Initial Temperature. (Temp0=1000)</param>
        /// <param name="alpha">Update K. (alpha less than 1, alpha=.99)</param>
        /// <param name="K0">Iterations Count each step (100).</param>
        /// <param name="rho">Update K. (rho=1.05)</param>
        /// <param name="A">Acceptations Count each step. (A=10)</param>
        /// <param name="Frz">Final Temperature. (Frz=.5)</param>
        /// <param name="iterationsCount">Iterations Count. (iterationsCount=1000)</param>
        /// <param name="Neighbor">Delegate to calculate an Neighbor.</param>
        /// <param name="parametersNeighbor">Neighbor's parameters.</param>
        /// <param name="EvaluateSolution">Function to evaluate.</param>
        /// <param name="parametersEvaluateSolution">EvaluateSolution's parameters.</param>ref int aMaxCluster
        /// <param name="aMaxCluster">aMaxCluster the parameter to create new cluster in OneMoveElement.</param>
        /// <returns>Best Solution.</returns>
        public static string[] RunBOM(Set Set, string[] initial_sol, List <string[]> partitions, double Temp0, double alpha, double K0, double rho, double A, double Frz, double iterationsCount, IContainerProgressBar IContainerProgressBar, int _current, GenericDistances aGenericDistance, ref int aMaxCluster)
        {
            //string[] _result = initial_sol;
            string[] _best = initial_sol;
            double   Temp  = Temp0;
            double   K     = K0;

            double old_evaluation = 0;

            double k         = 0;
            double a         = 0;
            double iteration = 0;

            while (iteration < iterationsCount && A / K < Frz)
            {
                k = 0;
                a = 0;
                while (k < K && a < A)
                {
                    old_evaluation = DelegateImplementations.S(Set, _best, partitions, aGenericDistance);

                    string[] nextSolution = DelegateImplementations.MoveOneElement(Set, _best, ref aMaxCluster);

                    double new_evaluation = DelegateImplementations.S(Set, nextSolution, partitions, aGenericDistance);

                    double diff = new_evaluation - old_evaluation;

                    if (diff < 0)
                    {
                        _best = nextSolution;
                        a++;
                    }
                    else
                    {
                        aMaxCluster = _best.Distinct <string>().Count();
                    }

                    k++;
                }

                //Update
                Temp = alpha * Temp;
                K    = rho * K;

                iteration++;

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.UpdateProgressBar(_current++, "Running BOM algorithm...", false);
                }
            }

            return(_best);
        }
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null || Structurings == null)
                {
                    throw new NullReferenceException();
                }

                int _current = 1, _max = Set.ElementsCount * Structurings.Count;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running CSPA algorithm...", true);
                }

                if (ClustersCount <= 0)
                {
                    throw new Exception("La cantidad de clusters debe ser mayor que cero");
                }
                else if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus
                    };

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }
                else
                {
                    #region Algorithm
                    //Calcular la matrix V x H
                    int dimH = 0;
                    foreach (Structuring s in Structurings)
                    {
                        dimH += s.ClustersCount;
                    }

                    byte[,] VxH = new byte[Set.ElementsCount, dimH];

                    //rellenar VxH
                    int currentColumn = 0;//cada columna representa un cluster
                    //Recordar tbn que los elementos tienen un indice que los representa
                    foreach (Structuring s in Structurings)
                    {
                        foreach (Cluster cluster in s.Clusters.Values)
                        {
                            foreach (Element e in cluster.Elements)
                            {
                                VxH[e.Index, currentColumn] = 1;

                                if (IContainerProgressBar != null)
                                {
                                    IContainerProgressBar.UpdateProgressBar(_current++, "Running CSPA algorithm...", false);
                                }
                            }
                            //Debo actualizar currentColumn ya que cada cluser representa una columna
                            currentColumn++;
                        }
                    }

                    //Construir CoAsociationMatrixDissToMetis para pasarselo como similitud entre elementos
                    //al algoritmo Metis
                    Similarity _sim = new CoAsociationMatrixDissToMetis(Set, VxH, Structurings.Count);

                    ClusterAlgorithm ca = new Metis(Set, _sim);

                    //Llamar al algoritmo Metis
                    ca.ClustersCount = ClustersCount;
                    ca.BuildStructuring();

                    Structuring = ca.Structuring;

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);

                    #endregion
                }
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in CSPA algorithm.");
                }
                return(null);
            }
        }
        public override Structuring BuildStructuring()
        {
            if (Structurings == null || Set == null)
            {
                throw new NullReferenceException();
            }

            if (IContainerProgressBar != null)
            {
                IContainerProgressBar.ResetProgressBar(1, 1, true);
                IContainerProgressBar.UpdateProgressBar(0, "Running QMI algorithm...", true);
            }

            List <Attribute> list_att = new List <Attribute>();
            int cont = 0;

            foreach (Structuring s in Structurings)
            {
                foreach (Cluster c in s.Clusters.Values)
                {
                    Attribute att = new Attribute("x" + cont, null);
                    cont++;

                    att.AttributeType = AttributeType.Numeric;
                    list_att.Add(att);
                }
            }

            Set newset = new Set("Artificial");

            newset.Attributes  = new Attributes(list_att);
            newset.ElementType = ElementType.Numeric;


            foreach (Element e in Set.Elements)
            {
                List <object> values = new List <object>();
                foreach (Structuring s in Structurings)
                {
                    foreach (Cluster c in s.Clusters.Values)
                    {
                        double temp = c.HaveElement(e) ? 1 : 0;
                        temp = temp - ((double)c.ElementsCount / (double)Set.ElementsCount);
                        values.Add(temp);
                    }
                }
                Element newelement = new Element(newset, values);
                newelement.Name  = e.Name;
                newelement.Index = e.Index;

                newset.AddElement(newelement);
            }

            KMeans kms = new KMeans(newset, new EuclideanDistance()
            {
                AttributesToCalculateProximity = newset.Attributes.Values
            });

            kms.ClustersCount   = ClusterCount;
            kms.IterationsCount = IterationsCount;
            kms.Seed            = Environment.TickCount;

            kms.IContainerProgressBar = IContainerProgressBar;

            Structuring art_struct = kms.BuildStructuring();

            List <Cluster> clusters = new List <Cluster>();

            cont = 0;
            foreach (Cluster c in art_struct.Clusters.Values)
            {
                Cluster temp = new Cluster("C-" + cont);
                cont++;
                foreach (Element item in c.Elements)
                {
                    temp.AddElement(Set[item.Index]);
                }
                clusters.Add(temp);
            }

            Dictionary <string, Cluster> temp_dic = new Dictionary <string, Cluster>();

            foreach (Cluster item in clusters)
            {
                temp_dic.Add(item.Name, item);
            }

            Structuring real_struct = new Partition()
            {
                Clusters = temp_dic
            };

            return(real_struct);
        }
Exemple #19
0
        public override Structuring BuildStructuring()
        {
            try
            {
                if (Set == null)
                {
                    throw new NullReferenceException();
                }

                int _current = 1;
                int _max     = Set.ElementsCount;
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ResetProgressBar(1, _max, true);
                    IContainerProgressBar.UpdateProgressBar(1, "Running Hierarchical agglomerative algorithm...", true);
                }

                if (ClustersCount > Set.ElementsCount)
                {
                    ClustersCount = Set.ElementsCount;
                }

                if (ClustersCount <= 0)
                {
                    throw new Exception("La cantidad de clusters debe ser mayor que cero");
                }
                if (ClustersCount == 1)
                {
                    Dictionary <string, Cluster> dic_clus = new Dictionary <string, Cluster>();
                    string         name = "C-0";
                    List <Element> temp = new List <Element>();

                    for (int i = 0; i < Set.ElementsCount; i++)
                    {
                        if (IContainerProgressBar != null)
                        {
                            IContainerProgressBar.UpdateProgressBar(_current++, "Running Hierarchical agglomerative algorithm...", false);
                        }

                        temp.Add(Set[i]);
                    }

                    dic_clus.Add(name, new Cluster(name)
                    {
                        Elements = temp
                    });

                    Structuring = new Partition()
                    {
                        Clusters = dic_clus, Proximity = Proximity
                    };

                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.FinishProgressBar();
                    }

                    return(Structuring);
                }

                double AlfaI = 0, AlfaJ = 0, Beta = 0, Gamma = 0;

                //Al inicio cada elemento es un cluster
                double[,] DMatrix = new double[Set.Elements.Count, Set.Elements.Count];
                List <Cluster> clusters = new List <Cluster>();
                bool[]         des      = new bool[Set.Elements.Count];//true si ese elemento ya no es representativo

                for (int i = 0; i < Set.Elements.Count; i++)
                {
                    List <Element> l = new List <Element>();
                    l.Add(Set[i]);
                    clusters.Add(new Cluster("C-" + i, l));
                }

                //Construir para cada cluster una cola con prioridad
                //con las disimilitudes de el con el resto de los clusters
                //y la matriz de todas las disimilitudes O(n2*log n)

                List <HeapArray <Container> > lh = new List <HeapArray <Container> >();

                for (int i = 0; i < Set.Elements.Count; i++)
                {
                    lh.Add(new HeapArray <Container>(Set.Elements.Count - 1));//No se pone la diss de un elemento con el mismo
                }
                for (int i = 0; i < Set.Elements.Count; i++)
                {
                    for (int j = i + 1; j < Set.Elements.Count; j++)
                    {
                        double temp_diss = Proximity.CalculateProximity(Set.Elements[i], Set.Elements[j]);

                        DMatrix[i, j] = temp_diss;
                        DMatrix[j, i] = temp_diss;
                        lh[i].Add(new Container {
                            Rank = temp_diss, Name = i, Cluster = j
                        });
                        lh[j].Add(new Container {
                            Rank = temp_diss, Name = j, Cluster = i
                        });
                    }
                }

                //Algoritmo O(n2*log n)
                for (int i = Set.Elements.Count; i > ClustersCount; i--)
                {
                    if (IContainerProgressBar != null)
                    {
                        IContainerProgressBar.UpdateProgressBar(_current++, "Running Hierarchical agglomerative algorithm...", false);
                    }

                    //Seleccionar los 2 clusters mas similares O(n)
                    double min = double.MaxValue;
                    int    cluster_i = 0, cluster_j = 0;
                    int    pos_cluster_i = 0, pos_cluster_j = 0;

                    for (int j = lh.Count - 1; j >= 0; j--)
                    {
                        if (lh[j].First.Rank < min)
                        {
                            min           = lh[j].First.Rank;
                            cluster_i     = lh[j].First.Name;
                            cluster_j     = lh[j].First.Cluster;
                            pos_cluster_i = j;
                        }
                    }
                    for (int j = 0; j < lh.Count; j++)
                    {
                        if (lh[j].First != null && lh[j].First.Name == cluster_j)
                        {
                            pos_cluster_j = j;
                            break;
                        }
                    }

                    //Calcular posiciones para borrar y guardar

                    int erase_pos = 0, final_pos = 0;

                    erase_pos = pos_cluster_i > pos_cluster_j ? pos_cluster_i : pos_cluster_j;
                    final_pos = pos_cluster_i < pos_cluster_j ? pos_cluster_i : pos_cluster_j;

                    lh.RemoveAt(erase_pos);

                    //Actualizar los parametros AlfaI, AlfaJ, Beta y Gamma
                    double cluster_i_count = clusters[erase_pos].ElementsCount;
                    double cluster_j_count = clusters[final_pos].ElementsCount;

                    AlfaI = UpdateAlfaI(cluster_i_count, cluster_j_count);
                    AlfaJ = UpdateAlfaJ(cluster_i_count, cluster_j_count);
                    Beta  = UpdateBeta(cluster_i_count, cluster_j_count);
                    Gamma = UpdateGamma(cluster_i_count, cluster_j_count);

                    //Unir los clusters

                    foreach (Element item in clusters[erase_pos].Elements)
                    {
                        clusters[final_pos].AddElement(item);
                    }
                    clusters.RemoveAt(erase_pos);

                    //Actualizar DMatrix con la disimilitud del nuevo cluster
                    //y el resto de los clusters O(n)
                    //Formula que se usa segun el algoritmo

                    //La posicion del cluster i en Dmatrix es cluster_i
                    //La posicion del cluster j en Dmatrix es cluster_j

                    int pos_h = -1;
                    int pos_i = cluster_i;
                    int pos_j = cluster_j;

                    if (erase_pos == pos_cluster_i)
                    {
                        des[cluster_i] = true;
                        pos_h          = cluster_j;
                    }
                    else
                    {
                        des[cluster_j] = true;
                        pos_h          = cluster_i;
                    }

                    for (int k = 0; k < DMatrix.GetLength(0); k++)
                    {
                        DMatrix[pos_h, k] = AlfaI * DMatrix[pos_i, k] + AlfaJ * DMatrix[pos_j, k] + Beta * DMatrix[pos_i, pos_j] + Gamma * Math.Abs(DMatrix[pos_i, k] - DMatrix[pos_j, k]);
                        DMatrix[k, pos_h] = DMatrix[pos_h, k];
                    }

                    //Actualizar array de Heaps con la disimilitud del nuevo cluster
                    //y el resto de los clusters O(n*log n)

                    lh[final_pos] = new HeapArray <Container>(Set.Elements.Count - 1);

                    for (int j = 0; j < lh.Count; j++)
                    {
                        Container[] lc = lh[j].ToArray;
                        lh[j] = new HeapArray <Container>(Set.Elements.Count - 1);
                        for (int k = 1; k < lc.Length; k++)
                        {
                            if (lc[k] == null)
                            {
                                break;
                            }
                            if (lc[k].Cluster != cluster_i && lc[k].Cluster != cluster_j)
                            {
                                lh[j].Add(lc[k]);
                            }
                        }
                        if (j != final_pos && lh[j].First != null)
                        {
                            lh[j].Add(new Container {
                                Rank = DMatrix[pos_h, lh[j].First.Name], Name = lh[j].First.Name, Cluster = pos_h
                            });
                        }
                    }

                    for (int j = 0; j < DMatrix.GetLength(0); j++)
                    {
                        if (pos_h != j && pos_j != j && pos_i != j && !des[j])
                        {
                            lh[final_pos].Add(new Container {
                                Rank = DMatrix[pos_h, j], Name = pos_h, Cluster = j
                            });
                        }
                    }
                }

                //Crear Dictionary<string,Cluster> para construir la particion
                Dictionary <string, Cluster> dic_clusters = new Dictionary <string, Cluster>();
                int cont = 0;
                for (int i = 0; i < clusters.Count; i++)
                {
                    if (clusters[i] != null)
                    {
                        clusters[i].Name = "C-" + cont;
                        dic_clusters.Add(clusters[i].Name, clusters[i]);
                        cont++;
                    }
                }

                Structuring = new Partition()
                {
                    Clusters = dic_clusters, Proximity = Proximity
                };

                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.FinishProgressBar();
                }

                return(Structuring);
            }
            catch
            {
                if (IContainerProgressBar != null)
                {
                    IContainerProgressBar.ShowError("Error occurred in Hierarchical agglomerative algorithm.");
                }
                return(null);
            }
        }