|
| 1 | +# |
| 2 | +# |
| 3 | +# MobilityData 2025 |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | +import csv |
| 17 | +import os |
| 18 | +from shared.helpers.logger import get_logger |
| 19 | + |
| 20 | + |
| 21 | +STOP_TIMES_FILE = "stop_times.txt" |
| 22 | +SHAPES_FILE = "shapes.txt" |
| 23 | +TRIPS_FILE = "trips.txt" |
| 24 | +ROUTES_FILE = "routes.txt" |
| 25 | +STOPS_FILE = "stops.txt" |
| 26 | +AGENCY_FILE = "agency.txt" |
| 27 | + |
| 28 | + |
| 29 | +class CsvCache: |
| 30 | + """ |
| 31 | + CsvCache provides cached access to GTFS CSV files in a specified working directory. |
| 32 | + It lazily loads and caches file contents as lists of dictionaries, and offers |
| 33 | + helper methods to retrieve relationships between routes, trips, stops, and shapes. |
| 34 | + It lazily loads because not all files are necessarily needed. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + workdir: str = "./workdir", |
| 40 | + logger=None, |
| 41 | + ): |
| 42 | + if logger: |
| 43 | + self.logger = logger |
| 44 | + else: |
| 45 | + self.logger = get_logger(CsvCache.__name__) |
| 46 | + |
| 47 | + self.workdir = workdir |
| 48 | + |
| 49 | + self.file_data = {} |
| 50 | + self.trip_to_stops = None |
| 51 | + self.route_to_trip = None |
| 52 | + self.route_to_shape = None |
| 53 | + self.stop_to_route = None |
| 54 | + self.stop_to_coordinates = None |
| 55 | + |
| 56 | + self.logger.info("Using work directory: %s", self.workdir) |
| 57 | + |
| 58 | + def get_path(self, filename: str) -> str: |
| 59 | + return os.path.join(self.workdir, filename) |
| 60 | + |
| 61 | + def get_file(self, filename) -> list[dict]: |
| 62 | + if self.file_data.get(filename) is None: |
| 63 | + self.file_data[filename] = self._read_csv(self.get_path(filename)) |
| 64 | + return self.file_data[filename] |
| 65 | + |
| 66 | + def add_data(self, filename: str, data: list[dict]): |
| 67 | + self.file_data[filename] = data |
| 68 | + |
| 69 | + def _read_csv(self, filename) -> list[dict]: |
| 70 | + """ |
| 71 | + Reads the content of a CSV file and returns it as a list of dictionaries |
| 72 | + where each dictionary represents a row. |
| 73 | +
|
| 74 | + Parameters: |
| 75 | + filename (str): The file path of the CSV file to be read. |
| 76 | +
|
| 77 | + Raises: |
| 78 | + Exception: If there is an error during file opening or reading. The raised |
| 79 | + exception will include the original error message along with the file name. |
| 80 | +
|
| 81 | + Returns: |
| 82 | + list[dict]: A list of dictionaries, each representing a row in the CSV file. |
| 83 | + """ |
| 84 | + try: |
| 85 | + self.logger.debug("Loading %s", filename) |
| 86 | + with open(filename, newline="", encoding="utf-8") as f: |
| 87 | + return list(csv.DictReader(f)) |
| 88 | + except Exception as e: |
| 89 | + raise Exception(f"Failed to read CSV file {filename}: {e}") from e |
| 90 | + |
| 91 | + def get_trip_from_route(self, route_id): |
| 92 | + if self.route_to_trip is None: |
| 93 | + self.route_to_trip = {} |
| 94 | + for row in self.get_file(TRIPS_FILE): |
| 95 | + route_id = row["route_id"] |
| 96 | + trip_id = row["trip_id"] |
| 97 | + if trip_id: |
| 98 | + self.route_to_trip.setdefault(route_id, trip_id) |
| 99 | + return self.route_to_trip.get(route_id, "") |
| 100 | + |
| 101 | + def get_shape_from_route(self, route_id) -> str: |
| 102 | + """ |
| 103 | + Returns the first shape_id associated with a given route_id from the trips file. |
| 104 | + The relationship from the route to the shape is via the trips file. |
| 105 | + Parameters: |
| 106 | + route_id (str): The route identifier to look up. |
| 107 | +
|
| 108 | + Returns: |
| 109 | + The corresponding shape id. |
| 110 | + """ |
| 111 | + if self.route_to_shape is None: |
| 112 | + self.route_to_shape = {} |
| 113 | + for row in self.get_file(TRIPS_FILE): |
| 114 | + route_id = row["route_id"] |
| 115 | + shape_id = row["shape_id"] |
| 116 | + if shape_id: |
| 117 | + self.route_to_shape.setdefault(route_id, shape_id) |
| 118 | + return self.route_to_shape.get(route_id, "") |
| 119 | + |
| 120 | + def get_stops_from_trip(self, trip_id): |
| 121 | + # Lazy instantiation of the dictionary, because we may not need it al all if there is a shape. |
| 122 | + if self.trip_to_stops is None: |
| 123 | + self.trip_to_stops = {} |
| 124 | + for row in self.get_file(STOP_TIMES_FILE): |
| 125 | + self.trip_to_stops.setdefault(row["trip_id"], []).append(row["stop_id"]) |
| 126 | + return self.trip_to_stops.get(trip_id, []) |
| 127 | + |
| 128 | + def get_coordinates_for_stop(self, stop_id) -> tuple[float, float] | None: |
| 129 | + if self.stop_to_coordinates is None: |
| 130 | + self.stop_to_coordinates = { |
| 131 | + s["stop_id"]: (float(s["stop_lon"]), float(s["stop_lat"])) |
| 132 | + for s in self.get_file(STOPS_FILE) |
| 133 | + } |
| 134 | + return self.stop_to_coordinates.get(stop_id, None) |
| 135 | + |
| 136 | + def set_workdir(self, workdir): |
| 137 | + self.workdir = workdir |
0 commit comments