PCATest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace MathPHP\Tests\Statistics\Multivariate\PCA;
  3. use MathPHP\LinearAlgebra\NumericMatrix;
  4. use MathPHP\LinearAlgebra\MatrixFactory;
  5. use MathPHP\SampleData;
  6. use MathPHP\Statistics\Multivariate\PCA;
  7. use MathPHP\Exception;
  8. class PCATest extends \PHPUnit\Framework\TestCase
  9. {
  10. /** @var PCA */
  11. private static $pca;
  12. /** @var NumericMatrix */
  13. private static $matrix;
  14. /**
  15. * R code for expected values:
  16. * library(mdatools)
  17. * data = mtcars[,c(1:7,10,11)]
  18. * model = pca(data, center=TRUE, scale=TRUE)
  19. *
  20. * @throws Exception\MathException
  21. */
  22. public static function setUpBeforeClass(): void
  23. {
  24. $mtCars = new SampleData\MtCars();
  25. // Remove and categorical variables
  26. self::$matrix = MatrixFactory::create($mtCars->getData())->columnExclude(8)->columnExclude(7);
  27. self::$pca = new PCA(self::$matrix, true, true);
  28. }
  29. /**
  30. * @test Construction
  31. * @dataProvider dataProviderForConstructorParameters
  32. * @param bool $center
  33. * @param bool $scale
  34. * @throws Exception\MathException
  35. */
  36. public function testConstruction(bool $center, bool $scale)
  37. {
  38. // When
  39. $pca = new PCA(self::$matrix, $center, $scale);
  40. // Then
  41. $this->assertInstanceOf(PCA::class, $pca);
  42. }
  43. /**
  44. * @return array (center, scale)
  45. */
  46. public function dataProviderForConstructorParameters(): array
  47. {
  48. return [
  49. [true, true],
  50. [true, false],
  51. [false, true],
  52. [false, false],
  53. ];
  54. }
  55. /**
  56. * @test Test that the constructor throws an exception if the source matrix is too small
  57. * @throws \Exception
  58. */
  59. public function testConstructorException()
  60. {
  61. // Given
  62. $matrix = MatrixFactory::create([[1,2]]);
  63. // Then
  64. $this->expectException(Exception\BadDataException::class);
  65. // When
  66. $pca = new PCA($matrix, true, true);
  67. }
  68. /**
  69. * @test Test that the new data must have the have the same number of columns
  70. * @throws \Exception
  71. */
  72. public function testNewDataException()
  73. {
  74. // Given
  75. $new_data = MatrixFactory::create([[1,2]]);
  76. // Then
  77. $this->expectException(Exception\BadDataException::class);
  78. // When
  79. self::$pca->getScores($new_data);
  80. }
  81. }