gtfs_kit 2.0.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: gtfs-kit
3
- Version: 2.0.0
3
+ Version: 2.2.0
4
4
  Summary: A Python 3.6+ library for analyzing GTFS feeds.
5
5
  Home-page: https://github.com/mrcagney/gtfs_kit
6
6
  License: MIT
@@ -12,4 +12,4 @@ from .validators import *
12
12
  from .feed import *
13
13
 
14
14
 
15
- __version__ = "2.0.0"
15
+ __version__ = "2.2.0"
@@ -2,7 +2,7 @@
2
2
  Functions about cleaning feeds.
3
3
  """
4
4
  import math
5
- from typing import TYPE_CHECKING
5
+ from typing import TYPE_CHECKING, Dict
6
6
 
7
7
  import pandas as pd
8
8
  import numpy as np
@@ -167,6 +167,36 @@ def clean_route_short_names(feed: "Feed") -> "Feed":
167
167
  return feed
168
168
 
169
169
 
170
+ def build_aggregate_routes_dict(
171
+ routes: pd.DataFrame, by: str = "route_short_name", route_id_prefix: str = "route_"
172
+ ) -> Dict[str, str]:
173
+ """
174
+ Given a DataFrame of routes, group the routes by route short name, say,
175
+ and assign new route IDs using the given prefix.
176
+ Return a dictionary of the form <old route ID> -> <new route ID>.
177
+ Helper function for :func:`aggregate_routes`.
178
+
179
+ More specifically, group ``routes`` by the ``by`` column, and for each group make
180
+ one new route ID for all the old route IDs in that group based on the given
181
+ ``route_id_prefix`` string and a running count, e.g. ``'route_013'``.
182
+ """
183
+ if by not in routes.columns:
184
+ raise ValueError(f"Column {by} not in routes.")
185
+
186
+ # Create new route IDs
187
+ n = routes.groupby(by).ngroups
188
+ k = int(math.log10(n)) + 1 # Number of digits for padding IDs
189
+ nid_by_oid = dict()
190
+ i = 1
191
+ for col, group in routes.groupby(by):
192
+ nid = f"{route_id_prefix}{i:0{k}d}"
193
+ d = {oid: nid for oid in group.route_id.values}
194
+ nid_by_oid.update(d)
195
+ i += 1
196
+
197
+ return nid_by_oid
198
+
199
+
170
200
  def aggregate_routes(
171
201
  feed: "Feed", by: str = "route_short_name", route_id_prefix: str = "route_"
172
202
  ) -> "Feed":
@@ -174,88 +204,91 @@ def aggregate_routes(
174
204
  Aggregate routes by route short name, say, and assign new route IDs using the
175
205
  given prefix.
176
206
 
177
- More specifically, the result is built from the given Feed as follows.
178
- Group ``feed.routes`` by the ``by`` column, and for each group
179
-
180
- 1. Choose the first route in the group
181
- 2. Assign a new route ID based on the given ``route_id_prefix``
182
- string and a running count, e.g. ``'route_013'``
183
- 3. Assign all the trips associated with routes in the group to
184
- that first route
185
- 4. Update the route IDs in the other "Feed" tables
186
-
207
+ More specifically, create new route IDs with the function
208
+ :func:`build_aggregate_routes_dict` and the parameters ``by`` and
209
+ ``route_id_prefix`` and update the old route IDs to the new ones in all the relevant
210
+ Feed tables.
211
+ Return the resulting Feed.
187
212
  """
188
- if by not in feed.routes.columns:
189
- raise ValueError(f"Column {by} not in feed.routes")
190
-
191
213
  feed = feed.copy()
192
214
 
193
- # Create new route IDs
215
+ # Make new route IDs
194
216
  routes = feed.routes
195
- n = routes.groupby(by).ngroups
196
- k = int(math.log10(n)) + 1 # Number of digits for padding IDs
197
- nrid_by_orid = dict()
198
- i = 1
199
- for col, group in routes.groupby(by):
200
- nrid = f"route_{i:0{k}d}"
201
- d = {orid: nrid for orid in group["route_id"].values}
202
- nrid_by_orid.update(d)
203
- i += 1
217
+ nid_by_oid = build_aggregate_routes_dict(routes, by, route_id_prefix)
204
218
 
205
- routes["route_id"] = routes["route_id"].map(lambda x: nrid_by_orid[x])
219
+ # Update to new route IDs
220
+ routes["route_id"] = routes["route_id"].map(lambda x: nid_by_oid[x])
206
221
  routes = routes.groupby(by).first().reset_index()
207
222
  feed.routes = routes
208
223
 
209
224
  # Update route IDs of trips
210
225
  trips = feed.trips
211
- trips["route_id"] = trips["route_id"].map(lambda x: nrid_by_orid[x])
226
+ trips["route_id"] = trips["route_id"].map(lambda x: nid_by_oid[x])
212
227
  feed.trips = trips
213
228
 
214
229
  # Update route IDs of transfers
215
230
  if feed.transfers is not None:
216
231
  transfers = feed.transfers
217
- transfers["route_id"] = transfers["route_id"].map(lambda x: nrid_by_orid[x])
232
+ transfers["route_id"] = transfers["route_id"].map(lambda x: nid_by_oid[x])
218
233
  feed.transfers = transfers
219
234
 
220
235
  return feed
221
236
 
222
237
 
223
- def aggregate_stops(
224
- feed: "Feed", by: str = "stop_code", stop_id_prefix: str = "stop_"
225
- ) -> "Feed":
238
+ def build_aggregate_stops_dict(
239
+ stops: pd.DataFrame, by: str = "stop_code", stop_id_prefix: str = "stop_"
240
+ ) -> Dict[str, str]:
226
241
  """
227
- Aggregate stops by stop code, say, and assign new stop IDs using the
228
- given prefix.
229
-
230
- More specifically, the result is built from the given Feed as follows.
231
- Group ``feed.stops`` by the ``by`` column, and for each group
232
-
233
- 1. Choose the first stop in the group
234
- 2. Assign a new stop ID based on the given ``stop_id_prefix``
235
- string and a running count, e.g. ``'stop_013'``
236
- 3. Assign all the stops associated with stops in the group to
237
- that first stop
238
- 4. Update the stop IDs in the other "Feed" tables
239
-
242
+ Given a DataFrame of stops, group the stops by stop code, say,
243
+ and assign new stop IDs using the given prefix.
244
+ Return a dictionary of the form <old stop ID> -> <new stop ID>.
245
+ Helper function for :func:`aggregate_stops`.
246
+
247
+ More specifically, group ``stops`` by the ``by`` column, and for each group make
248
+ one new stop ID for all the old stops IDs in that group based on the given
249
+ ``stop_id_prefix`` string and a running count, e.g. ``'stop_013'``.
240
250
  """
241
- if by not in feed.stops.columns:
242
- raise ValueError(f"Column {by} not in feed.stops")
243
-
244
- feed = feed.copy()
251
+ if by not in stops.columns:
252
+ raise ValueError(f"Column {by} not in stops.")
245
253
 
246
254
  # Create new stop IDs
247
- stops = feed.stops
248
255
  n = stops.groupby(by).ngroups
249
256
  k = int(math.log10(n)) + 1 # Number of digits for padding IDs
250
257
  nid_by_oid = dict()
251
258
  i = 1
252
259
  for col, group in stops.groupby(by):
253
- nid = f"stop_{i:0{k}d}"
254
- d = {oid: nid for oid in group["stop_id"].values}
260
+ nid = f"{stop_id_prefix}{i:0{k}d}"
261
+ d = {oid: nid for oid in group.stop_id.values}
255
262
  nid_by_oid.update(d)
256
263
  i += 1
257
264
 
258
- stops["stop_id"] = stops.stop_id.map(lambda x: nid_by_oid[x])
265
+ return nid_by_oid
266
+
267
+
268
+ def aggregate_stops(
269
+ feed: "Feed", by: str = "stop_code", stop_id_prefix: str = "stop_"
270
+ ) -> "Feed":
271
+ """
272
+ Aggregate routes by route short name, say, and assign new route IDs using the
273
+ given prefix.
274
+
275
+ More specifically, create new stop IDs with the function
276
+ :func:`build_aggregate_stops_dict` and the parameters ``by`` and
277
+ ``stop_id_prefix`` and update the old stop IDs to the new ones in all the relevant
278
+ Feed tables.
279
+ Return the resulting Feed.
280
+ """
281
+ feed = feed.copy()
282
+
283
+ # Make new stop ID by old stop ID dict
284
+ stops = feed.stops
285
+ nid_by_oid = build_aggregate_stops_dict(stops, by, stop_id_prefix)
286
+
287
+ # Apply dict
288
+ stops["stop_id"] = stops.stop_id.map(nid_by_oid)
289
+ if "parent_station" in stops:
290
+ stops["parent_station"] = stops.parent_station.map(nid_by_oid)
291
+
259
292
  stops = stops.groupby(by).first().reset_index()
260
293
  feed.stops = stops
261
294
 
@@ -485,11 +485,15 @@ def map_trips(
485
485
  color_palette: List[str] = cs.COLORS_SET2,
486
486
  *,
487
487
  include_stops: bool = False,
488
+ include_arrows: bool = False,
488
489
  ):
489
490
  """
490
491
  Return a Folium map showing the given trips and (optionally)
491
492
  their stops.
492
493
  If any of the given trip IDs are not found in the feed, then raise a ValueError.
494
+ If ``include_arrows``, then use the Folium plugin PolyLineTextPath to draw arrows
495
+ on each trip polyline indicating its direction of travel; this fails to work in some
496
+ browsers, such as Brave 0.68.132.
493
497
  """
494
498
  # Initialize map
495
499
  my_map = fl.Map(tiles="cartodbpositron")
@@ -504,6 +508,7 @@ def map_trips(
504
508
  # Create a feature group for each route and add it to the map
505
509
  for i, trip_id in enumerate(trip_ids):
506
510
  collection = trips_to_geojson(feed, [trip_id], include_stops=include_stops)
511
+
507
512
  group = fl.FeatureGroup(name=f"Trip {trip_id}")
508
513
  color = colors[i]
509
514
 
@@ -524,26 +529,24 @@ def map_trips(
524
529
 
525
530
  # Add trip
526
531
  else:
527
- prop["color"] = color
528
- path = fl.GeoJson(
529
- f,
530
- name=trip_id,
531
- style_function=lambda x: {"color": x["properties"]["color"]},
532
+ path = fl.PolyLine(
533
+ [[x[1], x[0]] for x in f["geometry"]["coordinates"]],
534
+ color=color,
535
+ popup=hp.make_html(prop),
532
536
  )
533
- path.add_child(fl.Popup(hp.make_html(prop)))
537
+
534
538
  path.add_to(group)
535
539
  bboxes.append(sg.box(*sg.shape(f["geometry"]).bounds))
536
540
 
537
- # if include_arrows:
538
- # # Direction arrows, assuming, as GTFS does, that
539
- # # trip direction equals LineString direction
540
- # fp.PolyLineTextPath(
541
- # path,
542
- # " \u27A4 ",
543
- # repeat=True,
544
- # offset=5.5,
545
- # attributes={"fill": color, "font-size": "18"},
546
- # ).add_to(group)
541
+ # Direction arrows, assuming, as GTFS does, that
542
+ # trip direction equals LineString direction
543
+ fp.PolyLineTextPath(
544
+ path,
545
+ " \u27A4 ",
546
+ repeat=True,
547
+ offset=5.5,
548
+ attributes={"fill": color, "font-size": "18"},
549
+ ).add_to(group)
547
550
 
548
551
  group.add_to(my_map)
549
552
 
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "gtfs_kit"
3
- version = "2.0.0"
3
+ version = "2.2.0"
4
4
  description = "A Python 3.6+ library for analyzing GTFS feeds."
5
5
  authors = ["Alex Raichev <araichev@mrcagney.com>"]
6
6
  readme = "README.rst"
@@ -19,7 +19,7 @@ install_requires = \
19
19
 
20
20
  setup_kwargs = {
21
21
  'name': 'gtfs-kit',
22
- 'version': '2.0.0',
22
+ 'version': '2.2.0',
23
23
  'description': 'A Python 3.6+ library for analyzing GTFS feeds.',
24
24
  'long_description': 'GTFS Kit\n********\n.. image:: https://travis-ci.org/mrcagney/gtfs_kit.svg?branch=master\n :target: https://travis-ci.org/mrcagney/gtfs_kit\n\nGTFS Kit is a Python 3.6+ kit for analyzing `General Transit Feed Specification (GTFS) <https://en.wikipedia.org/wiki/GTFS>`_ data in memory without a database.\nIt uses Pandas and Shapely to do the heavy lifting.\n\nThis project supersedes `GTFSTK <https://github.com/mrcagney/gtfstk>`_.\n\n\nInstallation\n=============\n``pip install gtfs_kit``.\n\n\nExamples\n========\nYou can play with ``ipynb/examples.ipynb`` in a Jupyter notebook.\n\n\nAuthors\n=========\n- Alex Raichev, 2019-09\n\n\nDocumentation\n=============\nOn Github Pages `here <https://mrcagney.github.io/gtfs_kit_docs>`_.\n\n\nNotes\n=====\n- Development status is Alpha\n- This project uses semantic versioning\n- Thanks to `MRCagney <http://www.mrcagney.com/>`_ for donating to this project\n- Constructive feedback and code contributions welcome. Please issue pull requests into the ``develop`` branch and include tests.\n',
25
25
  'author': 'Alex Raichev',
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes