MultinomialTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace MathPHP\Tests\Probability\Distribution\Multivariate;
  3. use MathPHP\Probability\Distribution\Multivariate\Multinomial;
  4. use MathPHP\Exception;
  5. class MultinomialTest extends \PHPUnit\Framework\TestCase
  6. {
  7. /**
  8. * @test pmf
  9. * @dataProvider dataProviderForPmf
  10. * @param array $frequencies
  11. * @param array $probabilities
  12. * @param $expectedPmf
  13. * @throws \Exception
  14. */
  15. public function testPmf(array $frequencies, array $probabilities, $expectedPmf)
  16. {
  17. // Given
  18. $multinomial = new Multinomial($probabilities);
  19. // When
  20. $pmf = $multinomial->pmf($frequencies);
  21. // Then
  22. $this->assertEqualsWithDelta($expectedPmf, $pmf, 0.001);
  23. }
  24. /**
  25. * @return array
  26. */
  27. public function dataProviderForPmf(): array
  28. {
  29. return [
  30. [ [1, 1], [0.5, 0.5], 0.5 ],
  31. [ [1, 1], [0.4, 0.6], 0.48 ],
  32. [ [7, 2, 3], [0.40, 0.35, 0.25], 0.0248 ],
  33. [ [1, 2, 3], [0.2, 0.3, 0.5], 0.135 ],
  34. [ [2, 3, 3, 2], [0.25, 0.25, 0.25, 0.25], 0.024 ],
  35. [ [5, 2], [0.4, 0.6], 0.07741440000000005 ],
  36. ];
  37. }
  38. /**
  39. * @test pmf throws Exception\BadDataException if the number of frequencies does not match the number of probabilities
  40. * @throws \Exception
  41. */
  42. public function testPmfExceptionCountFrequenciesAndProbabilitiesDoNotMatch()
  43. {
  44. // Given
  45. $probabilities = [0.3, 0.4, 0.2, 0.1];
  46. $frequencies = [1, 2, 3];
  47. $multinomial = new Multinomial($probabilities);
  48. // Then
  49. $this->expectException(Exception\BadDataException::class);
  50. // when
  51. $multinomial->pmf($frequencies);
  52. }
  53. /**
  54. * @test pmf throws Exception\BadDataException if one of the frequencies is not an int
  55. * @throws \Exception
  56. */
  57. public function testPmfExceptionFrequenciesAreNotAllIntegers()
  58. {
  59. // Given
  60. $probabilities = [0.3, 0.4, 0.2, 0.1];
  61. $frequencies = [1, 2.3, 3, 4.4];
  62. $multinomial = new Multinomial($probabilities);
  63. // Then
  64. $this->expectException(Exception\BadDataException::class);
  65. // when
  66. $multinomial->pmf($frequencies);
  67. }
  68. /**
  69. * @test constructor throws Exception\BadDataException if the probabilities do not add up to 1
  70. * @throws \Exception
  71. */
  72. public function testPMFExceptionProbabilitiesDoNotAddUpToOne()
  73. {
  74. // Then
  75. $this->expectException(Exception\BadDataException::class);
  76. // When
  77. $multinomial = new Multinomial([0.3, 0.2, 0.1]);
  78. }
  79. }