PageRenderTime 9ms CodeModel.GetById 2ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/details/smooth.php

http://showslow.googlecode.com/
PHP | 53 lines | 35 code | 7 blank | 11 comment | 10 complexity | 6e69b2f86e7096b121ff08a53ceb04af MD5 | raw file
 1<?php
 2#
 3# Smooths a series of data rows
 4#
 5# @rows - reference to array of rows each of which is an associative array of different values to smooth
 6# @to_smooth - array of metrics to smooth
 7# @size = distance between the value and the boundary - full range will be from x - size to x + size
 8#
 9# Return: rows are updated inplace - nothing is returned
10#
11function smooth(&$rows, $to_smooth) {
12	global $smoothDistance;
13
14	$total = count($rows);
15
16	for ($i = 0; $i <= $total - 1; $i++) {
17
18		# from and to define windown boudaries
19		if ($smoothDistance * 2 + 1 > $total) { # window is bigger then the array
20			$from = 0;
21			$to = $total - 1;
22		} else if ($i < $smoothDistance) {
23			$from = 0; # window starts at the beginnning of array
24			$to = $smoothDistance * 2;
25		} else if ($i > $total - 1 - $smoothDistance) {
26			$to = $total - 1; # widnow ends at the end of array
27			$from = $total - $smoothDistance * 2 - 1;
28		} else {
29			$from = $i - $smoothDistance;
30			$to = $i + $smoothDistance;
31		}
32
33		# j iterates through the window
34		for ($j = $from; $j <= $to; $j++) {
35			foreach ($to_smooth as $metric) {
36				if (!array_key_exists($metric.'_avg', $rows[$i])) {
37					$rows[$i][$metric.'_avg'] = 0;
38				}
39
40				$rows[$i][$metric.'_avg'] += $rows[$j][$metric];
41			}
42		}
43	}
44
45	$windowsize = ($smoothDistance * 2 + 1 > $total) ? $total : ($smoothDistance * 2 + 1);
46
47	for ($i = 0; $i <= $total - 1; $i++) {
48		foreach ($to_smooth as $metric) {
49			$rows[$i][$metric] = sprintf('%.2f', $rows[$i][$metric.'_avg'] / $windowsize);
50			unset($rows[$i][$metric.'_avg']);
51		}
52	}
53}