Skip to content

Commit

Permalink
Fix static analysis errors from phpstan upgrade to 0.12 (#426)
Browse files Browse the repository at this point in the history
  • Loading branch information
marmichalski authored Mar 3, 2020
1 parent deefbb3 commit 2ee0d37
Show file tree
Hide file tree
Showing 27 changed files with 278 additions and 279 deletions.
449 changes: 224 additions & 225 deletions composer.lock

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@ includes:
- vendor/phpstan/phpstan-phpunit/rules.neon

parameters:
checkGenericClassInNonGenericObjectType: false
checkMissingIterableValueType: false

ignoreErrors:
- '#Property Phpml\\Clustering\\KMeans\\Cluster\:\:\$points \(iterable\<Phpml\\Clustering\\KMeans\\Point\>\&SplObjectStorage\) does not accept SplObjectStorage#'
- '#Phpml\\Dataset\\(.*)Dataset::__construct\(\) does not call parent constructor from Phpml\\Dataset\\ArrayDataset#'
- '#Variable property access on .+#'
- '#Variable method call on .+#'

- message: '#ReflectionClass#'
paths:
- src/Classification/Ensemble/AdaBoost.php
- src/Classification/Ensemble/Bagging.php
# probably known value
- '#Method Phpml\\Classification\\DecisionTree::getBestSplit\(\) should return Phpml\\Classification\\DecisionTree\\DecisionTreeLeaf but returns Phpml\\Classification\\DecisionTree\\DecisionTreeLeaf\|null#'
- '#Call to an undefined method Phpml\\Helper\\Optimizer\\Optimizer::getCostValues\(\)#'
14 changes: 7 additions & 7 deletions src/Association/Apriori.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,11 @@ public function apriori(): array
*/
protected function predictSample(array $sample): array
{
$predicts = array_values(array_filter($this->getRules(), function ($rule) use ($sample) {
$predicts = array_values(array_filter($this->getRules(), function ($rule) use ($sample): bool {
return $this->equals($rule[self::ARRAY_KEY_ANTECEDENT], $sample);
}));

return array_map(function ($rule) {
return array_map(static function ($rule) {
return $rule[self::ARRAY_KEY_CONSEQUENT];
}, $predicts);
}
Expand Down Expand Up @@ -177,7 +177,7 @@ private function antecedents(array $sample): array
$cardinality = count($sample);
$antecedents = $this->powerSet($sample);

return array_filter($antecedents, function ($antecedent) use ($cardinality) {
return array_filter($antecedents, static function ($antecedent) use ($cardinality): bool {
return (count($antecedent) != $cardinality) && ($antecedent != []);
});
}
Expand All @@ -199,7 +199,7 @@ private function items(): array
}
}

return array_map(function ($entry) {
return array_map(static function ($entry): array {
return [$entry];
}, $items);
}
Expand All @@ -213,7 +213,7 @@ private function items(): array
*/
private function frequent(array $samples): array
{
return array_values(array_filter($samples, function ($entry) {
return array_values(array_filter($samples, function ($entry): bool {
return $this->support($entry) >= $this->support;
}));
}
Expand Down Expand Up @@ -288,7 +288,7 @@ private function support(array $sample): float
*/
private function frequency(array $sample): int
{
return count(array_filter($this->samples, function ($entry) use ($sample) {
return count(array_filter($this->samples, function ($entry) use ($sample): bool {
return $this->subset($entry, $sample);
}));
}
Expand All @@ -303,7 +303,7 @@ private function frequency(array $sample): int
*/
private function contains(array $system, array $set): bool
{
return (bool) array_filter($system, function ($entry) use ($set) {
return (bool) array_filter($system, function ($entry) use ($set): bool {
return $this->equals($entry, $set);
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/Classification/Linear/Adaline.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function __construct(
protected function runTraining(array $samples, array $targets): void
{
// The cost function is the sum of squares
$callback = function ($weights, $sample, $target) {
$callback = function ($weights, $sample, $target): array {
$this->weights = $weights;

$output = $this->output($sample);
Expand Down
4 changes: 2 additions & 2 deletions src/Classification/Linear/LogisticRegression.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ protected function getCostFunction(): Closure
* The gradient of the cost function to be used with gradient descent:
* ∇J(x) = -(y - h(x)) = (h(x) - y)
*/
return function ($weights, $sample, $y) use ($penalty) {
return function ($weights, $sample, $y) use ($penalty): array {
$this->weights = $weights;
$hX = $this->output($sample);

Expand Down Expand Up @@ -220,7 +220,7 @@ protected function getCostFunction(): Closure
* The gradient of the cost function:
* ∇J(x) = -(h(x) - y) . h(x) . (1 - h(x))
*/
return function ($weights, $sample, $y) use ($penalty) {
return function ($weights, $sample, $y) use ($penalty): array {
$this->weights = $weights;
$hX = $this->output($sample);

Expand Down
2 changes: 1 addition & 1 deletion src/Classification/Linear/Perceptron.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ protected function resetBinary(): void
protected function runTraining(array $samples, array $targets): void
{
// The cost function is the sum of squares
$callback = function ($weights, $sample, $target) {
$callback = function ($weights, $sample, $target): array {
$this->weights = $weights;

$prediction = $this->outputClass($sample);
Expand Down
2 changes: 1 addition & 1 deletion src/Clustering/FuzzyCMeans.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ protected function generateRandomMembership(int $rows, int $cols): void
$total += $val;
}

$this->membership[] = array_map(function ($val) use ($total) {
$this->membership[] = array_map(static function ($val) use ($total): float {
return $val / $total;
}, $row);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Clustering/KMeans/Space.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function getBoundaries()
$min = $this->newPoint(array_fill(0, $this->dimension, null));
$max = $this->newPoint(array_fill(0, $this->dimension, null));

/** @var self $point */
/** @var Point $point */
foreach ($this as $point) {
for ($n = 0; $n < $this->dimension; ++$n) {
if ($min[$n] === null || $min[$n] > $point[$n]) {
Expand Down
4 changes: 2 additions & 2 deletions src/Dataset/CsvDataset.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public function __construct(string $filepath, int $features, bool $headingRow =
}

$samples = $targets = [];
while (($data = fgetcsv($handle, $maxLineLength, $delimiter)) !== false) {
$samples[] = array_slice((array) $data, 0, $features);
while ($data = fgetcsv($handle, $maxLineLength, $delimiter)) {
$samples[] = array_slice($data, 0, $features);
$targets[] = $data[$features];
}

Expand Down
6 changes: 3 additions & 3 deletions src/DimensionReduction/KernelPCA.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,13 @@ protected function getKernel(): Closure
// k(x,y)=exp(-γ.|x-y|) where |..| is Euclidean distance
$dist = new Euclidean();

return function ($x, $y) use ($dist) {
return function ($x, $y) use ($dist): float {
return exp(-$this->gamma * $dist->sqDistance($x, $y));
};

case self::KERNEL_SIGMOID:
// k(x,y)=tanh(γ.xT.y+c0) where c0=1
return function ($x, $y) {
return function ($x, $y): float {
$res = Matrix::dot($x, $y)[0] + 1.0;

return tanh((float) $this->gamma * $res);
Expand All @@ -195,7 +195,7 @@ protected function getKernel(): Closure
// k(x,y)=exp(-γ.|x-y|) where |..| is Manhattan distance
$dist = new Manhattan();

return function ($x, $y) use ($dist) {
return function ($x, $y) use ($dist): float {
return exp(-$this->gamma * $dist->distance($x, $y));
};

Expand Down
2 changes: 1 addition & 1 deletion src/FeatureSelection/VarianceThreshold.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(float $threshold = 0.0)

public function fit(array $samples, ?array $targets = null): void
{
$this->variances = array_map(function (array $column) {
$this->variances = array_map(static function (array $column): float {
return Variance::population($column);
}, Matrix::transposeArray($samples));

Expand Down
2 changes: 1 addition & 1 deletion src/Helper/Optimizer/GD.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function runOptimization(array $samples, array $targets, Closure $gradien

$this->updateWeightsWithUpdates($updates, $totalPenalty);

$this->costValues[] = array_sum($errors) / $this->sampleCount;
$this->costValues[] = array_sum($errors) / (int) $this->sampleCount;

if ($this->earlyStop($theta)) {
break;
Expand Down
2 changes: 1 addition & 1 deletion src/Math/Matrix.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public function isSquare(): bool
public function transpose(): self
{
if ($this->rows === 1) {
$matrix = array_map(function ($el) {
$matrix = array_map(static function ($el): array {
return [$el];
}, $this->matrix[0]);
} else {
Expand Down
10 changes: 5 additions & 5 deletions src/Math/Statistic/ANOVA.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static function oneWayF(array $samples): array
throw new InvalidArgumentException('The array must have at least 2 elements');
}

$samplesPerClass = array_map(function (array $class): int {
$samplesPerClass = array_map(static function (array $class): int {
return count($class);
}, $samples);
$allSamples = (int) array_sum($samplesPerClass);
Expand All @@ -41,10 +41,10 @@ public static function oneWayF(array $samples): array
$dfbn = $classes - 1;
$dfwn = $allSamples - $classes;

$msb = array_map(function ($s) use ($dfbn) {
$msb = array_map(static function ($s) use ($dfbn) {
return $s / $dfbn;
}, $ssbn);
$msw = array_map(function ($s) use ($dfwn) {
$msw = array_map(static function ($s) use ($dfwn) {
if ($dfwn === 0) {
return 1;
}
Expand Down Expand Up @@ -76,7 +76,7 @@ private static function sumOfSquaresPerFeature(array $samples): array

private static function sumOfFeaturesPerClass(array $samples): array
{
return array_map(function (array $class) {
return array_map(static function (array $class): array {
$sum = array_fill(0, count($class[0]), 0);
foreach ($class as $sample) {
foreach ($sample as $index => $feature) {
Expand All @@ -97,7 +97,7 @@ private static function sumOfSquares(array $sums): array
}
}

return array_map(function ($sum) {
return array_map(static function ($sum) {
return $sum ** 2;
}, $squares);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Math/Statistic/StandardDeviation.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static function sumOfSquares(array $numbers): float
$mean = Mean::arithmetic($numbers);

return array_sum(array_map(
function ($val) use ($mean) {
static function ($val) use ($mean): float {
return ($val - $mean) ** 2;
},
$numbers
Expand Down
12 changes: 3 additions & 9 deletions src/Metric/ClassificationReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private function computeMicroAverage(): void

$precision = $this->computePrecision($truePositive, $falsePositive);
$recall = $this->computeRecall($truePositive, $falseNegative);
$f1score = $this->computeF1Score((float) $precision, (float) $recall);
$f1score = $this->computeF1Score($precision, $recall);

$this->average = compact('precision', 'recall', 'f1score');
}
Expand Down Expand Up @@ -186,10 +186,7 @@ private function computeWeightedAverage(): void
}
}

/**
* @return float|string
*/
private function computePrecision(int $truePositive, int $falsePositive)
private function computePrecision(int $truePositive, int $falsePositive): float
{
$divider = $truePositive + $falsePositive;
if ($divider == 0) {
Expand All @@ -199,10 +196,7 @@ private function computePrecision(int $truePositive, int $falsePositive)
return $truePositive / $divider;
}

/**
* @return float|string
*/
private function computeRecall(int $truePositive, int $falseNegative)
private function computeRecall(int $truePositive, int $falseNegative): float
{
$divider = $truePositive + $falseNegative;
if ($divider == 0) {
Expand Down
2 changes: 1 addition & 1 deletion src/NeuralNetwork/Node/Neuron.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Neuron implements Node

public function __construct(?ActivationFunction $activationFunction = null)
{
$this->activationFunction = $activationFunction ?: new Sigmoid();
$this->activationFunction = $activationFunction ?? new Sigmoid();
}

public function addSynapse(Synapse $synapse): void
Expand Down
2 changes: 1 addition & 1 deletion src/NeuralNetwork/Node/Neuron/Synapse.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Synapse
public function __construct(Node $node, ?float $weight = null)
{
$this->node = $node;
$this->weight = $weight ?: $this->generateRandomWeight();
$this->weight = $weight ?? $this->generateRandomWeight();
}

public function getOutput(): float
Expand Down
4 changes: 2 additions & 2 deletions src/Pipeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ public function train(array $samples, array $targets): void
*/
public function predict(array $samples)
{
$this->transform($samples);

if ($this->estimator === null) {
throw new InvalidOperationException('Pipeline without estimator can\'t use predict method');
}

$this->transform($samples);

return $this->estimator->predict($samples);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Regression/DecisionTreeRegressor.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ protected function terminate(array $targets): BinaryNode

protected function splitImpurity(array $groups): float
{
$samplesCount = (int) array_sum(array_map(static function (array $group) {
$samplesCount = (int) array_sum(array_map(static function (array $group): int {
return count($group[0]);
}, $groups));

Expand Down
2 changes: 1 addition & 1 deletion src/Tree/Node/DecisionNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function __construct(int $column, $value, array $groups, float $impurity)
$this->value = $value;
$this->groups = $groups;
$this->impurity = $impurity;
$this->samplesCount = (int) array_sum(array_map(function (array $group) {
$this->samplesCount = (int) array_sum(array_map(static function (array $group): int {
return count($group[0]);
}, $groups));
}
Expand Down
2 changes: 1 addition & 1 deletion tests/DimensionReduction/KernelPCATest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function testKernelPCA(): void
// during the calculation of eigenValues, we have to compare
// absolute value of the values
array_map(function ($val1, $val2) use ($epsilon): void {
self::assertEqualsWithDelta(abs($val1), abs($val2), $epsilon);
self::assertEqualsWithDelta(abs($val1[0]), abs($val2[0]), $epsilon);
}, $transformed, $reducedData);

// Fitted KernelPCA object can also transform an arbitrary sample of the
Expand Down
4 changes: 2 additions & 2 deletions tests/DimensionReduction/PCATest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function testPCA(): void
// during the calculation of eigenValues, we have to compare
// absolute value of the values
array_map(function ($val1, $val2) use ($epsilon): void {
self::assertEqualsWithDelta(abs($val1), abs($val2), $epsilon);
self::assertEqualsWithDelta(abs($val1[0]), abs($val2[0]), $epsilon);
}, $transformed, $reducedData);

// Test fitted PCA object to transform an arbitrary sample of the
Expand All @@ -52,7 +52,7 @@ public function testPCA(): void
$newRow2 = $pca->transform($row);

array_map(function ($val1, $val2) use ($epsilon): void {
self::assertEqualsWithDelta(abs($val1), abs($val2), $epsilon);
self::assertEqualsWithDelta(abs($val1[0][0]), abs($val2[0]), $epsilon);
}, $newRow, $newRow2);
}
}
Expand Down
6 changes: 3 additions & 3 deletions tests/Helper/Optimizer/ConjugateGradientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function testRunOptimization(): void
$targets[] = -1 + 2 * $x;
}

$callback = function ($theta, $sample, $target) {
$callback = static function ($theta, $sample, $target): array {
$y = $theta[0] + $theta[1] * $sample[0];
$cost = (($y - $target) ** 2) / 2;
$grad = $y - $target;
Expand All @@ -47,7 +47,7 @@ public function testRunOptimizationWithCustomInitialTheta(): void
$targets[] = -1 + 2 * $x;
}

$callback = function ($theta, $sample, $target) {
$callback = static function ($theta, $sample, $target): array {
$y = $theta[0] + $theta[1] * $sample[0];
$cost = (($y - $target) ** 2) / 2;
$grad = $y - $target;
Expand Down Expand Up @@ -76,7 +76,7 @@ public function testRunOptimization2Dim(): void
$targets[] = -1 + 2 * $x0 - 3 * $x1;
}

$callback = function ($theta, $sample, $target) {
$callback = static function ($theta, $sample, $target): array {
$y = $theta[0] + $theta[1] * $sample[0] + $theta[2] * $sample[1];
$cost = (($y - $target) ** 2) / 2;
$grad = $y - $target;
Expand Down
Loading

0 comments on commit 2ee0d37

Please sign in to comment.