Calculate the local outlier factor of a given sample.

@param array $sample
@throws \RuntimeException
@return float
421378
protected function localOutlierFactor(array $sample) : float
    {
        if (empty($this->lrds)) {
            throw new RuntimeException('Local reachability distances have'
                . ' not been computed, must train estimator first.');
        }

        $distances = $this->localRegion($sample);

        $lrd = $this->localReachabilityDensity($distances);

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

        $ratios = [];

        foreach ($lrds as $lHat) {
            $ratios[] = $lHat / $lrd;
        }

        return Stats::mean($ratios);
    }
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;
    }
540762
public function transform(array &$samples) : void
    {
        foreach ($samples as &$sample) {
            $vector = [];

            foreach ($sample as $feature) {
                for ($i = 1; $i <= $this->degree; $i++) {
                    $vector[] = $feature ** $i;
                }
            }

            $sample = $vector;
        }
    }
428881
public static function stdev(array $values, $sample = false)
    {
        $variance = self::variance($values, $sample);

        return \sqrt($variance);
    }
1085938
public function transform(array $sample): array
    {
        if (!$this->fit) {
            throw new InvalidOperationException('LDA has not been fitted with respect to original dataset, please run LDA::fit() first');
        }

        if (!is_array($sample[0])) {
            $sample = [$sample];
        }

        return $this->reduce($sample);
    }
257048
public function transform(array &$samples) : void
    {
        if ($this->selected === null) {
            throw new RuntimeException('Transformer has not been fitted.');
        }

        foreach ($samples as &$sample) {
            $sample = array_intersect_key($sample, $this->selected);
        }
    }
1222932
protected function calculate_sample($sampleid, \core_analytics\analysable $analysable, $starttime = false, $endtime = false) {

        $activitiesdueindicator = $this->retrieve('\core_course\analytics\indicator\activities_due', $sampleid);
        if ($activitiesdueindicator == \core_course\analytics\indicator\activities_due::get_max_value()) {
            return 1;
        }
        return 0;
    }
844921
protected function localRegion(array $sample) : array
    {
        $distances = [];

        foreach ($this->samples as $neighbor) {
            $distances[] = $this->kernel->compute($sample, $neighbor);
        }

        asort($distances);

        return array_slice($distances, 0, $this->k, true);
    }
940934
private function frequency(array $sample): int
    {
        return count(array_filter($this->samples, function ($entry) use ($sample) {
            return $this->subset($entry, $sample);
        }));
    }
274043
protected function localReachabilityDensity(array $indices, array $distances) : float
    {
        if (empty($this->kdistances)) {
            throw new RuntimeException('K distances have not been computed,'
                . ' must train estimator first.');
        }

        $kdistances = [];

        foreach ($indices as $index) {
            $kdistances[] = $this->kdistances[$index];
        }

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

        $mean = Stats::mean($rds);

        return 1. / ($mean ?: EPSILON);
    }
397909
public function range(array $sample, float $radius) : array
    {
        if ($radius <= 0.) {
            throw new InvalidArgumentException('Radius must be'
                . " greater than 0, $radius given.");
        }

        $samples = $labels = $distances = [];

        $stack = [$this->root];

        while ($stack) {
            $current = array_pop($stack);

            if (!$current instanceof BinaryNode) {
                continue 1;
            }

            if ($current instanceof Cluster) {
                foreach ($current->samples() as $i => $neighbor) {
                    $distance = $this->kernel->compute($sample, $neighbor);

                    if ($distance <= $radius) {
                        $samples[] = $neighbor;
                        $labels[] = $current->label($i);
                        $distances[] = $distance;
                    }
                }

                continue 1;
            }

            foreach ($current->children() as $child) {
                if ($child instanceof Ball) {
                    $distance = $this->kernel->compute($sample, $child->center());

                    if ($distance <= ($child->radius() + $radius)) {
                        $stack[] = $child;
                    }
                }
            }
        }

        return [$samples, $labels, $distances];
    }
1217596
public function rank(Dataset $dataset) : array
    {
        if (!$this->r or !$this->histograms) {
            throw new RuntimeException('The learner has not'
                . ' been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $z = Matrix::quick($dataset->samples())
            ->matmul($this->r)
            ->transpose();

        return $this->logLikelihood($z);
    }
1095219
public function guess() : float
    {
        if ($this->percentile === null or $this->mad === null) {
            throw new RuntimeException('Strategy has not been fitted.');
        }

        return $this->percentile
            + $this->blur
            * $this->gaussian()
            * $this->mad;
    }
724391
protected function predictProbability(array $sample, $label): float
    {
        $sample = $this->checkNormalizedSample($sample);
        $probability = $this->output($sample);

        if (array_search($label, $this->labels, true) > 0) {
            return $probability;
        }

        return 1 - $probability;
    }
1119211
protected function calculate_sample($sampleid, \core_analytics\analysable $analysable, $starttime = false, $endtime = false) {

        $noteachersindicator = $this->retrieve('\core_course\analytics\indicator\no_teacher', $sampleid);
        $nostudentsindicator = $this->retrieve('\core_course\analytics\indicator\no_student', $sampleid);
        if ($noteachersindicator == \core_course\analytics\indicator\no_teacher::get_min_value() ||
                $nostudentsindicator == \core_course\analytics\indicator\no_student::get_min_value()) {
            // No teachers or no students :(.
            return 1;
        }
        return 0;
    }
338376
public function predict(Dataset $dataset) : array
    {
        if (empty($this->samples) or empty($this->labels)) {
            throw new RuntimeException('Estimator has not been trained.');
        }

        DatasetIsCompatibleWithEstimator::check($dataset, $this);

        $predictions = [];

        foreach ($dataset as $sample) {
            [$labels, $distances] = $this->nearest($sample);

            if ($this->weighted) {
                $weights = [];

                foreach ($distances as $i => $distance) {
                    $weights[] = 1. / (1. + $distance);
                }

                $outcome = Stats::weightedMean($labels, $weights);
            } else {
                $outcome = Stats::mean($labels);
            }

            $predictions[] = $outcome;
        }

        return $predictions;
    }
371021
public function transform(array &$samples) : void
    {
        if ($this->vocabulary === null) {
            throw new RuntimeException('Transformer is not fitted.');
        }

        $templates = [];

        foreach ($this->vocabulary as $column => $vocabulary) {
            $templates[$column] = array_fill(0, count($vocabulary), 0);
        }

        foreach ($samples as &$sample) {
            $vectors = [];

            foreach ($this->vocabulary as $column => $vocabulary) {
                $text = $sample[$column];

                $tokens = $this->tokenizer->tokenize($text);

                $counts = array_count_values($tokens);

                $features = $templates[$column];

                foreach ($counts as $token => $count) {
                    if (isset($vocabulary[$token])) {
                        $features[$vocabulary[$token]] = $count;
                    }
                }

                $vectors[] = $features;

                unset($sample[$column]);
            }

            $sample = array_merge($sample, ...$vectors);
        }
    }