Experiment about making graphs of route trips
Experiment about making graphs of route trips

<?php <?php
$service_periods = Array( $service_periods = Array(
'sunday', 'sunday',
'saturday', 'saturday',
'weekday' 'weekday'
); );
function getServiceOverride() { function getServiceOverride() {
global $conn; global $conn;
$query = "Select * from calendar_dates where date = '".date("Ymd")."' and exception_type = '1'"; $query = "Select * from calendar_dates where date = '".date("Ymd")."' and exception_type = '1'";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
function service_period() function service_period()
{ {
if (isset($_SESSION['service_period'])) return $_SESSION['service_period']; if (isset($_SESSION['service_period'])) return $_SESSION['service_period'];
$override = getServiceOverride(); $override = getServiceOverride();
if ($override['service_id']){ if ($override['service_id']){
return $override['service_id']; return $override['service_id'];
} }
   
switch (date('w')) { switch (date('w')) {
case 0: case 0:
return 'sunday'; return 'sunday';
case 6: case 6:
return 'saturday'; return 'saturday';
default: default:
return 'weekday'; return 'weekday';
} }
} }
  function midnight_seconds()
  {
  // from http://www.perturb.org/display/Perlfunc__Seconds_Since_Midnight.html
  if (isset($_SESSION['time'])) {
  $time = strtotime($_SESSION['time']);
  return (date("G", $time) * 3600) + (date("i", $time) * 60) + date("s", $time);
  }
  return (date("G") * 3600) + (date("i") * 60) + date("s");
  }
  function midnight_seconds_to_time($seconds)
  {
  if ($seconds > 0) {
  $midnight = mktime(0, 0, 0, date("n") , date("j") , date("Y"));
  return date("h:ia", $midnight + $seconds);
  }
  else {
  return "";
  }
  }
  ?>
   
?>  
<?php <?php
   
function getRoute($routeID) { function getRoute($routeID) {
  global $conn;
$query = "Select * from routes where route_id = '$routeID' LIMIT 1"; $query = "Select * from routes where route_id = '$routeID' LIMIT 1";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
function getRoutes() { function getRoutes() {
global $conn; global $conn;
$query = "Select * from routes order by route_short_name;"; $query = "Select * from routes order by route_short_name;";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesByNumber($routeNumber = "") { function getRoutesByNumber($routeNumber = "") {
global $conn; global $conn;
if ($routeNumber != "") { if ($routeNumber != "") {
$query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id = $query = "Select distinct routes.route_id,routes.route_short_name,routes.route_long_name,service_id from routes join trips on trips.route_id =
routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = '$routeNumber' order by route_short_name;"; routes.route_id join stop_times on stop_times.trip_id = trips.trip_id where route_short_name = '$routeNumber' order by route_short_name;";
} else { } else {
$query = "SELECT DISTINCT route_short_name from routes order by route_short_name"; $query = "SELECT DISTINCT route_short_name from routes order by route_short_name";
} }
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRouteNextTrip($routeID) { function getRouteNextTrip($routeID) {
global $conn; global $conn;
$query = "select * from routes join trips on trips.route_id = routes.route_id $query = "select * from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where join stop_times on stop_times.trip_id = trips.trip_id where
arrival_time > '".current_time()."' and routes.route_id = '$routeID' order by arrival_time > '".current_time()."' and routes.route_id = '$routeID' order by
arrival_time limit 1"; arrival_time limit 1";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$r = pg_fetch_assoc($result); $r = pg_fetch_assoc($result);
// past last trip of the day special case // past last trip of the day special case
if (sizeof($r) == 0) { if (sizeof($r) == 0) {
$query = "select * from routes join trips on trips.route_id = routes.route_id $query = "select * from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' order by
arrival_time DESC limit 1"; arrival_time DESC limit 1";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$r = pg_fetch_assoc($result); $r = pg_fetch_assoc($result);
} }
return $r; return $r;
} }
function getTimeInterpolatedRouteAtStop($routeID, $stop_id) function getTimeInterpolatedRouteAtStop($routeID, $stop_id)
{ {
$nextTrip = getRouteNextTrip($routeID); $nextTrip = getRouteNextTrip($routeID);
if ($nextTrip['trip_id']){ if ($nextTrip['trip_id']){
foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) { foreach (getTimeInterpolatedTrip($nextTrip['trip_id']) as $tripStop) {
if ($tripStop['stop_id'] == $stop_id) return $tripStop; if ($tripStop['stop_id'] == $stop_id) return $tripStop;
} }
} }
return Array(); return Array();
} }
function getRouteTrips($routeID) { function getRouteTrips($routeID) {
global $conn; global $conn;
$query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id $query = "select routes.route_id,trips.trip_id,service_id,arrival_time, stop_id, stop_sequence from routes join trips on trips.route_id = routes.route_id
join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' and stop_sequence = '1' order by join stop_times on stop_times.trip_id = trips.trip_id where routes.route_id = '$routeID' and stop_sequence = '1' order by
arrival_time "; arrival_time ";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
function getRoutesByDestination($destination = "", $service_period = "") { function getRoutesByDestination($destination = "", $service_period = "") {
global $conn; global $conn;
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($destination != "") { if ($destination != "") {
$query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id $query = "SELECT DISTINCT trips.route_id,route_short_name,route_long_name, service_id
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE route_long_name = '$destination' AND service_id='$service_period' order by route_short_name"; WHERE route_long_name = '$destination' AND service_id='$service_period' order by route_short_name";
} else { } else {
$query = "SELECT DISTINCT route_long_name $query = "SELECT DISTINCT route_long_name
FROM stop_times join trips on trips.trip_id = FROM stop_times join trips on trips.trip_id =
stop_times.trip_id join routes on trips.route_id = routes.route_id stop_times.trip_id join routes on trips.route_id = routes.route_id
WHERE service_id='$service_period' order by route_long_name"; WHERE service_id='$service_period' order by route_long_name";
} }
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesBySuburb($suburb, $service_period = "") { function getRoutesBySuburb($suburb, $service_period = "") {
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
global $conn; global $conn;
$query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name $query = "SELECT DISTINCT service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times join trips on trips.trip_id = stop_times.trip_id FROM stop_times join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE zone_id LIKE '%$suburb;%' AND service_id='$service_period' ORDER BY route_short_name"; WHERE zone_id LIKE '%$suburb;%' AND service_id='$service_period' ORDER BY route_short_name";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
   
function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) { function getRoutesNearby($lat, $lng, $limit = "", $distance = 500) {
   
if ($service_period == "") $service_period = service_period(); if ($service_period == "") $service_period = service_period();
if ($limit != "") $limit = " LIMIT $limit "; if ($limit != "") $limit = " LIMIT $limit ";
global $conn; global $conn;
$query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id, $query = "SELECT service_id,trips.route_id,route_short_name,route_long_name,min(stops.stop_id) as stop_id,
min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance min(ST_Distance(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), FALSE)) as distance
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE service_id='$service_period' WHERE service_id='$service_period'
AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE) AND ST_DWithin(position, ST_GeographyFromText('SRID=4326;POINT($lng $lat)'), $distance, FALSE)
group by service_id,trips.route_id,route_short_name,route_long_name group by service_id,trips.route_id,route_short_name,route_long_name
order by distance $limit"; order by distance $limit";
debug($query,"database"); debug($query,"database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_all($result); return pg_fetch_all($result);
} }
?> ?>
<?php <?php
function getTrip($tripID) function getTrip($tripID)
{ {
global $conn; global $conn;
$query = "Select * from trips $query = "Select * from trips
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
where trip_id = '$tripID' where trip_id = '$tripID'
LIMIT 1"; LIMIT 1";
debug($query, "database"); debug($query, "database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
return pg_fetch_assoc($result); return pg_fetch_assoc($result);
} }
function getTripShape() function getTripShape()
{ {
/* def handle_json_GET_tripstopTimes(self, params): /* def handle_json_GET_tripstopTimes(self, params):
schedule = self.server.schedule schedule = self.server.schedule
try: try:
trip = schedule.GetTrip(params.get('trip')) trip = schedule.GetTrip(params.get('trip'))
except KeyError: except KeyError:
# if a non-existent trip is searched for, the return nothing # if a non-existent trip is searched for, the return nothing
return return
time_stops = trip.GetTimeInterpolatedStops() time_stops = trip.GetTimeInterpolatedStops()
stops = [] stops = []
times = [] times = []
for arr,ts,is_timingpoint in time_stops: for arr,ts,is_timingpoint in time_stops:
stops.append(StopToTuple(ts.stop)) stops.append(StopToTuple(ts.stop))
times.append(arr) times.append(arr)
return [stops, times] return [stops, times]
def handle_json_GET_tripshape(self, params): def handle_json_GET_tripshape(self, params):
schedule = self.server.schedule schedule = self.server.schedule
try: try:
trip = schedule.GetTrip(params.get('trip')) trip = schedule.GetTrip(params.get('trip'))
except KeyError: except KeyError:
# if a non-existent trip is searched for, the return nothing # if a non-existent trip is searched for, the return nothing
return return
points = [] points = []
if trip.shape_id: if trip.shape_id:
shape = schedule.GetShape(trip.shape_id) shape = schedule.GetShape(trip.shape_id)
for (lat, lon, dist) in shape.points: for (lat, lon, dist) in shape.points:
points.append((lat, lon)) points.append((lat, lon))
else: else:
time_stops = trip.GetTimeStops() time_stops = trip.GetTimeStops()
for arr,dep,stop in time_stops: for arr,dep,stop in time_stops:
points.append((stop.stop_lat, stop.stop_lon)) points.append((stop.stop_lat, stop.stop_lon))
return points*/ return points*/
} }
function getTimeInterpolatedTrip($tripID, $range = "") function getTimeInterpolatedTrip($tripID, $range = "")
{ {
global $conn; global $conn;
$query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code, $query = "SELECT stop_times.trip_id,arrival_time,stop_times.stop_id,stop_lat,stop_lon,stop_name,stop_code,
stop_sequence,service_id,trips.route_id,route_short_name,route_long_name stop_sequence,service_id,trips.route_id,route_short_name,route_long_name
FROM stop_times FROM stop_times
join trips on trips.trip_id = stop_times.trip_id join trips on trips.trip_id = stop_times.trip_id
join routes on trips.route_id = routes.route_id join routes on trips.route_id = routes.route_id
join stops on stops.stop_id = stop_times.stop_id join stops on stops.stop_id = stop_times.stop_id
WHERE trips.trip_id = '$tripID' $range ORDER BY stop_sequence"; WHERE trips.trip_id = '$tripID' $range ORDER BY stop_sequence";
debug($query, "database"); debug($query, "database");
$result = pg_query($conn, $query); $result = pg_query($conn, $query);
if (!$result) { if (!$result) {
databaseError(pg_result_error($result)); databaseError(pg_result_error($result));
return Array(); return Array();
} }
$stopTimes = pg_fetch_all($result); $stopTimes = pg_fetch_all($result);
$cur_timepoint = Array(); $cur_timepoint = Array();
$next_timepoint = Array(); $next_timepoint = Array();
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
$rv = Array(); $rv = Array();
foreach ($stopTimes as $i => $stopTime) { foreach ($stopTimes as $i => $stopTime) {
if ($stopTime['arrival_time'] != "") { if ($stopTime['arrival_time'] != "") {
// is timepoint // is timepoint
$cur_timepoint = $stopTime; $cur_timepoint = $stopTime;
$distance_between_timepoints = 0.0; $distance_between_timepoints = 0.0;
$distance_traveled_between_timepoints = 0.0; $distance_traveled_between_timepoints = 0.0;
if ($i + 1 < sizeof($stopTimes)) { if ($i + 1 < sizeof($stopTimes)) {
$k = $i + 1; $k = $i + 1;
$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) { while ($stopTimes[$k]["arrival_time"] == "" && $k + 1 < sizeof($stopTimes)) {
$k += 1; $k += 1;
//echo "k".$k; //echo "k".$k;
$distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]); $distance_between_timepoints += distance($stopTimes[$k - 1]["stop_lat"], $stopTimes[$k - 1]["stop_lon"], $stopTimes[$k]["stop_lat"], $stopTimes[$k]["stop_lon"]);
} }
$next_timepoint = $stopTimes[$k]; $next_timepoint = $stopTimes[$k];
$rv[] = $stopTime; $rv[] = $stopTime;
} }
} }
else { else {
// is untimed point // is untimed point
//echo "i".$i; //echo "i".$i;
$distance_traveled_between_timepoints += distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]); $distance_traveled_between_timepoints += distance($stopTimes[$i - 1]["stop_lat"], $stopTimes[$i - 1]["stop_lon"], $stopTimes[$i]["stop_lat"], $stopTimes[$i]["stop_lon"]);
//echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>"; //echo "$distance_traveled_between_timepoints / $distance_between_timepoints<br>";
$distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints; $distance_percent = $distance_traveled_between_timepoints / $distance_between_timepoints;
if ($next_timepoint["arrival_time"] != "") { if ($next_timepoint["arrival_time"] != "") {
$total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]); $total_time = strtotime($next_timepoint["arrival_time"]) - strtotime($cur_timepoint["arrival_time"]);
//echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>"; //echo strtotime($next_timepoint["arrival_time"])." - ".strtotime($cur_timepoint["arrival_time"])."<br>";
$time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]); $time_estimate = ($distance_percent * $total_time) + strtotime($cur_timepoint["arrival_time"]);
$stopTime["arrival_time"] = date("H:i:s", $time_estimate); $stopTime["arrival_time"] = date("H:i:s", $time_estimate);
} else { } else {
$stopTime["arrival_time"] = $cur_timepoint["arrival_time"]; $stopTime["arrival_time"] = $cur_timepoint["arrival_time"];
} }
$rv[] = $stopTime; $rv[] = $stopTime;
//var_dump($rv); //var_dump($rv);
} }
} }
return