gtfs_kit 2.2.0__tar.gz → 3.0.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.2.0
3
+ Version: 3.0.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
@@ -11,6 +11,7 @@ Classifier: License :: OSI Approved :: MIT License
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.6
13
13
  Classifier: Programming Language :: Python :: 3.7
14
+ Classifier: Programming Language :: Python :: 3.8
14
15
  Requires-Dist: folium (<1)
15
16
  Requires-Dist: geopandas (<1)
16
17
  Requires-Dist: json2table (>=1.1,<2.0)
@@ -12,4 +12,4 @@ from .validators import *
12
12
  from .feed import *
13
13
 
14
14
 
15
- __version__ = "2.2.0"
15
+ __version__ = "3.0.0"
@@ -8,6 +8,7 @@ import pandas as pd
8
8
  import numpy as np
9
9
 
10
10
  from . import constants as cs
11
+ from . import helpers as hp
11
12
 
12
13
  # Help mypy but avoid circular imports
13
14
  if TYPE_CHECKING:
@@ -185,12 +186,11 @@ def build_aggregate_routes_dict(
185
186
 
186
187
  # Create new route IDs
187
188
  n = routes.groupby(by).ngroups
188
- k = int(math.log10(n)) + 1 # Number of digits for padding IDs
189
+ nids = hp.make_ids(n, route_id_prefix)
189
190
  nid_by_oid = dict()
190
- i = 1
191
+ i = 0
191
192
  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}
193
+ d = {oid: nids[i] for oid in group.route_id.values}
194
194
  nid_by_oid.update(d)
195
195
  i += 1
196
196
 
@@ -253,12 +253,11 @@ def build_aggregate_stops_dict(
253
253
 
254
254
  # Create new stop IDs
255
255
  n = stops.groupby(by).ngroups
256
- k = int(math.log10(n)) + 1 # Number of digits for padding IDs
256
+ nids = hp.make_ids(n, stop_id_prefix)
257
257
  nid_by_oid = dict()
258
- i = 1
258
+ i = 0
259
259
  for col, group in stops.groupby(by):
260
- nid = f"{stop_id_prefix}{i:0{k}d}"
261
- d = {oid: nid for oid in group.stop_id.values}
260
+ d = {oid: nids[i] for oid in group.stop_id.values}
262
261
  nid_by_oid.update(d)
263
262
  i += 1
264
263
 
@@ -6,6 +6,7 @@ from typing import Optional, Dict, List, Union, Callable
6
6
  import copy
7
7
  from bisect import bisect_left, bisect_right
8
8
  from functools import cmp_to_key
9
+ import math
9
10
 
10
11
  import pandas as pd
11
12
  import numpy as np
@@ -587,3 +588,24 @@ def longest_subsequence(
587
588
  indices = trace(lastoflength[-1])
588
589
 
589
590
  return list(indices) if index else [seq[i] for i in indices]
591
+
592
+
593
+ def make_ids(n: int, prefix: str = "id_"):
594
+ """
595
+ Return a length ``n`` list of unique sequentially labelled strings for use as IDs.
596
+
597
+ Example::
598
+
599
+ >>> make_ids(10, prefix="s")
600
+ ['s01', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10']
601
+
602
+ """
603
+ if n < 1:
604
+ result = []
605
+ elif n == 1:
606
+ result = [f"{prefix}0"]
607
+ else:
608
+ k = int(math.log10(n - 1)) + 1 # Number of digits for IDs
609
+ result = [f"{prefix}{i:0{k}d}" for i in range(n)]
610
+
611
+ return result
@@ -8,6 +8,7 @@ from typing import List, Optional, Tuple, TYPE_CHECKING
8
8
  import pandas as pd
9
9
  import numpy as np
10
10
  import shapely.geometry as sg
11
+ import geopandas as gpd
11
12
 
12
13
  from . import helpers as hp
13
14
  from . import constants as cs
@@ -120,9 +121,7 @@ def describe(feed: "Feed", sample_date: Optional[str] = None) -> pd.DataFrame:
120
121
  if sample_date is None or sample_date not in feed.get_dates():
121
122
  sample_date = cl.get_first_week(feed)[3]
122
123
  d["sample_date"] = sample_date
123
- d["num_routes_active_on_sample_date"] = feed.get_routes(sample_date).shape[
124
- 0
125
- ]
124
+ d["num_routes_active_on_sample_date"] = feed.get_routes(sample_date).shape[0]
126
125
  trips = feed.get_trips(sample_date)
127
126
  d["num_trips_active_on_sample_date"] = trips.shape[0]
128
127
  d["num_stops_active_on_sample_date"] = feed.get_stops(sample_date).shape[0]
@@ -244,9 +243,9 @@ def convert_dist(feed: "Feed", new_dist_units: str) -> "Feed":
244
243
  ].map(converter)
245
244
 
246
245
  if hp.is_not_null(feed.shapes, "shape_dist_traveled"):
247
- feed.shapes["shape_dist_traveled"] = feed.shapes[
248
- "shape_dist_traveled"
249
- ].map(converter)
246
+ feed.shapes["shape_dist_traveled"] = feed.shapes["shape_dist_traveled"].map(
247
+ converter
248
+ )
250
249
 
251
250
  return feed
252
251
 
@@ -277,22 +276,16 @@ def compute_feed_stats_0(
277
276
  d["num_routes"] = g.route_id.nunique()
278
277
  d["num_trips"] = g.shape[0]
279
278
  d["num_trip_starts"] = g.start_time.count()
280
- d["num_trip_ends"] = g.loc[
281
- g.end_time < 24 * 3600, "end_time"
282
- ].count()
279
+ d["num_trip_ends"] = g.loc[g.end_time < 24 * 3600, "end_time"].count()
283
280
  d["service_distance"] = g.distance.sum()
284
281
  d["service_duration"] = g.duration.sum()
285
282
  if d["service_distance"]:
286
- d["service_speed"] = (
287
- d["service_distance"] / d["service_duration"]
288
- )
283
+ d["service_speed"] = d["service_distance"] / d["service_duration"]
289
284
  else:
290
285
  d["service_speed"] = 0
291
286
 
292
287
  # Compute peak stats, which is the slowest part
293
- active_trips = hp.get_active_trips_df(
294
- g[["start_time", "end_time"]]
295
- )
288
+ active_trips = hp.get_active_trips_df(g[["start_time", "end_time"]])
296
289
  times, counts = (active_trips.index.values, active_trips.values)
297
290
  start, end = hp.get_peak_indices(times, counts)
298
291
  d["peak_num_trips"] = counts[start]
@@ -310,9 +303,7 @@ def compute_feed_stats_0(
310
303
  d["num_routes"] = ts.route_id.nunique()
311
304
  d["num_trips"] = ts.shape[0]
312
305
  d["num_trip_starts"] = ts.start_time.count()
313
- d["num_trip_ends"] = ts.loc[
314
- ts.end_time < 24 * 3600, "end_time"
315
- ].count()
306
+ d["num_trip_ends"] = ts.loc[ts.end_time < 24 * 3600, "end_time"].count()
316
307
  d["service_distance"] = ts.distance.sum()
317
308
  d["service_duration"] = ts.duration.sum()
318
309
  d["service_speed"] = d["service_distance"] / d["service_duration"]
@@ -404,9 +395,7 @@ def compute_feed_stats(
404
395
  # Compute stats
405
396
  ts = trip_stats.loc[lambda x: x.trip_id.isin(ids)].copy()
406
397
  stats = (
407
- compute_feed_stats_0(
408
- feed, ts, split_route_types=split_route_types
409
- )
398
+ compute_feed_stats_0(feed, ts, split_route_types=split_route_types)
410
399
  # Assign date
411
400
  .assign(date=date)
412
401
  )
@@ -487,9 +476,7 @@ def compute_feed_time_series(
487
476
  hp.unstack_time_series(rts)
488
477
  .merge(feed.routes.filter(["route_id", "route_type"]), how="left")
489
478
  .groupby(["datetime", "indicator", "route_type"])
490
- .agg(
491
- {"value": lambda x: x.sum(min_count=1)}
492
- ) # All-NaNs should sum to NaN
479
+ .agg({"value": lambda x: x.sum(min_count=1)}) # All-NaNs should sum to NaN
493
480
  .reset_index()
494
481
  .pipe(hp.restack_time_series)
495
482
  )
@@ -549,15 +536,10 @@ def create_shapes(feed: "Feed", *, all_trips: bool = False) -> "Feed":
549
536
  # sort them to impose a canonical order, and
550
537
  # assign shape IDs to them
551
538
  stop_seqs = sorted(
552
- set(
553
- tuple(group["stop_id"].values)
554
- for trip, group in f.groupby("trip_id")
555
- )
539
+ set(tuple(group["stop_id"].values) for trip, group in f.groupby("trip_id"))
556
540
  )
557
- k = int(math.log10(len(stop_seqs))) + 1 # Digits for padding shape IDs
558
- shape_by_stop_seq = {
559
- seq: f"shape_{i:0{k}d}" for i, seq in enumerate(stop_seqs)
560
- }
541
+ ids = hp.make_ids(len(stop_seqs), "shape_")
542
+ shape_by_stop_seq = {seq: ids[i] for i, seq in enumerate(stop_seqs)}
561
543
 
562
544
  # Assign these new shape IDs to given trips
563
545
  shape_by_trip = {
@@ -565,9 +547,9 @@ def create_shapes(feed: "Feed", *, all_trips: bool = False) -> "Feed":
565
547
  for trip, group in f.groupby("trip_id")
566
548
  }
567
549
  trip_cond = feed.trips["trip_id"].isin(trip_ids)
568
- feed.trips.loc[trip_cond, "shape_id"] = feed.trips.loc[
569
- trip_cond, "trip_id"
570
- ].map(lambda x: shape_by_trip[x])
550
+ feed.trips.loc[trip_cond, "shape_id"] = feed.trips.loc[trip_cond, "trip_id"].map(
551
+ lambda x: shape_by_trip[x]
552
+ )
571
553
 
572
554
  # Build new shapes for given trips
573
555
  G = [
@@ -580,9 +562,7 @@ def create_shapes(feed: "Feed", *, all_trips: bool = False) -> "Feed":
580
562
  ["shape_id", "shape_pt_sequence"]
581
563
  )
582
564
  g = g.drop(["stop_id"], axis=1)
583
- g = g.rename(
584
- columns={"stop_lon": "shape_pt_lon", "stop_lat": "shape_pt_lat"}
585
- )
565
+ g = g.rename(columns={"stop_lon": "shape_pt_lon", "stop_lat": "shape_pt_lat"})
586
566
 
587
567
  if feed.shapes is not None and not all_trips:
588
568
  # Update feed shapes with new shapes
@@ -641,8 +621,7 @@ def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed":
641
621
  # Get every trip that is active on at least one of the dates
642
622
  try:
643
623
  trip_ids = feed.compute_trip_activity(dates).loc[
644
- lambda x: x[[c for c in x.columns if c != "trip_id"]].sum(axis=1)
645
- > 0,
624
+ lambda x: x[[c for c in x.columns if c != "trip_id"]].sum(axis=1) > 0,
646
625
  "trip_id",
647
626
  ]
648
627
  except KeyError:
@@ -653,9 +632,7 @@ def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed":
653
632
  feed.trips = feed.trips.loc[lambda x: x.trip_id.isin(trip_ids)]
654
633
 
655
634
  # Slice routes
656
- feed.routes = feed.routes.loc[
657
- lambda x: x.route_id.isin(feed.trips.route_id)
658
- ]
635
+ feed.routes = feed.routes.loc[lambda x: x.route_id.isin(feed.trips.route_id)]
659
636
 
660
637
  # Slice stop times
661
638
  feed.stop_times = feed.stop_times.loc[lambda x: x.trip_id.isin(trip_ids)]
@@ -671,17 +648,13 @@ def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed":
671
648
  # Slice calendar
672
649
  service_ids = feed.trips.service_id
673
650
  if feed.calendar is not None:
674
- feed.calendar = feed.calendar.loc[
675
- lambda x: x.service_id.isin(service_ids)
676
- ]
651
+ feed.calendar = feed.calendar.loc[lambda x: x.service_id.isin(service_ids)]
677
652
 
678
653
  # Get agency for trips
679
654
  if "agency_id" in feed.routes.columns:
680
655
  agency_ids = feed.routes.agency_id
681
656
  if len(agency_ids):
682
- feed.agency = feed.agency.loc[
683
- lambda x: x.agency_id.isin(agency_ids)
684
- ]
657
+ feed.agency = feed.agency.loc[lambda x: x.agency_id.isin(agency_ids)]
685
658
 
686
659
  # Now for the optional files.
687
660
  # Get calendar dates for trips.
@@ -692,9 +665,7 @@ def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed":
692
665
 
693
666
  # Get frequencies for trips
694
667
  if feed.frequencies is not None:
695
- feed.frequencies = feed.frequencies.loc[
696
- lambda x: x.trip_id.isin(trip_ids)
697
- ]
668
+ feed.frequencies = feed.frequencies.loc[lambda x: x.trip_id.isin(trip_ids)]
698
669
 
699
670
  # Get shapes for trips
700
671
  if feed.shapes is not None:
@@ -704,8 +675,7 @@ def restrict_to_dates(feed: "Feed", dates: List[str]) -> "Feed":
704
675
  # Get transfers for stops
705
676
  if feed.transfers is not None:
706
677
  feed.transfers = feed.transfers.loc[
707
- lambda x: x.from_stop_id.isin(stop_ids)
708
- & x.to_stop_id.isin(stop_ids)
678
+ lambda x: x.from_stop_id.isin(stop_ids) & x.to_stop_id.isin(stop_ids)
709
679
  ]
710
680
 
711
681
  return feed
@@ -730,9 +700,7 @@ def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
730
700
 
731
701
  # Slice stop times
732
702
  trip_ids = feed.trips.trip_id
733
- feed.stop_times = feed.stop_times.loc[
734
- lambda x: x.trip_id.isin(trip_ids)
735
- ].copy()
703
+ feed.stop_times = feed.stop_times.loc[lambda x: x.trip_id.isin(trip_ids)].copy()
736
704
 
737
705
  # Slice stops
738
706
  stop_ids = feed.stop_times.stop_id.unique()
@@ -753,9 +721,7 @@ def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
753
721
  if "agency_id" in feed.routes.columns:
754
722
  agency_ids = feed.routes.agency_id
755
723
  if len(agency_ids):
756
- feed.agency = feed.agency.loc[
757
- lambda x: x.agency_id.isin(agency_ids)
758
- ].copy()
724
+ feed.agency = feed.agency.loc[lambda x: x.agency_id.isin(agency_ids)].copy()
759
725
 
760
726
  # Now for the optional files.
761
727
  # Get calendar dates for trips.
@@ -778,9 +744,7 @@ def restrict_to_routes(feed: "Feed", route_ids: List[str]) -> "Feed":
778
744
  # Get transfers for stops
779
745
  if feed.transfers is not None:
780
746
  feed.transfers = feed.transfers.loc[
781
- lambda x: (
782
- x.from_stop_id.isin(stop_ids) & x.to_stop_id.isin(stop_ids)
783
- )
747
+ lambda x: (x.from_stop_id.isin(stop_ids) & x.to_stop_id.isin(stop_ids))
784
748
  ].copy()
785
749
 
786
750
  return feed
@@ -843,17 +807,13 @@ def restrict_to_polygon(feed: "Feed", polygon: sg.Polygon) -> "Feed":
843
807
  if "agency_id" in feed.routes.columns:
844
808
  agency_ids = feed.routes.agency_id
845
809
  if len(agency_ids):
846
- feed.agency = feed.agency.loc[
847
- lambda x: x.agency_id.isin(agency_ids)
848
- ].copy()
810
+ feed.agency = feed.agency.loc[lambda x: x.agency_id.isin(agency_ids)].copy()
849
811
 
850
812
  # Now for the optional files.
851
813
  # Get calendar dates for trips.
852
814
  cd = feed.calendar_dates
853
815
  if cd is not None:
854
- feed.calendar_dates = cd.loc[
855
- lambda x: x.service_id.isin(service_ids)
856
- ].copy()
816
+ feed.calendar_dates = cd.loc[lambda x: x.service_id.isin(service_ids)].copy()
857
817
 
858
818
  # Get frequencies for trips
859
819
  if feed.frequencies is not None:
@@ -864,189 +824,198 @@ def restrict_to_polygon(feed: "Feed", polygon: sg.Polygon) -> "Feed":
864
824
  # Get shapes for trips
865
825
  if feed.shapes is not None:
866
826
  shape_ids = feed.trips.shape_id
867
- feed.shapes = feed.shapes.loc[
868
- lambda x: x.shape_id.isin(shape_ids)
869
- ].copy()
827
+ feed.shapes = feed.shapes.loc[lambda x: x.shape_id.isin(shape_ids)].copy()
870
828
 
871
829
  # Get transfers for stops
872
830
  if feed.transfers is not None:
873
831
  t = feed.transfers
874
832
  feed.transfers = t.loc[
875
- lambda x: x.from_stop_id.isin(stop_ids)
876
- & x.to_stop_id.isin(stop_ids)
833
+ lambda x: x.from_stop_id.isin(stop_ids) & x.to_stop_id.isin(stop_ids)
877
834
  ].copy()
878
835
 
879
836
  return feed
880
837
 
881
838
 
882
839
  def compute_screen_line_counts(
883
- feed: "Feed", linestring: sg.LineString, dates: List[str], geo_shapes=None
840
+ feed: "Feed", screen_lines: gpd.GeoDataFrame, dates: List[str]
884
841
  ) -> pd.DataFrame:
885
842
  """
886
- Find all the Feed trips active on the given dates
887
- that intersect the given Shapely LineString (with WGS84
888
- longitude-latitude coordinates).
889
-
890
- Parameters
891
- ----------
892
- feed : Feed
893
- linestring : Shapely LineString
894
- dates : list
895
- YYYYMMDD date strings
896
-
897
- Returns
898
- -------
899
- DataFrame
900
- The columns are
901
-
902
- - ``'date'``
903
- - ``'trip_id'``
904
- - ``'route_id'``
905
- - ``'route_short_name'``
906
- - ``'crossing_time'``: time that the trip's vehicle crosses
907
- the linestring; one trip could cross multiple times
908
- - ``'orientation'``: 1 or -1; 1 indicates trip travel from the
909
- left side to the right side of the screen line;
910
- -1 indicates trip travel in the opposite direction
911
-
912
- Notes
913
- -----
914
- - Requires GeoPandas
915
- - The first step is to geometrize ``feed.shapes`` via
916
- :func:`.shapes.geometrize_shapes`. Alternatively, use the
917
- ``geo_shapes`` GeoDataFrame, if given.
918
- - Assume ``feed.stop_times`` has an accurate
919
- ``shape_dist_traveled`` column.
920
- - Assume that trips travel in the same direction as their
921
- shapes. That restriction is part of GTFS, by the way.
922
- To calculate direction quickly and accurately, assume that
923
- the screen line is straight and doesn't double back on itself.
924
- - Probably does not give correct results for trips with
925
- self-intersecting shapes.
843
+ Find all the Feed trips active on the given YYYYMMDD dates whose shapes
844
+ intersect the given GeoDataFrame of screen lines, that is, of straight WGS84
845
+ LineStrings.
846
+ Compute the intersection times and directions for each trip.
847
+
848
+ Return a DataFrame with the columns
849
+
850
+ - ``'date'``
851
+ - ``'trip_id'``
852
+ - ``'route_id'``
853
+ - ``'route_short_name'``
854
+ - ``'shape_id'``: shape ID of the trip
855
+ - ``'screen_line_id'``: ID of the screen line as specified in ``screen_lines`` or as
856
+ assigned after the fact.
857
+ - ``'crossing_distance'``: distance along the trip shape of the screen line
858
+ intersection
859
+ ``'crossing_time'``: time that the trip's vehicle crosses
860
+ the scren line; one trip could cross multiple times
861
+ - ``'crossing_direction'``: 1 or -1; 1 indicates trip travel from the
862
+ left side to the right side of the screen line;
863
+ -1 indicates trip travel in the opposite direction
864
+
865
+ Notes:
866
+
867
+ - Assume the Feed's stop times DataFrame has an accurate ``shape_dist_traveled`` column.
868
+ - Assume that trips travel in the same direction as their shapes, an assumption
869
+ that is part of the GTFS.
870
+ - Assume that the screen line is straight and simple.
871
+ - Probably does not give correct results for trips with self-intersecting shapes.
926
872
  - The algorithm works as follows
927
873
 
928
- 1. Compute all the shapes that intersect the linestring
929
- 2. For each such shape, compute the intersection points
930
- 3. For each point p, scan through all the trips in the feed
931
- that have that shape
932
- 4. For each date in ``dates``, restrict to trips active on the
933
- date and interpolate a stop time for p by assuming that the
934
- feed has the shape_dist_traveled field in stop times
935
- 5. Use that interpolated time as the crossing time of the trip
936
- vehicle, and compute the trip orientation to the screen line
937
- via a cross product of a vector in the direction of the
938
- screen line and a tiny vector in the direction of trip travel
939
-
940
- - Assume the following feed attributes are not ``None``:
941
- * ``feed.shapes``, if ``geo_shapes`` is not given
874
+ 1. Find the trip shapes that intersect the screen lines.
875
+ 2. For each such shape and screen line, compute the intersection points, the distance
876
+ of the point along the shape, and the orientation of the screen line relative to
877
+ the shape.
878
+ 3. For each given date, restrict to trips active on the
879
+ date and interpolate a stop time for the intersection point using
880
+ the ``shape_dist_traveled`` column.
881
+ 4. Use that interpolated time as the crossing time of the trip vehicle.
942
882
 
943
883
  """
944
884
  dates = feed.subset_dates(dates)
945
885
  if not dates:
946
886
  return pd.DataFrame()
947
887
 
948
- # Get all shapes that intersect the screen line
949
- shapes = feed.get_shapes_intersecting_geometry(
950
- linestring, geo_shapes, geometrized=True
951
- )
952
-
953
- # Convert shapes to UTM
954
- lat, lon = feed.shapes.loc[0, ["shape_pt_lat", "shape_pt_lon"]].values
955
- crs = hp.get_utm_crs(lat, lon)
956
- shapes = shapes.to_crs(crs)
888
+ # Get shapes as GeoDataFrame
889
+ shapes_g = feed.geometrize_shapes(use_utm=True)
957
890
 
958
- # Convert linestring to UTM
959
- linestring = hp.linestring_to_utm(linestring)
891
+ # Convert screen lines to UTM
892
+ crs = shapes_g.crs
893
+ screen_lines = screen_lines.to_crs(crs)
960
894
 
961
- # Get all intersection points of shapes and linestring
962
- shapes["intersection"] = shapes.intersection(linestring)
895
+ # Create screen line IDs if necessary
896
+ n = screen_lines.shape[0]
897
+ if "screen_line_id" not in screen_lines.columns:
898
+ screen_lines["screen_line_id"] = hp.make_ids(n, "sl")
963
899
 
964
- # Make a vector in the direction of the screen line
965
- # to later calculate trip orientation.
900
+ # Make a vector in the direction of each screen line to calculate crossing orientation.
966
901
  # Does not work in case of a bent screen line.
967
- p1 = sg.Point(linestring.coords[0])
968
- p2 = sg.Point(linestring.coords[-1])
969
- w = np.array([p2.x - p1.x, p2.y - p1.y])
970
-
971
- # Build a dictionary from the shapes DataFrame of the form
972
- # shape ID -> list of pairs (d, v), one for each intersection point,
973
- # where d is the distance of the intersection point along shape,
974
- # and v is a tiny vectors from the point in direction of shape.
975
- # Assume here that trips travel in the same direction as their shapes.
976
- dv_by_shape = {}
977
- eps = 1
978
- convert_dist = hp.get_convert_dist("m", feed.dist_units)
979
- for __, sid, geom, intersection in shapes.itertuples():
980
- # Get distances along shape of intersection points (in meters)
981
- distances = [geom.project(p) for p in intersection]
982
- # Build tiny vectors
983
- vectors = []
984
- for i, p in enumerate(intersection):
985
- q = geom.interpolate(distances[i] + eps)
986
- vector = np.array([q.x - p.x, q.y - p.y])
987
- vectors.append(vector)
988
- # Convert distances to units used in feed
989
- distances = [convert_dist(d) for d in distances]
990
- dv_by_shape[sid] = list(zip(distances, vectors))
991
-
992
- # Get trips with those shapes
993
- t = feed.trips
994
- t = t[t["shape_id"].isin(dv_by_shape.keys())].copy()
902
+ p1 = screen_lines.geometry.map(lambda x: np.array(x.coords[0]))
903
+ p2 = screen_lines.geometry.map(lambda x: np.array(x.coords[-1]))
904
+ screen_lines["screen_line_vector"] = p2 - p1
905
+
906
+ # Get intersection points of shapes and screen lines
907
+ g0 = (
908
+ # Only keep shapes that intersect screen lines to reduce computations
909
+ gpd.sjoin(shapes_g, screen_lines.filter(["screen_line_id", "geometry"]))
910
+ .merge(screen_lines, on="screen_line_id")
911
+ .assign(geometry_x=lambda x: gpd.GeoSeries(x.geometry_x, crs=crs))
912
+ .set_geometry("geometry_x")
913
+ # Compute intersection points
914
+ .assign(
915
+ int_point=lambda x: x.geometry_x.intersection(
916
+ gpd.GeoSeries(x.geometry_y, crs=crs)
917
+ )
918
+ )
919
+ )
995
920
 
996
- # Merge in route short names and stop times
997
- t = t.merge(feed.routes[["route_id", "route_short_name"]]).merge(
998
- feed.stop_times
921
+ # Unpack multipoint intersections to yield a new GeoDataFrame
922
+ records = []
923
+ for row in g0.itertuples(index=False):
924
+ if isinstance(row.int_point, sg.Point):
925
+ intersections = [row.int_point]
926
+ else:
927
+ intersections = row.int_point
928
+ for int_point in intersections:
929
+ record = {
930
+ "shape_id": row.shape_id,
931
+ "screen_line_id": row.screen_line_id,
932
+ "geometry": row.geometry_x,
933
+ "int_point": int_point,
934
+ "screen_line_vector": row.screen_line_vector,
935
+ }
936
+ records.append(record)
937
+
938
+ g = gpd.GeoDataFrame.from_records(records)
939
+ g.crs = crs
940
+
941
+ # Get distance (in meters) of each intersection point along shape
942
+ g["crossing_dist"] = g.apply(lambda x: x.geometry.project(x.int_point), axis=1)
943
+
944
+ # Build a tiny vector along each shape
945
+ p2 = g.apply(lambda x: x.geometry.interpolate(x.crossing_dist + 1), axis=1).map(
946
+ lambda x: np.array(x.coords[0])
947
+ )
948
+ p1 = g.int_point.map(lambda x: np.array(x.coords[0]))
949
+ g["shape_vector"] = p2 - p1
950
+
951
+ # Compute crossing direction by taking the vector cross product of
952
+ # the shape vector and the screen line vector
953
+ det = g.apply(
954
+ lambda x: np.linalg.det(np.array([x.shape_vector, x.screen_line_vector])),
955
+ axis=1,
956
+ )
957
+ g["crossing_direction"] = det.map(lambda x: 1 if x >= 0 else -1)
958
+
959
+ # Convert to feed distance units
960
+ converter = hp.get_convert_dist("m", feed.dist_units)
961
+ g["crossing_dist"] = g["crossing_dist"].map(converter)
962
+
963
+ # Summarize work so far into a lookup table
964
+ h = (
965
+ g.filter(["shape_id", "screen_line_id", "crossing_direction", "crossing_dist"])
966
+ .set_index("shape_id")
967
+ .sort_values(
968
+ ["shape_id", "crossing_dist"]
969
+ ) # Need this sorting for interpolation to work
999
970
  )
1000
971
 
1001
- # Drop NaN departure times and convert to seconds past midnight
1002
- t = t[t["departure_time"].notnull()].copy()
1003
- t["departure_time"] = t["departure_time"].map(hp.timestr_to_seconds)
972
+ # Get stop times of trips whose shapes lie in h
973
+ st = (
974
+ feed.trips.loc[lambda x: x.shape_id.isin(h.index)]
975
+ # Merge in route short names and stop times
976
+ .merge(feed.routes[["route_id", "route_short_name"]]).merge(feed.stop_times)
977
+ # Keep only non-NaN departure times
978
+ .loc[lambda x: x.departure_time.notna()]
979
+ # Convert to seconds past midnight
980
+ .assign(departure_time=lambda x: x.departure_time.map(hp.timestr_to_seconds))
981
+ )
1004
982
 
1005
- # Compile crossings by date
1006
- a = feed.compute_trip_activity(dates)
1007
- rows = []
983
+ # Compute crossing times by date
984
+ records = []
985
+ ta = feed.compute_trip_activity(dates)
1008
986
  for date in dates:
1009
- # Slice to trips active on date
1010
- ids = a.loc[a[date] == 1, "trip_id"]
1011
- f = t[t["trip_id"].isin(ids)].copy()
987
+ # Subset to trips active on date and merge with g
988
+ ids = ta.loc[lambda x: x[date] == 1, "trip_id"]
989
+ f = st.loc[lambda x: x.trip_id.isin(ids)].sort_values(
990
+ ["trip_id", "shape_dist_traveled"]
991
+ ) # Need this sorting for interpolation to work
1012
992
 
1013
- # For each shape find the trips that cross the screen line
1014
- # and get crossing times and orientation
1015
- f = f.sort_values(["trip_id", "stop_sequence"])
993
+ # Get crossing time for each trip
1016
994
  for tid, group in f.groupby("trip_id"):
1017
995
  sid = group["shape_id"].iat[0]
1018
996
  rid = group["route_id"].iat[0]
1019
997
  rsn = group["route_short_name"].iat[0]
1020
- stop_times = group["departure_time"].values
1021
- stop_distances = group["shape_dist_traveled"].values
1022
- for d, v in dv_by_shape[sid]:
1023
- # Interpolate crossing time
1024
- time = np.interp(d, stop_distances, stop_times)
1025
- # Compute direction of trip travel relative to
1026
- # screen line by looking at the sign of the cross
1027
- # product of tiny shape vector and screen line vector
1028
- det = np.linalg.det(np.array([v, w]))
1029
- if det >= 0:
1030
- orientation = 1
1031
- else:
1032
- orientation = -1
1033
- # Update rows
1034
- rows.append([date, tid, rid, rsn, time, orientation])
1035
-
1036
- # Create DataFrame
1037
- cols = [
1038
- "date",
1039
- "trip_id",
1040
- "route_id",
1041
- "route_short_name",
1042
- "crossing_time",
1043
- "orientation",
1044
- ]
1045
- g = pd.DataFrame(rows, columns=cols).sort_values(["date", "crossing_time"])
1046
-
1047
- # Convert departure times back to time strings
1048
- g["crossing_time"] = g["crossing_time"].map(
1049
- lambda x: hp.timestr_to_seconds(x, inverse=True)
998
+ dists = group["shape_dist_traveled"].values
999
+ times = group["departure_time"].values
1000
+ crossing_dists = h.loc[[sid], "crossing_dist"].values
1001
+ crossing_times = np.interp(crossing_dists, dists, times)
1002
+ for i, row in enumerate(h.loc[[sid]].itertuples(index=False)):
1003
+ record = {
1004
+ "date": date,
1005
+ "trip_id": tid,
1006
+ "route_id": group.route_id.iat[0],
1007
+ "route_short_name": group.route_short_name.iat[0],
1008
+ "shape_id": group.shape_id.iat[0],
1009
+ "screen_line_id": row.screen_line_id,
1010
+ "crossing_direction": row.crossing_direction,
1011
+ "crossing_distance": row.crossing_dist,
1012
+ "crossing_time": crossing_times[i],
1013
+ }
1014
+ records.append(record)
1015
+
1016
+ result = pd.DataFrame.from_records(records).assign(
1017
+ crossing_time=lambda x: x.crossing_time.map(
1018
+ lambda x: hp.timestr_to_seconds(x, inverse=True)
1019
+ )
1050
1020
  )
1051
-
1052
- return g
1021
+ return result
@@ -30,9 +30,7 @@ def append_dist_to_shapes(feed: "Feed") -> "Feed":
30
30
  0.016 km in absolute value from of the original values.
31
31
  """
32
32
  if feed.shapes is None:
33
- raise ValueError(
34
- "This function requires the feed to have a shapes.txt file"
35
- )
33
+ raise ValueError("This function requires the feed to have a shapes.txt file")
36
34
 
37
35
  feed = feed.copy()
38
36
  f = feed.shapes
@@ -82,9 +80,7 @@ def geometrize_shapes_0(
82
80
 
83
81
  def my_agg(group):
84
82
  d = {}
85
- d["geometry"] = sg.LineString(
86
- group[["shape_pt_lon", "shape_pt_lat"]].values
87
- )
83
+ d["geometry"] = sg.LineString(group[["shape_pt_lon", "shape_pt_lat"]].values)
88
84
  return pd.Series(d)
89
85
 
90
86
  g = f.groupby("shape_id").apply(my_agg).reset_index()
@@ -98,18 +94,18 @@ def geometrize_shapes_0(
98
94
  return g
99
95
 
100
96
 
101
- def ungeometrize_shapes_0(geo_shapes: gpd.GeoDataFrame) -> pd.DataFrame:
97
+ def ungeometrize_shapes_0(shapes_g: gpd.GeoDataFrame) -> pd.DataFrame:
102
98
  """
103
99
  The inverse of :func:`geometrize_shapes_0`.
104
100
 
105
- If ``geo_shapes`` is in UTM coordinates (has a UTM CRS property),
101
+ If ``shapes_g`` is in UTM coordinates (has a UTM CRS property),
106
102
  then convert those UTM coordinates back to WGS84 coordinates,
107
103
  which is the standard for a GTFS shapes table.
108
104
  """
109
- geo_shapes = geo_shapes.to_crs(cs.WGS84)
105
+ shapes_g = shapes_g.to_crs(cs.WGS84)
110
106
 
111
107
  F = []
112
- for index, row in geo_shapes.iterrows():
108
+ for index, row in shapes_g.iterrows():
113
109
  F.extend(
114
110
  [
115
111
  [row["shape_id"], i, x, y]
@@ -118,17 +114,13 @@ def ungeometrize_shapes_0(geo_shapes: gpd.GeoDataFrame) -> pd.DataFrame:
118
114
  )
119
115
 
120
116
  return pd.DataFrame(
121
- F,
122
- columns=[
123
- "shape_id",
124
- "shape_pt_sequence",
125
- "shape_pt_lon",
126
- "shape_pt_lat",
127
- ],
117
+ F, columns=["shape_id", "shape_pt_sequence", "shape_pt_lon", "shape_pt_lat",],
128
118
  )
129
119
 
130
120
 
131
- def geometrize_shapes(feed: "Feed", shape_ids: Optional[Iterable[str]] = None, *, use_utm: bool = False) -> gpd.GeoDataFrame:
121
+ def geometrize_shapes(
122
+ feed: "Feed", shape_ids: Optional[Iterable[str]] = None, *, use_utm: bool = False
123
+ ) -> gpd.GeoDataFrame:
132
124
  """
133
125
  Given a Feed instance, convert its shapes DataFrame to a GeoDataFrame of
134
126
  LineStrings and return the result, which will no longer have the columns
@@ -150,7 +142,9 @@ def geometrize_shapes(feed: "Feed", shape_ids: Optional[Iterable[str]] = None, *
150
142
  return geometrize_shapes_0(shapes, use_utm=use_utm)
151
143
 
152
144
 
153
- def build_geometry_by_shape(feed: "Feed", shape_ids: Optional[Iterable[str]] = None, *, use_utm: bool = False) -> Dict:
145
+ def build_geometry_by_shape(
146
+ feed: "Feed", shape_ids: Optional[Iterable[str]] = None, *, use_utm: bool = False
147
+ ) -> Dict:
154
148
  """
155
149
  Return a dictionary of the form <shape ID> -> <Shapely LineString representing shape>.
156
150
  """
@@ -160,9 +154,8 @@ def build_geometry_by_shape(feed: "Feed", shape_ids: Optional[Iterable[str]] = N
160
154
  .values
161
155
  )
162
156
 
163
- def shapes_to_geojson(
164
- feed: "Feed", shape_ids: Optional[Iterable[str]] = None
165
- ) -> Dict:
157
+
158
+ def shapes_to_geojson(feed: "Feed", shape_ids: Optional[Iterable[str]] = None) -> Dict:
166
159
  """
167
160
  Return a GeoJSON FeatureCollection of LineString features
168
161
  representing ``feed.shapes``.
@@ -184,19 +177,24 @@ def shapes_to_geojson(
184
177
  result = hp.drop_feature_ids(json.loads(g.to_json()))
185
178
  return result
186
179
 
180
+
187
181
  def get_shapes_intersecting_geometry(
188
- feed: "Feed", geometry: sg.base.BaseGeometry, geo_shapes:Optional[gpd.GeoDataFrame]=None, *, geometrized: bool = False
182
+ feed: "Feed",
183
+ geometry: sg.base.BaseGeometry,
184
+ shapes_g: Optional[gpd.GeoDataFrame] = None,
185
+ *,
186
+ geometrized: bool = False
189
187
  ) -> pd.DataFrame:
190
188
  """
191
189
  Return the subset of ``feed.shapes`` that contains all shapes that
192
190
  intersect the given Shapely geometry, e.g. a Polygon or LineString.
193
191
 
194
192
  If ``geometrized``, then return the shapes as a GeoDataFrame.
195
- Specifying ``geo_shapes`` will skip the first step of the
193
+ Specifying ``shapes_g`` will skip the first step of the
196
194
  algorithm, namely, geometrizing ``feed.shapes``.
197
195
  """
198
- if geo_shapes is not None:
199
- f = geo_shapes.copy()
196
+ if shapes_g is not None:
197
+ f = shapes_g.copy()
200
198
  else:
201
199
  f = geometrize_shapes(feed)
202
200
 
@@ -598,15 +598,15 @@ def geometrize_stops_0(
598
598
  return g
599
599
 
600
600
 
601
- def ungeometrize_stops_0(geo_stops: gpd.GeoDataFrame) -> pd.DataFrame:
601
+ def ungeometrize_stops_0(stops_g: gpd.GeoDataFrame) -> pd.DataFrame:
602
602
  """
603
603
  The inverse of :func:`geometrize_stops_0`.
604
604
 
605
- If ``geo_stops`` is in UTM coordinates (has a UTM CRS property),
605
+ If ``stops_g`` is in UTM coordinates (has a UTM CRS property),
606
606
  then convert those UTM coordinates back to WGS84 coordinates,
607
607
  which is the standard for a GTFS shapes table.
608
608
  """
609
- f = geo_stops.copy().to_crs(cs.WGS84)
609
+ f = stops_g.copy().to_crs(cs.WGS84)
610
610
  f["stop_lon"], f["stop_lat"] = zip(*f["geometry"].map(lambda p: [p.x, p.y]))
611
611
  del f["geometry"]
612
612
  return f
@@ -654,7 +654,7 @@ def stops_to_geojson(feed: "Feed", stop_ids: Optional[Iterable[str]] = None) ->
654
654
  If an iterable of stop IDs is given, then subset to those stops.
655
655
  If the subset is empty, then return a FeatureCollection with an empty list of
656
656
  features.
657
- If some of the given stop IDs are not found in the feed, then raise a ValueError.
657
+ If some of the given stop IDs are not found in the feed, then raise a ValueError.
658
658
  """
659
659
  if stop_ids is not None:
660
660
  D = set(stop_ids) - set(feed.stops.stop_id)
@@ -672,7 +672,7 @@ def stops_to_geojson(feed: "Feed", stop_ids: Optional[Iterable[str]] = None) ->
672
672
  def get_stops_in_polygon(
673
673
  feed: "Feed",
674
674
  polygon: sg.Polygon,
675
- geo_stops: Optional[gpd.GeoDataFrame] = None,
675
+ stops_g: Optional[gpd.GeoDataFrame] = None,
676
676
  *,
677
677
  geometrized: bool = False,
678
678
  ) -> pd.DataFrame:
@@ -682,11 +682,11 @@ def get_stops_in_polygon(
682
682
  WGS84 coordinates.
683
683
 
684
684
  If ``geometrized``, then return the stops as a GeoDataFrame.
685
- Specifying ``geo_stops`` will skip the first step of the
685
+ Specifying ``stops_g`` will skip the first step of the
686
686
  algorithm, namely, geometrizing ``feed.stops``.
687
687
  """
688
- if geo_stops is not None:
689
- f = geo_stops.copy()
688
+ if stops_g is not None:
689
+ f = stops_g.copy()
690
690
  else:
691
691
  f = geometrize_stops(feed)
692
692
 
@@ -705,7 +705,7 @@ def get_stops_in_polygon(
705
705
  def map_stops(feed: "Feed", stop_ids: Iterable[str], stop_style: Dict = STOP_STYLE):
706
706
  """
707
707
  Return a Folium map showing the given stops of this Feed.
708
- If some of the given stop IDs are not found in the feed, then raise a ValueError.
708
+ If some of the given stop IDs are not found in the feed, then raise a ValueError.
709
709
  """
710
710
  # Initialize map
711
711
  my_map = fl.Map(tiles="cartodbpositron")
@@ -515,7 +515,7 @@ def map_trips(
515
515
  for f in collection["features"]:
516
516
  prop = f["properties"]
517
517
 
518
- # Add stop
518
+ # Add stop if present
519
519
  if f["geometry"]["type"] == "Point":
520
520
  lon, lat = f["geometry"]["coordinates"]
521
521
  fl.CircleMarker(
@@ -538,15 +538,16 @@ def map_trips(
538
538
  path.add_to(group)
539
539
  bboxes.append(sg.box(*sg.shape(f["geometry"]).bounds))
540
540
 
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)
541
+ if include_arrows:
542
+ # Direction arrows, assuming, as GTFS does, that
543
+ # trip direction equals LineString direction
544
+ fp.PolyLineTextPath(
545
+ path,
546
+ " \u27A4 ",
547
+ repeat=True,
548
+ offset=5.5,
549
+ attributes={"fill": color, "font-size": "18"},
550
+ ).add_to(group)
550
551
 
551
552
  group.add_to(my_map)
552
553
 
@@ -554,7 +555,8 @@ def map_trips(
554
555
 
555
556
  # Fit map to bounds
556
557
  bounds = so.unary_union(bboxes).bounds
557
- bounds2 = [bounds[1::-1], bounds[3:1:-1]] # Folium expects this ordering
558
- my_map.fit_bounds(bounds2)
558
+ # Folium wants a different ordering
559
+ bounds = [(bounds[1], bounds[0]), (bounds[3], bounds[2])]
560
+ my_map.fit_bounds(bounds)
559
561
 
560
562
  return my_map
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "gtfs_kit"
3
- version = "2.2.0"
3
+ version = "3.0.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"
@@ -1,5 +1,5 @@
1
1
  # -*- coding: utf-8 -*-
2
- from distutils.core import setup
2
+ from setuptools import setup
3
3
 
4
4
  packages = \
5
5
  ['gtfs_kit']
@@ -19,11 +19,13 @@ install_requires = \
19
19
 
20
20
  setup_kwargs = {
21
21
  'name': 'gtfs-kit',
22
- 'version': '2.2.0',
22
+ 'version': '3.0.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',
26
26
  'author_email': 'araichev@mrcagney.com',
27
+ 'maintainer': None,
28
+ 'maintainer_email': None,
27
29
  'url': 'https://github.com/mrcagney/gtfs_kit',
28
30
  'packages': packages,
29
31
  'package_data': package_data,
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes