Python API: Server.py

This page is generated automatically from Server.py during docs builds.

Module Overview

QGas – Interactive Map Interface
================================

Academic Software Description
-----------------------------

This application provides an interactive web-based visualization interface for
European gas pipeline infrastructure data. The system serves processed pipeline
network data through an integrated web server with real-time updates.

Key Functionalities
-------------------
- Interactive web-based visualization with Folium mapping interface
- Local HTTP server for serving map data
- Data caching and compression for optimized performance
- Manual change management for pipeline data

Technical Implementation
------------------------
The system uses a tkinter-based GUI with an integrated HTTP server for serving
interactive maps. Data is cached in memory for performance and can be updated
through the web interface.

Development Information
------------------------
- Authors: Marco Quantschnig, Yannick Werner, Sonja Wogrin and Thomas Klatzer
- Institution: Institute of Electricity Economics and Energy Innovation (IEE), Graz University of
Technology, Inffeldgasse 18, Graz, 8010, Austria
- License: See LICENSE file
- Disclaimer: AI-assisted tools were used to support development and documentation.

Inputs
------
- Runtime environment: Python 3.x with Tkinter.
- Local project folders (Input/ and related assets).
- Map HTML entry point: GUI.html served over the local HTTP server.

Classes

CombinedGUI
Methods (28)
__init__(root)

Initialize the QGas application GUI. Configures the main window geometry, determines the application base path (supporting both script and PyInstaller frozen-exe execution), initializes the HTTP server state variables, and builds all UI widgets.

ParameterTypeDescription
roottk.TkThe root Tkinter window instance created by ``main()``.
ensure_directories()

Create any missing required directories for the application. Since we now use Input project folders, Output directories are no longer needed.

create_widgets()

Create the main GUI layout with the QGas Interactive Map interface. Modern design with logo and tile-based layout optimized for larger window.

create_header(parent)

Create the header section with logo, application title, and LED server-status indicator. Attempts to load ``Images/QGas_Logo.png`` (requires Pillow); falls back to a text emoji placeholder if the image is unavailable. The LED indicator in the top-right corner is updated by ``update_status()`` whenever the server state changes.

ParameterTypeDescription
parenttk.FrameParent container frame that the header is packed into.
create_control_tiles(parent)

Create the tile-based control interface with Start, Open Map, and Stop action tiles. Arranges three action tiles in a responsive 3-column grid (row 0) and an information tile spanning all columns below (row 1). Row weights are set so action tiles receive three times more vertical space than the info tile.

ParameterTypeDescription
parenttk.FrameParent container frame for the tile grid.
create_action_tile(parent, title, description, icon, button_text, command, color, row, column)

Create a single action tile widget and place it in the given grid cell. Each tile contains a large emoji icon, a heading, a short description and a colored action button. Hover effects darken the button color using ``darken_color()``.

ParameterTypeDescription
parenttk.FrameParent grid container.
titlestrHeading text displayed inside the tile.
descriptionstrLonger description text shown below the heading.
iconstrUnicode emoji used as the tile icon (e.g. ``"🚀"``).
button_textstrLabel text of the action button.
commandcallableCallback invoked when the button is clicked.
colorstrHex color code for the button background (e.g. ``"#28a745"``).
rowintGrid row index for tile placement.
columnintGrid column index for tile placement.
create_info_tile(parent)

Create the compact information tile that spans all three columns. Displays static server metadata in a 3-column grid: map file name, HTTP port, server URL, working directory, and a feature summary.

ParameterTypeDescription
parenttk.FrameParent container whose grid row 1 receives the tile.
darken_color(color)

Utility function to darken colors for hover effects

ParameterTypeDescription
colorstrHex color code

Returns: str — Darker version of the color

update_status(status, is_running=False)

Update the header LED indicator to reflect server status

ParameterTypeDescription
statusstrStatus text (e.g., "Running", "Stopped")
is_runningboolTrue if server is running, False otherwise
create_map_tab(parent)

Legacy method for map tab creation Now handled by create_widgets for unified interface

start_server()

Start the HTTP server for map visualization

Features:

  • Serves static files (HTML, JS, CSS)
  • Provides API endpoints for dynamic data
  • Handles GeoJSON with compression
  • Dynamic project path routing
show_project_selection_after_start()

Scan the ``Input/`` folder and auto-select or prompt for a project after server start. If only one sub-folder exists it is selected automatically. If multiple folders exist the user is shown the project selection dialog. Falls back to ``"Standard"`` on any error.

get_cached_layer_data(layer_name, bbox=None)

Load layer data with caching and optional bounding box filtering

ParameterTypeDescription
layer_namestrName of the layer to load
bboxstr, optionalBounding box string "minX,minY,maxX,maxY"

Returns: dict — GeoJSON FeatureCollection

filter_data_by_bbox(geojson_data, bbox_str)

Filter GeoJSON data by bounding box for viewport optimization

ParameterTypeDescription
geojson_datadictGeoJSON FeatureCollection
bbox_strstrBounding box "minX,minY,maxX,maxY"

Returns: dict — Filtered GeoJSON FeatureCollection

update_layer_feature(layer_name, feature)

Update a feature in the layer data Note: Currently logs the update. Extend this method to persist changes to files or database as needed.

ParameterTypeDescription
layer_namestrName of the layer
featuredictUpdated GeoJSON feature

Returns: bool — True if update was successful

stop_server()

Stop all running servers and cleanup resources

Actions:

  • Shutdown HTTP server
  • Clear data cache
  • Reset UI status
  • Reset selected project
open_browser()

Open the interactive map in web browser with project selection

Features:

  • Project selection dialog before opening
  • Automatic URL parameter injection with selected project
  • Preference for Microsoft Edge browser
  • Fallback to default browser if Edge unavailable
select_project()

Show project selection dialog if multiple projects exist

Returns: bool — True if project selected or default used, False if cancelled

show_project_selection_dialog(projects)

Display a modal project-selection dialog with a dropdown and project-creation support. Defaults to ``"Standard"`` in the dropdown if that folder exists. The dialog also exposes a *Create New Project* button that calls ``prompt_new_project_dialog()`` before returning.

ParameterTypeDescription
projectslist[str]Sorted list of available project folder names.

Returns: str | None — The selected or newly created project name, or ``None`` if the user cancelled the dialog.

prompt_new_project_dialog(parent, projects)

Show a secondary modal dialog to collect a new project name and create it on disk. Validates the name with ``validate_project_name()`` and then calls ``create_project_from_template()`` to scaffold the folder structure.

ParameterTypeDescription
parenttk.ToplevelParent dialog window used as the transient owner.
projectslist[str]Existing project names used for duplicate detection.

Returns: str | None — The validated new project name on success, or ``None`` if the user cancelled or validation failed.

validate_project_name(name, projects)

Validate a proposed project name against Windows filesystem and uniqueness rules. Checks for empty input, forbidden characters (``< > : / \ | ? * "``), reserved names (``"."`` / ``".."``), trailing spaces or dots, and case-insensitive duplicates in *projects*. Displays an error dialog for each violation.

ParameterTypeDescription
namestrRaw name string entered by the user.
projectslist[str]Existing project folder names for duplicate checking.

Returns: str | None — The validated name if all checks pass, ``None`` otherwise.

create_project_from_template(project_name)

Scaffold a new project folder under ``Input/`` with minimal required files. Creates ``Input/<project_name>/`` and populates it with: - ``PL_Pipelines.geojson`` — empty feature collection (schema from Standard) - ``N_Nodes.geojson`` — empty feature collection (schema from Standard) - ``config.xlsx`` — minimal configuration workbook - ``license.txt`` — empty placeholder

ParameterTypeDescription
project_namestrValidated name for the new project folder.

Returns: bool — ``True`` if the project was created successfully, ``False`` on error.

write_empty_geojson(template_path, dest_path)

Write an empty GeoJSON FeatureCollection to *dest_path*. Preserves the ``name`` and ``crs`` fields from *template_path* if it exists; otherwise writes a minimal FeatureCollection whose ``name`` is derived from the destination filename stem.

ParameterTypeDescription
template_pathstrPath to an existing GeoJSON used as schema source. If the file does not exist, a bare FeatureCollection is created.
dest_pathstrAbsolute or relative output path for the new GeoJSON file.
write_minimal_configuration_xlsx(dest_path)

Write a minimal OOXML ``.xlsx`` workbook to *dest_path* without requiring openpyxl. The workbook contains a single ``Input_Files`` sheet pre-populated with header row and two data rows (pipelines and nodes) matching the expected QGas configuration schema.

ParameterTypeDescription
dest_pathstrAbsolute or relative path where the ``.xlsx`` file is written.
update_map_paths(project_name)

Rewrite ``fetch()`` URLs in ``GUI.html`` to point to ``Input/<project_name>/``. First normalises any pre-existing ``Input/<old_project>/`` prefix to plain ``Input/`` (prevents double-nesting on repeated calls), then replaces all ``fetch('Input/`` occurrences with ``fetch('Input/<project_name>/``.

ParameterTypeDescription
project_namestrName of the project folder to activate in the map.
reset_map_paths()

Revert all ``fetch('Input/<project>/``) URLs in ``GUI.html`` back to ``fetch('Output/``. Intended as a cleanup step when the application shuts down or when the user reverts to the legacy Output-folder layout.

clear_browser_cache()

Add or update a ``?v=<timestamp>`` cache-busting query parameter in ``GUI.html``. Scans all ``.geojson`` fetch URLs in the HTML and replaces or appends a ``v`` parameter set to the current Unix timestamp so the browser fetches fresh data on the next page load.

on_closing()

Handle application shutdown gracefully. Stops the map server if running and cleans up any background processes before closing the application window.

Module-level Functions

Functions (1)
main()

Main entry point for the QGas Interactive Map application. Initializes the Tkinter GUI, creates the application instance, and starts the main event loop. Includes error handling for startup issues.