source: stat_functions.php@ 9

Last change on this file since 9 was 9, checked in by george, 18 years ago

Oprava funkce přidání nové položky

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