-
Notifications
You must be signed in to change notification settings - Fork 1
Test out LAMP for bus #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ankoure
wants to merge
7
commits into
main
Choose a base branch
from
experiment-with-lamp-for-bus
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b29d732
test out lamp for bus
ankoure ae5e15c
updated timeout and memory allocations
ankoure c77ca0d
Added backfill script
ankoure a4998f9
i forget what I did here
ankoure 0934529
Merge branch 'main' into experiment-with-lamp-for-bus
ankoure 956315a
Merge branch 'main' into experiment-with-lamp-for-bus
ankoure d1162bf
Merge branch 'main' into experiment-with-lamp-for-bus
devinmatte File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| { | ||
| "Version": "2012-10-17", | ||
| "Statement": [ | ||
| { | ||
| "Action": [ | ||
| "logs:CreateLogGroup", | ||
| "logs:CreateLogStream", | ||
| "logs:PutLogEvents" | ||
| ], | ||
| "Effect": "Allow", | ||
| "Resource": "arn:*:logs:*:*:*" | ||
| }, | ||
| { | ||
| "Action": ["s3:GetObject", "s3:PutObject"], | ||
| "Effect": "Allow", | ||
| "Resource": ["arn:aws:s3:::tm-mbta-performance/Events-lamp/bus-daily-data/*"] | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,9 @@ | ||
| __all__ = ["ingest_today_lamp_data", "ingest_yesterday_lamp_data"] | ||
| __all__ = [ | ||
| "ingest_today_lamp_data", | ||
| "ingest_yesterday_lamp_data", | ||
| "ingest_today_bus_data", | ||
| "ingest_yesterday_bus_data", | ||
| ] | ||
|
|
||
| from .bus_ingest import ingest_today_bus_data, ingest_yesterday_bus_data | ||
| from .ingest import ingest_today_lamp_data, ingest_yesterday_lamp_data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import logging | ||
| import os | ||
| from datetime import date, timedelta | ||
|
|
||
| import pandas as pd | ||
|
|
||
| from ... import parallel | ||
| from ..bus_ingest import RTE_DIR_STOP, fetch_bus_pq_file_from_remote, ingest_bus_pq_file, upload_bus_to_s3 | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _parallel_upload = parallel.make_parallel(upload_bus_to_s3) | ||
|
|
||
| EARLIEST_BUS_LAMP_DATA = date(2020, 1, 8) | ||
|
|
||
| LOCAL_ARCHIVE_PATH = os.environ.get("LOCAL_ARCHIVE_PATH", "./feeds") | ||
|
|
||
|
|
||
| def backfill_all_bus_dates(start_date: date = EARLIEST_BUS_LAMP_DATA): | ||
| """Backfill all dates with bus LAMP data, most recent to oldest.""" | ||
|
|
||
| if start_date < EARLIEST_BUS_LAMP_DATA: | ||
| raise ValueError(f"start_date {start_date} is before earliest available data {EARLIEST_BUS_LAMP_DATA}") | ||
|
|
||
| end_date = date.today() - timedelta(days=1) | ||
| dates = pd.date_range(start_date, end_date, freq="d") | ||
| num_days = len(dates) | ||
| estimated_cost = num_days / 30 | ||
|
|
||
| confirmation = input( | ||
| f"This will backfill {num_days} days of bus LAMP data ({start_date} to {end_date}). " | ||
| f"Estimated cost: ~${estimated_cost:.2f} (based on ~$1 per 30 days). " | ||
| "This will take hours. Are you sure you want to proceed? (yes/no): " | ||
| ) | ||
| if confirmation.lower() not in ("yes", "y"): | ||
| print("You must enter 'yes' to proceed. Exiting.") | ||
| exit(1) | ||
|
|
||
| for backfill_timestamp in dates[::-1]: | ||
| date_to_backfill = backfill_timestamp.date() | ||
| try: | ||
| pq_df = fetch_bus_pq_file_from_remote(date_to_backfill) | ||
| except ValueError as e: | ||
| logger.warning(f"Failed to fetch {date_to_backfill}: {e}") | ||
| continue | ||
|
|
||
| logger.info(f"Processing {date_to_backfill}") | ||
| processed = ingest_bus_pq_file(pq_df, date_to_backfill, local_archive_path=LOCAL_ARCHIVE_PATH) | ||
|
|
||
| group_event_groups = processed.groupby(RTE_DIR_STOP) | ||
| logger.info(f"Uploading events for {len(group_event_groups)} route-direction-stop groups to S3") | ||
| _parallel_upload(group_event_groups, date_to_backfill) | ||
| logger.info(f"Finished {date_to_backfill}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import argparse | ||
| import os | ||
| from datetime import datetime | ||
|
|
||
| parser = argparse.ArgumentParser(description="Backfill bus LAMP data from a start date up to yesterday.") | ||
| parser.add_argument( | ||
| "--start-date", | ||
| type=lambda s: datetime.strptime(s, "%Y-%m-%d").date(), | ||
| default=EARLIEST_BUS_LAMP_DATA, | ||
| help=f"Start date in YYYY-MM-DD format (default: {EARLIEST_BUS_LAMP_DATA}).", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| log_level = os.environ.get("LOG_LEVEL", "INFO").upper() | ||
| logging.basicConfig( | ||
| level=getattr(logging, log_level, logging.INFO), | ||
| format="%(asctime)s - %(levelname)s: %(message)s", | ||
| datefmt="%H:%M:%S", | ||
| ) | ||
| backfill_all_bus_dates(start_date=args.start_date) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| # Remote URL for fetching bus LAMP data (daily parquet files) | ||
| BUS_DAILY_URL_TEMPLATE = "https://performancedata.mbta.com/lamp/bus_vehicle_events/{YYYYMMDD}.parquet" | ||
|
|
||
| # Columns to read from the source parquet files | ||
| BUS_LAMP_COLUMNS = [ | ||
| "service_date", | ||
| "route_id", | ||
| "trip_id", | ||
| "stop_id", | ||
| "direction_id", | ||
| "stop_sequence", | ||
| "vehicle_label", | ||
| "previous_stop_id", | ||
| # Actual timestamps (UTC-aware) | ||
| "stop_arrival_dt", | ||
| "stop_departure_dt", | ||
| # Actual metrics | ||
| "travel_time_seconds", | ||
| "stopped_duration_seconds", | ||
| "route_direction_headway_seconds", | ||
| # Scheduled metrics | ||
| "plan_travel_time_seconds", | ||
| "plan_route_direction_headway_seconds", | ||
| ] | ||
|
|
||
| # Columns output to S3 events.csv | ||
| BUS_S3_COLUMNS = [ | ||
| "service_date", | ||
| "route_id", | ||
| "trip_id", | ||
| "direction_id", | ||
| "stop_id", | ||
| "stop_sequence", | ||
| "vehicle_label", | ||
| "event_type", | ||
| "event_time", | ||
| "travel_time_seconds", | ||
| "dwell_time_seconds", | ||
| "headway_seconds", | ||
| "scheduled_tt", | ||
| "scheduled_headway", | ||
| ] | ||
|
|
||
| BUS_COLUMN_RENAME_MAP = { | ||
| "stopped_duration_seconds": "dwell_time_seconds", | ||
| "route_direction_headway_seconds": "headway_seconds", | ||
| "plan_travel_time_seconds": "scheduled_tt", | ||
| "plan_route_direction_headway_seconds": "scheduled_headway", | ||
| } | ||
|
|
||
| # Output S3 bucket and key template | ||
| BUS_S3_BUCKET = "tm-mbta-performance" | ||
| # month and day are not zero-padded | ||
| BUS_S3_KEY_TEMPLATE = ( | ||
| "Events-lamp/bus-daily-data/{route_id}-{direction_id}-{stop_id}/Year={YYYY}/Month={_M}/Day={_D}/events.csv" | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For first round of testing let's ingest once or twice a day to start since running more frequently can get costly. After a short testing window we can expand this to hourly and then we may no longer need gobble once this data is considered good enough