API Reference

This page documents the public modules and functions in wikipediaGATN.

The names re-exported at the top level of the package (see wikipediaGATN.__all__) are the recommended entry points:

Network-level crawling

Network-level BFS crawling of airport Wikipedia pages.

This module drives the breadth-first expansion of the airport network. Starting from a seed IATA code, it iteratively fetches each airport’s destinations (both passenger and cargo), saves the results as <CODE>.<level>.json files in TEMP_RESULTS_DIR/airports_rooted_sweep, and tracks progress in processed_locations.csv so that interrupted runs can be resumed.

Typical usage:

from wikipediaGATN.wikipedia_network_level import iterate_search_until_distance_N

# Crawl two hops out from Winnipeg
iterate_search_until_distance_N("YWG", dist=2, delay=0.5, verbose=True)

Functions

clean_output_directory delete scraped files to start fresh get_connections_level_N expand one BFS level check_processed_list deduplicate / clean progress CSV iterate_search_until_distance_N crawl to a fixed depth iterate_search_until_empty crawl until no new airports are found continue_existing_search_one_step resume a partially-complete crawl by one step continue_existing_search_until_empty resume and run to completion

wikipediaGATN.wikipedia_network_level.check_processed_list(verbose: bool = False) → None[source]

Deduplicate and clean processed_locations.csv.

  • Exports rows with iata == "None" to failed_lookups.csv.

  • Removes those rows and any duplicate URLs from the main file.

  • Re-sorts by (iata, url).

Parameters:

verbose (bool, optional) – Print summary counts. Default: False.

wikipediaGATN.wikipedia_network_level.clean_output_directory(levels=None, verbose: bool = False) → int[source]

Delete scraped airport JSON files from TEMP_RESULTS_DIR.

Also removes processed_locations.csv so the next run starts fresh.

Parameters:
  • levels (list of int or None, optional) – If None (default), removes all .<N>.json files. If a list of integers is given, only files at those BFS levels are removed (e.g. levels=[2, 3]).

  • verbose (bool, optional) – Print a summary of what was removed. Default: False.

Returns:

Total number of JSON files removed.

Return type:

int

wikipediaGATN.wikipedia_network_level.continue_existing_search_one_step(delay: float = 1.0, verbose: bool = False) → None[source]

Resume a partially-complete crawl by processing one additional BFS step.

Finds the highest level N already present in TEMP_RESULTS_DIR and re-runs get_connections_level_N(from_length=N-1) — stepping back one level ensures the previous frontier is complete before advancing.

Parameters:
  • delay (float, optional) – Seconds between Wikipedia requests. Default: 1.0.

  • verbose (bool, optional) – Print progress. Default: False.

wikipediaGATN.wikipedia_network_level.continue_existing_search_until_empty(delay: float = 1.0, verbose: bool = False) → None[source]

Resume a partially-complete crawl and run to completion.

Finds the highest BFS level N already present in TEMP_RESULTS_DIR and continues expanding from that point until no new airports are found.

Parameters:
  • delay (float, optional) – Seconds between Wikipedia requests. Default: 1.0.

  • verbose (bool, optional) – Print progress. Default: False.

Notes

Assumes the current highest level is already complete. If it is not, use continue_existing_search_one_step() first.

wikipediaGATN.wikipedia_network_level.get_connections_level_N(from_length: int = 0, delay: float = 1.0, verbose: bool = False) → int[source]

Expand the airport network by one BFS level.

For every airport file at level from_length (<CODE>.<from_length>.json), fetch each listed destination (both passenger and cargo) that has not yet been processed and save its data as <CODE>.<from_length+1>.json.

Parameters:
  • from_length (int, optional) – Source BFS level. Default: 0.

  • delay (float, optional) – Seconds to sleep between Wikipedia requests. Default: 1.0.

  • verbose (bool, optional) – Print per-destination progress. Default: False.

Returns:

Number of new destination files written.

Return type:

int

wikipediaGATN.wikipedia_network_level.iterate_search_until_distance_N(seed_iata: str, dist: int = 1, delay: float = 1.0, verbose: bool = False) → None[source]

Crawl the airport network to a fixed BFS depth.

Parameters:
  • seed_iata (str) – IATA code of the starting airport (e.g. "YWG").

  • dist (int, optional) – Maximum BFS depth. dist=1 fetches only direct connections from the seed. Default: 1.

  • delay (float, optional) – Seconds to sleep between Wikipedia requests. Default: 1.0.

  • verbose (bool, optional) – Print per-airport progress. Default: False.

wikipediaGATN.wikipedia_network_level.iterate_search_until_empty(seed_iata: str, delay: float = 1.0, verbose: bool = False) → None[source]

Crawl the airport network until no new airports are discovered.

Parameters:
  • seed_iata (str) – IATA code of the starting airport.

  • delay (float, optional) – Seconds between Wikipedia requests. Default: 1.0.

  • verbose (bool, optional) – Print per-airport progress. Default: False.

Notes

For a global crawl this may run for many hours. Use iterate_search_until_distance_N() if you want a bounded run.

Airport-level parsing

Airport-level Wikipedia scraping and data extraction functions.

Functions in this module interact with the Wikipedia API to fetch and parse airport pages, and supplement the extracted data using the authoritative OurAirports database.

Core Pipeline Functions:

  1. fetch_wikipedia_airport_link() resolve an identifier to a URL

  2. fetch_wikipedia_airport_html() fetch parsed HTML

  3. fetch_wikipedia_airport_wikitext() fetch raw wikitext

  4. fetch_wikipedia_airlines() set of airline names

  5. fetch_wikipedia_destinations() set of (name, URL) tuples

  6. fetch_wikipedia_airlines_destinations() airline → destinations map

  7. fetch_wikipedia_airport_info() all metadata in one dict

  8. save_airport_info() persist dict to JSON + progress CSV

OurAirports Integration & Validation:

  • infer_missing_geographic_data() supplement missing data via OurAirports

  • compare_airports_with_ourairports() audit extracted data against OurAirports

  • find_active_missing_airports() identify unmapped airports in OurAirports

  • build_url_to_codes_map() map Wikipedia URLs to IATA codes

Helper / Fallback functions:

wikipediaGATN.airport_level_functions.clean_infobox_value(value: str) → str[source]

Normalise a wikitext infobox value string.

  • {{nowrap|...}} -> inner content

  • {{Unbulleted list|...}} -> comma-separated items

  • {{URL|...}} -> bare URL

Parameters:

value (str) – Raw wikitext value.

Returns:

Cleaned string with wikilinks preserved as [[X]].

Return type:

str

wikipediaGATN.airport_level_functions.fallback_fetch_wikipedia_airport_info(html_content: str) → dict[source]

Extract basic airport info from HTML when the infobox cannot be parsed.

Parameters:

html_content (str) – Parsed HTML of the airport Wikipedia page.

Returns:

Keys: iata, icao, serves, location, coordinates, wikipedia_url. Values are strings or None.

Return type:

dict

wikipediaGATN.airport_level_functions.fetch_wikipedia_airlines(identifier: str = 'YWG', link=None, html_content=None, verbose: bool = False, soup=None) → set[source]

Extract airline names from an airport’s Wikipedia page.

Parameters:
  • identifier (str, optional) – IATA/ICAO code, Wikipedia URL, or name. Default: "YWG".

  • link (str or None, optional) – Wikipedia page URL (fetched automatically if absent).

  • html_content (str or None, optional) – Pre-fetched HTML (fetched automatically if absent).

  • verbose (bool, optional) – Print progress. Default: False.

  • soup (BeautifulSoup or None, optional) – Pre-parsed BeautifulSoup object. Default: None.

Returns:

Airline names extracted from the Airlines and destinations table.

Return type:

set of str

wikipediaGATN.airport_level_functions.fetch_wikipedia_airlines_destinations(identifier: str = 'YWG', link=None, html_content=None, verbose: bool = False, soup=None) → dict[source]

Extract an airline to destinations mapping from an airport’s Wikipedia page.

Falls back to parse_fallback_nlp_airlines_destinations() if no table-based data is found.

Parameters:
  • identifier (str, optional) – IATA/ICAO code, Wikipedia URL, or name. Default: "YWG".

  • link (str or None, optional) – Wikipedia page URL (fetched automatically if absent).

  • html_content (str or None, optional) – Pre-fetched HTML (fetched automatically if absent).

  • verbose (bool, optional) – Print progress. Default: False.

  • soup (BeautifulSoup or None, optional) – Pre-parsed BeautifulSoup object. Default: None.

Returns:

{"passenger": {airline_name: {destination_name, ...}, ...}, "cargo": {...}}

Return type:

dict

wikipediaGATN.airport_level_functions.fetch_wikipedia_airport_html(link: str, verbose: bool = False)[source]

Fetch the parsed HTML content of a Wikipedia page.

Parameters:
  • link (str) – Wikipedia page URL (https://en.wikipedia.org/wiki/<Title>).

  • verbose (bool, optional) – Print progress messages. Default: False.

Returns:

HTML string, or None on failure.

Return type:

str or None

wikipediaGATN.airport_level_functions.fetch_wikipedia_airport_info(identifier: str = 'YWG', link=None, verbose: bool = False) → dict[source]

Extract all available metadata for an airport from its Wikipedia page.

Parameters:
  • identifier (str, optional) – IATA/ICAO code, Wikipedia URL, or name. Default: "YWG".

  • link (str or None, optional) – Wikipedia page URL (fetched automatically if absent).

  • verbose (bool, optional) – Print progress. Default: False.

Returns:

Keys: iata, icao, city-served, location, lat, lon, altitude, region, country_alpha3, country_name, subdivision_code, wikipedia_url, airlines, destinations, airlines_destinations.

Return type:

dict

Resolve an airport identifier to its Wikipedia page URL.

Resolution order:

  1. If identifier is already a Wikipedia URL, the title is decoded from it.

  2. If identifier matches [A-Za-z]{3} or [A-Za-z]{4} (IATA/ICAO), search for "<CODE> airport".

  3. Otherwise, treat identifier as a free-text name; append " airport" if the word is not already present.

Parameters:
  • identifier (str) – IATA code, ICAO code, Wikipedia URL, or free-text airport name.

  • verbose (bool, optional) – Print search term and result. Default: False.

Returns:

Canonical Wikipedia URL, or None if no page was found.

Return type:

str or None

wikipediaGATN.airport_level_functions.fetch_wikipedia_airport_wikitext(link: str, verbose: bool = False)[source]

Fetch the raw wikitext source of a Wikipedia page.

Parameters:
  • link (str) – Wikipedia page URL.

  • verbose (bool, optional) – Print progress messages. Default: False.

Returns:

Wikitext string, or None on failure.

Return type:

str or None

wikipediaGATN.airport_level_functions.fetch_wikipedia_destinations(identifier: str = 'YWG', link=None, html_content=None, verbose: bool = False, soup=None) → set[source]

Extract destination (name, Wikipedia URL) pairs from an airport page.

Parameters:
  • identifier (str, optional) – IATA/ICAO code, Wikipedia URL, or name. Default: "YWG".

  • link (str or None, optional) – Wikipedia page URL (fetched automatically if absent).

  • html_content (str or None, optional) – Pre-fetched HTML (fetched automatically if absent).

  • verbose (bool, optional) – Print progress. Default: False.

  • soup (BeautifulSoup or None, optional) – Pre-parsed BeautifulSoup object. Default: None.

Returns:

(destination_name, wikipedia_url) pairs.

Return type:

set of tuple[str, str]

wikipediaGATN.airport_level_functions.format_airport_json(data: dict) → dict[source]

Enforce a strict ordering of JSON keys for airport data output.

wikipediaGATN.airport_level_functions.parse_fallback_nlp_airlines_destinations(html_content: str, verbose: bool = False, soup=None) → set[source]

Use spaCy NER to extract (airline, destination) pairs as a last resort.

Parameters:
  • html_content (str) – Parsed HTML of the airport Wikipedia page.

  • verbose (bool, optional) – Print match counts. Default: False.

  • soup (BeautifulSoup or None, optional) – Pre-parsed BeautifulSoup object. Default: None.

Returns:

(ORG entity, GPE entity) pairs.

Return type:

set of tuple[str, str]

Notes

Requires en_core_web_sm. Install with:

python -m spacy download en_core_web_sm

Returns an empty set if the model is not available.

wikipediaGATN.airport_level_functions.parse_infobox_from_wikitext(wikitext: str, verbose: bool = False) → dict[source]

Parse the {{Infobox airport}} template from wikitext into a dict.

Parameters:
  • wikitext (str) – Full wikitext source of the airport Wikipedia page.

  • verbose (bool, optional) – Print parsed key list. Default: False.

Returns:

{field_name: cleaned_value, ...} plus derived lat, lon, region, and ISO 3166-2 country fields when available. Returns {} if no infobox is found.

Return type:

dict

wikipediaGATN.airport_level_functions.parse_iso3166_2(region_code: str)[source]

Resolve an ISO 3166-2 region code to country and subdivision details.

Parameters:

region_code (str) – Code in the form "CC-SUB" (e.g. "CA-MB").

Returns:

{'country_alpha3': str, 'country_name': str, 'subdivision_code': str} or None if region_code is invalid or the country is not found.

Return type:

dict or None

wikipediaGATN.airport_level_functions.parse_lat_lon_from_string(coord_string: str)[source]

Parse a coordinate string into decimal-degree latitude and longitude.

Parameters:

coord_string (str) – Any format accepted by geopy (DMS, decimal, etc.).

Returns:

(latitude, longitude) as 6-decimal-place strings, or ("", "") on parse failure.

Return type:

tuple[str, str]

wikipediaGATN.airport_level_functions.parse_wikitext_airlines_destinations(wikitext: str) → dict[source]

Extract airline to destinations data from {{Airport-dest-list}} templates.

Only destinations expressed as Wikipedia wikilinks are included.

Parameters:

wikitext (str) – Full wikitext of the airport Wikipedia page.

Returns:

{"passenger": {airline_name: [{"name": str, "wikipedia_url": str}, ...], ...}, "cargo": {...}}

Return type:

dict

wikipediaGATN.airport_level_functions.save_airport_info(airport_info: dict, level: int = 0, verbose: bool = False, save_progress: bool = True, iata_from: str = '') → str[source]

Persist an airport info dictionary to TEMP_RESULTS_DIR/<CODE>.<level>.json.

Parameters:
  • airport_info (dict) – Dict as returned by fetch_wikipedia_airport_info().

  • level (int, optional) – BFS distance level from the seed airport. Default: 0.

  • verbose (bool, optional) – Print the saved path. Default: False.

  • save_progress (bool, optional) – Append to processed_locations.csv. Default: True.

Returns:

The IATA code (or wiki_<title> / "unknown") used as the filename prefix.

Return type:

str

Connections

Generate outbound airport connections list from public JSON data.

This module parses augmented JSON files from the public airport_data directory and creates CSV files listing outbound passenger and cargo connections for each airport. It exports unmapped destination URLs to a separate CSV for later processing via web scraping.

wikipediaGATN.connections.create_outbound_connections_list(verbose: bool = False, export_unmapped: bool = True)[source]

Parse JSON files in PUBLIC_DATA_DIR/airport_data and write connection CSVs.

Reads every <IATA>.json file, extracts the pre-mapped destination IATA codes, and writes the results to global-air-pax-network.csv and global-air-cargo-network.csv.

Optionally exports a third CSV listing destination URLs that could not be mapped, so they can be resolved in a subsequent scraping pass.

Parameters:
  • verbose (bool, optional) – If True, prints detailed progress to stdout. Default: False.

  • export_unmapped (bool, optional) – If True, writes unmapped_destinations.csv listing all destination URLs that could not be resolved to an IATA code. Default: True.

Returns:

(pax_csv_path, cargo_csv_path, unmapped_csv_path). unmapped_csv_path is None when no unmapped URLs were found or when export_unmapped=False.

Return type:

tuple of (str, str, str | None)

Raises:

FileNotFoundError – If PUBLIC_DATA_DIR/airport_data does not exist.

Adjacency matrices

Generate adjacency matrices and network graphs from airport connections.

This module processes outbound connection data to build structural representations of the airport networks (both passenger and cargo). It outputs highly efficient sparse matrix formats (.npz) alongside node lists, as well as rich graph-theoretic network exports (GraphML, GEXF, DOT) annotated with airport metadata.

wikipediaGATN.adjacency.create_outbound_adjacency_matrix(symmetric: bool = False, export_csv: bool = False, export_networks: bool = True, verbose: bool = False, is_cargo: bool = False) → tuple[source]

Create a sparse adjacency matrix of outbound airport connections.

Reads airport connections from global-air-pax-network.csv (or global-air-cargo-network.csv if is_cargo is True) and creates a sparse adjacency matrix where each airport is a node and edges represent direct outbound connections. Can optionally create a symmetric matrix to account for incomplete destination data from smaller airports.

Parameters:
  • symmetric (bool, optional) – If True, the matrix is made symmetric (A -> B implies B -> A). Default is False.

  • export_csv (bool, optional) – If True, also writes a dense adjacency_matrix[_cargo][_sym].csv alongside the .npz file. This file can be very large for global-scale networks (≥ 4 000 nodes → > 100 MB), so it is off by default and intended only for small-scale inspection. Default is False.

  • export_networks (bool, optional) – If True, exports the network as GraphML, GEXF, and DOT formats with rich node attributes. Default is True.

  • verbose (bool, optional) – If True, prints status messages about processing. Default is False.

  • is_cargo (bool, optional) – If True, uses the cargo dataset instead of the passenger dataset. Default is False.

Returns:

  • tuple of (str, str) – Paths to the output files:

    • output_matrix – path to the sparse matrix file (.npz).

    • output_nodes – path to the node-list file (.txt).

  • Edge weights

  • ————

  • An edge A → B is **weighted by the number of distinct airlines* reported to*

  • operate that route (observed range roughly 1–25 for passenger, 1–19 for

  • cargo), **not* a 0/1 presence flag. A missing edge is absent (stored as 0*

  • in the sparse matrix); a present edge stores its airline count. Because the

  • weight is an airline count, **summing a node’s row is not its out-degree* —*

  • use the number of non-zero entries in the row for out-degree, and the row

  • sum only when you specifically want total airline-route multiplicity.

  • Output files

  • ————

  • Base matrix files

  • * adjacency_matrix[_cargo][_sym].npz – sparse adjacency matrix whose – non-zero entries are airline counts (see Edge weights above).

  • * nodes[_cargo][_sym].txt – sorted list of airport codes.

  • * adjacency_matrix[_cargo][_sym].csv – dense matrix with code labels – (only written when export_csv=True ).

  • Network files (when export_networks=True ). The _sym suffix is

  • applied to **every* format so a symmetric build never overwrites the*

  • directed graphs

  • * global-air-[pax|cargo]-network[_sym].graphml

  • * global-air-[pax|cargo]-network[_sym].gexf

  • * global-air-[pax|cargo]-network[_sym].dot

Notes

The matrix is stored in CSR (Compressed Sparse Row) format for efficient storage and computation. The node list ensures row/column indices match the airport codes in alphabetical order.

Node codes are mostly 3-letter IATA codes, but a minority are 4-letter ICAO codes for airports that lack an IATA code; each exported graph node carries a code_type attribute ("IATA" or "ICAO") recording which it is.

Each exported graph edge carries a seasonal attribute (1 for a seasonal-only or not-yet-started route, 0 for a year-round one), read from the seasonal column of the connections CSV when present. Seasonality is directional; reverse edges added when symmetrising default to 0.

When symmetric=True, if an edge A → B exists but B → A does not, both directions are added, and each symmetric entry takes the maximum of the two directional weights (max(A, A.T)), not their sum. This is useful when working with data that under-reports small-airport outbound routes; prefer the directed build when edge directionality matters.

Malformed airport-code tokens (not matching [A-Z]{3,4}) and self-loops are silently skipped with a warning.

Examples

>>>
>>> matrix_path, nodes_path = create_outbound_adjacency_matrix()
>>> from scipy.sparse import load_npz
>>> matrix = load_npz(matrix_path)
>>> with open(nodes_path) as f:
...     nodes = [line.strip() for line in f]
>>> print(f"Matrix shape: {matrix.shape}, Airports: {len(nodes)}")

IATA recovery

Extract IATA codes from unmapped destination URLs.

This module resolves destination airports by first performing a fast, offline lookup against the authoritative OurAirports database. If the airport is not found, it falls back to fetching the Wikipedia page and extracting the IATA code using pattern matching (e.g. (IATA: XXX, ICAO: YYYY)).

Typical workflow

  1. Run create_outbound_connections_list() → generates unmapped_destinations.csv

  2. Run extract_iata_from_unmapped_destinations() → populates IATA codes in that CSV

  3. Run create_manual_mapping_from_scraped_data() → builds manual_airport_mapping.csv

  4. Rerun create_outbound_connections_list() → better coverage using the new mappings

wikipediaGATN.extract_iata_from_wikipedia.create_manual_mapping_from_scraped_data(unmapped_csv: str | None = None, output_csv: str | None = None, min_confidence: float = 0.7, verbose: bool = False) → int[source]

Build manual_airport_mapping.csv from successfully scraped IATA codes.

Reads the updated unmapped_destinations.csv produced by extract_iata_from_unmapped_destinations(), filters entries by confidence threshold, and writes a clean mapping file that create_outbound_connections_list() will use as its highest-priority source on the next run.

Parameters:
  • unmapped_csv (str, optional) – Path to unmapped_destinations.csv. Defaults to data/tmp_results/unmapped_destinations.csv.

  • output_csv (str, optional) – Destination path for manual_airport_mapping.csv. Defaults to data/tmp_results/manual_airport_mapping.csv.

  • min_confidence (float, optional) – Minimum confidence threshold in [0, 1]. Entries scraped with confidence below this value are excluded. Default: 0.70.

  • verbose (bool, optional) – If True, prints a summary. Default: False.

Returns:

Number of entries written to the manual mapping file.

Return type:

int

Raises:
  • FileNotFoundError – If unmapped_csv does not exist.

  • ValueError – If min_confidence is outside [0, 1].

wikipediaGATN.extract_iata_from_wikipedia.extract_iata_from_unmapped_destinations(csv_path: str | None = None, batch_size: int = 50, delay: float = 0.5, verbose: bool = False) → dict[source]

Extract IATA codes from Wikipedia pages for unmapped destinations.

Reads unmapped_destinations.csv and attempts to resolve each URL. It prioritizes an instantaneous offline lookup against the OurAirports database, falling back to Wikipedia web scraping only if the URL is not found. Results are written back to the same file atomically (write to a temp file then rename).

Rows that already have an IATA code are skipped and reported separately so that the success count only reflects codes extracted in this run.

Parameters:
  • csv_path (str, optional) – Path to unmapped_destinations.csv. Defaults to data/tmp_results/unmapped_destinations.csv.

  • batch_size (int, optional) – After every batch_size HTTP requests a longer pause is inserted to be polite to Wikipedia’s servers. Default: 50.

  • delay (float, optional) – Per-request delay in seconds. Default: 0.5.

  • verbose (bool, optional) – If True, prints detailed per-URL progress. Default: False.

Returns:

Summary with keys 'total', 'successful', 'skipped', 'failed', and 'csv_path'.

Return type:

dict

Raises:

FileNotFoundError – If csv_path does not exist.

Examples

>>>
>>> from wikipediaGATN.extract_iata_from_wikipedia import (
...     extract_iata_from_unmapped_destinations)
>>> result = extract_iata_from_unmapped_destinations(verbose=True)
>>> print(f"Extracted {result['successful']} new IATA codes")

Result processing — airports

Airport data extraction and validation.

This module transforms raw airport JSON files (produced by Wikipedia scraping) into structured airport metadata, and deduplicates scraping results.

wikipediaGATN.result_processing_airports.check_duplicated_iata_codes(verbose: bool = False) → int[source]

Remove duplicate airport JSON files, keeping the lowest-distance version.

When the scraper revisits an airport at a greater distance from the seed (e.g. both YWG.0.json and YWG.1.json exist), the higher-distance file is deleted because the lower-distance file was scraped closer to the seed and is considered more accurate.

Parameters:

verbose (bool, optional) – If True, prints the name of each removed file. Default: False.

Returns:

Number of duplicate files removed.

Return type:

int

Raises:

FileNotFoundError – If TEMP_RESULTS_DIR does not exist.

Notes

This function modifies the filesystem by deleting files. Run it after Wikipedia scraping is complete and before any processing steps.

wikipediaGATN.result_processing_airports.enrich_missing_airport_data(verbose: bool = False) → int[source]

Attempt a second round of geocoding for airports with missing data.

Reads data/tmp_results/missing_airport_data.csv, attempts multiple queries with Geopy to find lat/lon, and reverse geocodes to find the country. Updates the JSON files in data/public/airport_data in place.

Parameters:

verbose (bool, optional) – If True, prints progress and success/failure for each missing airport.

Returns:

The number of airports successfully updated.

Return type:

int

wikipediaGATN.result_processing_airports.export_all_airport_data(use_new_data: bool = False, verbose: bool = False) → str[source]

Extract metadata from all airport JSON files and write to CSV.

Scans every <IATA>.<distance>.json and wiki_*.<distance>.json file in PUBLIC_DATA_DIR/airport_data (or TEMP_RESULTS_DIR if use_new_data is True) and collects airport metadata into a single airports_information.csv. During the process, it performs offline geographic inference and destination URL mapping.

Parameters:
  • use_new_data (bool, optional) – If True, reads from TEMP_RESULTS_DIR/airports_rooted_sweep. Default: False (reads from PUBLIC_DATA_DIR/airport_data).

  • verbose (bool, optional) – If True, prints per-file status and a final summary. Default: False.

Returns:

Absolute path to data/public/airports_information.csv.

Return type:

str

Raises:

FileNotFoundError – If the selected directory does not exist.

Notes

  • outdegree and outdegree_cargo represent the number of verified destinations listed for each airport in the JSON file.

  • Fields absent from the JSON file are written as empty strings.

  • Run this function before create_outbound_connections_list() so that airports_information.csv is available for URL→IATA mapping.

wikipediaGATN.result_processing_airports.identify_missing_airport_data(verbose: bool = False) → str[source]

Identify airports with missing geographical data.

Scans all JSON files in data/public/airport_data and writes a CSV to data/tmp_results/missing_airport_data.csv listing airports that lack latitude, longitude, or country information.

Parameters:

verbose (bool, optional) – If True, prints a summary of the missing data. Default: False.

Returns:

Absolute path to the generated CSV file.

Return type:

str

Result processing — network pipeline

Orchestration functions for GATN (Global Air Transportation Networks) generation.

This module provides the complete pipeline to extract network structures from the parsed airport data. It drives the multi-pass IATA code recovery workflow, generates outbound connection lists, builds sparse adjacency matrices, and exports rich network graphs for both the Passenger (Pax) and Cargo networks.

wikipediaGATN.result_processing_network.run_two_pass_iata_extraction(batch_size: int = 50, delay: float = 0.5, verbose: bool = False) → dict[source]

Execute Passes 2 and 3 of the IATA recovery workflow.

Assumes Pass 1 (create_outbound_connections_list()) has already been run and unmapped_destinations.csv exists.

Pass 2

Attempts instantaneous offline OurAirports lookup for unmapped URLs, falling back to fetching the Wikipedia page to extract the IATA code.

Pass 3

Filters successful extractions by confidence and writes manual_airport_mapping.csv for use in the next create_outbound_connections_list() call.

Parameters:
  • batch_size (int, optional) – Number of HTTP requests before a longer pause is inserted to respect Wikipedia’s servers. Default: 50.

  • delay (float, optional) – Per-request delay in seconds. Default: 0.5.

  • verbose (bool, optional) – If True, prints detailed per-URL progress. Default: False.

Returns:

{'extraction_result': dict, 'mapping_count': int}

extraction_result is the dict returned by extract_iata_from_unmapped_destinations() (keys: total, successful, skipped, failed, csv_path).

mapping_count is the number of entries written to manual_airport_mapping.csv.

Return type:

dict

Visualisation

Interactive visualisation of the airport network.

Reads a graphml object from PUBLIC_DATA_DIR and writes an interactive Plotly HTML graph.

Three layout strategies are supported:

  • Geographic (default): nodes are placed at their real-world longitude/latitude on a flat map.

  • Globe: nodes are placed at their real-world longitude/latitude on a 3D globe.

  • Spring (fallback): force-directed layout via networkx.spring_layout(). Slow for large graphs (> 500 nodes) and non-deterministic unless seed is fixed — use the seed parameter to get reproducible figures.

Warning

Spring layout on the full global network (~4 000 nodes) can take several minutes and produces a spatially meaningless result. Geographic layout is strongly preferred for publication figures.

wikipediaGATN.visualise_gatn.visualize_graph_plotly(input_path: Path | str | None = None, output_path: Path | str | None = None, seed: int = 42, layout: str = 'geographic', verbose: bool = False) → str[source]

Build and save an interactive Plotly HTML graph of the airport network.

Parameters:
  • input_path (path-like or None, optional) – Path to the input graphml file. If None, defaults to the global pax network.

  • output_path (path-like or None, optional) – Destination for the HTML file. Defaults to PUBLIC_DATA_DIR/<input_stem>-plotly-<layout>.html.

  • seed (int, optional) – Random seed passed to networkx.spring_layout() for reproducible layouts. Ignored when layout is “geographic” or “globe”. Default: 42.

  • layout (str, optional) – Layout strategy: “geographic”, “globe”, or “spring”. Default: “geographic”.

  • verbose (bool, optional) – If True, prints progress messages. Default: False.

Returns:

Absolute path to the saved HTML file.

Return type:

str

Raises:

FileNotFoundError – If the input graphml file does not exist.

Data refresh

Incremental updater for airport JSON data.

This module provides tools to refresh existing airport JSON data files without needing to scrape everything from scratch. It utilizes the Wikipedia API to check the ‘last modified’ timestamps of Wikipedia pages and compares them against the local parse times. Only airports whose Wikipedia pages have been updated since they were last parsed are fetched again.

It also supports partial refreshes (only updating airlines and destinations) and local-only migrations (applying geographic inference without network calls).

Typical usage:

python -m wikipediaGATN.refresh_airport_data –target all –local-only python -m wikipediaGATN.refresh_airport_data –target all

wikipediaGATN.refresh_airport_data.check_needs_refresh(file_paths: list[str], verbose: bool = False) → list[str][source]

Filter a list of JSON files to find those that need to be refreshed.

This function compares the local date-time-parse timestamp stored in each JSON file against the latest revision timestamp from the Wikipedia API. It batches Wikipedia API requests (up to 50 titles per query) for efficiency.

Parameters:
  • file_paths (list of str) – List of absolute file paths to the airport JSON files.

  • verbose (bool, optional) – If True, prints progress and details about which files need updates. Default is False.

Returns:

A subset of file_paths containing only the files that have either: 1. Been updated on Wikipedia since they were last scraped. 2. Are missing a date-time-parse field and therefore must be repaired. 3. Encountered a parsing or decode error.

Return type:

list of str

wikipediaGATN.refresh_airport_data.refresh_airport_file(fpath: str, refresh_all_data: bool = False, local_only: bool = False, verbose: bool = False, file_idx: int | None = None, total_files: int | None = None, url_map: dict | None = None, start_time: float | None = None) → bool[source]

Refresh a single airport JSON file.

Depending on the flags provided, this function can perform a full web scrape, a partial web scrape (only destinations), or a purely offline data migration.

Parameters:
  • fpath (str) – Absolute path to the airport JSON file to refresh.

  • refresh_all_data (bool, optional) – If True, re-fetches all metadata (infobox) from Wikipedia. If False, only re-fetches the airlines and destinations. Default is False.

  • local_only (bool, optional) – If True, skips Wikipedia web scraping completely and purely applies the latest formatting, data schema migrations, and geographic inferences using the offline OurAirports database. Default is False.

  • verbose (bool, optional) – If True, prints detailed progress output. Default is False.

  • file_idx (int, optional) – Current index in a batch (for logging ETA).

  • total_files (int, optional) – Total number of files in the batch (for logging ETA).

  • url_map (dict, optional) – A pre-computed mapping from Wikipedia URLs to IATA/ICAO codes. If not provided, it will be built dynamically.

  • start_time (float, optional) – The Unix timestamp when the batch started (for logging ETA).

Returns:

True if the file was successfully loaded, updated, and saved. False otherwise.

Return type:

bool

wikipediaGATN.refresh_airport_data.refresh_airports(target: str | list[str] = 'all', refresh_all_data: bool = False, local_only: bool = False, force: bool = False, verbose: bool = True)[source]

Orchestrate the batch refresh of airport JSON files.

Scans the PUBLIC_DATA_DIR/airport_data directory, determines which files require an update (via Wikipedia API timestamps), and refreshes them.

Parameters:
  • target (str or list of str, optional) – Can be “all” to check all files in the directory, a single file path, or a list of specific file paths. Default is “all”.

  • refresh_all_data (bool, optional) – If True, re-fetches all metadata (infobox). If False, only updates airlines and destinations. Default is False.

  • local_only (bool, optional) – If True, skips Wikipedia timestamp checks and scraping, and only applies local geographic inferences and schema migrations. Default is False.

  • force (bool, optional) – If True, skips the Wikipedia timestamp check and forces a refresh on all targeted files. Default is False.

  • verbose (bool, optional) – If True, prints detailed progress and ETA. Default is True.

Paths

Canonical filesystem paths for the wikipediaGATN package.

All modules import their directory constants from here so that path logic is defined exactly once. The directory layout assumed by this module is:

<repo_root>/
├── src/
│   └── wikipediaGATN/   ← this file lives here (two levels below repo root)
│       └── paths.py
└── data/
    ├── tmp_results/     ← TEMP_RESULTS_DIR  (raw scraper output)
    └── public/          ← PUBLIC_DATA_DIR   (CSVs, matrices, network graphs)

Environment variable override

Set WIKIPEDIAGATN_DATA_DIR to redirect all data I/O to a different directory. This is primarily useful for testing:

WIKIPEDIAGATN_DATA_DIR=/tmp/test_data pytest

When the variable is set, DATA_DIR, TEMP_RESULTS_DIR, and PUBLIC_DATA_DIR all resolve relative to the override root instead of the repository root.

Resolution order

DATA_DIR (the writable root for scraper output and exports) is resolved as:

  1. WIKIPEDIAGATN_DATA_DIR if set;

  2. <repo_root>/data when running from a source checkout;

  3. <cwd>/data otherwise.

PUBLIC_DATA_DIR normally sits at DATA_DIR/public. When that directory does not exist — the typical case for a plain pip install with no local crawl — it falls back to the pre-built network data bundled inside the installed wheel (wikipediaGATN/_data/public), so reading the published networks works out of the box. This fallback is read-only: to run your own crawl, point WIKIPEDIAGATN_DATA_DIR at a writable directory.

wikipediaGATN.paths.PUBLIC_DATA_DIR: Path = PosixPath('/home/runner/work/wikipediaGATN/wikipediaGATN/data/public')

Directory for processed, public-facing outputs (CSVs, sparse matrices, network graphs). Falls back to the data bundled inside the installed wheel when no local public directory exists, so a plain pip install can read the pre-built networks without a prior crawl (see module docstring).

wikipediaGATN.paths.TEMP_RESULTS_DIR: Path = PosixPath('/home/runner/work/wikipediaGATN/wikipediaGATN/data/tmp_results')

Temporary directory for raw JSON files produced by the Wikipedia scraper.

wikipediaGATN.paths.escape_reserved_code(code: str) → str[source]

Return a filesystem-safe stem for code.

Appends a single underscore to Windows reserved device names (AUX -> AUX_); all other codes are returned unchanged. Inverse of unescape_reserved_code().

wikipediaGATN.paths.is_reserved_code(code: str) → bool[source]

Return True if code collides with a Windows reserved device name.

wikipediaGATN.paths.unescape_reserved_code(stem: str) → str[source]

Recover an airport code from an on-disk stem.

Strips the trailing underscore added by escape_reserved_code() when, and only when, the remaining stem is a Windows reserved device name. A .json (or other) extension, if present, is ignored and preserved-free: pass the stem without extension.