API Reference¶
The supported public contract is now subpackage-first:
subway_access.modelssubway_access.iosubway_access.analysissubway_access.factorssubway_access.helperssubway_access.exportsubway_access.pipelinesubway_access.reporting(optional; requires[factor-factory]or[tearsheets])subway_access.temporalsubway_access.cli
The root subway_access namespace is intentionally minimal and only exposes
__version__.
The advanced network layer lives alongside the baseline analysis surfaces under
subway_access.analysis, while graph cache helpers live under
subway_access.io and subway_access.pipeline.
Root¶
subway_access ¶
Minimal root namespace for the subway-access package.
Models¶
subway_access.models ¶
Public typed models for subway-access.
AccessibilityLabel
module-attribute
¶
AccessibilityLabel = Literal[
"accessible",
"partially_accessible",
"not_accessible",
"unknown",
]
EquipmentType
module-attribute
¶
EquipmentType = Literal[
"elevator",
"escalator",
"station",
"platform",
"unknown",
]
OutageStatus
module-attribute
¶
OutageStatus = Literal[
"active", "resolved", "scheduled", "unknown"
]
AccessibilityQuery
dataclass
¶
High-level filter for a borough or district analysis pass.
Source code in src/subway_access/models/_common.py
25 26 27 28 29 30 | |
Entrance
dataclass
¶
A street-level subway entrance or exit from MTA Open Data (entrances / exits layer).
Source code in src/subway_access/models/_entrance.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
EntranceDataset
dataclass
¶
Loaded entrance / exit point rows for a study area.
Source code in src/subway_access/models/_entrance.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
count_by_gtfs_stop_id ¶
count_by_gtfs_stop_id() -> dict[str, int]
Count entrances per GTFS parent stop id.
Source code in src/subway_access/models/_entrance.py
37 38 39 40 41 42 43 44 | |
count_by_complex_id ¶
count_by_complex_id() -> dict[str, int]
Count entrances per station complex id.
Source code in src/subway_access/models/_entrance.py
46 47 48 49 50 51 52 53 | |
for_station_id ¶
for_station_id(station_id: str) -> tuple[Entrance, ...]
Return entrances whose MTA station id matches.
Source code in src/subway_access/models/_entrance.py
55 56 57 58 | |
GtfsLocation
dataclass
¶
One row from GTFS locations.txt (GTFS-Pathways extension).
Source code in src/subway_access/models/_entrance.py
78 79 80 81 82 83 84 85 86 | |
GtfsPathway
dataclass
¶
One row from GTFS pathways.txt (GTFS-Pathways extension).
Source code in src/subway_access/models/_entrance.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
GtfsPathwaysSnapshot
dataclass
¶
Optional pathways + locations parsed from a static GTFS zip.
Source code in src/subway_access/models/_entrance.py
89 90 91 92 93 94 | |
GapAnalysis
dataclass
¶
Ranked tract accessibility gap results.
Source code in src/subway_access/models/_gap.py
29 30 31 32 33 | |
GapRecord
dataclass
¶
Final tract-level accessibility gap output.
Source code in src/subway_access/models/_gap.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
nearest_accessible_distance_meters
instance-attribute
¶
nearest_accessible_distance_meters: float | None
CatchmentDataset
dataclass
¶
Generated catchment geometries.
Source code in src/subway_access/models/_metric.py
44 45 46 47 48 49 50 51 | |
radius_by_station_id ¶
radius_by_station_id() -> dict[str, float]
Source code in src/subway_access/models/_metric.py
50 51 | |
CatchmentFeature
dataclass
¶
Map-friendly catchment geometry for a station.
Source code in src/subway_access/models/_metric.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
CatchmentRequest
dataclass
¶
Request parameters for station catchment generation.
Source code in src/subway_access/models/_metric.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
StationMetricDataset
dataclass
¶
Export-ready station metrics.
Source code in src/subway_access/models/_metric.py
80 81 82 83 84 | |
StationMetricRecord
dataclass
¶
Station-level metrics derived from coverage and reliability outputs.
Source code in src/subway_access/models/_metric.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
AccessibilityComparisonDataset
dataclass
¶
Collection of tract-level Euclidean vs network comparison results.
Source code in src/subway_access/models/_network.py
84 85 86 87 88 | |
AccessibilityComparisonRecord
dataclass
¶
Per-tract comparison between Euclidean and network accessibility models.
Source code in src/subway_access/models/_network.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
NetworkGraphSnapshot
dataclass
¶
Cached OSM walking graph metadata for one study area.
Source code in src/subway_access/models/_network.py
48 49 50 51 52 53 54 55 56 57 58 59 60 | |
PedestrianConnection
dataclass
¶
A simplified pedestrian connection between two stations or nodes.
Source code in src/subway_access/models/_network.py
16 17 18 19 20 21 22 23 24 25 26 27 28 | |
PedestrianNetworkDataset
dataclass
¶
Loaded pedestrian connections used for richer examples and metrics.
Source code in src/subway_access/models/_network.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
connection_count_by_station ¶
connection_count_by_station() -> dict[str, int]
Source code in src/subway_access/models/_network.py
38 39 40 41 42 43 44 45 | |
OutageDataset
dataclass
¶
Loaded outage events.
Source code in src/subway_access/models/_outage.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
outage_minutes_by_station ¶
outage_minutes_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, int]
Source code in src/subway_access/models/_outage.py
102 103 104 105 106 107 108 109 110 111 | |
outage_count_by_station ¶
outage_count_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, int]
Source code in src/subway_access/models/_outage.py
113 114 115 116 117 118 119 120 | |
recommended_as_of ¶
recommended_as_of() -> datetime | None
Return the latest timestamp represented in the dataset.
Source code in src/subway_access/models/_outage.py
122 123 124 125 126 127 128 129 130 131 | |
outage_total_by_station ¶
outage_total_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, int]
Source code in src/subway_access/models/_outage.py
133 134 135 136 137 138 139 140 141 142 143 | |
scheduled_outage_total_by_station ¶
scheduled_outage_total_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, int]
Source code in src/subway_access/models/_outage.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
unscheduled_outage_total_by_station ¶
unscheduled_outage_total_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, int]
Source code in src/subway_access/models/_outage.py
160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
mean_availability_ratio_by_station ¶
mean_availability_ratio_by_station(
window: TimeWindow, *, as_of: datetime | None = None
) -> dict[str, float]
Source code in src/subway_access/models/_outage.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
OutageRecord
dataclass
¶
Single elevator or escalator outage event.
Source code in src/subway_access/models/_outage.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
outage_minutes_override
class-attribute
instance-attribute
¶
outage_minutes_override: int | None = None
overlap_minutes ¶
overlap_minutes(
window: TimeWindow, *, as_of: datetime | None = None
) -> int
Return outage minutes that fall inside the supplied rolling window.
Source code in src/subway_access/models/_outage.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
ReliabilityDataset
dataclass
¶
Rolling reliability results for stations.
Source code in src/subway_access/models/_outage.py
197 198 199 200 201 202 203 204 | |
ReliabilityRecord
dataclass
¶
Rolling reliability summary for a station.
Source code in src/subway_access/models/_outage.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
mean_availability_ratio
class-attribute
instance-attribute
¶
mean_availability_ratio: float | None = None
TimeWindow
dataclass
¶
Rolling time window used for reliability calculations.
Source code in src/subway_access/models/_outage.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
AccessibilitySummaryDataset
dataclass
¶
Grouped rollup summaries for accessibility results.
Source code in src/subway_access/models/_snapshot.py
74 75 76 77 78 | |
AccessibilitySummaryRecord
dataclass
¶
Rollup summary for accessibility metrics at a group level.
Source code in src/subway_access/models/_snapshot.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
DataSourceMetadata
dataclass
¶
Metadata describing one cached or fetched public dataset.
Source code in src/subway_access/models/_snapshot.py
28 29 30 31 32 33 34 35 36 37 | |
ExportTarget
dataclass
¶
Destination metadata for export commands.
Source code in src/subway_access/models/_snapshot.py
20 21 22 23 24 25 | |
StudyAreaSnapshot
dataclass
¶
In-memory snapshot of one real-data accessibility study area.
Source code in src/subway_access/models/_snapshot.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
AccessibilityDataset
dataclass
¶
Loaded ADA status rows.
Source code in src/subway_access/models/_station.py
98 99 100 101 102 103 104 105 | |
as_mapping ¶
as_mapping() -> dict[str, AccessibilityStatus]
Source code in src/subway_access/models/_station.py
104 105 | |
AccessibilityStatus
dataclass
¶
ADA accessibility status keyed by station identifier.
Source code in src/subway_access/models/_station.py
46 47 48 49 50 51 52 53 | |
Station
dataclass
¶
Station record used by the current accessibility workflow.
Source code in src/subway_access/models/_station.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
StationDataset
dataclass
¶
Loaded station rows for an analysis run.
Source code in src/subway_access/models/_station.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
as_mapping ¶
as_mapping() -> dict[str, Station]
Source code in src/subway_access/models/_station.py
62 63 | |
with_accessibility ¶
with_accessibility(
accessibility: AccessibilityDataset,
) -> StationDataset
Merge ADA status into the station dataset.
Source code in src/subway_access/models/_station.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
AccessibilityScoreDataset
dataclass
¶
Joined tract accessibility scoring results.
Source code in src/subway_access/models/_tract.py
55 56 57 58 59 | |
DemographicDataset
dataclass
¶
Loaded tract-level demographic rows.
Source code in src/subway_access/models/_tract.py
48 49 50 51 52 | |
TractAccessibilityRecord
dataclass
¶
Joined tract-level accessibility score for the current workflow.
Source code in src/subway_access/models/_tract.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | |
nearest_accessible_distance_meters
instance-attribute
¶
nearest_accessible_distance_meters: float | None
nearest_accessible_path_meters
class-attribute
instance-attribute
¶
nearest_accessible_path_meters: float | None = None
nearest_accessible_travel_minutes
class-attribute
instance-attribute
¶
nearest_accessible_travel_minutes: float | None = None
TractDemographics
dataclass
¶
Demographic summary for a tract centroid.
Source code in src/subway_access/models/_tract.py
8 9 10 11 12 13 14 15 16 17 18 19 20 | |
IO¶
subway_access.io ¶
Public loader entry points for subway-access.
MTA_ELEVATOR_AVAILABILITY_API_URL
module-attribute
¶
MTA_ELEVATOR_AVAILABILITY_API_URL = (
"https://data.ny.gov/resource/rc78-7x78.json"
)
MTA_EQUIPMENT_ASSET_API_URL
module-attribute
¶
MTA_EQUIPMENT_ASSET_API_URL = (
"https://data.ny.gov/resource/94fv-bak7.json"
)
MTA_GTFS_STATIC_URL
module-attribute
¶
MTA_GTFS_STATIC_URL = (
"https://rrgtfsfeeds.s3.amazonaws.com/gtfs_subway.zip"
)
MTA_SUBWAY_ENTRANCES_API_URL
module-attribute
¶
MTA_SUBWAY_ENTRANCES_API_URL = (
"https://data.ny.gov/resource/i9wp-a4ja.json"
)
MTA_SUBWAY_STATIONS_API_URL
module-attribute
¶
MTA_SUBWAY_STATIONS_API_URL = (
"https://data.ny.gov/resource/39hk-dx4f.json"
)
fetch_nyc_acs_tract_estimates ¶
fetch_nyc_acs_tract_estimates(
*, tract_geoids: tuple[str, ...] | None = None
) -> dict[str, dict[str, object]]
Fetch ACS tract-level population, senior, disability, and poverty data.
Source code in src/subway_access/io/_acs.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
cache_timestamp ¶
cache_timestamp() -> str
Return an ISO-8601 UTC timestamp for cache metadata.
Source code in src/subway_access/io/_cache.py
21 22 23 24 | |
ensure_directory ¶
ensure_directory(path: Path) -> Path
Create a directory if needed and return it.
Source code in src/subway_access/io/_cache.py
14 15 16 17 18 | |
write_csv_rows ¶
write_csv_rows(
path: Path, rows: list[dict[str, Any]]
) -> Path
Write a tabular CSV snapshot.
Source code in src/subway_access/io/_cache.py
27 28 29 30 31 32 33 34 35 36 37 | |
write_json ¶
write_json(path: Path, payload: object) -> Path
Write JSON with stable formatting.
Source code in src/subway_access/io/_cache.py
40 41 42 43 44 45 | |
load_accessibility_status ¶
load_accessibility_status(
source: str | Path,
) -> AccessibilityDataset
Load cached station accessibility status keyed by station identifier.
Source code in src/subway_access/io/_core.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
load_census_data ¶
load_census_data(source: str | Path) -> DemographicDataset
Load cached tract-level demographic variables used in need scoring.
Source code in src/subway_access/io/_core.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | |
load_gtfs ¶
load_gtfs(source: str | Path) -> StationDataset
Load a cached real-data station snapshot CSV.
Source code in src/subway_access/io/_core.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
load_outages ¶
load_outages(source: str | Path) -> OutageDataset
Load cached elevator availability or outage history from CSV or JSON.
Source code in src/subway_access/io/_core.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
load_pedestrian_network ¶
load_pedestrian_network(
source: str | Path,
) -> PedestrianNetworkDataset
Load a cached pedestrian connection graph from CSV or GeoJSON.
Source code in src/subway_access/io/_core.py
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 | |
load_entrances ¶
load_entrances(source: str | Path) -> EntranceDataset
Load a cached entrances.geojson FeatureCollection into an EntranceDataset.
Source code in src/subway_access/io/_entrances.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
load_gtfs_pathways_snapshot ¶
load_gtfs_pathways_snapshot(
source: str | Path,
) -> GtfsPathwaysSnapshot
Load gtfs-pathways.json written by the pipeline.
Source code in src/subway_access/io/_gtfs_static.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
parse_gtfs_pathways_zip ¶
parse_gtfs_pathways_zip(
zip_path: Path,
) -> GtfsPathwaysSnapshot | None
Parse GTFS-Pathways files from a static archive if present.
Returns None when neither pathways.txt nor locations.txt exists in the zip
(current MTA gtfs_subway.zip has neither).
Source code in src/subway_access/io/_gtfs_static.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
build_entrance_snapshot_rows ¶
build_entrance_snapshot_rows(
entrance_rows: list[dict[str, Any]],
) -> list[dict[str, Any]]
Normalize raw entrance API rows into cacheable property dicts (with latitude/longitude).
Join keys: station_id (MTA station id), complex_id, gtfs_stop_id (parent stop).
Source code in src/subway_access/io/_mta.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
build_outage_snapshot_rows ¶
build_outage_snapshot_rows(
availability_rows: list[dict[str, Any]],
) -> list[dict[str, Any]]
Normalize public availability history rows into outage-style snapshot rows.
Source code in src/subway_access/io/_mta.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | |
build_station_snapshot_rows ¶
build_station_snapshot_rows(
station_catalog_rows: list[dict[str, Any]],
) -> tuple[list[dict[str, str]], list[dict[str, str]]]
Normalize raw station catalog rows into cacheable CSV snapshots.
Source code in src/subway_access/io/_mta.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
fetch_mta_availability_history ¶
fetch_mta_availability_history(
*,
station_complex_ids: tuple[str, ...] | None = None,
start_month: date | None = None,
limit: int = 50000,
) -> list[dict[str, Any]]
Fetch public monthly elevator and escalator availability history.
Source code in src/subway_access/io/_mta.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 | |
fetch_mta_equipment_assets ¶
fetch_mta_equipment_assets(
*,
station_complex_ids: tuple[str, ...] | None = None,
limit: int = 5000,
) -> list[dict[str, Any]]
Fetch elevator and escalator asset inventory rows.
Source code in src/subway_access/io/_mta.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
fetch_mta_gtfs_archive ¶
fetch_mta_gtfs_archive(
target_path: Path,
*,
source_url: str = MTA_GTFS_STATIC_URL,
refresh: bool = False,
) -> Path
Download the official subway GTFS archive into the cache.
Source code in src/subway_access/io/_mta.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 | |
fetch_mta_station_catalog ¶
fetch_mta_station_catalog(
*, limit: int = 2000
) -> list[dict[str, Any]]
Fetch the public MTA subway station catalog from Open NY.
Source code in src/subway_access/io/_mta.py
151 152 153 154 155 156 157 158 159 | |
fetch_mta_subway_entrances ¶
fetch_mta_subway_entrances(
*, limit: int = 5000
) -> list[dict[str, Any]]
Fetch MTA subway entrance and exit points (NYC Transit) from Open NY.
Source code in src/subway_access/io/_mta.py
162 163 164 165 166 167 168 169 170 | |
fetch_walk_graph ¶
fetch_walk_graph(
query: AccessibilityQuery,
*,
cache_dir: str | Path,
refresh: bool = False,
network_type: str = "walk",
buffer_meters: int = 0,
) -> NetworkGraphSnapshot
Fetch and cache an OSM walking graph for the selected study area.
Source code in src/subway_access/io/_osm.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
load_cached_walk_graph ¶
load_cached_walk_graph(
cache_dir: str | Path,
) -> tuple[Any, NetworkGraphSnapshot]
Load a previously cached OSM walking graph and its metadata.
Source code in src/subway_access/io/_osm.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
Analysis¶
subway_access.analysis ¶
Public analysis helpers for subway-access.
analyze_gaps ¶
analyze_gaps(
scored_data: AccessibilityScoreDataset,
) -> GapAnalysis
Identify tracts with high need and weak accessible station coverage.
Classifies each tract as "covered" or "gap" based on whether
it has at least one accessible station in its catchment. Gap score
is 0.0 for covered tracts, or the need score for uncovered tracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scored_data
|
AccessibilityScoreDataset
|
Tract accessibility scores from |
required |
Returns:
| Type | Description |
|---|---|
GapAnalysis
|
A |
Example
gaps = analyze_gaps(scores) gaps.records[0].gap_label 'gap'
Source code in src/subway_access/analysis/_core.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
build_station_metrics ¶
build_station_metrics(
station_data: StationDataset,
catchments: CatchmentDataset,
scored_data: AccessibilityScoreDataset,
*,
reliability: ReliabilityDataset | None = None,
pedestrian_network: PedestrianNetworkDataset
| None = None,
analysis_method: str = "euclidean",
) -> StationMetricDataset
Aggregate station-level metrics for reporting and export.
Combines coverage counts, population served, need scores, and optional reliability data into one record per station.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_data
|
StationDataset
|
Loaded station rows. |
required |
catchments
|
CatchmentDataset
|
Generated catchment geometries. |
required |
scored_data
|
AccessibilityScoreDataset
|
Tract accessibility scores. |
required |
reliability
|
ReliabilityDataset | None
|
Optional reliability dataset for score/label inclusion. |
None
|
pedestrian_network
|
PedestrianNetworkDataset | None
|
Optional pedestrian network for connection counts. |
None
|
analysis_method
|
str
|
Label for the analysis method used. |
'euclidean'
|
Returns:
| Type | Description |
|---|---|
StationMetricDataset
|
A |
Example
metrics = build_station_metrics( ... stations, catchments, scores, reliability=reliability ... )
Source code in src/subway_access/analysis/_core.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 | |
compute_reliability ¶
compute_reliability(
accessibility_data: StationDataset
| AccessibilityDataset,
outage_data: OutageDataset,
window: TimeWindow,
) -> ReliabilityDataset
Compute a rolling station reliability score from outage history.
For each station, calculates the fraction of the time window that was outage-free and assigns a reliability label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accessibility_data
|
StationDataset | AccessibilityDataset
|
Station or accessibility dataset with ADA status. |
required |
outage_data
|
OutageDataset
|
Loaded outage events. |
required |
window
|
TimeWindow
|
Rolling time window (e.g. 30 days, 365 days). |
required |
Returns:
| Type | Description |
|---|---|
ReliabilityDataset
|
A |
Example
reliability = compute_reliability( ... stations, outages, models.TimeWindow(days=30) ... )
Source code in src/subway_access/analysis/_core.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | |
generate_catchments ¶
generate_catchments(
station_data: StationDataset, request: CatchmentRequest
) -> CatchmentDataset
Generate first-pass Euclidean catchments for a walk threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_data
|
StationDataset
|
Loaded station rows for the study area. |
required |
request
|
CatchmentRequest
|
Catchment parameters (walk minutes, mode). |
required |
Returns:
| Type | Description |
|---|---|
CatchmentDataset
|
A |
Example
catchments = generate_catchments( ... stations, models.CatchmentRequest(minutes=10) ... )
Source code in src/subway_access/analysis/_core.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
score_accessibility ¶
score_accessibility(
station_data: StationDataset,
catchments: CatchmentDataset,
demographics: DemographicDataset,
) -> AccessibilityScoreDataset
Score tract accessibility using station, catchment, and demographic inputs.
For each tract, tests whether its centroid falls within any accessible station's catchment radius and computes a composite need score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_data
|
StationDataset
|
Loaded station rows with ADA status. |
required |
catchments
|
CatchmentDataset
|
Generated catchment geometries. |
required |
demographics
|
DemographicDataset
|
Tract-level demographic data. |
required |
Returns:
| Type | Description |
|---|---|
AccessibilityScoreDataset
|
An |
Example
scores = score_accessibility(stations, catchments, demographics) scores.records[0].has_accessible_station True
Source code in src/subway_access/analysis/_core.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
entrances_per_complex_id ¶
entrances_per_complex_id(
dataset: EntranceDataset,
) -> dict[str, int]
Return entrance counts keyed by station complex id.
Source code in src/subway_access/analysis/_entrances.py
17 18 19 20 | |
entrances_per_gtfs_stop_id ¶
entrances_per_gtfs_stop_id(
dataset: EntranceDataset,
) -> dict[str, int]
Return entrance counts keyed by GTFS parent stop id.
Source code in src/subway_access/analysis/_entrances.py
11 12 13 14 | |
pathways_and_locations_counts ¶
pathways_and_locations_counts(
snapshot: GtfsPathwaysSnapshot | None,
) -> tuple[int, int]
Return (pathway row count, location row count) for optional GTFS-Pathways data.
Source code in src/subway_access/analysis/_entrances.py
23 24 25 26 27 28 29 30 | |
compare_accessibility_models ¶
compare_accessibility_models(
euclidean_scores: AccessibilityScoreDataset,
network_scores: AccessibilityScoreDataset,
) -> AccessibilityComparisonDataset
Compare tract accessibility results between Euclidean and network models.
Source code in src/subway_access/analysis/_network.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
generate_network_isochrones ¶
generate_network_isochrones(
station_data: StationDataset,
graph: Any,
request: CatchmentRequest,
) -> CatchmentDataset
Generate walking-network catchments from a cached OSM graph.
Source code in src/subway_access/analysis/_network.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
score_accessibility_network ¶
score_accessibility_network(
station_data: StationDataset,
graph: Any,
demographics: DemographicDataset,
request: CatchmentRequest,
) -> AccessibilityScoreDataset
Score tract accessibility using walking-network travel rather than circles.
Source code in src/subway_access/analysis/_network.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
summarize_accessibility_by_group ¶
summarize_accessibility_by_group(
scored_data: AccessibilityScoreDataset,
*,
group_by: str = "borough",
) -> AccessibilitySummaryDataset
Summarize tract accessibility results by a record attribute.
Groups scored tracts by the given attribute and computes aggregate coverage rates, population counts, need scores, and travel times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scored_data
|
AccessibilityScoreDataset
|
Tract accessibility scores from |
required |
group_by
|
str
|
Attribute name to group by (default |
'borough'
|
Returns:
| Type | Description |
|---|---|
AccessibilitySummaryDataset
|
An |
Example
summary = summarize_accessibility_by_group(scores, group_by="borough") summary.records[0].coverage_rate 0.72
Source code in src/subway_access/analysis/_summaries.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
Factors¶
subway_access.factors ¶
Composable factor pipeline for accessibility analysis.
Factor ¶
Bases: ABC
Base class for a single computed column in the accessibility pipeline.
Subclass this and implement compute to create custom factors.
Each factor produces one value per tract when the pipeline runs.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Column name for this factor in pipeline output. |
dtype |
Literal['float', 'str', 'bool', 'int']
|
Data type of the computed value. |
Example
class MyFactor(Factor): ... name = "my_metric" ... dtype = "float" ... def compute(self, context: FactorContext) -> float: ... return context.tract.disability_rate * 2
Source code in src/subway_access/factors/_base.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
compute
abstractmethod
¶
compute(context: FactorContext) -> float | str | bool | int
Compute this factor's value for a single tract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
FactorContext
|
Row-level context with tract demographics, stations, catchments, and optional external data. |
required |
Returns:
| Type | Description |
|---|---|
float | str | bool | int
|
The computed value for this tract. |
Source code in src/subway_access/factors/_base.py
62 63 64 65 66 67 68 69 70 71 72 | |
FactorContext
dataclass
¶
Row-level context passed to each Factor during pipeline execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tract
|
TractDemographics
|
Demographic summary for the tract being evaluated. |
required |
stations
|
StationDataset
|
All stations in the study area. |
required |
catchments
|
CatchmentDataset
|
Generated catchment geometries for all stations. |
required |
extras
|
dict[str, Any] | None
|
Extensible slot for external data (housing costs, etc.). |
None
|
Example
ctx = FactorContext(tract=tract, stations=stations, catchments=catchments) factor.compute(ctx) 0.42
Source code in src/subway_access/factors/_base.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
Pipeline ¶
Composable factor pipeline -- add factors, run across a dataset.
Pipelines are immutable: add returns a new Pipeline instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
tuple[Factor, ...]
|
Initial tuple of factors. |
()
|
Example
from subway_access.factors import Pipeline, NeedScoreFactor, CoverageFactor pipe = Pipeline().add(NeedScoreFactor()).add(CoverageFactor()) result = pipe.run(contexts)
Source code in src/subway_access/factors/_base.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
add ¶
add(factor: Factor) -> Pipeline
Return a new Pipeline with the given factor appended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
Factor
|
The factor to add. |
required |
Returns:
| Type | Description |
|---|---|
Pipeline
|
A new Pipeline instance containing all previous factors plus this one. |
Source code in src/subway_access/factors/_base.py
155 156 157 158 159 160 161 162 163 164 165 | |
run ¶
run(contexts: Iterable[FactorContext]) -> PipelineResult
Execute all factors across the provided contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
Iterable[FactorContext]
|
One FactorContext per tract to evaluate. |
required |
Returns:
| Type | Description |
|---|---|
PipelineResult
|
A PipelineResult with one column per factor and one row per tract. |
Source code in src/subway_access/factors/_base.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
PipelineResult
dataclass
¶
Output of a Pipeline run -- one column per factor, one row per tract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
dict[str, tuple[Any, ...]]
|
Mapping of factor name to tuple of computed values. |
required |
tract_ids
|
tuple[str, ...]
|
Tuple of tract identifiers, one per row. |
required |
Example
result = pipeline.run(contexts) result.columns["need_score"] (0.12, 0.34, 0.56)
Source code in src/subway_access/factors/_base.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
to_records ¶
to_records() -> tuple[dict[str, Any], ...]
Convert to a tuple of row dicts.
Returns:
| Type | Description |
|---|---|
tuple[dict[str, Any], ...]
|
One dict per tract with tract_id plus all factor columns. |
Source code in src/subway_access/factors/_base.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 | |
to_dataframe ¶
to_dataframe() -> Any
Convert to a pandas DataFrame.
Returns:
| Type | Description |
|---|---|
Any
|
A DataFrame with tract_id index and one column per factor. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
Source code in src/subway_access/factors/_base.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
CoverageFactor ¶
Bases: Factor
Whether a tract is covered by at least one accessible station's catchment.
Example
CoverageFactor().compute(ctx) True
Source code in src/subway_access/factors/_builtin.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
compute ¶
compute(context: FactorContext) -> bool
Source code in src/subway_access/factors/_builtin.py
82 83 84 85 86 87 88 89 90 91 92 93 | |
GapScoreFactor ¶
Bases: Factor
Gap score: 0.0 if covered, need_score otherwise.
Depends on coverage and need score computations.
Uses a NeedScoreFactor and CoverageFactor internally.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
need_weights
|
dict[str, float] | None
|
Optional weights forwarded to the internal NeedScoreFactor. |
None
|
Example
GapScoreFactor().compute(ctx) 0.0
Source code in src/subway_access/factors/_builtin.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
compute ¶
compute(context: FactorContext) -> float
Source code in src/subway_access/factors/_builtin.py
117 118 119 120 | |
NearestStationDistanceFactor ¶
Bases: Factor
Haversine distance in meters to the nearest accessible station.
Returns -1.0 if no accessible stations exist.
Example
NearestStationDistanceFactor().compute(ctx) 423.7
Source code in src/subway_access/factors/_builtin.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
compute ¶
compute(context: FactorContext) -> float
Source code in src/subway_access/factors/_builtin.py
136 137 138 139 140 141 142 143 144 145 146 147 | |
NearestStationTravelMinutesFactor ¶
Bases: Factor
Estimated walking time in minutes to the nearest accessible station.
Uses a fixed walking speed of 80 m/min. Returns -1.0 if no accessible stations exist.
Example
NearestStationTravelMinutesFactor().compute(ctx) 5.3
Source code in src/subway_access/factors/_builtin.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
compute ¶
compute(context: FactorContext) -> float
Source code in src/subway_access/factors/_builtin.py
164 165 166 167 168 | |
NeedScoreFactor ¶
Bases: Factor
Composite need score from demographic vulnerability indicators.
By default, computes the unweighted mean of disability_rate,
senior_rate, and poverty_rate. Pass weights to override.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
dict[str, float] | None
|
Optional mapping of indicator name to weight.
Keys must be a subset of |
None
|
Example
factor = NeedScoreFactor() factor.compute(ctx) 0.15 weighted = NeedScoreFactor(weights={"disability": 0.5, "senior": 0.3, "poverty": 0.2})
Source code in src/subway_access/factors/_builtin.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
compute ¶
compute(context: FactorContext) -> float
Source code in src/subway_access/factors/_builtin.py
56 57 58 59 60 61 62 63 64 65 66 67 68 | |
ReliabilityWeightedCoverageFactor ¶
Bases: Factor
Coverage weighted by the best-covering station's reliability score.
Returns the highest reliability score among accessible stations whose catchment covers this tract, or 0.0 if the tract is uncovered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reliability_scores
|
dict[str, float]
|
Mapping of station_id to reliability score (0-1). |
required |
Example
scores = {"station_1": 0.99, "station_2": 0.85} ReliabilityWeightedCoverageFactor(scores).compute(ctx) 0.99
Source code in src/subway_access/factors/_builtin.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
compute ¶
compute(context: FactorContext) -> float
Source code in src/subway_access/factors/_builtin.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
StationCountFactor ¶
Bases: Factor
Number of accessible stations whose catchment covers this tract.
Example
StationCountFactor().compute(ctx) 2
Source code in src/subway_access/factors/_builtin.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
compute ¶
compute(context: FactorContext) -> int
Source code in src/subway_access/factors/_builtin.py
182 183 184 185 186 187 188 189 190 191 192 193 194 | |
Helpers¶
subway_access.helpers ¶
Reusable helpers extracted from example scaffolding.
ALL_BOROUGHS
module-attribute
¶
ALL_BOROUGHS: tuple[str, ...] = (
"Manhattan",
"Brooklyn",
"Queens",
"Bronx",
"Staten Island",
)
dataclass_fieldnames ¶
dataclass_fieldnames(cls: type) -> tuple[str, ...]
Return field names for a frozen dataclass type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls
|
type
|
A dataclass type. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Tuple of field name strings in declaration order. |
Example
from subway_access.models import GapRecord dataclass_fieldnames(GapRecord) ('tract_id', 'tract_name', 'borough', ...)
Source code in src/subway_access/helpers/_export.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
export_records_csv ¶
export_records_csv(
records: tuple[Any, ...],
path: Path,
*,
fieldnames: tuple[str, ...] | None = None,
formatters: dict[str, str] | None = None,
) -> Path
Export a tuple of frozen dataclass records to CSV.
Automatically extracts field names from the dataclass type if
fieldnames is not provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
tuple[Any, ...]
|
Tuple of frozen dataclass instances. |
required |
path
|
Path
|
Output file path. |
required |
fieldnames
|
tuple[str, ...] | None
|
Column names to include. Defaults to all fields. |
None
|
formatters
|
dict[str, str] | None
|
Optional mapping of field name to format string
(e.g. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Example
export_records_csv(gap_analysis.records, Path("gaps.csv")) PosixPath('gaps.csv')
Source code in src/subway_access/helpers/_export.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
borough_cache_dir ¶
borough_cache_dir(
cache_root: str | Path, borough: str
) -> Path
Return the canonical cache directory for a borough snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_root
|
str | Path
|
Parent directory for all borough caches. |
required |
borough
|
str
|
Borough name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the borough-specific cache directory. |
Example
borough_cache_dir("cache", "Manhattan") PosixPath('cache/manhattan')
Source code in src/subway_access/helpers/_iteration.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
fetch_borough_snapshots ¶
fetch_borough_snapshots(
boroughs: tuple[str, ...] | None = None,
*,
cache_root: str | Path,
refresh: bool = False,
availability_months: int = 12,
include_gtfs_archive: bool = True,
) -> dict[str, StudyAreaSnapshot]
Fetch and cache study-area snapshots for multiple boroughs.
Downloads GTFS archive only for the first borough to avoid redundant fetches of the same static feed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boroughs
|
tuple[str, ...] | None
|
Borough names to fetch. Defaults to all five boroughs. |
None
|
cache_root
|
str | Path
|
Parent directory for all borough caches. |
required |
refresh
|
bool
|
Force re-download of all data sources. |
False
|
availability_months
|
int
|
Months of availability history to fetch. |
12
|
include_gtfs_archive
|
bool
|
Whether to download the GTFS static archive. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, StudyAreaSnapshot]
|
Mapping of borough name to loaded |
Example
snapshots = fetch_borough_snapshots( ... ("Manhattan", "Brooklyn"), ... cache_root="cache", ... ) len(snapshots["Manhattan"].stations.stations) 151
Source code in src/subway_access/helpers/_iteration.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
iter_borough_snapshots ¶
iter_borough_snapshots(
boroughs: tuple[str, ...] | None = None,
*,
cache_root: str | Path,
) -> Iterator[tuple[str, StudyAreaSnapshot]]
Iterate over cached borough snapshots lazily.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boroughs
|
tuple[str, ...] | None
|
Borough names to iterate. Defaults to all five boroughs. |
None
|
cache_root
|
str | Path
|
Parent directory for all borough caches. |
required |
Yields:
| Type | Description |
|---|---|
tuple[str, StudyAreaSnapshot]
|
Tuples of |
Example
for borough, snap in iter_borough_snapshots(cache_root="cache"): ... print(borough, len(snap.stations.stations))
Source code in src/subway_access/helpers/_iteration.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
load_borough_snapshots ¶
load_borough_snapshots(
boroughs: tuple[str, ...] | None = None,
*,
cache_root: str | Path,
) -> dict[str, StudyAreaSnapshot]
Load previously cached snapshots for multiple boroughs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boroughs
|
tuple[str, ...] | None
|
Borough names to load. Defaults to all five boroughs. |
None
|
cache_root
|
str | Path
|
Parent directory for all borough caches. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, StudyAreaSnapshot]
|
Mapping of borough name to loaded |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If any borough's cache is missing. |
Example
snapshots = load_borough_snapshots( ... ("Manhattan",), cache_root="cache" ... )
Source code in src/subway_access/helpers/_iteration.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
write_markdown_report ¶
write_markdown_report(path: Path, content: str) -> Path
Write a markdown report file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Output file path. |
required |
content
|
str
|
Markdown content to write. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Source code in src/subway_access/helpers/_metadata.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
write_metadata_json ¶
write_metadata_json(
path: Path,
*,
title: str,
generated_at: datetime | None = None,
extra: dict[str, Any] | None = None,
) -> Path
Write a timestamped metadata JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Output file path. |
required |
title
|
str
|
Human-readable title for the metadata record. |
required |
generated_at
|
datetime | None
|
Timestamp. Defaults to now (UTC). |
None
|
extra
|
dict[str, Any] | None
|
Additional key-value pairs to include. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Example
write_metadata_json( ... Path("metadata.json"), ... title="Manhattan gap analysis", ... extra={"tract_count": 200}, ... )
Source code in src/subway_access/helpers/_metadata.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
Export¶
subway_access.export ¶
Public exporters for subway-access.
export_catchments_geojson ¶
export_catchments_geojson(
data: CatchmentDataset, target: ExportTarget
) -> Path
Export station catchments to GeoJSON for mapping workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
CatchmentDataset
|
Generated catchment geometries. |
required |
target
|
ExportTarget
|
Export target with format |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Source code in src/subway_access/export/_core.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
export_gap_table ¶
export_gap_table(
data: GapAnalysis, target: ExportTarget
) -> Path
Export tract-level accessibility gap tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
GapAnalysis
|
Gap analysis results from |
required |
target
|
ExportTarget
|
Export target with format |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Source code in src/subway_access/export/_core.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
export_station_metrics ¶
export_station_metrics(
data: StationMetricDataset, target: ExportTarget
) -> Path
Export station-level accessibility and reliability metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
StationMetricDataset
|
Station metric dataset from |
required |
target
|
ExportTarget
|
Export target with format |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The resolved output path. |
Source code in src/subway_access/export/_core.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
Pipeline¶
subway_access.pipeline ¶
High-level real-data pipeline helpers for subway-access.
fetch_study_area_snapshot ¶
fetch_study_area_snapshot(
query: AccessibilityQuery,
*,
cache_dir: str | Path,
refresh: bool = False,
availability_months: int = 12,
include_gtfs_archive: bool = True,
) -> StudyAreaSnapshot
Fetch, cache, and load a real-data study-area snapshot.
Source code in src/subway_access/pipeline/_fetch.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
load_cached_snapshot ¶
load_cached_snapshot(
cache_dir: str | Path,
) -> StudyAreaSnapshot
Load a previously fetched real-data study-area snapshot.
Source code in src/subway_access/pipeline/_load.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
fetch_walk_graph ¶
fetch_walk_graph(
query: AccessibilityQuery,
*,
cache_dir: str | Path,
refresh: bool = False,
buffer_meters: int = 0,
) -> NetworkGraphSnapshot
Fetch and cache an OSM walking graph for a study area.
Source code in src/subway_access/pipeline/_walk_graph.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
load_cached_walk_graph ¶
load_cached_walk_graph(
cache_dir: str | Path,
) -> tuple[Any, NetworkGraphSnapshot]
Load a cached OSM walking graph and its typed metadata.
Source code in src/subway_access/pipeline/_walk_graph.py
40 41 42 43 44 45 | |
Reporting¶
subway_access.reporting ¶
Optional reporting helpers: jellycell tearsheets from factor-factory engine results.
This module is an optional surface. All dependencies on factor_factory
and jellycell are deferred to call time, so importing
subway_access.reporting succeeds even when those extras are not installed.
Invoking any of the helpers below without the relevant extras raises a
:class:ImportError that points at the right pip install command.
Install via::
pip install "subway-access[factor-factory,tearsheets]"
EngineKind
module-attribute
¶
EngineKind = Literal[
"did",
"rdd",
"scm",
"spatial",
"event_study",
"mediation",
]
Factor-factory engine-family identifiers supported by the bridge.
The family name is used as the artifact filename stem: an EngineKind of
"did" writes to <artifacts_dir>/did_results.json, matching the key
the shipped jellycell findings template reads from.
emit_findings_tearsheet ¶
emit_findings_tearsheet(
project_dir: Path,
*,
overwrite: bool = True,
template_overrides: dict[str, Any] | None = None,
) -> Path
Render the FINDINGS.md tearsheet for a project directory.
Thin wrapper around factor_factory.jellycell.tearsheets.findings(...).
The target project directory is expected to follow the factor-factory
convention:
<project_dir>/artifacts/<family>_results.json(one per engine family fit, written via :func:write_engine_results_json)<project_dir>/artifacts/figures/(optional, picked up by the template if present)<project_dir>/manuscripts/FINDINGS.md(the rendered output)
The freeze-marker splicing behavior of factor-factory is preserved: when
overwrite=True, any text in an existing FINDINGS.md that sits
below a <!-- tearsheet:freeze --> line is kept verbatim; text above
the marker is regenerated from the template.
Parameters¶
project_dir
Absolute or relative path to the project directory.
overwrite
When True (the default), regenerate the tearsheet using
freeze-marker splicing. When False, raise FileExistsError if
the target already exists.
template_overrides
Optional mapping overlaid on top of the default template context.
Keys depend on the shipped findings.md.j2 template — consult
factor-factory documentation for the supported fields.
Returns¶
Path The absolute path of the rendered tearsheet.
Raises¶
ImportError
If factor-factory (which bundles jellycell bindings) is not
installed.
Source code in src/subway_access/reporting/_jellycell_bridge.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
render_findings_from_dict ¶
render_findings_from_dict(
results: Mapping[str, Mapping[str, Any]],
*,
out_path: Path,
project: str,
template_overrides: Mapping[str, Any] | None = None,
) -> Path
Render a FINDINGS.md tearsheet directly from in-memory results.
Thin wrapper over
jellycell.tearsheets.findings
(new in jellycell v1.4.0). Complementary to
:func:emit_findings_tearsheet: that helper scans a factor-factory project
directory for artifacts/<family>_results.json files and renders
manuscripts/FINDINGS.md with freeze-marker splicing. This one takes a
plain Python dict and writes to any path — useful when you already have
engine fits in memory (notebook, CI smoke, blog-post assembly) and don't
want the project-directory dance.
Parameters¶
results
Mapping of method_name -> {field: value}. One ## <method_name>
heading + two-column metric table is emitted per top-level key. Nested
dicts flatten with dotted keys ({"cs": {"att": 0.2}} → cs.att
row). The canonical way to produce this shape from factor-factory
results is::
results_dict = {r.method: r.to_dict() for r in did_results}
out_path
Target markdown path. Parent directories are created if needed.
project
Project name rendered in the manuscript header (e.g.
"subway-access / accessibility-change"). Does not have to be a
filesystem path — this is just a label.
template_overrides
Optional header-field overrides forwarded to
jellycell.tearsheets.findings. Supported keys include author,
author_url, month_year, version, project.
Returns¶
Path The resolved path of the rendered tearsheet.
Raises¶
ImportError
If jellycell is not installed (points at [tearsheets]) or if
the installed jellycell is older than v1.4.0.
Source code in src/subway_access/reporting/_jellycell_bridge.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
require_factor_factory ¶
require_factor_factory() -> ModuleType
Return the factor_factory top-level module or raise a crisp error.
Returns¶
ModuleType
The imported factor_factory module.
Raises¶
ImportError
If factor-factory is not installed. The message includes the
exact pip install command to recover.
Source code in src/subway_access/reporting/_jellycell_bridge.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
require_jellycell ¶
require_jellycell() -> ModuleType
Return the jellycell top-level module or raise a crisp error.
Returns¶
ModuleType
The imported jellycell module.
Raises¶
ImportError
If jellycell is not installed. The message includes the exact
pip install command to recover.
Source code in src/subway_access/reporting/_jellycell_bridge.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
write_engine_results_json ¶
write_engine_results_json(
results: Iterable[Any] | Any,
*,
artifacts_dir: Path,
family: EngineKind | str,
) -> Path
Serialize one or more factor-factory engine results to <family>_results.json.
The shipped jellycell findings.md.j2 template reads from a structured
JSON file at <project_dir>/artifacts/<family>_results.json with the
shape {"results": [<to_dict>...]}. This helper accepts either a
single result dataclass (with a .to_dict() method), an iterable of
them, or a pre-built Results wrapper (with a .to_records()
method, as returned by factor_factory.engines.<family>.estimate(...)).
Parameters¶
results One of:
- A ``*Results`` wrapper exposing ``.to_records()`` (e.g.
``DidResults``, ``RddResults``, ``ScmResults``, ``SpatialResults``).
- A single ``*Result`` frozen dataclass exposing ``.to_dict()``.
- An iterable of such dataclasses.
artifacts_dir
Directory where the JSON file is written. Created if it does not
already exist.
family
Engine-family name used as the filename stem. Supported values are
listed in :data:EngineKind; any string is accepted to support
downstream engines not yet enumerated here.
Returns¶
Path The absolute path of the written JSON file.
Source code in src/subway_access/reporting/_jellycell_bridge.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
Temporal¶
subway_access.temporal ¶
Temporal panel infrastructure for accessibility-over-time analysis.
AVAILABLE_VINTAGE_YEARS
module-attribute
¶
AVAILABLE_VINTAGE_YEARS: tuple[int, ...] = (
2017,
2018,
2019,
2020,
2021,
2022,
2023,
)
PanelDataset
dataclass
¶
Geographic panel: unit x time observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observations
|
tuple[PanelObservation, ...]
|
All panel rows. |
required |
unit_type
|
str
|
Geographic unit type ( |
required |
periods
|
tuple[str, ...]
|
Ordered tuple of period labels. |
required |
Example
panel.periods ('2017', '2018', '2019', '2020', '2021', '2022', '2023') len(panel.observations) 1400
Source code in src/subway_access/temporal/_models.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
treatment_group ¶
treatment_group() -> PanelDataset
Return only observations in units that were ever treated.
Source code in src/subway_access/temporal/_models.py
75 76 77 78 79 80 81 82 83 84 85 86 87 | |
control_group ¶
control_group() -> PanelDataset
Return only observations in units that were never treated.
Source code in src/subway_access/temporal/_models.py
89 90 91 92 93 94 95 96 97 98 99 100 101 | |
to_dataframe ¶
to_dataframe() -> Any
Convert to a pandas DataFrame with (unit_id, period) index.
Returns:
| Type | Description |
|---|---|
Any
|
A pandas DataFrame. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If pandas is not installed. |
Source code in src/subway_access/temporal/_models.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
PanelObservation
dataclass
¶
Single (unit x period) observation in the geographic panel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_id
|
str
|
NTA code or census tract GEOID. |
required |
period
|
str
|
ACS vintage year, e.g. |
required |
has_accessible_station
|
bool
|
Treatment indicator -- True if this unit gained at least one accessible station by this period. |
required |
treatment_year
|
int | None
|
Year the first accessible station opened in this unit's catchment, or None if never treated. |
required |
disability_rate
|
float
|
ACS 5-year estimate for this vintage. |
required |
senior_rate
|
float
|
ACS 5-year estimate for this vintage. |
required |
poverty_rate
|
float
|
ACS 5-year estimate for this vintage. |
required |
total_population
|
int
|
ACS 5-year estimate for this vintage. |
required |
accessible_station_count
|
int
|
Number of accessible stations in catchment. |
required |
nearest_accessible_distance_m
|
float | None
|
Haversine distance to nearest accessible station, or None if none exist. |
required |
need_score
|
float
|
Composite factor pipeline output. |
required |
covariates
|
dict[str, float] | None
|
Extensible dict for additional time-varying covariates (median_rent, employment rate, etc.). |
None
|
Example
obs = PanelObservation( ... unit_id="36061000100", period="2020", ... has_accessible_station=True, treatment_year=2019, ... disability_rate=0.08, senior_rate=0.12, poverty_rate=0.15, ... total_population=4500, accessible_station_count=2, ... nearest_accessible_distance_m=320.0, need_score=0.117, ... )
Source code in src/subway_access/temporal/_models.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
StationUpgradeRecord
dataclass
¶
Record of a station's ADA upgrade timeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_id
|
str
|
MTA station identifier. |
required |
station_name
|
str
|
Human-readable station name. |
required |
borough
|
str
|
NYC borough. |
required |
latitude
|
float
|
Station latitude. |
required |
longitude
|
float
|
Station longitude. |
required |
upgrade_year
|
int | None
|
Year the station became ADA-accessible, or None. |
required |
upgrade_source
|
str
|
Data source for the upgrade date. |
''
|
Source code in src/subway_access/temporal/_models.py
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
UpgradeTimeline
dataclass
¶
Collection of station ADA upgrade records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
tuple[StationUpgradeRecord, ...]
|
All station upgrade records. |
required |
Example
timeline.stations_upgraded_by(2020) ('S1', 'S2', 'S3')
Source code in src/subway_access/temporal/_models.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
stations_upgraded_by ¶
stations_upgraded_by(year: int) -> tuple[str, ...]
Return station IDs upgraded on or before the given year.
Source code in src/subway_access/temporal/_models.py
186 187 188 189 190 191 192 193 | |
upgrade_year_for ¶
upgrade_year_for(station_id: str) -> int | None
Return the upgrade year for a specific station, or None.
Source code in src/subway_access/temporal/_models.py
195 196 197 198 199 200 201 | |
fetch_acs_tract_estimates_for_year ¶
fetch_acs_tract_estimates_for_year(
year: int,
*,
tract_geoids: tuple[str, ...] | None = None,
) -> dict[str, dict[str, object]]
Fetch ACS tract-level estimates for a specific vintage year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
ACS 5-year vintage year (e.g. 2020). |
required |
tract_geoids
|
tuple[str, ...] | None
|
Optional tuple of tract GEOIDs to filter to. If None, fetches all NYC tracts. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, object]]
|
Mapping of tract GEOID to estimate dict with keys: tract_id, |
dict[str, dict[str, object]]
|
tract_name, total_population, senior_rate, poverty_rate, |
dict[str, dict[str, object]]
|
disability_rate. |
Example
estimates = fetch_acs_tract_estimates_for_year(2020) len(estimates) 2168
Source code in src/subway_access/temporal/_acs_vintage.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | |
fetch_multi_vintage_estimates ¶
fetch_multi_vintage_estimates(
years: tuple[int, ...] | None = None,
*,
tract_geoids: tuple[str, ...] | None = None,
) -> dict[int, dict[str, dict[str, object]]]
Fetch ACS estimates for multiple vintage years.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
years
|
tuple[int, ...] | None
|
Tuple of vintage years to fetch. Defaults to all available. |
None
|
tract_geoids
|
tuple[str, ...] | None
|
Optional tuple of tract GEOIDs to filter to. |
None
|
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, dict[str, object]]]
|
Nested mapping: year -> tract_geoid -> estimate dict. |
Example
multi = fetch_multi_vintage_estimates(years=(2019, 2020, 2021)) sorted(multi.keys()) [2019, 2020, 2021]
Source code in src/subway_access/temporal/_acs_vintage.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
build_panel_dataset ¶
build_panel_dataset(
vintage_estimates: dict[
int, dict[str, dict[str, object]]
],
station_locations: dict[str, tuple[float, float]],
upgrade_timeline: UpgradeTimeline,
*,
catchment_radius_meters: float = 800.0,
unit_type: str = "tract",
extra_covariates: dict[int, dict[str, dict[str, float]]]
| None = None,
) -> PanelDataset
Construct a geographic panel dataset from multi-vintage ACS estimates.
Joins demographic estimates across vintage years with station accessibility status (derived from the upgrade timeline) to produce a panel suitable for difference-in-differences or spatial panel regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vintage_estimates
|
dict[int, dict[str, dict[str, object]]]
|
Nested mapping year -> tract_geoid -> estimate dict. Each estimate dict must have keys: disability_rate, senior_rate, poverty_rate, total_population. |
required |
station_locations
|
dict[str, tuple[float, float]]
|
Mapping of station_id -> (latitude, longitude) for all stations in the study area. |
required |
upgrade_timeline
|
UpgradeTimeline
|
Station ADA upgrade records with year information. |
required |
catchment_radius_meters
|
float
|
Maximum distance in meters for a tract to be considered "covered" by a station. Defaults to 800m (~10 min walk). |
800.0
|
unit_type
|
str
|
Geographic unit type label ( |
'tract'
|
extra_covariates
|
dict[int, dict[str, dict[str, float]]] | None
|
Optional nested mapping year -> tract_geoid -> dict of additional time-varying covariates (e.g. median_rent). |
None
|
Returns:
| Type | Description |
|---|---|
PanelDataset
|
A PanelDataset with one observation per (unit, period) pair. |
Example
panel = build_panel_dataset( ... vintage_estimates=multi_vintage, ... station_locations=stations, ... upgrade_timeline=timeline, ... ) len(panel.observations) 1400
Source code in src/subway_access/temporal/_panel.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |
build_distance_weights ¶
build_distance_weights(
unit_centroids: dict[str, tuple[float, float]],
*,
threshold_meters: float = 2000.0,
row_standardize: bool = True,
) -> dict[str, dict[str, float]]
Build a distance-based spatial weights matrix.
Creates a symmetric weights matrix where units within the distance threshold are neighbors, weighted by inverse distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_centroids
|
dict[str, tuple[float, float]]
|
Mapping of unit_id -> (latitude, longitude). |
required |
threshold_meters
|
float
|
Maximum distance for two units to be neighbors. |
2000.0
|
row_standardize
|
bool
|
If True, normalize each row to sum to 1.0. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, float]]
|
Nested dict: unit_id -> neighbor_unit_id -> weight. |
dict[str, dict[str, float]]
|
Units with no neighbors have an empty inner dict. |
Example
centroids = {"T1": (40.75, -73.99), "T2": (40.751, -73.991)} weights = build_distance_weights(centroids, threshold_meters=500) len(weights) 2
Source code in src/subway_access/temporal/_spatial_weights.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
weights_to_pysal ¶
weights_to_pysal(
weights: dict[str, dict[str, float]],
) -> Any
Convert a weights dict to a PySAL W object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
dict[str, dict[str, float]]
|
Nested dict from |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A |
Raises:
| Type | Description |
|---|---|
ImportError
|
If libpysal is not installed. |
Example
w = weights_to_pysal(weights) w.n 200
Source code in src/subway_access/temporal/_spatial_weights.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
build_upgrade_timeline ¶
build_upgrade_timeline(
station_data: StationDataset,
*,
known_upgrades: dict[str, int] | None = None,
known_upgrade_sources: dict[str, str] | None = None,
source: str = "mta_ada_status",
) -> UpgradeTimeline
Build an upgrade timeline from station dataset and known upgrade years.
For stations currently marked "accessible" but without a known upgrade year, they are treated as always-accessible (upgrade_year=None, which means they are in the treatment group for all periods).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
station_data
|
StationDataset
|
Current station dataset with ADA status. |
required |
known_upgrades
|
dict[str, int] | None
|
Optional mapping of station_id -> upgrade year. Overrides or supplements the built-in database. |
None
|
known_upgrade_sources
|
dict[str, str] | None
|
Optional mapping of station_id -> per-station
provenance tag. When a station id appears here, the tag is used
as the record's |
None
|
source
|
str
|
Default label used for the data source when no per-station
tag is supplied via |
'mta_ada_status'
|
Returns:
| Type | Description |
|---|---|
UpgradeTimeline
|
An UpgradeTimeline with one record per station. |
Example
timeline = build_upgrade_timeline(stations) timeline.stations_upgraded_by(2020) ('S1', 'S2')
Source code in src/subway_access/temporal/_upgrade_timeline.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
load_known_upgrades ¶
load_known_upgrades(csv_path: Path) -> dict[str, int]
Read a seeds CSV and return {station_id: upgrade_year} for filled rows.
Rows where upgrade_year is empty or non-numeric are silently skipped.
Source code in src/subway_access/temporal/_upgrade_timeline.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
load_known_upgrades_from_dir ¶
load_known_upgrades_from_dir(
directory: Path,
) -> dict[str, int]
Scan directory for per-borough CSVs and merge all filled upgrade years.
_all_boroughs.csv is excluded to avoid double-counting.
Source code in src/subway_access/temporal/_upgrade_timeline.py
103 104 105 106 107 108 109 110 111 112 113 | |
CLI¶
subway_access.cli ¶
Public CLI entry points for subway-access.
main ¶
main(argv: Sequence[str] | None = None) -> int
Entry point for the installed CLI.
Source code in src/subway_access/cli/_main.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
run_analyze_snapshot ¶
run_analyze_snapshot(
cache_dir: Path,
output_dir: Path,
*,
minutes: int,
reliability_window_days: int,
) -> int
Analyze a cached snapshot and export real-data outputs.
Source code in src/subway_access/cli/_main.py
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
run_fetch_snapshot ¶
run_fetch_snapshot(
cache_dir: Path,
*,
geography: str,
value: str,
availability_months: int,
refresh: bool,
skip_gtfs_archive: bool,
) -> int
Fetch and cache a real-data snapshot for one study area.
Source code in src/subway_access/cli/_main.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |