Single iteration of k-modes clustering algorithm
557598
def _k_modes_iter(X, centroids, cl_attr_freq, membship, dissim, random_state):
    """"""
    moves = 0
    for ipoint, curpoint in enumerate(X):
        clust = np.argmin(dissim(centroids, curpoint, X=X, membship=membship))
        if membship[clust, ipoint]:
            # Point is already in its right place.
            continue

        # Move point, and update old/new cluster frequencies and centroids.
        moves += 1
        old_clust = np.argwhere(membship[:, ipoint])[0][0]

        cl_attr_freq, membship, centroids = move_point_cat(
            curpoint, ipoint, clust, old_clust, cl_attr_freq, membship, centroids
        )

        # In case of an empty cluster, reinitialize with a random point
        # from the largest cluster.
        if not membship[old_clust, :].any():
            from_clust = membship.sum(axis=1).argmax()
            choices = [ii for ii, ch in enumerate(membship[from_clust, :]) if ch]
            rindx = random_state.choice(choices)

            cl_attr_freq, membship, centroids = move_point_cat(
                X[rindx], rindx, old_clust, from_clust, cl_attr_freq, membship, centroids
            )

    return centroids, moves
881985
protected void findClusters() {

		for (int i = 0; i < nodes.size(); i++) {
			SquareNode n = nodes.get(i);

			if( n.graph < 0 ) {
				n.graph = clusters.size();
				List<SquareNode> graph = clusters.grow();
				graph.add(n);
				addToCluster(n, graph);
			}
		}
	}
1179113
protected static Clustering cleanUpKMeans(Clustering kMeansResult, ArrayList<CFCluster> microclusters) {
		/* Convert k-means result to CFClusters */
		int k = kMeansResult.size();
		CFCluster[] converted = new CFCluster[k];

		for (CFCluster mc : microclusters) {
		    // Find closest kMeans cluster
		    double minDistance = Double.MAX_VALUE;
		    int closestCluster = 0;
		    for (int i = 0; i < k; i++) {
		    	double distance = distance(kMeansResult.get(i).getCenter(), mc.getCenter());
				if (distance < minDistance) {
				    closestCluster = i;
				    minDistance = distance;
				}
		    }

		    // Add to cluster
		    if ( converted[closestCluster] == null ) {
		    	converted[closestCluster] = (CFCluster)mc.copy();
		    } else {
		    	converted[closestCluster].add(mc);
		    }
		}

		// Clean up
		int count = 0;
		for (int i = 0; i < converted.length; i++) {
		    if (converted[i] != null)
			count++;
		}

		CFCluster[] cleaned = new CFCluster[count];
		count = 0;
		for (int i = 0; i < converted.length; i++) {
		    if (converted[i] != null)
			cleaned[count++] = converted[i];
		}

		return new Clustering(cleaned);
	}
876812
def cluster(dset,min_distance,min_cluster_size,prefix=None):
    ''''''
    if prefix==None:
        prefix = nl.suffix(dset,'_clust%d' % min_cluster_size)
    return available_method('cluster')(dset,min_distance,min_cluster_size,prefix)
483763
def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
    
    pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
                         for grp_id in grp_ids})
    # Get temporal occurrence model
    # Number of occurrences for the cluster
    first = True
    for nocc in range(0, 50):
        # TODO fix this once the occurrence rate will be used just as
        # an object attribute
        ocr = tom.occurrence_rate
        prob_n_occ = tom.get_probability_n_occurrences(ocr, nocc)
        if first:
            pmapclu = prob_n_occ * (~pmap)**nocc
            first = False
        else:
            pmapclu += prob_n_occ * (~pmap)**nocc
    pmap = ~pmapclu
    return pmap
1092413
private Clustering<SubspaceModel> computeClusters(Relation<V> database, DiSHClusterOrder clusterOrder) {
    final int dimensionality = RelationUtil.dimensionality(database);

    // extract clusters
    Object2ObjectOpenCustomHashMap<long[], List<ArrayModifiableDBIDs>> clustersMap = extractClusters(database, clusterOrder);
    logClusterSizes("Step 1: extract clusters", dimensionality, clustersMap);

    // check if there are clusters < minpts
    checkClusters(database, clustersMap);
    logClusterSizes("Step 2: check clusters", dimensionality, clustersMap);

    // sort the clusters
    List<Cluster<SubspaceModel>> clusters = sortClusters(database, clustersMap);
    if(LOG.isVerbose()) {
      StringBuilder msg = new StringBuilder("Step 3: sort clusters");
      for(Cluster<SubspaceModel> c : clusters) {
        msg.append('\n').append(BitsUtil.toStringLow(c.getModel().getSubspace().getDimensions(), dimensionality)).append(" ids ").append(c.size());
      }
      LOG.verbose(msg.toString());
    }

    // build the hierarchy
    Clustering<SubspaceModel> clustering = new Clustering<>("DiSH clustering", "dish-clustering");
    buildHierarchy(database, clustering, clusters, dimensionality);
    if(LOG.isVerbose()) {
      StringBuilder msg = new StringBuilder("Step 4: build hierarchy");
      for(Cluster<SubspaceModel> c : clusters) {
        msg.append('\n').append(BitsUtil.toStringLow(c.getModel().getSubspace().getDimensions(), dimensionality)).append(" ids ").append(c.size());
        for(It<Cluster<SubspaceModel>> iter = clustering.getClusterHierarchy().iterParents(c); iter.valid(); iter.advance()) {
          msg.append("\n   parent ").append(iter.get());
        }
        for(It<Cluster<SubspaceModel>> iter = clustering.getClusterHierarchy().iterChildren(c); iter.valid(); iter.advance()) {
          msg.append("\n   child ").append(iter.get());
        }
      }
      LOG.verbose(msg.toString());
    }

    // build result
    for(Cluster<SubspaceModel> c : clusters) {
      if(clustering.getClusterHierarchy().numParents(c) == 0) {
        clustering.addToplevelCluster(c);
      }
    }
    return clustering;
  }
221784
def fuzzy_c_means(points, num_centers, m=2., tol=1e-4, max_iter=100,
                  verbose=False):
  '''
  '''
  num_points = points.shape[0]
  if num_centers >= num_points:
    return np.arange(num_points)
  # randomly initialize cluster assignments matrix
  assn = np.random.random((points.shape[0], num_centers))
  # iterate assignments until they converge
  for i in range(max_iter):
    # compute centers
    w = assn ** m
    w /= w.sum(axis=0)
    centers = w.T.dot(points)
    # calculate new assignments
    d = pairwise_distances(points, centers)
    d **= 2. / (m - 1)
    np.maximum(d, 1e-10, out=d)
    new_assn = 1. / np.einsum('ik,ij->ik', d, 1./d)
    # check for convergence
    change = np.linalg.norm(new_assn - assn)
    if verbose:
      print('At iteration %d: change = %g' % (i+1, change))
    if change < tol:
      break
    assn = new_assn
  else:
    warnings.warn("fuzzy_c_means didn't converge in %d iterations" % max_iter)
  # find points closest to the selected cluster centers
  return d.argmin(axis=0)
1081307
private Clustering<OPTICSModel> extractClusters(ClusterOrder clusterOrderResult, Relation<?> relation, double ixi, int minpts) {
    ArrayDBIDs clusterOrder = clusterOrderResult.ids;
    DoubleDataStore reach = clusterOrderResult.reachability;

    DBIDArrayIter tmp = clusterOrder.iter();
    DBIDVar tmp2 = DBIDUtil.newVar();
    double mib = 0.0;
    List<SteepArea> salist = keepsteep ? new ArrayList<SteepArea>() : null;
    List<SteepDownArea> sdaset = new ArrayList<>();
    final Clustering<OPTICSModel> clustering = new Clustering<>("OPTICS Xi-Clusters", "optics");
    HashSet<Cluster<OPTICSModel>> curclusters = new HashSet<>();
    HashSetModifiableDBIDs unclaimedids = DBIDUtil.newHashSet(relation.getDBIDs());

    FiniteProgress scanprog = LOG.isVerbose() ? new FiniteProgress("OPTICS Xi cluster extraction", clusterOrder.size(), LOG) : null;
    for(SteepScanPosition scan = new SteepScanPosition(clusterOrderResult); scan.hasNext();) {
      if(scanprog != null) {
        scanprog.setProcessed(scan.index, LOG);
      }
      // Update maximum-inbetween
      mib = MathUtil.max(mib, scan.getReachability());
      // The last point cannot be the start of a steep area.
      if(!scan.next.valid()) {
        break;
      }
      // Xi-steep down area
      if(scan.steepDown(ixi)) {
        // Update mib values with current mib and filter
        updateFilterSDASet(mib, sdaset, ixi);
        final double startval = scan.getReachability();
        mib = 0.;
        int startsteep = scan.index, endsteep = scan.index;
        for(scan.next(); scan.hasNext(); scan.next()) {
          // still steep - continue.
          if(scan.steepDown(ixi)) {
            endsteep = scan.index;
            continue;
          }
          // Not going downward at all - stop here.
          // Always stop looking after minpts "flat" steps.
          if(!scan.steepDown(1.0) || scan.index - endsteep > minpts) {
            break;
          }
        }
        final SteepDownArea sda = new SteepDownArea(startsteep, endsteep, startval, 0);
        if(LOG.isDebuggingFinest()) {
          LOG.debugFinest("New steep down area: " + sda.toString());
        }
        sdaset.add(sda);
        if(salist != null) {
          salist.add(sda);
        }
        continue;
      }
      // Xi-steep up area
      if(scan.steepUp(ixi)) {
        // Update mib values with current mib and filter
        updateFilterSDASet(mib, sdaset, ixi);
        final SteepUpArea sua;
        // Compute steep-up area
        {
          int startsteep = scan.index, endsteep = scan.index;
          mib = scan.getReachability();
          double esuccr = scan.getNextReachability();
          // Find end of steep-up-area, eventually updating mib again
          while(!Double.isInfinite(esuccr) && scan.hasNext()) {
            scan.next();
            // still steep - continue.
            if(scan.steepUp(ixi)) {
              endsteep = scan.index;
              mib = scan.getReachability();
              esuccr = scan.getNextReachability();
              continue;
            }
            // Not going upward - stop here.
            // Stop looking after minpts non-up steps.
            if(!scan.steepUp(1.0) || scan.index - endsteep > minpts) {
              break;
            }
          }
          if(Double.isInfinite(esuccr)) {
            scan.next();
          }
          sua = new SteepUpArea(startsteep, endsteep, esuccr);
          if(LOG.isDebuggingFinest()) {
            LOG.debugFinest("New steep up area: " + sua.toString());
          }
          if(salist != null) {
            salist.add(sua);
          }
        }
        // Validate and computer clusters
        // LOG.debug("SDA size:"+sdaset.size()+" "+sdaset);
        ListIterator<SteepDownArea> sdaiter = sdaset.listIterator(sdaset.size());
        // Iterate backwards for correct hierarchy generation.
        while(sdaiter.hasPrevious()) {
          SteepDownArea sda = sdaiter.previous();
          if(LOG.isDebuggingFinest()) {
            LOG.debugFinest("Comparing: eU=" + mib + " SDA: " + sda.toString());
          }
          // Condition 3b: end-of-steep-up > maximum-in-between lower
          if(mib * ixi < sda.getMib()) {
            if(LOG.isDebuggingFinest()) {
              LOG.debugFinest("mib * ixi = " + mib * ixi + " >= sda.getMib() = " + sda.getMib());
            }
            continue;
          }
          // By default, clusters cover both the steep up and steep down area
          int cstart = sda.getStartIndex(),
              cend = MathUtil.min(sua.getEndIndex(), clusterOrder.size() - 1);
          // However, we sometimes have to adjust this (Condition 4):
          {
            // Case b)
            if(sda.getMaximum() * ixi >= sua.getMaximum()) {
              while(cstart < cend && //
                  reach.doubleValue(tmp.seek(cstart + 1)) > sua.getMaximum()) {
                cstart++;
              }
            }
            // Case c)
            else if(sua.getMaximum() * ixi >= sda.getMaximum()) {
              while(cend > cstart && //
                  reach.doubleValue(tmp.seek(cend - 1)) > sda.getMaximum()) {
                cend--;
              }
            }
            // Case a) is the default
          }
          // MST-based filtering technique of Schubert:
          // ensure that the predecessor is in the current cluster.
          // This filter removes common artifacts from the Xi method
          if(!nocorrect) {
            double startval = clusterOrderResult.reachability.doubleValue(tmp.seek(cstart));
            simplify: while(cend > cstart) {
              tmp.seek(cend);
              // If the reachability is less than the first points', then there
              // must be some point inbetween that "reached" the current point.
              if(clusterOrderResult.reachability.doubleValue(tmp) < startval) {
                break simplify;
              }
              clusterOrderResult.predecessor.assignVar(tmp, tmp2);
              // "Slow" search for predecessor:
              for(int i = cstart; i < cend; i++) {
                if(DBIDUtil.equal(tmp2, tmp.seek(i))) {
                  break simplify;
                }
              }
              // Not found, prune the last point
              if(LOG.isDebuggingFinest()) {
                LOG.debugFinest("Pruned one point by predecessor rule.");
              }
              --cend;
            }
          }
          // Condition 3a: obey minpts
          if(cend - cstart + 1 < minpts) {
            if(LOG.isDebuggingFinest()) {
              LOG.debugFinest("MinPts not satisfied.");
            }
            continue;
          }
          // Build the cluster
          ModifiableDBIDs dbids = DBIDUtil.newArray();
          for(int idx = cstart; idx <= cend; idx++) {
            tmp.seek(idx);
            // Collect only unclaimed IDs.
            if(unclaimedids.remove(tmp)) {
              dbids.add(tmp);
            }
          }
          if(LOG.isDebuggingFine()) {
            LOG.debugFine("Found cluster with " + dbids.size() + " new objects, length " + (cend - cstart + 1));
          }
          OPTICSModel model = new OPTICSModel(cstart, cend);
          Cluster<OPTICSModel> cluster = new Cluster<>("Cluster_" + cstart + "_" + cend, dbids, model);
          // Build the hierarchy
          for(Iterator<Cluster<OPTICSModel>> iter = curclusters.iterator(); iter.hasNext();) {
            Cluster<OPTICSModel> clus = iter.next();
            OPTICSModel omodel = clus.getModel();
            if(model.getStartIndex() <= omodel.getStartIndex() && omodel.getEndIndex() <= model.getEndIndex()) {
              clustering.addChildCluster(cluster, clus);
              iter.remove(); // Not a top-level cluster
            }
          }
          curclusters.add(cluster);
        }
        continue;
      }
      // Flat - advance anyway.
      scan.next();
    }
    if(scanprog != null) {
      scanprog.setProcessed(clusterOrder.size(), LOG);
    }
    if(!unclaimedids.isEmpty()) {
      boolean noise = reach.doubleValue(tmp.seek(clusterOrder.size() - 1)) >= Double.POSITIVE_INFINITY;
      Cluster<OPTICSModel> allcluster = new Cluster<>(noise ? "Noise" : "Cluster", unclaimedids, noise, new OPTICSModel(0, clusterOrder.size() - 1));
      for(Cluster<OPTICSModel> cluster : curclusters) {
        clustering.addChildCluster(allcluster, cluster);
      }
      clustering.addToplevelCluster(allcluster);
    }
    else {
      for(Cluster<OPTICSModel> cluster : curclusters) {
        clustering.addToplevelCluster(cluster);
      }
    }
    clustering.addChildResult(clusterOrderResult);
    if(salist != null) {
      clusterOrderResult.addChildResult(new SteepAreaResult(salist));
    }
    return clustering;
  }
14594
def k_means(
    X,
    n_clusters,
    init="k-means||",
    precompute_distances="auto",
    n_init=1,
    max_iter=300,
    verbose=False,
    tol=1e-4,
    random_state=None,
    copy_x=True,
    n_jobs=-1,
    algorithm="full",
    return_n_iter=False,
    oversampling_factor=2,
    init_max_iter=None,
):
    
    labels, inertia, centers, n_iter = _kmeans_single_lloyd(
        X,
        n_clusters,
        max_iter=max_iter,
        init=init,
        verbose=verbose,
        tol=tol,
        random_state=random_state,
        oversampling_factor=oversampling_factor,
        init_max_iter=init_max_iter,
    )
    if return_n_iter:
        return labels, centers, inertia, n_iter
    else:
        return labels, centers, inertia
400051
def cluster_number(self, data, maxgap): 
        '''

        '''

        data.sort()
        groups = [[data[0]]]
        for x in data[1:]:
            if abs(x - groups[-1][-1]) <= maxgap:
                groups[-1].append(x)
            else:
                groups.append([x])
        return groups
776057
private void buildHierarchy(Relation<V> database, Clustering<SubspaceModel> clustering, List<Cluster<SubspaceModel>> clusters, int dimensionality) {
    StringBuilder msg = LOG.isDebugging() ? new StringBuilder() : null;
    final int db_dim = RelationUtil.dimensionality(database);
    Hierarchy<Cluster<SubspaceModel>> hier = clustering.getClusterHierarchy();

    for(int i = 0; i < clusters.size() - 1; i++) {
      Cluster<SubspaceModel> c_i = clusters.get(i);
      final Subspace s_i = c_i.getModel().getSubspace();
      int subspaceDim_i = dimensionality - s_i.dimensionality();
      NumberVector ci_centroid = ProjectedCentroid.make(s_i.getDimensions(), database, c_i.getIDs());
      long[] pv1 = s_i.getDimensions();

      for(int j = i + 1; j < clusters.size(); j++) {
        Cluster<SubspaceModel> c_j = clusters.get(j);
        final Subspace s_j = c_j.getModel().getSubspace();
        int subspaceDim_j = dimensionality - s_j.dimensionality();

        if(subspaceDim_i < subspaceDim_j) {
          if(msg != null) {
            msg.append("\n l_i=").append(subspaceDim_i).append(" pv_i=[").append(BitsUtil.toStringLow(s_i.getDimensions(), db_dim)).append(']') //
                .append("\n l_j=").append(subspaceDim_j).append(" pv_j=[").append(BitsUtil.toStringLow(s_j.getDimensions(), db_dim)).append(']');
          }

          // noise level reached
          if(s_j.dimensionality() == 0) {
            // no parents exists -> parent is noise
            if(hier.numParents(c_i) == 0) {
              clustering.addChildCluster(c_j, c_i);
              if(msg != null) {
                msg.append("\n [").append(BitsUtil.toStringLow(s_j.getDimensions(), db_dim)) //
                    .append("] is parent of [").append(BitsUtil.toStringLow(s_i.getDimensions(), db_dim)).append(']');
              }
            }
          }
          else {
            NumberVector cj_centroid = ProjectedCentroid.make(c_j.getModel().getDimensions(), database, c_j.getIDs());
            long[] pv2 = s_j.getDimensions();
            long[] commonPreferenceVector = BitsUtil.andCMin(pv1, pv2);
            int subspaceDim = subspaceDimensionality(ci_centroid, cj_centroid, pv1, pv2, commonPreferenceVector);

            double d = weightedDistance(ci_centroid, cj_centroid, commonPreferenceVector);
            if(msg != null) {
              msg.append("\n dist = ").append(subspaceDim);
            }

            if(subspaceDim == subspaceDim_j) {
              if(msg != null) {
                msg.append("\n d = ").append(d);
              }
              if(d <= 2 * epsilon) {
                // no parent exists or c_j is not a parent of the already
                // existing parents
                if(hier.numParents(c_i) == 0 || !isParent(database, c_j, hier.iterParents(c_i), db_dim)) {
                  clustering.addChildCluster(c_j, c_i);
                  if(msg != null) {
                    msg.append("\n [").append(BitsUtil.toStringLow(s_j.getDimensions(), db_dim)) //
                        .append("] is parent of [") //
                        .append(BitsUtil.toStringLow(s_i.getDimensions(), db_dim)).append(']');
                  }
                }
              }
              else {
                throw new RuntimeException("Should never happen: d = " + d);
              }
            }
          }
        }
      }
    }
    if(msg != null) {
      LOG.debug(msg.toString());
    }
  }
1047984
public Clustering<?> run(final Database database, final Relation<DiscreteUncertainObject> relation) {
    if(relation.size() <= 0) {
      return new Clustering<>("Uk-Means Clustering", "ukmeans-clustering");
    }
    // Choose initial means randomly
    DBIDs sampleids = DBIDUtil.randomSample(relation.getDBIDs(), k, rnd);
    List<double[]> means = new ArrayList<>(k);
    for(DBIDIter iter = sampleids.iter(); iter.valid(); iter.advance()) {
      means.add(ArrayLikeUtil.toPrimitiveDoubleArray(relation.get(iter).getCenterOfMass()));
    }

    // Setup cluster assignment store
    List<ModifiableDBIDs> clusters = new ArrayList<>();
    for(int i = 0; i < k; i++) {
      clusters.add(DBIDUtil.newHashSet((int) (relation.size() * 2. / k)));
    }
    WritableIntegerDataStore assignment = DataStoreUtil.makeIntegerStorage(relation.getDBIDs(), DataStoreFactory.HINT_TEMP | DataStoreFactory.HINT_HOT, -1);
    double[] varsum = new double[k];

    IndefiniteProgress prog = LOG.isVerbose() ? new IndefiniteProgress("UK-Means iteration", LOG) : null;
    DoubleStatistic varstat = LOG.isStatistics() ? new DoubleStatistic(this.getClass().getName() + ".variance-sum") : null;
    int iteration = 0;
    for(; maxiter <= 0 || iteration < maxiter; iteration++) {
      LOG.incrementProcessed(prog);
      boolean changed = assignToNearestCluster(relation, means, clusters, assignment, varsum);
      logVarstat(varstat, varsum);
      // Stop if no cluster assignment changed.
      if(!changed) {
        break;
      }
      // Recompute means.
      means = means(clusters, means, relation);
    }
    LOG.setCompleted(prog);
    if(LOG.isStatistics()) {
      LOG.statistics(new LongStatistic(KEY + ".iterations", iteration));
    }

    // Wrap result
    Clustering<KMeansModel> result = new Clustering<>("Uk-Means Clustering", "ukmeans-clustering");
    for(int i = 0; i < clusters.size(); i++) {
      DBIDs ids = clusters.get(i);
      if(ids.isEmpty()) {
        continue;
      }
      result.addToplevelCluster(new Cluster<>(ids, new KMeansModel(means.get(i), varsum[i])));
    }
    return result;
  }
1199134
public Clustering addToClustering(Clustering clustering) {
		if (center != null && getClusteringFeature() != null) {
			clustering.add(getClusteringFeature().toCluster());
		}
		for (ClusteringTreeNode child : children) {
			child.addToClustering(clustering);
		}
		return clustering;
	}
861117
def _kmeans(y, k=5):
    

    y = y * 1.  # KMEANS needs float or double dtype
    centroids = KMEANS(y, k)[0]
    centroids.sort()
    try:
        class_ids = np.abs(y - centroids).argmin(axis=1)
    except:
        class_ids = np.abs(y[:, np.newaxis] - centroids).argmin(axis=1)

    uc = np.unique(class_ids)
    cuts = np.array([y[class_ids == c].max() for c in uc])
    y_cent = np.zeros_like(y)
    for c in uc:
        y_cent[class_ids == c] = centroids[c]
    diffs = y - y_cent
    diffs *= diffs

    return class_ids, cuts, diffs.sum(), centroids
1206479
def _run(self):
        
#        print("Doing APM Clustering...")
        # Start looping for maxIter times
        n_macrostates = 1  # initialized as 1 because no macrostate exist in loop 0
        metaQ = -1.0
        prevQ = -1.0
        global_maxQ = -1.0
        local_maxQ = -1.0

        for iter in range(self.max_iter):
            self.__max_state = -1
            self.__micro_stack = []
            for k in range(n_macrostates):
                self._do_split(micro_state=k, sub_clus=self.sub_clus)
                self._do_time_clustering(macro_state=k)

            # do Lumping
            n_micro_states = np.amax(self.__temp_labels_) + 1
            if n_micro_states > self.n_macrostates:
#                print("PCCA Lumping...", n_micro_states, "microstates")
                self.__temp_MacroAssignments_ = self._do_lumping(
                    n_macrostates=n_macrostates)
                #self.__temp_labels_ = [copy.copy(element) for element in self.__temp_MacroAssignments_]

                #Calculate Metastabilty
                prevQ = metaQ
                metaQ = self.__temp_transmat_.diagonal().sum()
                metaQ /= len(self.__temp_transmat_)
            else:
                self.__temp_MacroAssignments_ = [
                    copy.copy(element) for element in self.__temp_labels_
                ]

            # Optimization / Monte-Carlo
            acceptedMove = False
            MCacc = np.exp(metaQ * metaQ - prevQ * prevQ)

            if MCacc > 1.0:
                MCacc = 1.0
            optLim = 0.95

            if MCacc > optLim:
                acceptedMove = True

            if acceptedMove:
                local_maxQ = metaQ
                if metaQ > global_maxQ:
                    global_maxQ = metaQ
                    self.MacroAssignments_ = [
                        copy.copy(element)
                        for element in self.__temp_MacroAssignments_
                    ]
                    self.labels_ = [copy.copy(element)
                                    for element in self.__temp_labels_]
                    self.transmat_ = self.__temp_transmat_

#            print("Loop:", iter, "AcceptedMove?", acceptedMove, "metaQ:",
#                  metaQ, "prevQ:", prevQ, "global_maxQ:", global_maxQ,
#                  "local_maxQ:", local_maxQ, "macroCount:", n_macrostates)
            #set n_macrostates
            n_macrostates = self.n_macrostates
            self.__temp_labels_ = [copy.copy(element)
                                   for element in self.__temp_MacroAssignments_
                                   ]
1264326
def _centroids(n_clusters: int, points: List[List[float]]) -> List[List[float]]:
    

    k_means = KMeans(n_clusters=n_clusters)
    k_means.fit(points)

    closest, _ = pairwise_distances_argmin_min(k_means.cluster_centers_, points)

    return list(map(list, np.array(points)[closest.tolist()]))
592952
def _regroup(self):
        
        # clean up old maps
        for j in range(self.nout):
            self.inv_map[j] = []

        # find smallest divergence between input component i
        # and output component j of the cluster mixture density
        for i in range(self.nin):
            self.min_kl[i] = np.inf
            j_min = None
            for j in range(self.nout):
                kl = kullback_leibler(self.f.components[i], self.g.components[j])
                if kl < self.min_kl[i]:
                    self.min_kl[i] = kl
                    j_min = j
            assert j_min is not None
            self.inv_map[j_min].append(i)