From cbd9f5fde192548669245d3aa56cb2858eac9399 Mon Sep 17 00:00:00 2001 From: Yuji Uchiyama Date: Sun, 4 Mar 2018 00:03:53 +0900 Subject: [PATCH] Inline static constructors of exceptions (#250) --- src/Classification/MLPClassifier.php | 4 +- src/Clustering/FuzzyCMeans.php | 2 +- src/Clustering/KMeans.php | 2 +- src/CrossValidation/Split.php | 2 +- src/Dataset/ArrayDataset.php | 2 +- src/Dataset/CsvDataset.php | 4 +- src/Dataset/FilesDataset.php | 2 +- src/Dataset/SvmDataset.php | 14 +-- src/Exception/DatasetException.php | 19 ---- src/Exception/FileException.php | 14 --- src/Exception/InvalidArgumentException.php | 92 ------------------- src/Exception/LibsvmCommandException.php | 4 - src/Exception/MatrixException.php | 14 --- src/Exception/NormalizerException.php | 4 - src/Exception/SerializeException.php | 9 -- src/FeatureExtraction/StopWords.php | 2 +- src/FeatureSelection/SelectKBest.php | 2 +- src/Math/Comparison.php | 2 +- src/Math/Distance/Chebyshev.php | 2 +- src/Math/Distance/Euclidean.php | 2 +- src/Math/Distance/Manhattan.php | 2 +- src/Math/Distance/Minkowski.php | 2 +- src/Math/LinearAlgebra/LUDecomposition.php | 6 +- src/Math/Matrix.php | 10 +- src/Math/Statistic/ANOVA.php | 2 +- src/Math/Statistic/Correlation.php | 2 +- src/Math/Statistic/Covariance.php | 8 +- src/Math/Statistic/Mean.php | 2 +- src/Math/Statistic/StandardDeviation.php | 6 +- src/Metric/Accuracy.php | 2 +- src/ModelManager.php | 10 +- src/NeuralNetwork/Layer.php | 2 +- .../Network/MultilayerPerceptron.php | 8 +- src/Preprocessing/Normalizer.php | 2 +- src/SupportVectorMachine/DataTransformer.php | 2 +- .../SupportVectorMachine.php | 16 ++-- 36 files changed, 66 insertions(+), 214 deletions(-) diff --git a/src/Classification/MLPClassifier.php b/src/Classification/MLPClassifier.php index 432582be..13963f3d 100644 --- a/src/Classification/MLPClassifier.php +++ b/src/Classification/MLPClassifier.php @@ -17,7 +17,9 @@ class MLPClassifier extends MultilayerPerceptron implements Classifier public function getTargetClass($target): int { if (!in_array($target, $this->classes, true)) { - throw InvalidArgumentException::invalidTarget($target); + throw new InvalidArgumentException( + sprintf('Target with value "%s" is not part of the accepted classes', $target) + ); } return array_search($target, $this->classes, true); diff --git a/src/Clustering/FuzzyCMeans.php b/src/Clustering/FuzzyCMeans.php index a5408c03..5e6fa0c0 100644 --- a/src/Clustering/FuzzyCMeans.php +++ b/src/Clustering/FuzzyCMeans.php @@ -63,7 +63,7 @@ class FuzzyCMeans implements Clusterer public function __construct(int $clustersNumber, float $fuzziness = 2.0, float $epsilon = 1e-2, int $maxIterations = 100) { if ($clustersNumber <= 0) { - throw InvalidArgumentException::invalidClustersNumber(); + throw new InvalidArgumentException('Invalid clusters number'); } $this->clustersNumber = $clustersNumber; diff --git a/src/Clustering/KMeans.php b/src/Clustering/KMeans.php index 78a2e4ab..86ad754b 100644 --- a/src/Clustering/KMeans.php +++ b/src/Clustering/KMeans.php @@ -26,7 +26,7 @@ class KMeans implements Clusterer public function __construct(int $clustersNumber, int $initialization = self::INIT_KMEANS_PLUS_PLUS) { if ($clustersNumber <= 0) { - throw InvalidArgumentException::invalidClustersNumber(); + throw new InvalidArgumentException('Invalid clusters number'); } $this->clustersNumber = $clustersNumber; diff --git a/src/CrossValidation/Split.php b/src/CrossValidation/Split.php index 96c9019d..bffb59aa 100644 --- a/src/CrossValidation/Split.php +++ b/src/CrossValidation/Split.php @@ -32,7 +32,7 @@ abstract class Split public function __construct(Dataset $dataset, float $testSize = 0.3, ?int $seed = null) { if ($testSize <= 0 || $testSize >= 1) { - throw InvalidArgumentException::percentNotInRange('testSize'); + throw new InvalidArgumentException('testsize must be between 0.0 and 1.0'); } $this->seedGenerator($seed); diff --git a/src/Dataset/ArrayDataset.php b/src/Dataset/ArrayDataset.php index 7d30b0b0..618814ae 100644 --- a/src/Dataset/ArrayDataset.php +++ b/src/Dataset/ArrayDataset.php @@ -24,7 +24,7 @@ class ArrayDataset implements Dataset public function __construct(array $samples, array $targets) { if (count($samples) != count($targets)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $this->samples = $samples; diff --git a/src/Dataset/CsvDataset.php b/src/Dataset/CsvDataset.php index f88fe314..631c6a6e 100644 --- a/src/Dataset/CsvDataset.php +++ b/src/Dataset/CsvDataset.php @@ -19,12 +19,12 @@ class CsvDataset extends ArrayDataset public function __construct(string $filepath, int $features, bool $headingRow = true, string $delimiter = ',', int $maxLineLength = 0) { if (!file_exists($filepath)) { - throw FileException::missingFile(basename($filepath)); + throw new FileException(sprintf('File "%s" missing.', basename($filepath))); } $handle = fopen($filepath, 'rb'); if ($handle === false) { - throw FileException::cantOpenFile(basename($filepath)); + throw new FileException(sprintf('File "%s" can\'t be open.', basename($filepath))); } if ($headingRow) { diff --git a/src/Dataset/FilesDataset.php b/src/Dataset/FilesDataset.php index ca04a3e6..a1597535 100644 --- a/src/Dataset/FilesDataset.php +++ b/src/Dataset/FilesDataset.php @@ -11,7 +11,7 @@ class FilesDataset extends ArrayDataset public function __construct(string $rootPath) { if (!is_dir($rootPath)) { - throw DatasetException::missingFolder($rootPath); + throw new DatasetException(sprintf('Dataset root folder "%s" missing.', $rootPath)); } $this->scanRootPath($rootPath); diff --git a/src/Dataset/SvmDataset.php b/src/Dataset/SvmDataset.php index 8bd172b5..c1e261b2 100644 --- a/src/Dataset/SvmDataset.php +++ b/src/Dataset/SvmDataset.php @@ -41,12 +41,12 @@ private static function readProblem(string $filePath): array private static function openFile(string $filePath) { if (!file_exists($filePath)) { - throw FileException::missingFile(basename($filePath)); + throw new FileException(sprintf('File "%s" missing.', basename($filePath))); } $handle = fopen($filePath, 'rb'); if ($handle === false) { - throw FileException::cantOpenFile(basename($filePath)); + throw new FileException(sprintf('File "%s" can\'t be open.', basename($filePath))); } return $handle; @@ -87,7 +87,7 @@ private static function parseLine(string $line): array private static function parseTargetColumn(string $column): float { if (!is_numeric($column)) { - throw DatasetException::invalidTarget($column); + throw new DatasetException(sprintf('Invalid target "%s".', $column)); } return (float) $column; @@ -97,7 +97,7 @@ private static function parseFeatureColumn(string $column): array { $feature = explode(':', $column, 2); if (count($feature) != 2) { - throw DatasetException::invalidValue($column); + throw new DatasetException(sprintf('Invalid value "%s".', $column)); } $index = self::parseFeatureIndex($feature[0]); @@ -109,11 +109,11 @@ private static function parseFeatureColumn(string $column): array private static function parseFeatureIndex(string $index): int { if (!is_numeric($index) || !ctype_digit($index)) { - throw DatasetException::invalidIndex($index); + throw new DatasetException(sprintf('Invalid index "%s".', $index)); } if ((int) $index < 1) { - throw DatasetException::invalidIndex($index); + throw new DatasetException(sprintf('Invalid index "%s".', $index)); } return (int) $index - 1; @@ -122,7 +122,7 @@ private static function parseFeatureIndex(string $index): int private static function parseFeatureValue(string $value): float { if (!is_numeric($value)) { - throw DatasetException::invalidValue($value); + throw new DatasetException(sprintf('Invalid value "%s".', $value)); } return (float) $value; diff --git a/src/Exception/DatasetException.php b/src/Exception/DatasetException.php index 1cb0bfc4..d6f22192 100644 --- a/src/Exception/DatasetException.php +++ b/src/Exception/DatasetException.php @@ -8,23 +8,4 @@ class DatasetException extends Exception { - public static function missingFolder(string $path): self - { - return new self(sprintf('Dataset root folder "%s" missing.', $path)); - } - - public static function invalidTarget(string $target): self - { - return new self(sprintf('Invalid target "%s".', $target)); - } - - public static function invalidIndex(string $index): self - { - return new self(sprintf('Invalid index "%s".', $index)); - } - - public static function invalidValue(string $value): self - { - return new self(sprintf('Invalid value "%s".', $value)); - } } diff --git a/src/Exception/FileException.php b/src/Exception/FileException.php index 719c2c2b..e00acff8 100644 --- a/src/Exception/FileException.php +++ b/src/Exception/FileException.php @@ -8,18 +8,4 @@ class FileException extends Exception { - public static function missingFile(string $filepath): self - { - return new self(sprintf('File "%s" missing.', $filepath)); - } - - public static function cantOpenFile(string $filepath): self - { - return new self(sprintf('File "%s" can\'t be open.', $filepath)); - } - - public static function cantSaveFile(string $filepath): self - { - return new self(sprintf('File "%s" can\'t be saved.', $filepath)); - } } diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index 8aebbe01..a25599b4 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -8,96 +8,4 @@ class InvalidArgumentException extends Exception { - public static function arraySizeNotMatch(): self - { - return new self('Size of given arrays does not match'); - } - - public static function percentNotInRange($name): self - { - return new self(sprintf('%s must be between 0.0 and 1.0', $name)); - } - - public static function arrayCantBeEmpty(): self - { - return new self('The array has zero elements'); - } - - public static function arraySizeTooSmall(int $minimumSize = 2): self - { - return new self(sprintf('The array must have at least %d elements', $minimumSize)); - } - - public static function matrixDimensionsDidNotMatch(): self - { - return new self('Matrix dimensions did not match'); - } - - public static function inconsistentMatrixSupplied(): self - { - return new self('Inconsistent matrix supplied'); - } - - public static function invalidClustersNumber(): self - { - return new self('Invalid clusters number'); - } - - /** - * @param mixed $target - */ - public static function invalidTarget($target): self - { - return new self(sprintf('Target with value "%s" is not part of the accepted classes', $target)); - } - - public static function invalidStopWordsLanguage(string $language): self - { - return new self(sprintf('Can\'t find "%s" language for StopWords', $language)); - } - - public static function invalidLayerNodeClass(): self - { - return new self('Layer node class must implement Node interface'); - } - - public static function invalidLayersNumber(): self - { - return new self('Provide at least 1 hidden layer'); - } - - public static function invalidClassesNumber(): self - { - return new self('Provide at least 2 different classes'); - } - - public static function inconsistentClasses(): self - { - return new self('The provided classes don\'t match the classes provided in the constructor'); - } - - public static function fileNotFound(string $file): self - { - return new self(sprintf('File "%s" not found', $file)); - } - - public static function fileNotExecutable(string $file): self - { - return new self(sprintf('File "%s" is not executable', $file)); - } - - public static function pathNotFound(string $path): self - { - return new self(sprintf('The specified path "%s" does not exist', $path)); - } - - public static function pathNotWritable(string $path): self - { - return new self(sprintf('The specified path "%s" is not writable', $path)); - } - - public static function invalidOperator(string $operator): self - { - return new self(sprintf('Invalid operator "%s" provided', $operator)); - } } diff --git a/src/Exception/LibsvmCommandException.php b/src/Exception/LibsvmCommandException.php index a9d11e3a..d4d353eb 100644 --- a/src/Exception/LibsvmCommandException.php +++ b/src/Exception/LibsvmCommandException.php @@ -8,8 +8,4 @@ class LibsvmCommandException extends Exception { - public static function failedToRun(string $command, string $reason): self - { - return new self(sprintf('Failed running libsvm command: "%s" with reason: "%s"', $command, $reason)); - } } diff --git a/src/Exception/MatrixException.php b/src/Exception/MatrixException.php index b309bfff..eb6e9d3a 100644 --- a/src/Exception/MatrixException.php +++ b/src/Exception/MatrixException.php @@ -8,18 +8,4 @@ class MatrixException extends Exception { - public static function notSquareMatrix(): self - { - return new self('Matrix is not square matrix'); - } - - public static function columnOutOfRange(): self - { - return new self('Column out of range'); - } - - public static function singularMatrix(): self - { - return new self('Matrix is singular'); - } } diff --git a/src/Exception/NormalizerException.php b/src/Exception/NormalizerException.php index 282fa1b3..197876ea 100644 --- a/src/Exception/NormalizerException.php +++ b/src/Exception/NormalizerException.php @@ -8,8 +8,4 @@ class NormalizerException extends Exception { - public static function unknownNorm(): self - { - return new self('Unknown norm supplied.'); - } } diff --git a/src/Exception/SerializeException.php b/src/Exception/SerializeException.php index 6d1abaae..27cd744f 100644 --- a/src/Exception/SerializeException.php +++ b/src/Exception/SerializeException.php @@ -8,13 +8,4 @@ class SerializeException extends Exception { - public static function cantUnserialize(string $filepath): self - { - return new self(sprintf('"%s" can not be unserialized.', $filepath)); - } - - public static function cantSerialize(string $classname): self - { - return new self(sprintf('Class "%s" can not be serialized.', $classname)); - } } diff --git a/src/FeatureExtraction/StopWords.php b/src/FeatureExtraction/StopWords.php index f8fc69e8..f5622fd6 100644 --- a/src/FeatureExtraction/StopWords.php +++ b/src/FeatureExtraction/StopWords.php @@ -28,7 +28,7 @@ public static function factory(string $language = 'English'): self $className = __NAMESPACE__."\\StopWords\\${language}"; if (!class_exists($className)) { - throw InvalidArgumentException::invalidStopWordsLanguage($language); + throw new InvalidArgumentException(sprintf('Can\'t find "%s" language for StopWords', $language)); } return new $className(); diff --git a/src/FeatureSelection/SelectKBest.php b/src/FeatureSelection/SelectKBest.php index bd84e736..b0ff6449 100644 --- a/src/FeatureSelection/SelectKBest.php +++ b/src/FeatureSelection/SelectKBest.php @@ -44,7 +44,7 @@ public function __construct(int $k = 10, ?ScoringFunction $scoringFunction = nul public function fit(array $samples, ?array $targets = null): void { if ($targets === null || empty($targets)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } $this->scores = $sorted = $this->scoringFunction->score($samples, $targets); diff --git a/src/Math/Comparison.php b/src/Math/Comparison.php index de7414d1..d9ad00cc 100644 --- a/src/Math/Comparison.php +++ b/src/Math/Comparison.php @@ -33,7 +33,7 @@ public static function compare($a, $b, string $operator): bool case '!==': return $a !== $b; default: - throw InvalidArgumentException::invalidOperator($operator); + throw new InvalidArgumentException(sprintf('Invalid operator "%s" provided', $operator)); } } } diff --git a/src/Math/Distance/Chebyshev.php b/src/Math/Distance/Chebyshev.php index 52e969cb..0ccd29a8 100644 --- a/src/Math/Distance/Chebyshev.php +++ b/src/Math/Distance/Chebyshev.php @@ -15,7 +15,7 @@ class Chebyshev implements Distance public function distance(array $a, array $b): float { if (count($a) !== count($b)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $differences = []; diff --git a/src/Math/Distance/Euclidean.php b/src/Math/Distance/Euclidean.php index 4ecc576e..4f437dcf 100644 --- a/src/Math/Distance/Euclidean.php +++ b/src/Math/Distance/Euclidean.php @@ -15,7 +15,7 @@ class Euclidean implements Distance public function distance(array $a, array $b): float { if (count($a) !== count($b)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $distance = 0; diff --git a/src/Math/Distance/Manhattan.php b/src/Math/Distance/Manhattan.php index 457333c4..459a5ec4 100644 --- a/src/Math/Distance/Manhattan.php +++ b/src/Math/Distance/Manhattan.php @@ -15,7 +15,7 @@ class Manhattan implements Distance public function distance(array $a, array $b): float { if (count($a) !== count($b)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } return array_sum(array_map(function ($m, $n) { diff --git a/src/Math/Distance/Minkowski.php b/src/Math/Distance/Minkowski.php index 5ff7364f..36edf9be 100644 --- a/src/Math/Distance/Minkowski.php +++ b/src/Math/Distance/Minkowski.php @@ -25,7 +25,7 @@ public function __construct(float $lambda = 3.0) public function distance(array $a, array $b): float { if (count($a) !== count($b)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $distance = 0; diff --git a/src/Math/LinearAlgebra/LUDecomposition.php b/src/Math/LinearAlgebra/LUDecomposition.php index 1594837a..44e8a268 100644 --- a/src/Math/LinearAlgebra/LUDecomposition.php +++ b/src/Math/LinearAlgebra/LUDecomposition.php @@ -81,7 +81,7 @@ class LUDecomposition public function __construct(Matrix $A) { if ($A->getRows() != $A->getColumns()) { - throw MatrixException::notSquareMatrix(); + throw new MatrixException('Matrix is not square matrix'); } // Use a "left-looking", dot-product, Crout/Doolittle algorithm. @@ -247,11 +247,11 @@ public function det(): float public function solve(Matrix $B): array { if ($B->getRows() != $this->m) { - throw MatrixException::notSquareMatrix(); + throw new MatrixException('Matrix is not square matrix'); } if (!$this->isNonsingular()) { - throw MatrixException::singularMatrix(); + throw new MatrixException('Matrix is singular'); } // Copy right hand side with pivoting diff --git a/src/Math/Matrix.php b/src/Math/Matrix.php index 908ec4d7..f69d8e6a 100644 --- a/src/Math/Matrix.php +++ b/src/Math/Matrix.php @@ -48,7 +48,7 @@ public function __construct(array $matrix, bool $validate = true) if ($validate) { for ($i = 0; $i < $this->rows; ++$i) { if (count($matrix[$i]) !== $this->columns) { - throw InvalidArgumentException::matrixDimensionsDidNotMatch(); + throw new InvalidArgumentException('Matrix dimensions did not match'); } } } @@ -92,7 +92,7 @@ public function getColumns(): int public function getColumnValues($column): array { if ($column >= $this->columns) { - throw MatrixException::columnOutOfRange(); + throw new MatrixException('Column out of range'); } return array_column($this->matrix, $column); @@ -110,7 +110,7 @@ public function getDeterminant() } if (!$this->isSquare()) { - throw MatrixException::notSquareMatrix(); + throw new MatrixException('Matrix is not square matrix'); } $lu = new LUDecomposition($this); @@ -139,7 +139,7 @@ public function transpose(): self public function multiply(self $matrix): self { if ($this->columns != $matrix->getRows()) { - throw InvalidArgumentException::inconsistentMatrixSupplied(); + throw new InvalidArgumentException('Inconsistent matrix supplied'); } $product = []; @@ -200,7 +200,7 @@ public function subtract(self $other): self public function inverse(): self { if (!$this->isSquare()) { - throw MatrixException::notSquareMatrix(); + throw new MatrixException('Matrix is not square matrix'); } $LU = new LUDecomposition($this); diff --git a/src/Math/Statistic/ANOVA.php b/src/Math/Statistic/ANOVA.php index 65548a19..2732ba79 100644 --- a/src/Math/Statistic/ANOVA.php +++ b/src/Math/Statistic/ANOVA.php @@ -25,7 +25,7 @@ public static function oneWayF(array $samples): array { $classes = count($samples); if ($classes < 2) { - throw InvalidArgumentException::arraySizeTooSmall(2); + throw new InvalidArgumentException('The array must have at least 2 elements'); } $samplesPerClass = array_map(function (array $class): int { diff --git a/src/Math/Statistic/Correlation.php b/src/Math/Statistic/Correlation.php index 8803cbfb..ce52f3b6 100644 --- a/src/Math/Statistic/Correlation.php +++ b/src/Math/Statistic/Correlation.php @@ -17,7 +17,7 @@ class Correlation public static function pearson(array $x, array $y): float { if (count($x) !== count($y)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $count = count($x); diff --git a/src/Math/Statistic/Covariance.php b/src/Math/Statistic/Covariance.php index 3dfce4bf..4ed07764 100644 --- a/src/Math/Statistic/Covariance.php +++ b/src/Math/Statistic/Covariance.php @@ -16,12 +16,12 @@ class Covariance public static function fromXYArrays(array $x, array $y, bool $sample = true, ?float $meanX = null, ?float $meanY = null): float { if (empty($x) || empty($y)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } $n = count($x); if ($sample && $n === 1) { - throw InvalidArgumentException::arraySizeTooSmall(2); + throw new InvalidArgumentException('The array must have at least 2 elements'); } if ($meanX === null) { @@ -54,12 +54,12 @@ public static function fromXYArrays(array $x, array $y, bool $sample = true, ?fl public static function fromDataset(array $data, int $i, int $k, bool $sample = true, ?float $meanX = null, ?float $meanY = null): float { if (empty($data)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } $n = count($data); if ($sample && $n === 1) { - throw InvalidArgumentException::arraySizeTooSmall(2); + throw new InvalidArgumentException('The array must have at least 2 elements'); } if ($i < 0 || $k < 0 || $i >= $n || $k >= $n) { diff --git a/src/Math/Statistic/Mean.php b/src/Math/Statistic/Mean.php index 8e761dfb..6b6d555a 100644 --- a/src/Math/Statistic/Mean.php +++ b/src/Math/Statistic/Mean.php @@ -59,7 +59,7 @@ public static function mode(array $numbers) private static function checkArrayLength(array $array): void { if (empty($array)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } } } diff --git a/src/Math/Statistic/StandardDeviation.php b/src/Math/Statistic/StandardDeviation.php index 5bf4940a..f1eae8a8 100644 --- a/src/Math/Statistic/StandardDeviation.php +++ b/src/Math/Statistic/StandardDeviation.php @@ -14,13 +14,13 @@ class StandardDeviation public static function population(array $numbers, bool $sample = true): float { if (empty($numbers)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } $n = count($numbers); if ($sample && $n === 1) { - throw InvalidArgumentException::arraySizeTooSmall(2); + throw new InvalidArgumentException('The array must have at least 2 elements'); } $mean = Mean::arithmetic($numbers); @@ -45,7 +45,7 @@ public static function population(array $numbers, bool $sample = true): float public static function sumOfSquares(array $numbers): float { if (empty($numbers)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } $mean = Mean::arithmetic($numbers); diff --git a/src/Metric/Accuracy.php b/src/Metric/Accuracy.php index 3fd545cd..92f6860d 100644 --- a/src/Metric/Accuracy.php +++ b/src/Metric/Accuracy.php @@ -16,7 +16,7 @@ class Accuracy public static function score(array $actualLabels, array $predictedLabels, bool $normalize = true) { if (count($actualLabels) != count($predictedLabels)) { - throw InvalidArgumentException::arraySizeNotMatch(); + throw new InvalidArgumentException('Size of given arrays does not match'); } $score = 0; diff --git a/src/ModelManager.php b/src/ModelManager.php index ebcdbe46..36e8e2c1 100644 --- a/src/ModelManager.php +++ b/src/ModelManager.php @@ -12,29 +12,29 @@ class ModelManager public function saveToFile(Estimator $estimator, string $filepath): void { if (!is_writable(dirname($filepath))) { - throw FileException::cantSaveFile(basename($filepath)); + throw new FileException(sprintf('File "%s" can\'t be saved.', basename($filepath))); } $serialized = serialize($estimator); if (empty($serialized)) { - throw SerializeException::cantSerialize(gettype($estimator)); + throw new SerializeException(sprintf('Class "%s" can not be serialized.', gettype($estimator))); } $result = file_put_contents($filepath, $serialized, LOCK_EX); if ($result === false) { - throw FileException::cantSaveFile(basename($filepath)); + throw new FileException(sprintf('File "%s" can\'t be saved.', basename($filepath))); } } public function restoreFromFile(string $filepath): Estimator { if (!file_exists($filepath) || !is_readable($filepath)) { - throw FileException::cantOpenFile(basename($filepath)); + throw new FileException(sprintf('File "%s" can\'t be open.', basename($filepath))); } $object = unserialize(file_get_contents($filepath)); if ($object === false) { - throw SerializeException::cantUnserialize(basename($filepath)); + throw new SerializeException(sprintf('"%s" can not be unserialized.', basename($filepath))); } return $object; diff --git a/src/NeuralNetwork/Layer.php b/src/NeuralNetwork/Layer.php index a604a536..1c681f89 100644 --- a/src/NeuralNetwork/Layer.php +++ b/src/NeuralNetwork/Layer.php @@ -20,7 +20,7 @@ class Layer public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ?ActivationFunction $activationFunction = null) { if (!in_array(Node::class, class_implements($nodeClass), true)) { - throw InvalidArgumentException::invalidLayerNodeClass(); + throw new InvalidArgumentException('Layer node class must implement Node interface'); } for ($i = 0; $i < $nodesNumber; ++$i) { diff --git a/src/NeuralNetwork/Network/MultilayerPerceptron.php b/src/NeuralNetwork/Network/MultilayerPerceptron.php index a6d3be0d..36260639 100644 --- a/src/NeuralNetwork/Network/MultilayerPerceptron.php +++ b/src/NeuralNetwork/Network/MultilayerPerceptron.php @@ -62,11 +62,11 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, public function __construct(int $inputLayerFeatures, array $hiddenLayers, array $classes, int $iterations = 10000, ?ActivationFunction $activationFunction = null, float $learningRate = 1) { if (empty($hiddenLayers)) { - throw InvalidArgumentException::invalidLayersNumber(); + throw new InvalidArgumentException('Provide at least 1 hidden layer'); } if (count($classes) < 2) { - throw InvalidArgumentException::invalidClassesNumber(); + throw new InvalidArgumentException('Provide at least 2 different classes'); } $this->classes = array_values($classes); @@ -93,7 +93,9 @@ public function partialTrain(array $samples, array $targets, array $classes = [] { if (!empty($classes) && array_values($classes) !== $this->classes) { // We require the list of classes in the constructor. - throw InvalidArgumentException::inconsistentClasses(); + throw new InvalidArgumentException( + 'The provided classes don\'t match the classes provided in the constructor' + ); } for ($i = 0; $i < $this->iterations; ++$i) { diff --git a/src/Preprocessing/Normalizer.php b/src/Preprocessing/Normalizer.php index 9654e48a..95927ea6 100644 --- a/src/Preprocessing/Normalizer.php +++ b/src/Preprocessing/Normalizer.php @@ -42,7 +42,7 @@ class Normalizer implements Preprocessor public function __construct(int $norm = self::NORM_L2) { if (!in_array($norm, [self::NORM_L1, self::NORM_L2, self::NORM_STD], true)) { - throw NormalizerException::unknownNorm(); + throw new NormalizerException('Unknown norm supplied.'); } $this->norm = $norm; diff --git a/src/SupportVectorMachine/DataTransformer.php b/src/SupportVectorMachine/DataTransformer.php index e1aeb7de..06272e20 100644 --- a/src/SupportVectorMachine/DataTransformer.php +++ b/src/SupportVectorMachine/DataTransformer.php @@ -27,7 +27,7 @@ public static function trainingSet(array $samples, array $labels, bool $targets public static function testSet(array $samples): string { if (empty($samples)) { - throw InvalidArgumentException::arrayCantBeEmpty(); + throw new InvalidArgumentException('The array has zero elements'); } if (!is_array($samples[0])) { diff --git a/src/SupportVectorMachine/SupportVectorMachine.php b/src/SupportVectorMachine/SupportVectorMachine.php index 561f65bd..be16ff4f 100644 --- a/src/SupportVectorMachine/SupportVectorMachine.php +++ b/src/SupportVectorMachine/SupportVectorMachine.php @@ -137,7 +137,7 @@ public function setBinPath(string $binPath): void public function setVarPath(string $varPath): void { if (!is_writable($varPath)) { - throw InvalidArgumentException::pathNotWritable($varPath); + throw new InvalidArgumentException(sprintf('The specified path "%s" is not writable', $varPath)); } $this->ensureDirectorySeparator($varPath); @@ -160,7 +160,9 @@ public function train(array $samples, array $targets): void unlink($trainingSetFileName); if ($return !== 0) { - throw LibsvmCommandException::failedToRun($command, array_pop($output)); + throw new LibsvmCommandException( + sprintf('Failed running libsvm command: "%s" with reason: "%s"', $command, array_pop($output)) + ); } $this->model = file_get_contents($modelFileName); @@ -244,7 +246,9 @@ private function runSvmPredict(array $samples, bool $probabilityEstimates): stri unlink($outputFileName); if ($return !== 0) { - throw LibsvmCommandException::failedToRun($command, array_pop($output)); + throw new LibsvmCommandException( + sprintf('Failed running libsvm command: "%s" with reason: "%s"', $command, array_pop($output)) + ); } return $predictions; @@ -312,18 +316,18 @@ private function ensureDirectorySeparator(string &$path): void private function verifyBinPath(string $path): void { if (!is_dir($path)) { - throw InvalidArgumentException::pathNotFound($path); + throw new InvalidArgumentException(sprintf('The specified path "%s" does not exist', $path)); } $osExtension = $this->getOSExtension(); foreach (['svm-predict', 'svm-scale', 'svm-train'] as $filename) { $filePath = $path.$filename.$osExtension; if (!file_exists($filePath)) { - throw InvalidArgumentException::fileNotFound($filePath); + throw new InvalidArgumentException(sprintf('File "%s" not found', $filePath)); } if (!is_executable($filePath)) { - throw InvalidArgumentException::fileNotExecutable($filePath); + throw new InvalidArgumentException(sprintf('File "%s" is not executable', $filePath)); } } }