Calculate the local reachability density of a sample given its
distances to its k nearest neighbors.

@param array $distances
@throws \RuntimeException
@return float
968873
protected function localReachabilityDensity(array $distances) : float
    {
        if (empty($this->kdistances)) {
            throw new RuntimeException('K distances have not been computed,'
                . ' must train estimator first.');
        }

        $kdistances = array_intersect_key($this->kdistances, $distances);

        $rds = array_map('max', $distances, $kdistances);

        return 1. / (Stats::mean($rds) ?: EPSILON);
    }
738226
private PolynomialApproximation approximateKnnDistances(double[] knnDistances) {
    StringBuilder msg = new StringBuilder();

    // count the zero distances (necessary of log-log space is used)
    int k_0 = 0;
    if(settings.log) {
      for(int i = 0; i < settings.kmax; i++) {
        double dist = knnDistances[i];
        if(dist == 0) {
          k_0++;
        }
        else {
          break;
        }
      }
    }

    double[] x = new double[settings.kmax - k_0];
    double[] y = new double[settings.kmax - k_0];

    for(int k = 0; k < settings.kmax - k_0; k++) {
      if(settings.log) {
        x[k] = FastMath.log(k + k_0);
        y[k] = FastMath.log(knnDistances[k + k_0]);
      }
      else {
        x[k] = k + k_0;
        y[k] = knnDistances[k + k_0];
      }
    }

    PolynomialRegression regression = new PolynomialRegression(y, x, settings.p);
    PolynomialApproximation approximation = new PolynomialApproximation(regression.getEstimatedCoefficients());

    if(LOG.isDebugging()) {
      msg.append("approximation ").append(approximation);
      LOG.debugFine(msg.toString());
    }
    return approximation;

  }
988982
public function count(array $locales = null,  array $filters = null)
    {
        $this->loadCustomHydrator();

        $builder = $this->createQueryBuilder('tu')
            ->select('COUNT(DISTINCT tu.id) AS number');

        $this->addTransUnitFilters($builder, $filters);
        $this->addTranslationFilter($builder, $locales, $filters);

        return (int) $builder->getQuery()->getResult(Query::HYDRATE_SINGLE_SCALAR);
    }
1343563
private function calculate()
    {
        if (count($this->points) < 2) {
            throw new \RuntimeException('There must be two or more points (co-ordinates) before a calculation can be performed.');
        }
        $total = 0;
        foreach ($this->points as $point) {
            if (isset($previous)) {
                $total += $this->distanceBetweenPoints($previous, $point);
            }
            $previous = $point;
        }
        return $total;
    }
156056
private function getSamplesInRegion($localSample, $samples)
    {
        $region = [];

        foreach ($samples as $index => $sample) {
            if ($this->distanceMetric->distance($localSample, $sample) < $this->epsilon) {
                $region[$index] = $sample;
            }
        }

        return $region;
    }
141043
public function getCoverage() : float
    {
        $processor = new Processor();
        $result    = $processor->run($this->phpUnit . ' --coverage-text|grep Classes|cut -d " " -f 4|cut -d "%" -f 1');
        $output    = $result->getStdOut();
        if (!$result->isSuccessful() || empty($output)) {
            throw new RuntimeException('Error while executing PHPUnit: ' . $result->getStdErr());
        }
        return (float) $output;
    }
250043
public function distance(array $a, array $b): float
    {
        if (count($a) !== count($b)) {
            throw InvalidArgumentException::arraySizeNotMatch();
        }

        $differences = [];
        $count = count($a);

        for ($i = 0; $i < $count; ++$i) {
            $differences[] = abs($a[$i] - $b[$i]);
        }

        return max($differences);
    }
1180989
private function findAvailableLocalization(array $availableLocales, array $localizations)
    {
        foreach ($localizations as $localization) {
            if (in_array($localization->getLocale(), $availableLocales)) {
                return $localization;
            }

            $children = $localization->getChildren();

            if ($children) {
                $result = $this->findAvailableLocalization($availableLocales, $children);

                if (null !== $result) {
                    return $result;
                }
            }
        }

        return;
    }
435291
public function selectConnection(array $connections)
    {
        $weighted = [];

        foreach ($connections as $connection) {
            foreach (range(0, $connection['weight']) as $i) {
                $weighted[] = $connection;
            }
        }

        $index = mt_rand(0, count($weighted) - 1);

        return $weighted[$index];
    }
291264
protected function getDistancePairs(array $sample)
    {
        $kernel = $this->getKernel();

        $pairs = [];
        foreach ($this->data as $row) {
            $pairs[] = $kernel($row, $sample);
        }

        return $pairs;
    }
294335
public function withADistanceOfAtLeast(int $distance): self
    {
        if ($this->elements->size() < 3) {
            throw new LogicException;
        }

        $path = clone $this;
        $path->elements = $this
            ->elements
            ->dropEnd(2)
            ->add(
                $this->elements->dropEnd(1)->last()->withADistanceOfAtLeast($distance)
            )
            ->add($this->elements->last());

        return $path;
    }
922933
private function computeLastCallOfAnyFrom(array $methods): int
    {
        $calls = array_filter($this->callerTokens, function (array $token) use ($methods) {
            return in_array($token['token']['content'], $methods, true);
        });
        if (count($calls) > 0) {
            return (int) array_search(end($calls), $this->callerTokens, true);
        }

        return -2;
    }
591337
public function predictProbability(array $samples)
    {
        if (!$this->probabilityEstimates) {
            throw new InvalidOperationException('Model does not support probabiliy estimates');
        }

        $predictions = $this->runSvmPredict($samples, true);

        if (in_array($this->type, [Type::C_SVC, Type::NU_SVC], true)) {
            $predictions = DataTransformer::probabilities($predictions, $this->targets);
        } else {
            $predictions = explode(PHP_EOL, trim($predictions));
        }

        if (!is_array($samples[0])) {
            return $predictions[0];
        }

        return $predictions;
    }
717803
public static function validate_distance( $distance ) {
    $valid = filter_var( $distance, FILTER_VALIDATE_INT,
        array( 'options' => array(
            'min_range' => 1,
            'max_range' => PHP_INT_MAX
        ))
        );

    return false !== $valid ? true : false;
  }
1162099
public function score(array $predictions, array $labels) : float
    {
        if (empty($predictions)) {
            return 0.;
        }

        if (count($predictions) !== count($labels)) {
            throw new InvalidArgumentException('The number of labels'
                . ' must equal the number of predictions.');
        }

        $classes = array_unique(array_merge($predictions, $labels));

        $truePos = $trueNeg = $falsePos = $falseNeg = array_fill_keys($classes, 0);

        foreach ($predictions as $i => $prediction) {
            $label = $labels[$i];

            if ($prediction === $label) {
                $truePos[$prediction]++;

                foreach ($classes as $class) {
                    if ($class !== $prediction) {
                        $trueNeg[$class]++;
                    }
                }
            } else {
                $falsePos[$prediction]++;
                $falseNeg[$label]++;
            }
        }

        return Stats::mean(
            array_map([$this, 'mcc'], $truePos, $trueNeg, $falsePos, $falseNeg)
        );
    }
272728
public static function pointDMS(array $bounds = null)
    {
        list($lat, $lng) = static::point($bounds);

        return sprintf('%s %s', self::floatToDMS($lat), self::floatToDMS($lng));
    }
1219939
protected function highAffinities(Matrix $distances) : Matrix
    {
        $zeros = array_fill(0, count($distances), 0);

        $p = [];

        foreach ($distances as $i => $row) {
            $affinities = $zeros;
            $minBeta = -INF;
            $maxBeta = INF;
            $beta = 1.;

            for ($l = 0; $l < self::BINARY_PRECISION; $l++) {
                $affinities = [];
                $pSigma = 0.;

                foreach ($row as $j => $distance) {
                    if ($i !== $j) {
                        $affinity = exp(-$distance * $beta);
                    } else {
                        $affinity = 0.;
                    }

                    $affinities[] = $affinity;
                    $pSigma += $affinity;
                }

                if ($pSigma === 0.) {
                    $pSigma = EPSILON;
                }

                $distSigma = 0.;

                foreach ($affinities as $j => &$prob) {
                    $prob /= $pSigma;
                    $distSigma += $row[$j] * $prob;
                }

                $entropy = log($pSigma) + $beta * $distSigma;

                $diff = $entropy - $this->entropy;

                if (abs($diff) < self::SEARCH_TOLERANCE) {
                    break 1;
                }

                if ($diff > 0.) {
                    $minBeta = $beta;

                    if ($maxBeta === INF) {
                        $beta *= 2.;
                    } else {
                        $beta = ($beta + $maxBeta) / 2.;
                    }
                } else {
                    $maxBeta = $beta;

                    if ($minBeta === -INF) {
                        $beta /= 2.;
                    } else {
                        $beta = ($beta + $minBeta) / 2.;
                    }
                }
            }

            $p[] = $affinities;
        }

        $p = Matrix::quick($p);

        $pHat = $p->add($p->transpose());

        $sigma = $pHat->sum()
            ->clipLower(EPSILON);

        return $pHat->divide($sigma);
    }