Skip to content
Snippets Groups Projects
Commit cfff60e6 authored by Jiří Kalvoda's avatar Jiří Kalvoda
Browse files

QGIS UI

parent 2478490c
No related branches found
No related tags found
No related merge requests found
......@@ -134,7 +134,10 @@ class Client():
assert id in self.waiting_questions
q = self.waiting_questions[id]
del self.waiting_questions[id]
try:
q.future.set_result((head, data_raw))
except asyncio.exceptions.InvalidStateError:
pass # Probably task canceled
async def question(self, head, data):
id = self.id_alocator
......
......@@ -97,11 +97,10 @@ class TripHistory:
self.history = []
self.trip_json = None
async def load_stops(self):
self.stops = await gtfs.for_date(self.trip.date).get_stops_for_trip_id(self.trip.trip_id)
async def load_stops(self, data=None):
self.stops = await gtfs.for_date(self.trip.date).get_stops_for_trip_id(self.trip.trip_id, data=data)
async def load_gtfs_shape(self):
await self.load_stops()
self.gtfs_shape = await gtfs.for_date(self.trip.date).get_shape_for_trip_id(self.trip.trip_id)
......@@ -210,6 +209,12 @@ class TripHistory:
class TripPoint:
def __init__(self, json, capture_time):
self.json = json
self.trip = Trip(json["properties"]["trip"]["gtfs"]["trip_id"], capture_time.date())
self.origin_timestamp = datetime.datetime.fromisoformat(json['properties']['last_position']['origin_timestamp'])
self.start_timestamp = datetime.datetime.fromisoformat(json['properties']['trip']['start_timestamp'])
self.trip = Trip(json["properties"]["trip"]["gtfs"]["trip_id"], self.start_timestamp.date())
self.capture_time = capture_time
self.state_position = json['properties']['last_position']['state_position']
self.openapi_shape_dist_traveled = json['properties']['last_position']['shape_dist_traveled']
self.openapi_last_stop = json['properties']['last_position']['last_stop']
self.openapi_next_stop = json['properties']['last_position']['next_stop']
self.openapi_delay = json['properties']['last_position']['delay']
import sys
import time
from qgis.core import *
from qgis.gui import *
from qgis.PyQt.QtXml import QDomDocument, QDomElement
from qgis.PyQt.QtWidgets import *
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
import numpy as np
from matplotlib.backends.backend_qtagg import FigureCanvas
from matplotlib.backends.backend_qtagg import \
NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from utils import *
import communication
from communication import dt_to_path
import data_utils
from data_utils import Trip, TripPoint, HistoryPoint, TripHistory, shape_indexer, dist, unzip_parse
class Graph(QWidget):
closed = pyqtSignal()
def closeEvent(self, event):
self.closed.emit()
super().closeEvent(event)
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
canvas = FigureCanvas(Figure(figsize=(5, 3)))
layout.addWidget(canvas)
layout.addWidget(NavigationToolbar(canvas, self))
self.ax = canvas.figure.subplots()
class HistoryGraph(Graph):
def __init__(self, stops):
super().__init__()
xticks = []
xlabels = []
for stop in stops:
x = stop.shape_dist_traveled
self.ax.axvline(x=x, ymin=0, ymax=1, color="black")
#self.ax.xlabel(xy =(((x-x_bounds[0])/(x_bounds[1]-x_bounds[0])),1.01), xycoords='axes fraction', verticalalignment='top', horizontalalignment='center' , rotation = 270, text=stop.stop.name)
#self.ax.text(x, 0.5, stop.stop.name, rotation=90, transform=ax.get_xaxis_text1_transform(0)[0])
#self.ax.text(x, 0.5, stop.stop.name, rotation=90, transform=ax.get_xaxis_text1_transform(0)[0])
xticks.append(x)
xlabels.append(stop.stop.name)
self.ax.set_xticks(xticks)
self.ax.tick_params(rotation=45)
self.ax.set_xticklabels(xlabels)
self.stops_to_shape_dist_traveled = {stop.stop.id: stop.shape_dist_traveled for stop in stops}
def add_trip(self, th: TripHistory):
offsets = [ self.stops_to_shape_dist_traveled[stop.stop.id] - stop.shape_dist_traveled if stop.stop.id in self.stops_to_shape_dist_traveled else None for stop in th.stops ]
defined_offdets = [ x for x in offsets if x is not None ]
if len(defined_offdets) == 0:
print(offsets)
print("No intersection")
return
offset = sorted(defined_offdets)[len(defined_offdets)//2]
if any(abs(x-offset) > 0.01 for x in defined_offdets):
print("Match failed")
print([ x-offset for x in defined_offdets ])
x = []
y = []
for hp in th.history:
if hp.shape_point_dist_traveled is not None:
x.append(hp.shape_point_dist_traveled + offset)
y.append(hp.first_captured)
self._line, = self.ax.plot(x, y, 'o-', color="red")
x = []
y = []
for stop in th.stops:
x += 2*[stop.shape_dist_traveled + offset]
y += [stop.arrival_time, stop.departure_time]
self._line, = self.ax.plot(x, y, color="green")
for stop in th.stops:
x = 2*[stop.shape_dist_traveled + offset]
y = [stop.arrival_time, stop.departure_time]
self.ax.plot(x, y, 'o', color='green' if stop.stop.id in self.stops_to_shape_dist_traveled else 'blue')
self._line.figure.canvas.draw()
......@@ -25,6 +25,9 @@ class Trip:
class Stop:
id: int
name: str
lat: float
lon: float
@dataclass
class ShapePoint:
......@@ -56,7 +59,7 @@ class GtfsDay():
async def get_file(self, name, cache=False):
if name in self._file_cahce:
return self._file_cahce[name]
s = await self.data_getter(self.date, name)
s = await self.data_getter(datetime.datetime.combine(self.date, datetime.time()), name) # HACK: Date is not CBOR supported type
r = list(csv.DictReader(s.decode("utf-8").split("\n")))
if cache:
self._file_cahce[name] = r
......@@ -109,7 +112,7 @@ class GtfsDay():
d = await self.get_file("stops.txt")
if self.stops: return
self.stops = {
x["stop_id"]: Stop(x["stop_id"], x["stop_name"])
x["stop_id"]: Stop(x["stop_id"], x["stop_name"], float(x["stop_lat"]), float(x["stop_lon"]))
for x in d
}
......@@ -131,11 +134,14 @@ class GtfsDay():
h, m, s = map(int, val.split(":"))
return datetime.datetime.combine(self.date, datetime.time(0, 0, 0), local_timezone) + datetime.timedelta(hours=h, minutes=m, seconds=s) # hack for h > 23
async def get_stops_for_trip_id(self, trip_id):
async def get_stops_for_trip_id(self, trip_id, data=None):
await self.load_trips()
await self.load_stops()
if self.stops_for_trip:
return self.stops_for_trip[trip_id]
if data is not None:
d = list(csv.DictReader(data.decode("utf-8").split("\n")))
else:
eprint("LOADING STOPS FOR", trip_id, "(without cache)")
d = await self.get_file("stop_times.txt", cache=True)
return [ TripStop(
......
This diff is collapsed.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment