Return diversity value for solution compared to given population.

    Metric is sum of distance between solution and each solution in population,
    normalized to [0.0, 1.0].
973812
def _diversity_metric(solution, population):
    
    # Edge case for empty population
    # If there are no other solutions, the given solution has maximum diversity
    if population == []:
        return 1.0

    return (
        sum([_manhattan_distance(solution, other) for other in population])
        # Normalize (assuming each value in solution is in range [0.0, 1.0])
        # NOTE: len(solution) is maximum manhattan distance
        / (len(population) * len(solution)))
624875
def top_n(max, metric_method)

      stat_totals = self.values.group_by(&metric_method).map do |metric, stats|
        [metric, stats.reduce(0) { |sum, stat| sum + stat.memsize }, stats.size]
      end

      stats_by_memsize = stat_totals.sort_by! { |metric, memsize, _count| [-memsize, metric] }.take(max).
          map! { |metric, memsize, _count| { data: metric, count: memsize } }
      stats_by_count = stat_totals.sort_by! { |metric, _memsize, count| [-count, metric] }.take(max).
          map! { |metric, _memsize, count| { data: metric, count: count } }

      [stats_by_memsize, stats_by_count]

    end
808907
def meanMutualInformation(sp, activeColumnsCurrentEpoch, columnsUnderInvestigation = []):
  
  if len(columnsUnderInvestigation) == 0:
    columns = range(np.prod(sp.getColumnDimensions()))
  else:
    columns = columnsUnderInvestigation
  numCols = len(columns)
  sumMutualInfo = 0
  normalizingConst = numCols*(numCols - 1)/2
  for i in range(numCols):
    for j in range(i+1, numCols):
      sumMutualInfo += mutualInformation(sp, activeColumnsCurrentEpoch, columns[i], columns[j])

  return sumMutualInfo/normalizingConst
83172
def _pdf_value(pdf, population, fitnesses, fitness_threshold):
    
    # Add the chance of obtaining a solution from the pdf
    # when the fitness for that solution exceeds a threshold
    value = 0.0
    for solution, fitness in zip(population, fitnesses):
        if fitness >= fitness_threshold:
            # 1.0 + chance to avoid issues with chance of 0
            value += math.log(1.0 + _chance(solution, pdf))

    # The official equation states that value is now divided by len(fitnesses)
    # however, this is unnecessary when we are only obtaining the best pdf,
    # because every solution is of the same size
    return value
66551
public static int RankCompare(Solution solution1, Solution solution2)
   {
      int rank1 = solution1.getRank();
      int rank2 = solution2.getRank();

      if (rank1 < rank2)
      {
         return -1;
      }
      else if (rank1 > rank2)
      {
         return 1;
      }
      else
      {
         return 0;
      }
   }
410707
def selection(x_bounds,
              x_types,
              clusteringmodel_gmm_good,
              clusteringmodel_gmm_bad,
              minimize_starting_points,
              minimize_constraints_fun=None):
    '''
    
    '''
    results = lib_acquisition_function.next_hyperparameter_lowest_mu(\
                    _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad],\
                    x_bounds, x_types, minimize_starting_points, \
                    minimize_constraints_fun=minimize_constraints_fun)

    return results
1374135
def _known_populations(row, pops):
    
    cutoff = 0.01
    out = set([])
    for pop, base in [("esp", "af_esp_all"), ("1000g", "af_1kg_all"),
                      ("exac", "af_exac_all"), ("anypop", "max_aaf_all")]:
        for key in [x for x in pops if x.startswith(base)]:
            val = row[key]
            if val and val > cutoff:
                out.add(pop)
    return sorted(list(out))
810744
private List<Double> knnDistances(S solution, L solutionList) {
    List<Double> listOfDistances = new ArrayList<>() ;
    for (int i = 0 ; i< solutionList.size(); i++) {
      double distanceBetweenSolutions = distance.getDistance(solution, solutionList.get(i)) ;
      if (distanceBetweenSolutions != 0) {
        listOfDistances.add(distanceBetweenSolutions) ;
      }
    }

    return listOfDistances ;
  }
637463
def feasible_ratio(self, solutions):
        
        raise NotImplementedError('Solution class disappeared')
        count = np.zeros(len(solutions[0]))
        for x in solutions:
            count += x.unrepaired == x
        return count / float(len(solutions))
483181
public static int CrowdingDistanceCompare(Solution solution1, Solution solution2)
   {
      double crowding1 = solution1.getCrowdingDistance();
      double crowding2 = solution2.getCrowdingDistance();

      if (crowding1 > crowding2)
      {
         return -1;
      }
      else if (crowding1 < crowding2)
      {
         return 1;
      }
      else
      {
         return 0;
      }
   }
608900
@Override
  public void computeDensityEstimator(List<S> solutionList) {
    int size = solutionList.size();

    if (size == 0) {
      return;
    }

    if (size == 1) {
      solutionList.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      return;
    }

    if (size == 2) {
      solutionList.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      solutionList.get(1).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);

      return;
    }

    // Use a new SolutionSet to avoid altering the original solutionSet
    List<S> front = new ArrayList<>(size);
    for (S solution : solutionList) {
      front.add(solution);
    }

    for (int i = 0; i < size; i++) {
      front.get(i).setAttribute(getAttributeIdentifier(), 0.0);
    }

    double objetiveMaxn;
    double objetiveMinn;
    double distance;

    int numberOfObjectives = solutionList.get(0).getNumberOfObjectives() ;

    for (int i = 0; i < numberOfObjectives; i++) {
      // Sort the population by Obj n
      Collections.sort(front, new ObjectiveComparator<S>(i)) ;
      objetiveMinn = front.get(0).getObjective(i);
      objetiveMaxn = front.get(front.size() - 1).getObjective(i);

      // Set de crowding distance
      front.get(0).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);
      front.get(size - 1).setAttribute(getAttributeIdentifier(), Double.POSITIVE_INFINITY);

      for (int j = 1; j < size - 1; j++) {
        distance = front.get(j + 1).getObjective(i) - front.get(j - 1).getObjective(i);
        distance = distance / (objetiveMaxn - objetiveMinn);
        distance += (double)front.get(j).getAttribute(getAttributeIdentifier());
        front.get(j).setAttribute(getAttributeIdentifier(), distance);
      }
    }
  }
765159
def distance(cluster, method = 0)
      d = 0
      norm = 0

      cluster.objects.each do |elem1|
        objects.each do |elem2|
          if method == 1
            d += elem1[1] * elem2[1] * (elem1[0] - elem2[0]).abs
            norm += elem1[1] * elem2[1]
          else
            d += (elem1[0] - elem2[0]).abs
            norm = cluster.objects.length * objects.length
          end
        end
      end

      # group average distance
      d /= (norm + 0.0)
    end
62694
def similarity(state_a, state_b):
        
        count_a = Counter(state_a.history.bbl_addrs)
        count_b = Counter(state_b.history.bbl_addrs)
        normal_distance = sum((count_a.get(addr, 0) - count_b.get(addr, 0)) ** 2
                              for addr in set(list(count_a.keys()) + list(count_b.keys()))) ** 0.5
        return 1.0 / (1 + normal_distance)
1164140
def _solve_conflict(list_c, s2p, n_cluster):
    
    logger.debug("_solve_conflict: count once")
    if parameters.decision_cluster == "bayes":
        return decide_by_bayes(list_c, s2p)
    loci_similarity = _calculate_similarity(list_c)
    loci_similarity = sorted(loci_similarity.iteritems(), key=operator.itemgetter(1), reverse=True)
    common = sum([score for p, score in loci_similarity])
    while common > 0:
        n_cluster += 1
        logger.debug("_solve_conflict: ma %s" % loci_similarity)
        pairs = loci_similarity[0][0]
        score = loci_similarity[0][1]
        logger.debug("_solve_conflict: common %s, new %s" % (score, n_cluster))
        if parameters.decision_cluster.startswith("most-voted"):
            list_c = _split_cluster_by_most_vote(list_c, pairs)
        else:
            list_c = _split_cluster(list_c, pairs, n_cluster)
        list_c = {k: v for k, v in list_c.iteritems() if len(v.loci2seq) > 0}
        loci_similarity = _calculate_similarity(list_c)
        loci_similarity = sorted(loci_similarity.iteritems(), key=operator.itemgetter(1), reverse=True)
        #logger.note("%s %s" % (pairs, loci_similarity[0][1]))
        common = sum([score for p, score in loci_similarity])
        logger.debug("_solve_conflict: solved clusters %s" % len(list_c.keys()))
    return list_c
1027951
def separation(X,y,samples=False):
    
    # pdb.set_trace()
    num_classes = len(np.unique(y))
    total_dist = (X.max()-X.min())**2
    if samples:
        # return intra-class distance for each sample
        separation = np.zeros(y.shape)
        for label in np.unique(y):
            for outsider in np.unique(y[y!=label]):
                separation[y==label] += (X[y==label] - np.mean(X[y==outsider])) ** 2

        #normalize between 0 and 1
        print('separation:',separation)
        print('num_classes:',num_classes)
        print('total_dist:',total_dist)
        separation = separation#/separation.max()

        print('separation after normalization:',separation)

    else:
        # return aggregate score
        separation = 0
        for i,label in enumerate(np.unique(y)):
            for outsider in np.unique(y[y!=label]):
                separation += np.sum((X[y==label] - np.mean(X[y==outsider])) ** 2)/len(y[y==label])
        separation = separation/len(np.unique(y))

    return separation
376774
def get_fitness(self, solution):
        """"""
        return self._fitness_function(solution, *self._fitness_args,
                                      **self._fitness_kwargs)
937338
def _calculate_gap(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, n_clusters: int) -> Tuple[float, int]:
        
        # Holder for reference dispersion results
        ref_dispersions = np.zeros(n_refs)  # type: np.ndarray

        # For n_references, generate random sample and perform kmeans getting resulting dispersion of each loop
        for i in range(n_refs):

            # Create new random reference set
            random_data = np.random.random_sample(size=X.shape)  # type: np.ndarray

            # Fit to it, getting the centroids and labels, and add to accumulated reference dispersions array.
            centroids, labels = kmeans2(data=random_data,
                                        k=n_clusters,
                                        iter=10,
                                        minit='points')  # type: Tuple[np.ndarray, np.ndarray]
            dispersion = self._calculate_dispersion(X=random_data, labels=labels, centroids=centroids)  # type: float
            ref_dispersions[i] = dispersion

        # Fit cluster to original data and create dispersion calc.
        centroids, labels = kmeans2(data=X, k=n_clusters, iter=10, minit='points')
        dispersion = self._calculate_dispersion(X=X, labels=labels, centroids=centroids)

        # Calculate gap statistic
        gap_value = np.mean(np.log(ref_dispersions)) - np.log(dispersion)

        return gap_value, int(n_clusters)