Statistics.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace App\Yr\Forecast\Tabular;
  3. use App\Yr\Forecast\Tabular\Time\AbstractUnit;
  4. use App\Yr\Forecast\Tabular\Time\CustomUnit;
  5. use App\Yr\Forecast\Tabular\Time\Temperature;
  6. use App\Yr\Forecast\Tabular\Time\WindSpeed;
  7. /**
  8. * Make simple statistic on analysed time objects,
  9. * such as highest/lowest wind speed and temperature,
  10. * average wind speed and temperature etc.
  11. *
  12. * @author Joachim M. Giæver (joachim[]giaever.org)
  13. */
  14. class Statistics {
  15. private $temp = [];
  16. private $wind = [];
  17. private $count = 0;
  18. private $symbol = [];
  19. public function __construct() {
  20. $this->temp = $this->struct();
  21. $this->wind = $this->struct();
  22. }
  23. private function struct(): array {
  24. return [
  25. 'high' => null,
  26. 'low' => null,
  27. 'mean' => null
  28. ];
  29. }
  30. /**
  31. * Analyse a single Time-object
  32. *
  33. * @param Time $t The time object.
  34. * @return Statistics
  35. */
  36. public function analyse(Time $t): self {
  37. $this->analyseHihgLow($t->getTemperature());
  38. $this->analyseHihgLow($t->getWindSpeed());
  39. $this->temp['mean'] = $this->temp['mean'] == null ? $t->getTemperature() : $this->temp['mean']->add($t->getTemperature());
  40. $this->wind['mean'] = $this->wind['mean'] == null ? $t->getWindSpeed() : $this->wind['mean']->add($t->getWindSpeed());
  41. $symboldId = $t->getSymbol()->getNumber();
  42. if (!isset($this->symbol[$symboldId]))
  43. $this->symbol[$symboldId] = [
  44. 'symbol' => $t->getSymbol()->getName(),
  45. 'count' => 1
  46. ];
  47. else
  48. $this->symbol[$symboldId]['count']++;
  49. $this->count++;
  50. return $this;
  51. }
  52. public function getAverageTemperature(): AbstractUnit {
  53. return $this->temp['mean']->div(
  54. new CustomUnit($this->count, $this->temp['mean']->getUnit())
  55. );
  56. }
  57. public function getAverageWindSpeed(): AbstractUnit {
  58. return $this->wind['mean']->div(
  59. new CustomUnit($this->count, $this->wind['mean']->getUnit())
  60. );
  61. }
  62. private function analyseHihgLow(AbstractUnit $au): self {
  63. $unit = null;
  64. if ($au instanceof Temperature)
  65. $unit = &$this->temp;
  66. elseif ($au instanceof WindSpeed)
  67. $unit = &$this->wind;
  68. else
  69. return $this;
  70. if ($unit['low'] == null || $au->getValue() < $unit['low']->getValue())
  71. $unit['low'] = $au;
  72. if ($unit['high'] == null || $au->getValue() < $unit['high']->getValue())
  73. $unit['high'] = $au;
  74. return $this;
  75. }
  76. }
  77. ?>