gtfs_kit 6.1.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.
- gtfs_kit-6.1.0/LICENSE.txt +21 -0
- gtfs_kit-6.1.0/PKG-INFO +73 -0
- gtfs_kit-6.1.0/README.rst +43 -0
- gtfs_kit-6.1.0/gtfs_kit/__init__.py +15 -0
- gtfs_kit-6.1.0/gtfs_kit/calendar.py +98 -0
- gtfs_kit-6.1.0/gtfs_kit/cleaners.py +373 -0
- gtfs_kit-6.1.0/gtfs_kit/constants.py +166 -0
- gtfs_kit-6.1.0/gtfs_kit/feed.py +525 -0
- gtfs_kit-6.1.0/gtfs_kit/helpers.py +632 -0
- gtfs_kit-6.1.0/gtfs_kit/miscellany.py +1019 -0
- gtfs_kit-6.1.0/gtfs_kit/routes.py +862 -0
- gtfs_kit-6.1.0/gtfs_kit/shapes.py +221 -0
- gtfs_kit-6.1.0/gtfs_kit/stop_times.py +174 -0
- gtfs_kit-6.1.0/gtfs_kit/stops.py +739 -0
- gtfs_kit-6.1.0/gtfs_kit/trips.py +565 -0
- gtfs_kit-6.1.0/gtfs_kit/validators.py +1644 -0
- gtfs_kit-6.1.0/pyproject.toml +49 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019 Alexander Raichev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
gtfs_kit-6.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: gtfs_kit
|
|
3
|
+
Version: 6.1.0
|
|
4
|
+
Summary: A Python 3.8+ library for analyzing GTFS feeds.
|
|
5
|
+
Home-page: https://github.com/mrcagney/gtfs_kit
|
|
6
|
+
License: MIT
|
|
7
|
+
Author: Alex Raichev
|
|
8
|
+
Author-email: araichev@mrcagney.com
|
|
9
|
+
Requires-Python: >=3.8,<4
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Requires-Dist: folium (>=0)
|
|
18
|
+
Requires-Dist: geopandas (>=0)
|
|
19
|
+
Requires-Dist: json2html (>=1)
|
|
20
|
+
Requires-Dist: pandas (>=1)
|
|
21
|
+
Requires-Dist: pycountry (>=19)
|
|
22
|
+
Requires-Dist: requests (>=2)
|
|
23
|
+
Requires-Dist: rtree (>=0)
|
|
24
|
+
Requires-Dist: shapely (>=1.8)
|
|
25
|
+
Requires-Dist: utm (>=0.6)
|
|
26
|
+
Project-URL: Documentation, https://mrcagney.github.io/gtfs_kit_docs
|
|
27
|
+
Project-URL: Repository, https://github.com/mrcagney/gtfs_kit
|
|
28
|
+
Description-Content-Type: text/x-rst
|
|
29
|
+
|
|
30
|
+
GTFS Kit
|
|
31
|
+
********
|
|
32
|
+
.. image:: https://github.com/mrcagney/gtfs_kit/actions/workflows/test.yml/badge.svg
|
|
33
|
+
|
|
34
|
+
GTFS Kit is a Python 3.8+ library for analyzing `General Transit Feed Specification (GTFS) <https://en.wikipedia.org/wiki/GTFS>`_ data in memory without a database.
|
|
35
|
+
It uses Pandas and Shapely to do the heavy lifting.
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
Installation
|
|
39
|
+
=============
|
|
40
|
+
``poetry add gtfs_kit``.
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
Examples
|
|
44
|
+
========
|
|
45
|
+
You can find examples in the Jupyter notebook ``notebooks/examples.ipynb``.
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
Authors
|
|
49
|
+
=========
|
|
50
|
+
- Alex Raichev (2019-09), maintainer
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
Documentation
|
|
54
|
+
=============
|
|
55
|
+
Documentation is built via Sphinx from the source code in the ``docs`` directory then published to Github Pages at `mrcagney.github.io/gtfs_kit_docs <https://mrcagney.github.io/gtfs_kit_docs>`_.
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
Notes
|
|
59
|
+
=====
|
|
60
|
+
- This project's development status is Alpha.
|
|
61
|
+
I use GTFS Kit for work and change it breakingly to suit my needs.
|
|
62
|
+
- This project uses semantic versioning.
|
|
63
|
+
- I aim for GTFS Kit to handle `the current GTFS <https://developers.google.com/transit/gtfs/reference>`_.
|
|
64
|
+
In particular, i avoid handling `GTFS extensions <https://developers.google.com/transit/gtfs/reference/gtfs-extensions>`_.
|
|
65
|
+
That is the most reasonable scope boundary i can draw at present, given this project's tiny budget.
|
|
66
|
+
If you would like to fund me to expand that scope, feel free to email me.
|
|
67
|
+
- Thanks to `MRCagney <http://www.mrcagney.com/>`_ for periodically donating to this project.
|
|
68
|
+
- Constructive feedback and contributions are welcome.
|
|
69
|
+
Please issue pull requests from a feature branch into the ``develop`` branch and include tests.
|
|
70
|
+
- GTFS time is measured relative noon minus 12 hours, which can mess things up when crossing into daylight savings time.
|
|
71
|
+
I don't think this issue causes any bugs in GTFS Kit, but you and i have been warned.
|
|
72
|
+
Thanks to user derhuerst for bringing this to my attention in `closed Issue 8 <https://github.com/mrcagney/gtfs_kit/issues/8#issue-1063633457>`_.
|
|
73
|
+
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
GTFS Kit
|
|
2
|
+
********
|
|
3
|
+
.. image:: https://github.com/mrcagney/gtfs_kit/actions/workflows/test.yml/badge.svg
|
|
4
|
+
|
|
5
|
+
GTFS Kit is a Python 3.8+ library for analyzing `General Transit Feed Specification (GTFS) <https://en.wikipedia.org/wiki/GTFS>`_ data in memory without a database.
|
|
6
|
+
It uses Pandas and Shapely to do the heavy lifting.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
Installation
|
|
10
|
+
=============
|
|
11
|
+
``poetry add gtfs_kit``.
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
Examples
|
|
15
|
+
========
|
|
16
|
+
You can find examples in the Jupyter notebook ``notebooks/examples.ipynb``.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
Authors
|
|
20
|
+
=========
|
|
21
|
+
- Alex Raichev (2019-09), maintainer
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
Documentation
|
|
25
|
+
=============
|
|
26
|
+
Documentation is built via Sphinx from the source code in the ``docs`` directory then published to Github Pages at `mrcagney.github.io/gtfs_kit_docs <https://mrcagney.github.io/gtfs_kit_docs>`_.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
Notes
|
|
30
|
+
=====
|
|
31
|
+
- This project's development status is Alpha.
|
|
32
|
+
I use GTFS Kit for work and change it breakingly to suit my needs.
|
|
33
|
+
- This project uses semantic versioning.
|
|
34
|
+
- I aim for GTFS Kit to handle `the current GTFS <https://developers.google.com/transit/gtfs/reference>`_.
|
|
35
|
+
In particular, i avoid handling `GTFS extensions <https://developers.google.com/transit/gtfs/reference/gtfs-extensions>`_.
|
|
36
|
+
That is the most reasonable scope boundary i can draw at present, given this project's tiny budget.
|
|
37
|
+
If you would like to fund me to expand that scope, feel free to email me.
|
|
38
|
+
- Thanks to `MRCagney <http://www.mrcagney.com/>`_ for periodically donating to this project.
|
|
39
|
+
- Constructive feedback and contributions are welcome.
|
|
40
|
+
Please issue pull requests from a feature branch into the ``develop`` branch and include tests.
|
|
41
|
+
- GTFS time is measured relative noon minus 12 hours, which can mess things up when crossing into daylight savings time.
|
|
42
|
+
I don't think this issue causes any bugs in GTFS Kit, but you and i have been warned.
|
|
43
|
+
Thanks to user derhuerst for bringing this to my attention in `closed Issue 8 <https://github.com/mrcagney/gtfs_kit/issues/8#issue-1063633457>`_.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .constants import *
|
|
2
|
+
from .helpers import *
|
|
3
|
+
from .calendar import *
|
|
4
|
+
from .routes import *
|
|
5
|
+
from .shapes import *
|
|
6
|
+
from .stops import *
|
|
7
|
+
from .stop_times import *
|
|
8
|
+
from .trips import *
|
|
9
|
+
from .miscellany import *
|
|
10
|
+
from .cleaners import *
|
|
11
|
+
from .validators import *
|
|
12
|
+
from .feed import *
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
__version__ = "6.1.0"
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions about calendar and calendar_dates.
|
|
3
|
+
"""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
import dateutil.relativedelta as rd
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from . import helpers as hp
|
|
9
|
+
|
|
10
|
+
# Help mypy but avoid circular imports
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from .feed import Feed
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def get_dates(feed: "Feed", *, as_date_obj: bool = False) -> list[str]:
|
|
16
|
+
"""
|
|
17
|
+
Return a list of YYYYMMDD date strings for which the given Feed is valid,
|
|
18
|
+
which could be the empty list if the Feed has no calendar information.
|
|
19
|
+
|
|
20
|
+
If ``as_date_obj``, then return datetime.date objects instead.
|
|
21
|
+
"""
|
|
22
|
+
dates = []
|
|
23
|
+
if feed.calendar is not None and not feed.calendar.empty:
|
|
24
|
+
if "start_date" in feed.calendar.columns:
|
|
25
|
+
dates.append(feed.calendar["start_date"].min())
|
|
26
|
+
if "end_date" in feed.calendar.columns:
|
|
27
|
+
dates.append(feed.calendar["end_date"].max())
|
|
28
|
+
if feed.calendar_dates is not None and not feed.calendar_dates.empty:
|
|
29
|
+
if "date" in feed.calendar_dates.columns:
|
|
30
|
+
start = feed.calendar_dates["date"].min()
|
|
31
|
+
end = feed.calendar_dates["date"].max()
|
|
32
|
+
dates.extend([start, end])
|
|
33
|
+
if not dates:
|
|
34
|
+
return []
|
|
35
|
+
|
|
36
|
+
start_date, end_date = min(dates), max(dates)
|
|
37
|
+
start_date, end_date = map(hp.datestr_to_date, [start_date, end_date])
|
|
38
|
+
num_days = (end_date - start_date).days
|
|
39
|
+
result = [start_date + rd.relativedelta(days=+d) for d in range(num_days + 1)]
|
|
40
|
+
|
|
41
|
+
# Convert dates back to strings if required
|
|
42
|
+
if not as_date_obj:
|
|
43
|
+
result = [hp.datestr_to_date(x, inverse=True) for x in result]
|
|
44
|
+
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def get_week(feed: "Feed", k: int, *, as_date_obj: bool = False) -> list[str]:
|
|
49
|
+
"""
|
|
50
|
+
Given a Feed and a positive integer ``k``,
|
|
51
|
+
return a list of YYYYMMDD date strings corresponding to the kth Monday--Sunday week
|
|
52
|
+
(or initial segment thereof) for which the Feed is valid.
|
|
53
|
+
For example, k=1 returns the first Monday--Sunday week (or initial segment thereof).
|
|
54
|
+
If the Feed does not have k Mondays, then return the empty list.
|
|
55
|
+
|
|
56
|
+
If ``as_date_obj``, then return datetime.date objects instead.
|
|
57
|
+
"""
|
|
58
|
+
dates = feed.get_dates(as_date_obj=True)
|
|
59
|
+
n = len(dates)
|
|
60
|
+
|
|
61
|
+
# Get first Monday
|
|
62
|
+
monday_index = None
|
|
63
|
+
for (i, date) in enumerate(dates):
|
|
64
|
+
if date.weekday() == 0:
|
|
65
|
+
monday_index = i
|
|
66
|
+
break
|
|
67
|
+
|
|
68
|
+
# Get week k
|
|
69
|
+
if k < 1 or monday_index is None or monday_index + 7 * (k - 1) > n:
|
|
70
|
+
result = []
|
|
71
|
+
else:
|
|
72
|
+
result = dates[monday_index + 7 * (k - 1) : monday_index + 7 * k]
|
|
73
|
+
|
|
74
|
+
# Convert to date strings if requested
|
|
75
|
+
if not as_date_obj:
|
|
76
|
+
result = [hp.datestr_to_date(x, inverse=True) for x in result]
|
|
77
|
+
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def get_first_week(feed: "Feed", *, as_date_obj: bool = False) -> list[str]:
|
|
82
|
+
"""
|
|
83
|
+
Return a list of YYYYMMDD date strings for the first Monday--Sunday
|
|
84
|
+
week (or initial segment thereof) for which the given Feed is valid.
|
|
85
|
+
If the feed has no Mondays, then return the empty list.
|
|
86
|
+
|
|
87
|
+
If ``as_date_obj``, then return date objects, otherwise return date strings.
|
|
88
|
+
"""
|
|
89
|
+
return get_week(feed, 1, as_date_obj=as_date_obj)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def subset_dates(feed: "Feed", dates: list[str]) -> list[str]:
|
|
93
|
+
"""
|
|
94
|
+
Given a Feed and a list of YYYYMMDD date strings,
|
|
95
|
+
return the sublist of dates that lie in the Feed's dates
|
|
96
|
+
(the output :func:`feed.get_dates`).
|
|
97
|
+
"""
|
|
98
|
+
return [d for d in dates if d in feed.get_dates()]
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions about cleaning feeds.
|
|
3
|
+
"""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from . import constants as cs
|
|
11
|
+
from . import helpers as hp
|
|
12
|
+
|
|
13
|
+
# Help mypy but avoid circular imports
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from .feed import Feed
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def clean_column_names(df: pd.DataFrame) -> pd.DataFrame:
|
|
19
|
+
"""
|
|
20
|
+
Strip the whitespace from all column names in the given DataFrame
|
|
21
|
+
and return the result.
|
|
22
|
+
"""
|
|
23
|
+
f = df.copy()
|
|
24
|
+
f.columns = [col.strip() for col in f.columns]
|
|
25
|
+
return f
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def clean_ids(feed: "Feed") -> "Feed":
|
|
29
|
+
"""
|
|
30
|
+
In the given Feed, strip whitespace from all string IDs and
|
|
31
|
+
then replace every remaining whitespace chunk with an underscore.
|
|
32
|
+
Return the resulting Feed.
|
|
33
|
+
"""
|
|
34
|
+
# Alter feed inputs only, and build a new feed from them.
|
|
35
|
+
# The derived feed attributes, such as feed.trips_i,
|
|
36
|
+
# will be automatically handled when creating the new feed.
|
|
37
|
+
feed = feed.copy()
|
|
38
|
+
|
|
39
|
+
for table in cs.GTFS_REF["table"].unique():
|
|
40
|
+
f = getattr(feed, table)
|
|
41
|
+
if f is None:
|
|
42
|
+
continue
|
|
43
|
+
for column in cs.GTFS_REF.loc[cs.GTFS_REF["table"] == table, "column"]:
|
|
44
|
+
if column in f.columns and column.endswith("_id"):
|
|
45
|
+
try:
|
|
46
|
+
f[column] = (
|
|
47
|
+
f[column].str.strip().str.replace(r"\s+", "_", regex=True)
|
|
48
|
+
)
|
|
49
|
+
setattr(feed, table, f)
|
|
50
|
+
except AttributeError:
|
|
51
|
+
# Column is not of string type
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
return feed
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def extend_id(feed: "Feed", id_col: str, extension: str, *, prefix=True) -> "Feed":
|
|
58
|
+
"""
|
|
59
|
+
Add a prefix (if ``prefix``) or a suffix (otherwise) to all values of column
|
|
60
|
+
``id_col`` across all tables of this Feed.
|
|
61
|
+
This can be helpful when preparing to merge multiple GTFS feeds with colliding
|
|
62
|
+
route IDs, say.
|
|
63
|
+
|
|
64
|
+
Raises a ValueError if ``id_col`` values can't have strings added to them,
|
|
65
|
+
e.g. if ``id_col`` is 'direction_id'.
|
|
66
|
+
"""
|
|
67
|
+
feed = feed.copy()
|
|
68
|
+
|
|
69
|
+
for table in cs.GTFS_REF.loc[lambda x: x["column"] == id_col, "table"].unique():
|
|
70
|
+
t = getattr(feed, table)
|
|
71
|
+
if t is None:
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
t[id_col] = extension + t[id_col] if prefix else t[id_col] + extension
|
|
75
|
+
setattr(feed, table, t)
|
|
76
|
+
except Exception as e:
|
|
77
|
+
raise ValueError(e)
|
|
78
|
+
|
|
79
|
+
return feed
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def clean_times(feed: "Feed") -> "Feed":
|
|
83
|
+
"""
|
|
84
|
+
In the given Feed, convert H:MM:SS time strings to HH:MM:SS time
|
|
85
|
+
strings to make sorting by time work as expected.
|
|
86
|
+
Return the resulting Feed.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def reformat(t):
|
|
90
|
+
if pd.isna(t):
|
|
91
|
+
return t
|
|
92
|
+
t = t.strip()
|
|
93
|
+
if len(t) == 7:
|
|
94
|
+
t = "0" + t
|
|
95
|
+
return t
|
|
96
|
+
|
|
97
|
+
feed = feed.copy()
|
|
98
|
+
tables_and_columns = [
|
|
99
|
+
("stop_times", ["arrival_time", "departure_time"]),
|
|
100
|
+
("frequencies", ["start_time", "end_time"]),
|
|
101
|
+
]
|
|
102
|
+
for table, columns in tables_and_columns:
|
|
103
|
+
f = getattr(feed, table)
|
|
104
|
+
if f is not None:
|
|
105
|
+
f[columns] = f[columns].applymap(reformat)
|
|
106
|
+
setattr(feed, table, f)
|
|
107
|
+
|
|
108
|
+
return feed
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def drop_zombies(feed: "Feed") -> "Feed":
|
|
112
|
+
"""
|
|
113
|
+
In the given Feed, do the following in order and return the resulting Feed.
|
|
114
|
+
|
|
115
|
+
1. Drop stops of location type 0 or NaN with no stop times.
|
|
116
|
+
2. Remove undefined parent stations from the ``parent_station`` column.
|
|
117
|
+
3. Drop trips with no stop times.
|
|
118
|
+
4. Drop shapes with no trips.
|
|
119
|
+
5. Drop routes with no trips.
|
|
120
|
+
6. Drop services with no trips.
|
|
121
|
+
|
|
122
|
+
"""
|
|
123
|
+
feed = feed.copy()
|
|
124
|
+
|
|
125
|
+
f = feed.stops.copy()
|
|
126
|
+
ids = feed.stop_times.stop_id.unique()
|
|
127
|
+
cond = f.stop_id.isin(ids)
|
|
128
|
+
if "location_type" in f.columns:
|
|
129
|
+
cond |= ~f.location_type.isin([0, np.nan])
|
|
130
|
+
feed.stops = f[cond].copy()
|
|
131
|
+
|
|
132
|
+
# Remove undefined parent stations from the ``parent_station`` column
|
|
133
|
+
if "parent_station" in feed.stops.columns:
|
|
134
|
+
f = feed.stops.copy()
|
|
135
|
+
ids = f.stop_id.unique()
|
|
136
|
+
f["parent_station"] = f.parent_station.map(lambda x: x if x in ids else np.nan)
|
|
137
|
+
feed.stops = f
|
|
138
|
+
|
|
139
|
+
# Drop trips with no stop times
|
|
140
|
+
ids = feed.stop_times["trip_id"].unique()
|
|
141
|
+
f = feed.trips
|
|
142
|
+
feed.trips = f[f["trip_id"].isin(ids)]
|
|
143
|
+
|
|
144
|
+
# Drop shapes with no trips
|
|
145
|
+
ids = feed.trips["shape_id"].unique()
|
|
146
|
+
f = feed.shapes
|
|
147
|
+
if f is not None:
|
|
148
|
+
feed.shapes = f[f["shape_id"].isin(ids)]
|
|
149
|
+
|
|
150
|
+
# Drop routes with no trips
|
|
151
|
+
ids = feed.trips["route_id"].unique()
|
|
152
|
+
f = feed.routes
|
|
153
|
+
feed.routes = f[f["route_id"].isin(ids)]
|
|
154
|
+
|
|
155
|
+
# Drop services with no trips
|
|
156
|
+
ids = feed.trips["service_id"].unique()
|
|
157
|
+
if feed.calendar is not None:
|
|
158
|
+
f = feed.calendar
|
|
159
|
+
feed.calendar = f[f["service_id"].isin(ids)]
|
|
160
|
+
if feed.calendar_dates is not None:
|
|
161
|
+
f = feed.calendar_dates
|
|
162
|
+
feed.calendar_dates = f[f["service_id"].isin(ids)]
|
|
163
|
+
|
|
164
|
+
return feed
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def clean_route_short_names(feed: "Feed") -> "Feed":
|
|
168
|
+
"""
|
|
169
|
+
In ``feed.routes``, assign 'n/a' to missing route short names and
|
|
170
|
+
strip whitespace from route short names.
|
|
171
|
+
Then disambiguate each route short name that is duplicated by
|
|
172
|
+
appending '-' and its route ID.
|
|
173
|
+
Return the resulting Feed.
|
|
174
|
+
"""
|
|
175
|
+
feed = feed.copy()
|
|
176
|
+
r = feed.routes
|
|
177
|
+
if r is None:
|
|
178
|
+
return feed
|
|
179
|
+
|
|
180
|
+
# Fill NaNs and strip whitespace
|
|
181
|
+
r["route_short_name"] = r["route_short_name"].fillna("n/a").str.strip()
|
|
182
|
+
|
|
183
|
+
# Disambiguate
|
|
184
|
+
def disambiguate(row):
|
|
185
|
+
rsn, rid = row
|
|
186
|
+
return rsn + "-" + rid
|
|
187
|
+
|
|
188
|
+
r["dup"] = r["route_short_name"].duplicated(keep=False)
|
|
189
|
+
r.loc[r["dup"], "route_short_name"] = r.loc[
|
|
190
|
+
r["dup"], ["route_short_name", "route_id"]
|
|
191
|
+
].apply(disambiguate, axis=1)
|
|
192
|
+
del r["dup"]
|
|
193
|
+
|
|
194
|
+
feed.routes = r
|
|
195
|
+
return feed
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def build_aggregate_routes_dict(
|
|
199
|
+
routes: pd.DataFrame, by: str = "route_short_name", route_id_prefix: str = "route_"
|
|
200
|
+
) -> dict[str, str]:
|
|
201
|
+
"""
|
|
202
|
+
Given a DataFrame of routes, group the routes by route short name, say,
|
|
203
|
+
and assign new route IDs using the given prefix.
|
|
204
|
+
Return a dictionary of the form <old route ID> -> <new route ID>.
|
|
205
|
+
Helper function for :func:`aggregate_routes`.
|
|
206
|
+
|
|
207
|
+
More specifically, group ``routes`` by the ``by`` column, and for each group make
|
|
208
|
+
one new route ID for all the old route IDs in that group based on the given
|
|
209
|
+
``route_id_prefix`` string and a running count, e.g. ``'route_013'``.
|
|
210
|
+
"""
|
|
211
|
+
if by not in routes.columns:
|
|
212
|
+
raise ValueError(f"Column {by} not in routes.")
|
|
213
|
+
|
|
214
|
+
# Create new route IDs
|
|
215
|
+
n = routes.groupby(by).ngroups
|
|
216
|
+
nids = hp.make_ids(n, route_id_prefix)
|
|
217
|
+
nid_by_oid = dict()
|
|
218
|
+
i = 0
|
|
219
|
+
for col, group in routes.groupby(by):
|
|
220
|
+
d = {oid: nids[i] for oid in group.route_id.values}
|
|
221
|
+
nid_by_oid.update(d)
|
|
222
|
+
i += 1
|
|
223
|
+
|
|
224
|
+
return nid_by_oid
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def aggregate_routes(
|
|
228
|
+
feed: "Feed", by: str = "route_short_name", route_id_prefix: str = "route_"
|
|
229
|
+
) -> "Feed":
|
|
230
|
+
"""
|
|
231
|
+
Aggregate routes by route short name, say, and assign new route IDs using the
|
|
232
|
+
given prefix.
|
|
233
|
+
|
|
234
|
+
More specifically, create new route IDs with the function
|
|
235
|
+
:func:`build_aggregate_routes_dict` and the parameters ``by`` and
|
|
236
|
+
``route_id_prefix`` and update the old route IDs to the new ones in all the relevant
|
|
237
|
+
Feed tables.
|
|
238
|
+
Return the resulting Feed.
|
|
239
|
+
"""
|
|
240
|
+
feed = feed.copy()
|
|
241
|
+
|
|
242
|
+
# Make new route IDs
|
|
243
|
+
routes = feed.routes
|
|
244
|
+
nid_by_oid = build_aggregate_routes_dict(routes, by, route_id_prefix)
|
|
245
|
+
|
|
246
|
+
# Update route IDs in routes
|
|
247
|
+
routes["route_id"] = routes.route_id.map(lambda x: nid_by_oid[x])
|
|
248
|
+
routes = routes.groupby(by).first().reset_index()
|
|
249
|
+
feed.routes = routes
|
|
250
|
+
|
|
251
|
+
# Update route IDs in trips
|
|
252
|
+
trips = feed.trips
|
|
253
|
+
trips["route_id"] = trips.route_id.map(lambda x: nid_by_oid[x])
|
|
254
|
+
feed.trips = trips
|
|
255
|
+
|
|
256
|
+
# Update route IDs of fare rules
|
|
257
|
+
if feed.fare_rules is not None and "route_id" in feed.fare_rules.columns:
|
|
258
|
+
fr = feed.fare_rules
|
|
259
|
+
fr["route_id"] = fr.route_id.map(lambda x: nid_by_oid[x])
|
|
260
|
+
feed.fare_rules = fr
|
|
261
|
+
|
|
262
|
+
return feed
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def build_aggregate_stops_dict(
|
|
266
|
+
stops: pd.DataFrame, by: str = "stop_code", stop_id_prefix: str = "stop_"
|
|
267
|
+
) -> dict[str, str]:
|
|
268
|
+
"""
|
|
269
|
+
Given a DataFrame of stops, group the stops by stop code, say,
|
|
270
|
+
and assign new stop IDs using the given prefix.
|
|
271
|
+
Return a dictionary of the form <old stop ID> -> <new stop ID>.
|
|
272
|
+
Helper function for :func:`aggregate_stops`.
|
|
273
|
+
|
|
274
|
+
More specifically, group ``stops`` by the ``by`` column, and for each group make
|
|
275
|
+
one new stop ID for all the old stops IDs in that group based on the given
|
|
276
|
+
``stop_id_prefix`` string and a running count, e.g. ``'stop_013'``.
|
|
277
|
+
"""
|
|
278
|
+
if by not in stops.columns:
|
|
279
|
+
raise ValueError(f"Column {by} not in stops.")
|
|
280
|
+
|
|
281
|
+
# Create new stop IDs
|
|
282
|
+
n = stops.groupby(by).ngroups
|
|
283
|
+
nids = hp.make_ids(n, stop_id_prefix)
|
|
284
|
+
nid_by_oid = dict()
|
|
285
|
+
i = 0
|
|
286
|
+
for col, group in stops.groupby(by):
|
|
287
|
+
d = {oid: nids[i] for oid in group.stop_id.values}
|
|
288
|
+
nid_by_oid.update(d)
|
|
289
|
+
i += 1
|
|
290
|
+
|
|
291
|
+
return nid_by_oid
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def aggregate_stops(
|
|
295
|
+
feed: "Feed", by: str = "stop_code", stop_id_prefix: str = "stop_"
|
|
296
|
+
) -> "Feed":
|
|
297
|
+
"""
|
|
298
|
+
Aggregate stops by stop code, say, and assign new stop IDs using the
|
|
299
|
+
given prefix.
|
|
300
|
+
|
|
301
|
+
More specifically, create new stop IDs with the function
|
|
302
|
+
:func:`build_aggregate_stops_dict` and the parameters ``by`` and
|
|
303
|
+
``stop_id_prefix`` and update the old stop IDs to the new ones in all the relevant
|
|
304
|
+
Feed tables.
|
|
305
|
+
Return the resulting Feed.
|
|
306
|
+
"""
|
|
307
|
+
feed = feed.copy()
|
|
308
|
+
|
|
309
|
+
# Make new stop ID by old stop ID dict
|
|
310
|
+
stops = feed.stops
|
|
311
|
+
nid_by_oid = build_aggregate_stops_dict(stops, by, stop_id_prefix)
|
|
312
|
+
|
|
313
|
+
# Apply dict
|
|
314
|
+
stops["stop_id"] = stops.stop_id.map(nid_by_oid)
|
|
315
|
+
if "parent_station" in stops:
|
|
316
|
+
stops["parent_station"] = stops.parent_station.map(nid_by_oid)
|
|
317
|
+
|
|
318
|
+
stops = stops.groupby(by).first().reset_index()
|
|
319
|
+
feed.stops = stops
|
|
320
|
+
|
|
321
|
+
# Update stop IDs of stop times
|
|
322
|
+
stop_times = feed.stop_times
|
|
323
|
+
stop_times["stop_id"] = stop_times.stop_id.map(lambda x: nid_by_oid[x])
|
|
324
|
+
feed.stop_times = stop_times
|
|
325
|
+
|
|
326
|
+
# Update route IDs of transfers
|
|
327
|
+
if feed.transfers is not None:
|
|
328
|
+
transfers = feed.transfers
|
|
329
|
+
transfers["to_stop_id"] = transfers.to_stop_id.map(lambda x: nid_by_oid[x])
|
|
330
|
+
transfers["from_stop_id"] = transfers.from_stop_id.map(lambda x: nid_by_oid[x])
|
|
331
|
+
feed.transfers = transfers
|
|
332
|
+
|
|
333
|
+
return feed
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def clean(feed: "Feed") -> "Feed":
|
|
337
|
+
"""
|
|
338
|
+
Apply the following functions to the given Feed in order and return the resulting
|
|
339
|
+
Feed.
|
|
340
|
+
|
|
341
|
+
#. :func:`clean_ids`
|
|
342
|
+
#. :func:`clean_times`
|
|
343
|
+
#. :func:`clean_route_short_names`
|
|
344
|
+
#. :func:`drop_zombies`
|
|
345
|
+
|
|
346
|
+
"""
|
|
347
|
+
feed = feed.copy()
|
|
348
|
+
ops = ["clean_ids", "clean_times", "clean_route_short_names", "drop_zombies"]
|
|
349
|
+
for op in ops:
|
|
350
|
+
feed = globals()[op](feed)
|
|
351
|
+
|
|
352
|
+
return feed
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def drop_invalid_columns(feed: "Feed") -> "Feed":
|
|
356
|
+
"""
|
|
357
|
+
Drop all DataFrame columns of the given Feed that are not
|
|
358
|
+
listed in the GTFS.
|
|
359
|
+
Return the resulting Feed.
|
|
360
|
+
"""
|
|
361
|
+
feed = feed.copy()
|
|
362
|
+
for table, group in cs.GTFS_REF.groupby("table"):
|
|
363
|
+
f = getattr(feed, table)
|
|
364
|
+
if f is None:
|
|
365
|
+
continue
|
|
366
|
+
valid_columns = group["column"].values
|
|
367
|
+
for col in f.columns:
|
|
368
|
+
if col not in valid_columns:
|
|
369
|
+
print(f"{table}: dropping invalid column {col}")
|
|
370
|
+
del f[col]
|
|
371
|
+
setattr(feed, table, f)
|
|
372
|
+
|
|
373
|
+
return feed
|