source: trunk/Modules/TimeMeasure/Measure.php

Last change on this file was 899, checked in by chronos, 4 years ago
File size: 19.2 KB
Line 
1<?php
2
3class Measure extends Model
4{
5 public array $Data;
6 public int $LevelReducing = 5;
7 public int $ReferenceTime = 0;
8 public int $MaxLevel = 4;
9 public int $Differential = 0;
10 public int $Debug = 0;
11 public int $DivisionCount = 500;
12 public array $ValueTypes = array('Min', 'Avg', 'Max');
13
14 static function GetModelDesc(): ModelDesc
15 {
16 $Desc = new ModelDesc(self::GetClassName());
17 $Desc->AddString('Name');
18 $Desc->AddString('Title');
19 $Desc->AddString('Description');
20 $Desc->AddString('Unit');
21 $Desc->AddBoolean('Continuity');
22 $Desc->AddInteger('Period');
23 $Desc->AddString('PermissionAdd');
24 $Desc->AddString('PermissionView');
25 $Desc->AddBoolean('Enabled');
26 $Desc->AddString('DataType');
27 $Desc->AddString('DataTable');
28 return $Desc;
29 }
30
31 function Load(int $Id): void
32 {
33 $Result = $this->Database->select('Measure', '*', 'Id='.$Id);
34 if ($Result->num_rows > 0)
35 {
36 $this->Data = $Result->fetch_assoc();
37 if ($this->Data['Continuity'] == 0) $this->Data['ContinuityEnabled'] = 0; // non continuous
38 else $this->Data['ContinuityEnabled'] = 2; // continuous graph
39 } else throw new Exception('Measure not found');
40 }
41
42 function TimeSegment($Base, $Level)
43 {
44 return pow($this->LevelReducing, $Level) * $Base;
45 }
46
47 function StatTableName(int $Level): string
48 {
49 if ($Level == 0) return 'Data';
50 else return 'DataCache';
51 }
52
53 function AlignTime($Time, $TimeSegment)
54 {
55 return round(($Time - $this->ReferenceTime) / $TimeSegment) * $TimeSegment + $this->ReferenceTime;
56 }
57
58 function AddValue($Value = array('Min' => 0, 'Avg' => 0, 'Max' => 0), $Level = 0, $Time = 0)
59 {
60 if ($Time == 0) $Time = time();
61
62 $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.
63 $this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 2');
64 if ($Result->num_rows == 0)
65 {
66 $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
67 'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
68 'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => 0));
69 } else if ($Result->num_rows == 1)
70 {
71 $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
72 'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
73 'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => 1));
74 } else
75 {
76 $LastValue = $Result->fetch_assoc();
77 $NextToLastValue = $Result->fetch_assoc();
78 if ((($Time - MysqlDateTimeToTime($LastValue['Time'])) < 0.75 * $this->Data['Period']) and ($Level == 0))
79 {
80 echo('Too short period. Minimal period is '.(0.75 * $this->Data['Period'])." seconds\n");
81 } else
82 {
83 if (($Time - MysqlDateTimeToTime($LastValue['Time'])) < 1.25 * $this->Data['Period']) $Continuity = 1;
84 else $Continuity = 0;
85 if (($LastValue['Min'] == $NextToLastValue['Min']) and ($LastValue['Min'] ==
86 $Value['Min']) and ($LastValue['Avg'] == $NextToLastValue['Avg']) and
87 ($LastValue['Avg'] == $Value['Avg']) and ($LastValue['Max'] == $NextToLastValue['Max'])
88 and ($LastValue['Max'] == $Value['Max']) and ($LastValue['Continuity'] == 1) and ($Continuity == 1))
89 {
90 $this->Database->update($this->Data['DataTable'], '(Time="'.$LastValue['Time'].
91 '") AND (Level='.$Level.') AND (Measure='.$this->Data['Id'].')', array('Time' => TimeToMysqlDateTime($Time)));
92 } else
93 {
94 $this->Database->insert($this->Data['DataTable'], array('Min' => $Value['Min'],
95 'Avg' => $Value['Avg'], 'Max' => $Value['Max'], 'Level' => $Level,
96 'Measure' => $this->Data['Id'], 'Time' => TimeToMysqlDateTime($Time), 'Continuity' => $Continuity));
97 }
98 }
99
100 // Update next level
101 if ($Level < $this->MaxLevel)
102 {
103 $Level = $Level + 1;
104 $TimeSegment = $this->TimeSegment($this->Data['Period'], 1);
105 $EndTime = $this->AlignTime($Time, $TimeSegment);
106 //if ($EndTime < $Time) $EndTime = $EndTime + $TimeSegment;
107 $StartTime = $EndTime - $TimeSegment;
108
109 // Load values in time range
110 $Values = array();
111 //.'" AND Time < "'.TimeToMysqlDateTime($EndTime).'" AND Measure='.$Measure['Id'].' AND Level='.($Level - 1).' ORDER BY Time');
112 $Result = $this->Database->select($this->Data['DataTable'], '*', '(Time > "'.
113 TimeToMysqlDateTime($StartTime).'") AND (Time < "'.TimeToMysqlDateTime($EndTime).
114 '") AND (Measure='.$this->Data['Id'].') AND (Level='.($Level - 1).') ORDER BY Time');
115 while ($Row = $Result->fetch_assoc())
116 {
117 $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
118 $Values[] = $Row;
119 }
120 //if (count($Values) > 2)
121 {
122 //array_pop($Values);
123
124 // Load subsidary values
125 $Values = array_merge($this->LoadLeftSideValue($Level - 1,
126 $StartTime), $Values, $this->LoadRightSideValue($Level - 1, $EndTime));
127
128 $Point = $this->ComputeOneValue($StartTime, $EndTime, $Values, $Level);
129
130 $this->Database->delete($this->Data['DataTable'], '(Time > "'.TimeToMysqlDateTime($StartTime).
131 '") AND (Time < "'.TimeToMysqlDateTime($EndTime).'") AND Measure='.$this->Data['Id'].' AND Level='.$Level);
132 $this->Data['Period'] = $TimeSegment;
133 $this->AddValue(array('Min' => $Point['Min'], 'Avg' => $Point['Avg'],
134 'Max' => $Point['Max']), $Level, $StartTime + ($EndTime - $StartTime) / 2);
135 }
136 }
137 }
138 }
139
140 function Interpolation($X1, $Y1, $X2, $Y2, $X)
141 {
142 $Y = ($Y2 - $Y1) / ($X2 - $X1) * ($X - $X1) + $Y1;
143 return $Y;
144 }
145
146 function ComputeOneValue($LeftTime, $RightTime, $Values, $Level)
147 {
148 $NewValue = array('Min' => +1000000000000000000, 'Avg' => 0, 'Max' => -1000000000000000000);
149
150 // Trim outside parts
151 foreach ($this->ValueTypes as $ValueType)
152 {
153 $Values[0][$ValueType] = $this->Interpolation($Values[0]['Time'], $Values[0][$ValueType], $Values[1]['Time'], $Values[1][$ValueType], $LeftTime);
154 }
155 $Values[0]['Time'] = $LeftTime;
156 foreach ($this->ValueTypes as $ValueType)
157 {
158 $Values[count($Values) - 1][$ValueType] = $this->Interpolation($Values[count($Values) - 2]['Time'], $Values[count($Values) - 2][$ValueType],
159 $Values[count($Values) - 1]['Time'], $Values[count($Values) - 1][$ValueType], $RightTime);
160 }
161 $Values[count($Values) - 1]['Time'] = $RightTime;
162
163 // Perform computation
164 foreach ($this->ValueTypes as $ValueType)
165 {
166 // Compute new value
167 for ($I = 0; $I < (count($Values) - 1); $I++)
168 {
169 if ($ValueType == 'Avg')
170 {
171 if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled']);
172 else if ($this->Differential == 0)
173 {
174 $NewValue[$ValueType] = $NewValue[$ValueType] + ($Values[$I + 1]['Time'] - $Values[$I]['Time']) *
175 (($Values[$I + 1][$ValueType] - $Values[$I][$ValueType]) / 2 + $Values[$I][$ValueType]);
176 } else
177 {
178 $NewValue[$ValueType] = $NewValue[$ValueType] + ($Values[$I + 1]['Time'] - $Values[$I]['Time']) *
179 (($Values[$I + 1][$ValueType] - $Values[$I][$ValueType]) / 2);
180 }
181 }
182 else if ($ValueType == 'Max')
183 {
184 if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled'])
185 {
186 if (0 > $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
187 } else
188 {
189 if ($this->Differential == 0)
190 {
191 if ($Values[$I + 1][$ValueType] > $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I + 1][$ValueType];
192 } else {
193 $Difference = $Values[$I + 1][$ValueType] - $Values[$I][$ValueType];
194 if ($Difference > $NewValue[$ValueType]) $NewValue[$ValueType] = $Difference;
195 }
196 }
197 }
198 else if ($ValueType == 'Min')
199 {
200 if ($Values[$I + 1]['Continuity'] == $this->Data['ContinuityEnabled'])
201 {
202 if (0 < $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
203 } else
204 {
205 if ($this->Differential == 0)
206 {
207 if ($Values[$I + 1][$ValueType] < $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I + 1][$ValueType];
208 } else {
209 $Difference = $Values[$I + 1][$ValueType] - $Values[$I][$ValueType];
210 if ($Difference < $NewValue[$ValueType]) $NewValue[$ValueType] = $Difference;
211 }
212 }
213 }
214 }
215 $NewValue[$ValueType] = $NewValue[$ValueType];
216 }
217 //if (($RightTime - $LeftTime) > 0)
218 if ($this->Data['Cumulative'] == 0)
219 {
220 $NewValue['Avg'] = $NewValue['Avg'] / ($RightTime - $LeftTime);
221 }
222 return $NewValue;
223 }
224
225 function GetTimeRange($Level)
226 {
227 // Get first and last time
228 $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time LIMIT 1');
229 if ($Result->num_rows > 0)
230 {
231 $Row = $Result->fetch_assoc();
232 $AbsoluteLeftTime = MysqlDateTimeToTime($Row['Time']);
233 } else $AbsoluteLeftTime = 0;
234
235 $Result = $this->Database->select($this->Data['DataTable'], '*', 'Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 1');
236 if ($Result->num_rows > 0)
237 {
238 $Row = $Result->fetch_assoc();
239 $AbsoluteRightTime = MysqlDateTimeToTime($Row['Time']);
240 } else $AbsoluteRightTime = 0;
241
242 if ($this->Debug)
243 {
244 echo('AbsoluteLeftTime: '.$AbsoluteLeftTime.'('.TimeToMysqlDateTime($AbsoluteLeftTime).')<br>');
245 echo('AbsoluteRightTime: '.$AbsoluteRightTime.'('.TimeToMysqlDateTime($AbsoluteRightTime).')<br>');
246 }
247 return array('Left' => $AbsoluteLeftTime, 'Right' => $AbsoluteRightTime);
248 }
249
250 function LoadRightSideValue($Level, $Time)
251 {
252 $Result = array();
253 $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time ASC LIMIT 1');
254 if ($DbResult->num_rows > 0)
255 {
256 $Row = $DbResult->fetch_assoc();
257 $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
258 return array($Row);
259 } else
260 {
261 //$Time = $Values[count($Values)-1]['Time'] + 60;
262 //array_push($Values, array('Time' => $Time, 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
263 $Result[] = array('Time' => ($Time + $this->TimeSegment($this->Data['Period'], $Level)), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0);
264 $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time < "'.
265 TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time DESC LIMIT 1');
266 if ($DbResult->num_rows > 0)
267 {
268 $Row = $DbResult->fetch_assoc();
269 array_unshift($Result, array('Time' => (MysqlDateTimeToTime($Row['Time']) + 10), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
270 }
271 // if ($Debug) print_r($Result);
272 return $Result;
273 }
274 }
275
276 function LoadLeftSideValue($Level, $Time)
277 {
278 $Result = array();
279 $DbResult = $this->Database->select($this->Data['DataTable'], '*', '(Time < "'.
280 TimeToMysqlDateTime($Time).'") AND (Measure='.$this->Data['Id'].') AND (Level='.$Level.') ORDER BY Time DESC LIMIT 1');
281 if ($DbResult->num_rows > 0)
282 {
283 $Row = $DbResult->fetch_assoc();
284 $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
285 return array($Row);
286 } else
287 {
288 //$Time = $Values[0]['Time'] - 60;
289 //array_unshift($Values, array('Time' => $Time, 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
290 if ($this->Debug) echo($this->TimeSegment($this->Data['Period'], $Level));
291 $Result[] = array('Time' => ($Time - $this->TimeSegment($this->Data['Period'], $Level)), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0);
292
293 $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.TimeToMysqlDateTime($Time).'" AND Measure='.$this->Data['Id'].' AND Level='.$Level.' ORDER BY Time ASC LIMIT 1');
294 if ($DbResult->num_rows > 0)
295 {
296 $Row = $DbResult->fetch_assoc();
297 array_push($Result, array('Time' => (MysqlDateTimeToTime($Row['Time']) - 10), 'Min' => 0, 'Avg' => 0, 'Max' => 0, 'Continuity' => 0));
298 }
299 return $Result;
300 }
301 }
302
303 function GetValues($TimeFrom, $TimeTo, $Level)
304 {
305 if ($this->Debug) echo('TimeFrom: '.$TimeFrom.'('.TimeToMysqlDateTime($TimeFrom).')<br>');
306 if ($this->Debug) echo('TimeTo: '.$TimeTo.'('.TimeToMysqlDateTime($TimeTo).')<br>');
307
308 //$AbsoluteTime = GetTimeRange($MeasureId);
309
310 // if (($TimeFrom > $AbsoluteLeftTime) and ($TimeStart < $AbsoluteRightTime) and
311 // ($TimeTo > $AbsoluteLeftTime) and ($TimeTo < $AbsoluteRightTime))
312 // {
313
314 // Load values in time range
315 $Result = $this->Database->select($this->Data['DataTable'], 'Time, Min, Avg, Max, Continuity', '(Time > "'.
316 TimeToMysqlDateTime($TimeFrom).'") AND (Time < "'.
317 TimeToMysqlDateTime($TimeTo).'") AND (Measure='.
318 $this->Data['Id'].') AND (Level='.$Level.') ORDER BY Time');
319 // echo($Level.' '.TimeToMysqlDateTime($TimeFrom).' '.TimeToMysqlDateTime($TimeTo));
320 $Values = array();
321 // echo(DB_NumRows());
322 // $III = 0;
323 while ($Row = $Result->fetch_assoc())
324 {
325 // echo($III.' '.$Row['Time'].' '.memory_get_usage().',');
326 // $III++;
327 $Values[] = array('Time' => MysqlDateTimeToTime($Row['Time']), 'Min' => $Row['Min'],
328 'Avg' => $Row['Avg'], 'Max' => $Row['Max'], 'Continuity' => $Row['Continuity']);
329 }
330 // array_pop($Values);
331 if ($this->Debug) echo('Item count: '.count($Values));
332
333 $Points = array();
334 if (count($Values) > 0)
335 {
336 $Values = array_merge($this->LoadLeftSideValue($Level, $TimeFrom), $Values, $this->LoadRightSideValue($Level, $TimeTo));
337 $StartIndex = 0;
338 $Points = array();
339 if ($this->Debug) print_r($Values);
340 for ($I = 0; $I < $this->DivisionCount; $I++)
341 {
342 $TimeStart = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * $I;
343 $TimeEnd = $TimeFrom + (($TimeTo - $TimeFrom) / $this->DivisionCount) * ($I + 1);
344 if ($this->Debug) echo('TimeEnd '.$I.': '.$TimeEnd.'('.TimeToMysqlDateTime($TimeEnd).')<br>');
345
346 $EndIndex = $StartIndex;
347 while (($Values[$EndIndex]['Time'] < $TimeEnd) and ($EndIndex < count($Values))) $EndIndex = $EndIndex + 1;
348 //while (($Values[$EndIndex]['Time'] < $TimeEnd)) $EndIndex = $EndIndex + 1;
349 $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
350 $Points[] = $this->ComputeOneValue($TimeStart, $TimeEnd, $SubValues, $Level);
351 $StartIndex = $EndIndex - 1;
352 }
353 if ($this->Debug) print_r($Points);
354 } else $Points[] = array('Min' => 0, 'Avg' => 0, 'Max' => 0);
355 return $Points;
356 }
357
358 function RebuildMeasureCache()
359 {
360 echo('Veličina '.$this->Data['Name']."<br>\n");
361 if ($this->Data['Continuity'] == 0) $this->Data['ContinuityEnabled'] = 0; // non continuous
362 else $this->Data['ContinuityEnabled'] = 2; // continuous graph
363
364 // Clear previous items
365 $DbResult = $this->Database->select($this->Data['DataTable'], 'COUNT(*)', 'Level > 0 AND Measure='.$this->Data['Id']);
366 $Row = $DbResult->fetch_row();
367 echo("Mazu starou cache (".$Row[0]." polozek)...");
368 $this->Database->delete($this->Data['DataTable'], 'Level > 0 AND Measure='.$this->Data['Id']);
369 echo("<br>\n");
370
371 for ($Level = 1; $Level <= $this->MaxLevel; $Level++)
372 {
373 echo('Uroven '.$Level."<br>\n");
374 $TimeRange = $this->GetTimeRange($Level - 1);
375 $TimeSegment = $this->TimeSegment($this->Data['Period'], $Level);
376 $StartTime = $this->AlignTime($TimeRange['Left'], $TimeSegment) - $TimeSegment;
377 $EndTime = $this->AlignTime($TimeRange['Right'], $TimeSegment);
378 $BurstCount = 500;
379 echo('For 0 to '.round(($EndTime - $StartTime) / $TimeSegment / $BurstCount)."<br>\n");
380 for ($I = 0; $I <= round(($EndTime - $StartTime) / $TimeSegment / $BurstCount); $I++)
381 {
382 echo($I.' ');
383 $StartTime2 = $StartTime + $I * $BurstCount * $TimeSegment;
384 $EndTime2 = $StartTime + ($I + 1) * $BurstCount * $TimeSegment;
385 $Values = array();
386 $DbResult = $this->Database->select($this->Data['DataTable'], '*', 'Time > "'.
387 TimeToMysqlDateTime($StartTime2).'" AND Time < "'.TimeToMysqlDateTime($EndTime2).'" AND Measure='.$this->Data['Id'].' AND Level='.($Level - 1).' ORDER BY Time');
388 while ($Row = $DbResult->fetch_assoc())
389 {
390 $Row['Time'] = MysqlDateTimeToTime($Row['Time']);
391 $Values[] = $Row;
392 }
393
394 if (count($Values) > 0)
395 {
396 $Values = array_merge($this->LoadLeftSideValue($Level - 1, $StartTime2),
397 $Values, $this->LoadRightSideValue($Level - 1, $this->Data, $EndTime2));
398
399 $StartIndex = 0;
400 for ($B = 0; $B < $BurstCount; $B++)
401 {
402 echo('.');
403 $StartTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * $B;
404 $EndTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * ($B + 1);
405
406 $EndIndex = $StartIndex;
407 while ($Values[$EndIndex]['Time'] < $EndTime3) $EndIndex = $EndIndex + 1;
408 $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
409 if (count($SubValues) > 2)
410 {
411 $Point = $this->ComputeOneValue($StartTime3, $EndTime3, $SubValues, $Level);
412 $Continuity = $SubValues[1]['Continuity'];
413 $this->Database->insert($this->Data['DataTable'], array('Level' => $Level,
414 'Measure' => $this->Data['Id'], 'Min' => $Point['Min'], 'Avg' => $Point['avg'],
415 'max' => $Point['Max'], 'Continuity' => $Continuity, 'Time' =>
416 TimeToMysqlDateTime($StartTime3 + ($EndTime3 - $StartTime3) / 2)));
417 }
418 $StartIndex = $EndIndex - 1;
419 }
420 }
421 // Load values in time range
422 //array_pop($NextValues);
423 }
424 echo("Uroven dokoncena<br>\n");
425 $DbResult = $this->Database->select($this->Data['DataTable'], 'COUNT(*)', 'Level='.$Level.' AND Measure='.$this->Data['Id']);
426 $Row = $DbResult->fetch_row();
427 echo("Vloženo ".$Row[0]." položek.<br>\n");
428 }
429 }
430
431 function RebuildAllMeasuresCache()
432 {
433 // echo("Vytvarim novou cache...\n");
434 // Load measures
435 $Measures = array();
436 $Result = $this->Database->select('Measure', '*');
437 while ($Row = $Result->fetch_assoc())
438 {
439 $Measure = new Measure($this->System);
440 $Measure->Load($Row['Id']);
441 }
442
443 foreach ($Measures as $Measure)
444 {
445 $Measure->RebuildMeasureCache();
446 echo('Velicina dokoncena<br>');
447 }
448 }
449
450 function InitMeasureDataTable()
451 {
452 $this->Database->query('CREATE TABLE `Data'.$this->Data['Name'].'` (
453`Time` TIMESTAMP NOT NULL ,
454`Avg` '.$this->Data['DataType'].' NOT NULL ,
455`Continuity` BOOL NOT NULL
456) ENGINE = MYISAM ;');
457
458 $this->Database->query('CREATE TABLE `Data'.$this->Data['Name'].'Cache` (
459`Time` TIMESTAMP NOT NULL ,
460`Level` TINYINT NOT NULL ,
461`Min` '.$this->Data['DataType'].' NOT NULL ,
462`Avg` '.$this->Data['DataType'].' NOT NULL ,
463`Max` '.$this->Data['DataType'].' NOT NULL ,
464`Continuity` BOOL NOT NULL
465) ENGINE = MYISAM ;');
466 }
467}
Note: See TracBrowser for help on using the repository browser.