Labs Tidy up, depreciate old trip planner tester, promote myway balance/service alerts to main site
[busui.git] / myway / myway_timeliness_calculate.php
blob:a/myway/myway_timeliness_calculate.php -> blob:b/myway/myway_timeliness_calculate.php
<?php <?php
   
  /*
  * Copyright 2010,2011 Alexander Sadleir
   
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
   
  http://www.apache.org/licenses/LICENSE-2.0
   
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  */
include ('../include/common.inc.php'); include ('../include/common.inc.php');
include_header("MyWay Delta Calculate", "mywayDeltaCalc"); include_header("MyWay Delta Calculate", "mywayDeltaCalc");
flush(); flush();
ob_flush(); ob_flush();
function abssort($a, $b)  
{ function abssort($a, $b) {
if ($a['timeDiff'] == $b['timeDiff']) { if ($a['timeDiff'] == $b['timeDiff']) {
return 0; return 0;
} }
return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1; return (abs($a['timeDiff']) < abs($b['timeDiff'])) ? -1 : 1;
} }
   
//collect all observation not in delta //collect all observation not in delta
$query = "select * from myway_observations INNER JOIN myway_stops $query = "select * from myway_observations INNER JOIN myway_stops
ON myway_observations.myway_stop=myway_stops.myway_stop INNER JOIN myway_routes ON myway_observations.myway_stop=myway_stops.myway_stop
ON myway_observations.myway_route=myway_routes.myway_route  
WHERE observation_id NOT IN WHERE observation_id NOT IN
( (
SELECT observation_id SELECT observation_id
FROM myway_timingdeltas FROM myway_timingdeltas
)"; )";
debug($query, "database"); debug($query, "database");
$query = $conn->prepare($query); $query = $conn->prepare($query);
$query->execute(); $query->execute();
if (!$query) { if (!$query) {
databaseError($conn->errorInfo()); databaseError($conn->errorInfo());
return Array(); return Array();
} }
$uncalcdObservations = $query->fetchAll(); $uncalcdObservations = $query->fetchAll();
//Display count //Display count
echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>"; echo "<h3>" . sizeof($uncalcdObservations) . " observations not yet processed</h2>";
//foreach observation not in delta //foreach observation not in delta
foreach ($uncalcdObservations as $obsv) { foreach ($uncalcdObservations as $obsv) {
//var_dump($obsv); //var_dump($obsv);
echo "<h3>Observation {$obsv['observation_id']}:</h1> echo "<h3>Observation {$obsv['observation_id']}:</h1>
<small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>"; <small>{$obsv['myway_stop']} @ {$obsv['time']} on {$obsv['myway_route']}</small><br>";
if ($obsv["stop_code"] == "") { if ($obsv["stop_id"] == "") {
echo "error, stop '{$obsv['myway_stop']}' unknown"; echo "error, stop '{$obsv['myway_stop']}' unknown";
continue; continue;
} }
if ($obsv["route_full_name"] == "") { // convert timestamp into time of day and date
echo "error, route '{$obsv['myway_route']}' unknown";  
continue;  
}  
// convert timestamp into time of day and date  
// timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html // timezones from http://www.postgresql.org/docs/8.0/static/datetime-keywords.html
$time = date("H:i:s", strtotime($obsv['time'])); $time = date("H:i:s", strtotime($obsv['time']));
$time_tz = date("H:i:s", strtotime($obsv['time']))." AESST"; $time_tz = date("H:i:s", strtotime($obsv['time'])) . " AESST";
$search_time = date("H:i:s", strtotime($obsv['time'])-(30*60)); // 30 minutes margin $search_time = date("H:i:s", strtotime($obsv['time']) - (30 * 60)); // 30 minutes margin
$date = date("c", strtotime($obsv['time'])); $date = date("c", strtotime($obsv['time']));
$timing_period = service_period(strtotime($date)); $timing_period = service_period(strtotime($date));
$potentialStops = getStopsByStopCode($obsv["stop_code"], $obsv["stop_street"]); $potentialStops = Array(getStop($obsv["stop_id"]));
//:get myway_stops records //:get myway_stops records
//:search by starts with stopcode and starts with street if street is not null //:search by starts with stopcode and starts with street if street is not null
//no result, skip and display error //no result, skip and display error
if (sizeof($potentialStops) < 1) { if (sizeof($potentialStops) < 1) {
echo "error, potential stops for stopcode {$obsv["stop_code"]} street {$obsv["stop_street"]} unknown"; echo "error, potential stops for stopid {$obsv["stop_id"]} unknown";
continue; continue;
} }
//print out stops //print out stops
echo "Matched stops: "; echo "Matched stops: ";
foreach ($potentialStops as $potentialStop) echo $potentialStop['stop_code'] . " "; foreach ($potentialStops as $potentialStop) {
echo "<br>"; echo $potentialStop['stop_id'] . " " . $potentialStop['stop_name'] . " ";
//:get myway_route record }
//no result, skip and display error echo "<br>";
//print out route //:get myway_route record
$potentialRoute = getRouteByFullName($obsv["route_full_name"]); //no result, skip and display error
if ($potentialRoute["route_short_name"] == "") { //print out route
echo "error, route '{$obsv["route_full_name"]}' unknown"; $potentialRoutes = getRoutesByShortName(preg_replace("/[A-Z]/", "", $obsv["myway_route"]));
continue; if (sizeof($potentialRoutes) < 1) {
} echo "error, route '{$obsv["myway_route"]}' unknown";
echo "Matched route: {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>"; continue;
$timeDeltas = Array(); }
foreach ($potentialStops as $potentialStop) { $timeDeltas = Array();
$stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period); foreach ($potentialRoutes as $potentialRoute) {
$foundRoute = Array(); echo "Matched route: {$potentialRoute['route_id']} {$potentialRoute['route_short_name']}{$potentialRoute['route_long_name']} {$timing_period}<br>";
foreach ($stopRoutes as $stopRoute) { foreach ($potentialStops as $potentialStop) {
//Check if this route stops at each stop $stopRoutes = getStopRoutes($potentialStop['stop_id'], $timing_period);
if ($stopRoute['route_short_name'] . $stopRoute['route_long_name'] == $obsv["route_full_name"]) { $foundRoute = Array();
echo "Matching route {$stopRoute['route_id']} found at {$potentialStop['stop_code']}<br>"; foreach ($stopRoutes as $stopRoute) {
$foundRoute = $stopRoute; //Check if this route stops at each stop
//if does get tripstoptimes for this route if ($stopRoute['route_id'] == $potentialRoute['route_id']) {
$trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time); echo "Matching route {$stopRoute['route_id']} found at stop #{$potentialStop['stop_id']}<br>";
foreach ($trips as $trip) { $foundRoute = $stopRoute;
//echo $trip['route_id']." ".$stopRoute['route_id'].";"; //if does get tripstoptimes for this route
if ($trip['route_id'] == $stopRoute['route_id']) { $trips = getStopTrips($potentialStop['stop_id'], $timing_period, $search_time);
$timedTrip = getTimeInterpolatedTripAtStop($trip['trip_id'], $trip['stop_sequence']); foreach ($trips as $trip) {
$actual_time = strtotime($time); //echo $trip['route_id']." ".$stopRoute['route_id'].";";
$trip_time = strtotime($timedTrip['arrival_time']); if ($trip['route_id'] == $stopRoute['route_id']) {
$timeDiff = $actual_time - $trip_time; $timedTrip = getTripAtStop($trip['trip_id'], $trip['stop_sequence']);
//work out time delta, put into array with index of delta $actual_time = strtotime($time);
$timeDeltas[] = Array( $trip_time = strtotime($timedTrip['arrival_time']);
"timeDiff" => $timeDiff, $timeDiff = $actual_time - $trip_time;
"stop_code" => $potentialStop['stop_code'], //work out time delta, put into array with index of delta
"stop_sequence" => $timedTrip['stop_sequence'] $timeDeltas[] = Array(
); "timeDiff" => $timeDiff,
echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_code']} (#{$potentialStop['stop_id']}, sequence #{$trip['stop_sequence']})<br>"; "stop_id" => $potentialStop['stop_id'],
echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>"; "stop_sequence" => $trip['stop_sequence'],
} "route_id" => $trip['route_id']
} );
break; // because have found route echo "Found trip {$trip['trip_id']} at stop {$potentialStop['stop_id']} (#{$potentialStop['stop_name']}, sequence #{$trip['stop_sequence']})<br>";
  echo "Arriving at {$timedTrip['arrival_time']}, difference of " . round($timeDiff / 60, 2) . " minutes<br>";
} }
} }
if (sizeof($foundRoute) < 1) { break; // because have found route
//print out that stops/does not stop }
echo "No matching routes found at {$potentialStop['stop_code']}<br>"; }
var_dump($stopRoutes); if (sizeof($foundRoute) < 1) {
flush(); //print out that stops/does not stop
  echo "No matching routes found at {$potentialStop['stop_id']}<br>";
} //var_dump($stopRoutes);
} flush();
// lowest delta is recorded delta }
usort($timeDeltas, "abssort"); }
$lowestDelta = $timeDeltas[0]["timeDiff"]; }
if (sizeof($timeDeltas) != 0) {  
echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>"; // lowest delta is recorded delta
$observation_id = $obsv['observation_id']; usort($timeDeltas, "abssort");
$route_full_name = $obsv['route_full_name']; $lowestDelta = $timeDeltas[0]["timeDiff"];
$stop_code = $timeDeltas[0]["stop_code"]; if (sizeof($timeDeltas) != 0) {
$stop_sequence = $timeDeltas[0]["stop_sequence"]; echo "Lowest difference of " . round($lowestDelta / 60, 2) . " minutes will be recorded for this observation<br>";
$stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_full_name, stop_code, timing_delta, time, date, timing_period, stop_sequence)  
values (:observation_id, :route_full_name, :stop_code, :timing_delta, :time, :date, :timing_period, :stop_sequence)"); $observation_id = $obsv['observation_id'];
$stmt->bindParam(':observation_id', $observation_id); $route_id = $timeDeltas[0]["route_id"];
$stmt->bindParam(':route_full_name', $route_full_name); $stop_id = $timeDeltas[0]["stop_id"];
$stmt->bindParam(':stop_code', $stop_code); $stop_sequence = $timeDeltas[0]["stop_sequence"];
$stmt->bindParam(':timing_delta', $lowestDelta); $stmt = $conn->prepare("insert into myway_timingdeltas (observation_id, route_id, stop_id, timing_delta, time, date, timing_period, stop_sequence)
$stmt->bindParam(':time', $time_tz); values (:observation_id, :route_id, :stop_id, :timing_delta, :time, :date, :timing_period, :stop_sequence)");
$stmt->bindParam(':date', $date); $stmt->bindParam(':observation_id', $observation_id);
$stmt->bindParam(':timing_period', $timing_period); $stmt->bindParam(':route_id', $route_id);
$stmt->bindParam(':stop_sequence', $stop_sequence); $stmt->bindParam(':stop_id', $stop_id);
// insert a record $stmt->bindParam(':timing_delta', $lowestDelta);
$stmt->execute(); $stmt->bindParam(':time', $time_tz);
if ($stmt->rowCount() > 0) { $stmt->bindParam(':date', $date);
echo "Recorded.<br>"; $stmt->bindParam(':timing_period', $timing_period);
} $stmt->bindParam(':stop_sequence', $stop_sequence);
var_dump($conn->errorInfo()); // insert a record
flush(); $stmt->execute();
} if ($stmt->rowCount() > 0) {
flush(); echo "Recorded.<br>";
  }
  var_dump($conn->errorInfo());
  flush();
  }
  flush();
} }