<?php

// function to determine time_period at which data is held
// $array is expected to be an array of time values
function get_time_period($timesteps){

	$median = median($timesteps);
	$mode = mode($timesteps);
	$mean = mean($timesteps);
	$stddev = std_dev($timesteps);

	// If mode and median are within 2% return their average
	if(get_tolerance($median,$mode) < 0.02){
		return ($mode + $median) / 2;
	}else{ // If all else fails return mean
		return $mean;
	}
}


function median($array){
	rsort($array);
    $middle = round(count($array) / 2);
    return $array[$middle-1]; 
}

function mean($array){
	if(count($array) != 0){
		return array_sum($array)/count($array);
	}else{
		return 0;
	}
}

function mode($array){
	$v = array_count_values($array);
    arsort($v);
    foreach($v as $k => $v){$total = $k; break;} 
	return $total;
}

function variance($aValues, $bSample = false){
	$fMean = array_sum($aValues) / count($aValues);
	$fVariance = 0.0;
	foreach ($aValues as $i)
	{
	$fVariance += pow($i - $fMean, 2);
	}
	$fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) );
	return $fVariance;
}

function std_dev($aValues, $bSample = false){
	$fVariance = variance($aValues, $bSample);
	return (float) sqrt($fVariance);
}

function get_tolerance($v1,$v2){
	return abs($v1-$v2) / max($v1,$v2);
}
?>