API Reference

ElectricityNetworkReduction._convex_hull_2dMethod
_convex_hull_2d(pts) -> Vector{Point2f}

Compute the 2-D convex hull via Andrew's monotone-chain algorithm. Pure Julia, no dependencies. Returns the hull vertices in counter-clockwise order. Falls back to the original point set for degenerate inputs (≤ 2 pts).

source
ElectricityNetworkReduction._draw_highres_highlight!Method
_draw_highres_highlight!(ax, nodes_df, cos_lat)

Overlay a semi-transparent convex-hull polygon on ax for every zone listed in CONFIG.high_res_zones, using the geographic positions in nodes_df. A single bold zone-code + "(high-res)" label is placed above the cluster.

Should be called BEFORE graphplot! so the network nodes render on top of the shaded area. No-op when CONFIG.high_res_zones is empty or when coordinates are unavailable.

source
ElectricityNetworkReduction._edge_infoMethod
_edge_info(g, node_info, lines_df) -> (edge_colors, edge_widths)

Build per-edge colour and width vectors (aligned with Graphs.edges(g)) from line-type metadata in lines_df.

:gray — AC line :red — AC tie-line :royalblue — DC interconnector (thicker)

source
ElectricityNetworkReduction._gis_paramsFunction
_gis_params(n_orig, n_red) -> NamedTuple

Compute size-tier parameters for CairoMakie/GraphMakie plots based on the number of buses in the original and reduced networks. All functions that produce PNG output call this helper so visual quality scales automatically from a 6-bus test case to a 6792-bus European grid.

source
ElectricityNetworkReduction._red_node_sizesMethod
_red_node_sizes(nodes_df, rep_sz, hr_sz) -> Vector{Float32}

Per-node size vector for the reduced network. External zone representative nodes get rep_sz (large). Individual buses inside high-resolution zones get hr_sz (small), so the lines between them stay visible rather than being hidden under large markers. Falls back to all-rep_sz when no high-res zones are configured.

source
ElectricityNetworkReduction._solve_miqp_modelFunction

Binding-line MILP solved by HiGHS.

This method supersedes the older Z-allocation MILP above. It fits the AC recomputed TTC directly:

TTC_eq[t] = min_l C_eq[l] / abs(PTDF[t,l])

Physical upper-bound constraints are enforced for every relevant (transaction, line) pair; binary binding choices are restricted to likely limiting lines for scalability.

source
ElectricityNetworkReduction.build_converter_mapMethod
build_converter_map(converters_df::DataFrame) -> Dict{String,String}

Return a Dict mapping each DC terminal bus name to its connected AC substation bus name. Used by remapdcendpoints! to rewrite DCLine endpoints before numeric ID assignment.

source
ElectricityNetworkReduction.build_dc_capacity_mapMethod
build_dc_capacity_map(dclines_df, node_info, rep_node_ids; lines_df, tielines_df)

Build a Dict mapping representative-node pairs to aggregated DC capacity (pu).

Physical DC converter buses are remapped to a representative node in the same AC connected component whenever AC line data are provided. Intra-zone DC lines are skipped only when both endpoints are in the same AC component; intra-zone DC bridges between separate AC islands are kept. Multiple DC lines between the same representative-node pair are summed. This map is later used for additive TTC contribution and as a floor constraint in optimisation.

Returns

Dict{Tuple{Int,Int}, Float64} keyed by (minrepid, maxrepid)

source
ElectricityNetworkReduction.calculate_all_ttc_resultsMethod
calculate_all_ttc_results(Ybus, lines_df, tie_lines_df; dc_cap_map)

Computes TTC for all canonical transactions (a < b) WITHOUT storing PTDFs. Memory-optimised for large-scale systems.

DC lines contribute additively: TTC(a,b) = TTCAC(a,b) + CDC(a,b)

Pass an empty Dict (default) when no DC lines are present — the function then behaves identically to the original.

When CONFIG.parallel_processing = true and Julia is started with multiple threads (e.g. julia --threads=auto), the TTC enumeration loop is distributed across all available threads using Threads.@threads :static. The PTDF basis computation (LU factorisation + back-solves) is always sequential because SuiteSparse UMFPACK back-solves are not thread-safe on a shared factorisation object.

Keyword arguments

  • dc_cap_map : Dict{Tuple{Int,Int},Float64} from builddccapacitymap(). Keys are (minrepid, maxrep_id), values are capacity in pu.
source
ElectricityNetworkReduction.calculate_ptdfs_reducedMethod
calculate_ptdfs_reduced(Y_kron, rep_node_ids; high_res_ids)

Calculates PTDFs for the smaller equivalent network. Uses local indices for calculation and maps back to original IDs for output.

When high_res_ids is non-empty (high-resolution zone mode), pairs where both endpoints are in the high-res set are skipped: their PTDFs are determined by the original physical network, and including them would make the computation O(n_hires²) — infeasible for large zones. Cross-boundary and external-only pairs are still computed normally.

source
ElectricityNetworkReduction.calculate_single_injection_ptdfsMethod
calculate_single_injection_ptdfs(Ybus; reference_bus=1)

Core Engine: Factorises B matrix once and solves for unit injections.

Handles multi-island (multi-synchronous-zone) networks by detecting AC connected components and using one reference bus per component. Returns a nodecomponent vector so callers can identify cross-island transactions (TTCAC = Inf).

source
ElectricityNetworkReduction.convert_line_to_pu!Method
convert_line_to_pu!(lines_df::DataFrame, Sbase::Float64; in_pu::Bool=false)

Convert line parameters to per-unit values based on system base power. If in_pu is true, assumes R, X, B are already in per-unit and only converts capacity.

source
ElectricityNetworkReduction.create_ttc_results_from_optimisationMethod
create_ttc_results_from_optimisation(
ttc_vals::Vector{Float64},
ttc_canonical::DataFrame;
model=model,
Type = CONFIG.optimisation_type,
synth_lines::Vector{Tuple{Int,Int}} = Tuple{Int,Int}[],
binding_dict::Union{Dict,Nothing} = nothing
)

Create TTC results directly from optimisation variables.

source
ElectricityNetworkReduction.detect_islandsFunction
detect_islands(lines_df, tielines_df, node_info, dclines_df)

Build the original-network graph (AC + DC edges) and label each node with its connected-component island index. DC lines are included as graph edges so that DC-only connections appear in the plot and island detection is correct.

source
ElectricityNetworkReduction.diagnose_islandsMethod
diagnose_islands(lines_df, tielines_df, node_info; dclines_df, top_n)

Analyse AC-only connected components and print a diagnostic report to help distinguish between physically-real islands and data-gap artefacts (e.g. missing transformers between voltage levels in the same zone).

Returns a summary DataFrame (one row per island, sorted largest-first) and the raw components / node_comp vectors for further use.

Columns in the returned DataFrame

  • island_id: internal component index
  • n_buses: number of buses in the island
  • zones: semicolon-separated list of zones with bus counts, e.g. "DE(43);FR(12)"
  • voltage_kv: semicolon-separated sorted unique voltage levels
  • dc_bridge: true if a DC line links this island to another
  • diagnosis: "SUSPECT", "DC-ONLY", "SINGLETON", or "REAL"
  • suspect_zones: zones that triggered SUSPECT (empty otherwise)

Arguments

  • lines_df, tielines_df: AC branch DataFrames (must have :From, :To)
  • node_info: bus metadata (must have :new_id, :Zone, :baseKV)
  • dclines_df: DC branch DataFrame (optional; used to flag DC-bridge islands)
  • top_n: print only the top_n largest islands in the terminal (0 = all)
source
ElectricityNetworkReduction.export_bus_id_mapMethod
export_bus_id_map(node_info, export_path)

Export a CSV file containing the mapping between old bus names and new numerical IDs.

Arguments

  • node_info::DataFrame: Node information with oldname and newid columns
  • export_path::String: Path where the CSV file will be saved

Output CSV Format

  • old_name: Original bus names from input data
  • new_id: Numerical IDs assigned during processing
source
ElectricityNetworkReduction.export_detailed_line_infoMethod
export_detailed_line_info(lines_df, tielines_df, export_path)

Export comprehensive line information including both original names and numerical IDs.

Arguments

  • lines_df::DataFrame: Regular transmission lines data
  • tielines_df::DataFrame: Tie lines data
  • export_path::String: Path where the CSV file will be saved

Output CSV Columns

  • EIC_Code: European Identification Code for the line
  • Fromnode, Tonode: Original bus names
  • NewIDFrom, NewIDTo: Numerical bus IDs
  • Voltage_level: Operating voltage level
  • Length_km: Line length in kilometers
  • CapacityMW, Capacitypu: Line capacity in MW and per-unit
  • Rpu, Xpu, B_pu: Line parameters in per-unit
  • IsTieLine: Boolean flag indicating if this is a tie line
source
ElectricityNetworkReduction.kron_reduce_ybusMethod
kron_reduce_ybus(Ybus, rep_node_ids)

Perform Kron reduction on the original Ybus matrix to eliminate non-representative nodes.

The Kron reduction technique eliminates internal nodes while preserving the electrical relationships between the representative nodes. This creates an equivalent network with fewer nodes but equivalent transfer characteristics.

Arguments

  • Ybus::SparseMatrixCSC{ComplexF64}: Original network admittance matrix
  • rep_node_ids::Vector{Int}: Indices of representative nodes to retain

Returns

  • Y_kron::SparseMatrixCSC{ComplexF64}: Reduced admittance matrix

Mathematical Background

The Kron reduction partitions the admittance matrix as:

Y = [K   L_T]
    [L   M  ]

where K connects representative nodes, M connects eliminated nodes, and L connects representative to eliminated nodes.

The reduced matrix is: Ykron = K - LT * M^(-1) * L

source
ElectricityNetworkReduction.main_full_analysisMethod
main_full_analysis(input_data_dir, output_data_dir)

Complete eleven-step network reduction analysis workflow:

  1. Data loading and preprocessing (AC lines, tie-lines, transformers, DC lines, converters)
  2. Island detection and original network plot (when CONFIG.enable_plots = true)
  3. Y-bus assembly (AC only) and export of island diagnostics, bus ID map, line details
  4. Representative node selection (auto by degree, or manual from Excel)
  5. Virtual line filter and DC capacity map construction
  6. Original network TTC/PTDF analysis (AC + additive DC, parallelised when parallel_processing = true)
  7. Kron reduction of non-representative nodes
  8. Reduced-network PTDF computation
  9. Optimisation of equivalent line capacities (QP / LP / MIQP via JuMP + Ipopt / HiGHS)
  10. Reduced network visualisation (when CONFIG.enable_plots = true)
  11. TTC comparison and export of all results to CSV

Set CONFIG.has_dc_lines = true and provide a DCLines sheet in the Excel file to enable DC line integration.

Returns

Nothing. All results are written to CSV files in output_data_dir.

Output Files

All filenames use CONFIG.suffix as a postfix:

  • Bus_ID_Map_<suffix>.csv: Mapping of original bus names to sequential integer IDs
  • Island_Diagnostics_<suffix>.csv: Per-island summary (size, zones, voltage levels, diagnosis)
  • Line_Details_<suffix>.csv: Comprehensive line information (per-unit parameters)
  • TTC_Original_Network_<suffix>.csv: Original network TTC values (AC + DC columns)
  • PTDF_Reduced_Network_<suffix>.csv: Reduced network PTDF values
  • Equivalent_Capacities_<suffix>.csv: Optimised synthetic line capacities, reactances, and DC flags
  • TTC_Comparison_<suffix>.csv: Comparison of original vs equivalent TTC values
  • Network_Original_<suffix>.png: Original network plot (only when enable_plots = true)
  • Network_Reduced_<suffix>.png: Reduced network plot (only when enable_plots = true)
  • Network_Original_vs_Reduced_<suffix>.png: Side-by-side comparison plot (only when enable_plots = true)
source
ElectricityNetworkReduction.plot_networkMethod
plot_network(g, node_info, lines_df; title, n_size, f_size, show_names)

Plot a network graph with nodes coloured by island (connected component). Only called when CONFIG.enable_plots = true.

Three separate graphplot layers are drawn so each line type gets a reliable single-colour call:

• Gray — AC lines • Red — AC tie-lines • Blue — DC interconnectors (curved, so parallel AC+DC pairs appear distinct)

Uses Latitude/Longitude columns for geo-layout if present in node_info; otherwise uses a deterministic circular layout.

source
ElectricityNetworkReduction.plot_network_gisMethod
plot_network_gis(g, node_info, lines_df; title, show_names, node_sz) -> Figure

Plot the power network on a plain lon/lat axis. Nodes are coloured by zone; edges are coloured by type (gray = AC, red = tie-line, blue = DC). No external GIS data is required.

source
ElectricityNetworkReduction.plot_original_vs_reducedMethod
plot_original_vs_reduced(g_orig, nodes_orig, lines_orig, g_red, nodes_red, lines_red, output_path)

Plot original and reduced networks side-by-side (1400×700 px) and save to output_path. Only called when CONFIG.enable_plots = true.

source
ElectricityNetworkReduction.plot_original_vs_reduced_gisMethod
plot_original_vs_reduced_gis(g_orig, nodes_orig, lines_orig,
                              g_red,  nodes_red,  lines_red;
                              main_title) -> Figure

Side-by-side lon/lat comparison (3000×1200 px). Left panel: full original network (nodes unlabelled for clarity). Right panel: reduced network (nodes labelled by name). Both panels share the same lon/lat bounding box from the original network.

source
ElectricityNetworkReduction.process_convertersMethod
process_converters(converters_df::DataFrame)

Clean and standardise the Converters sheet.

Each row represents one AC/DC interface: Fromnode — DC terminal bus name (bare OSM ID, e.g. way/920127890) Tonode — AC substation bus name (voltage-suffixed, e.g. way/920127890-380)

The same name-cleaning rules (uppercase + strip) used everywhere else are applied so that converter map keys match the names produced by renamebuses and renamedc_buses.

source
ElectricityNetworkReduction.process_dclinesMethod
process_dclines(dclines_df::DataFrame, Sbase::Float64)

Process DC interconnector lines.

DC lines have no AC impedance parameters (R, X, B are set to zero and must NEVER be passed to formybuswith_shunt or any PTDF calculation). Their capacity contributes additively to inter-zonal TTC after AC reduction.

Required columns in the DCLines Excel sheet: Fromnode – sending-end bus name (must exist in Nodes sheet) Tonode – receiving-end bus name (must exist in Nodes sheet) CapacityMW – rated capacity in MW (symmetric; same limit both directions) EICCode – identifier (optional)

source
ElectricityNetworkReduction.process_transformersMethod
process_transformers(transformers_df::DataFrame)

Prepare transformer data for integration with the AC line pipeline.

Transformers are treated as AC elements: IsTieLine = false, IsDCLine = false. The sheet must use the same column names as the Lines sheet for Fromnode, Tonode, X, and Capacity_MW. R and B columns are optional and default to 0 when absent.

Missing EIC codes are assigned synthetic identifiers.

source
ElectricityNetworkReduction.remap_dc_endpoints!Method
remap_dc_endpoints!(dclines_df, converter_map)

Replace DC terminal bus names in DCLines with their connected AC substation bus names, using the map built from the Converters sheet.

DC cables physically connect between converter-station DC terminals. For PTDF/TTC analysis the relevant injection point is the AC bus adjacent to the converter, not the DC terminal itself. After remapping, every DC line endpoint refers to an AC bus that exists in the Y-bus, eliminating DC-terminal singleton islands and ensuring correct zone attribution in builddccapacity_map.

Endpoints with no converter entry are left unchanged; renamedcbuses will validate them and raise a descriptive error if they are also absent from the Nodes sheet.

source
ElectricityNetworkReduction.rename_busesFunction
rename_buses(nodes_df, generators_df, lines_df, tie_lines_df, Sbase)

Rename buses, create numerical mapping, convert to per-unit, and preserve the IsRepresentative column from Excel.

source
ElectricityNetworkReduction.rename_dc_busesFunction
rename_dc_buses(dclines_df, bus_map)

Map DC line Fromnode/Tonode names to numerical IDs using the busmap produced by renamebuses. Validates that all DC bus names exist in the Nodes sheet and raises a descriptive error if any are missing.

source
ElectricityNetworkReduction.select_representative_nodesMethod
select_representative_nodes(Ybus::SparseMatrixCSC{ComplexF64}, node_info::DataFrame)

Select representative nodes using one of two modes controlled by CONFIG.repnodemode:

  • "auto" (default): Select top CONFIG.rep_node_k_per_zone nodes per zone by degree, using incident capacity as a tie-breaker. If an AC island is left without a representative, add the best-ranked bus from that island.
  • "manual_excel": Use nodes marked in column IsRepresentative in the Nodes sheet

If manual mode is selected but the column is missing, falls back to auto mode with a warning. Always ensures :isrepresentative column exists in nodeinfo.

source

Exported Functions

This section provides an overview of the main exported functions in ElectricityNetworkReduction.jl, grouped by their role in the overall workflow. These functions are designed to support data ingestion, physical modeling, network reduction, optimisation, and result export.


1. Data Loading and Cleaning

These functions handle the initial stage of reading input data from an Excel workbook and preparing it for mathematical modeling.

  • load_excel_data(file_path) Reads the mandatory Lines, Tielines, Nodes, and Generators sheets from an Excel input file. Also conditionally reads the DCLines, Transformers, and Converters sheets based on the corresponding CONFIG.has_* flags. Returns a dictionary of DataFrames keyed by element type.

  • clean_line_data(lines_df) Cleans AC branch data by removing self-loops and assigning unique identifiers to missing or incomplete EIC codes.

  • process_tielines(tielines_df) Processes inter-zonal AC transmission lines to ensure consistent representation of connections across zone boundaries. Deduplicates by EIC code (longest line kept) and assigns synthetic IDs for missing codes.

  • rename_buses(nodes_df, generators_df, lines_df, tielines_df, Sbase) Assigns sequential integer IDs to all AC buses and returns updated DataFrames alongside the node metadata table. Preserves the IsRepresentative column and Latitude/Longitude columns from the Nodes sheet. Converts AC line parameters to per-unit.

  • convert_line_to_pu!(df, baseMVA; in_pu) Converts line parameters from physical units (Ohms) to per-unit values using the Voltage_level column, if required. If in_pu = true, parameters are assumed already in per-unit. Modifies the data frame in place.

  • process_dclines(dclines_df, Sbase) Prepares DC interconnector data for use. Sets AC impedance parameters to zero (DC lines must never enter the Y-bus), converts capacity to per-unit, removes self-loops, and assigns synthetic EIC codes for missing entries.

  • rename_dc_buses(dclines_df, bus_map) Maps DC line From_node/To_node names to numerical bus IDs using the map produced by rename_buses. Raises a descriptive error if any DC bus name is absent from the Nodes sheet.

  • process_transformers(transformers_df) Prepares transformer data for merging with the AC line set. Adds missing optional columns (R, B) with zero defaults, removes self-loops, and assigns synthetic EIC codes.

  • process_converters(converters_df) Cleans and standardises the Converters sheet. Applies the same name-cleaning rules as rename_buses so that converter map keys match bus names throughout the pipeline.

  • build_converter_map(converters_df) Returns a Dict{String,String} mapping each DC terminal bus name to its connected AC substation bus name. Used by remap_dc_endpoints! before numeric ID assignment.

  • remap_dc_endpoints!(dclines_df, converter_map) Rewrites DC line endpoint bus names in-place: DC cable terminal names are replaced by their adjacent AC substation bus names using the converter map. Endpoints with no converter entry are left unchanged. This step must run before rename_buses so DC terminals are excluded from the Y-bus.

  • build_dc_capacity_map(dclines_df, node_info, rep_node_ids; lines_df, tielines_df) Aggregates DC line capacities (in p.u.) by representative-node pair. When AC line data are provided, each DC endpoint is mapped to a representative in its own AC connected component. Same-zone DC lines are skipped only when both endpoints are in the same AC component; same-zone DC bridges between separate AC islands are retained. Returns a Dict{Tuple{Int,Int}, Float64} keyed by (min_rep_id, max_rep_id). Used for additive TTC contribution in reporting and exported equivalent capacities.


2. Network Physics and Matrix Construction

These functions construct the mathematical representation of the electrical network.

  • form_ybus_with_shunt(lines, tielines, nodes, Sbase) Assembles the bus admittance matrix ($Y_{bus}$), including the contribution of line shunt susceptances. AC lines and transformers (after merging) are included; DC interconnectors are excluded.

  • calculate_all_ttc_results(Ybus, lines_df, tie_lines_df; dc_cap_map) Memory-optimised TTC computation for all $\binom{N}{2}$ bus-pair transactions. Factorises the $B$ matrix once, then computes PTDFs and TTC via shared back-solves. DC capacity is added additively using dc_cap_map. Supports multi-threaded execution when CONFIG.parallel_processing = true. Returns both the TTC DataFrame and a Dict of per-pair physical line capacities for downstream use.

  • calculate_single_injection_ptdfs(Ybus; reference_bus=1) Core PTDF engine. Factorises the susceptance matrix once and computes voltage-angle sensitivities to unit injections at every non-reference bus. Handles multi-island networks by assigning one reference bus per AC connected component. Returns (ptdf_single, lines_info, node_component). Used internally by calculate_all_ttc_results and calculate_ptdfs_reduced.


3. Island Detection and Diagnostics

These functions detect network connectivity issues and export diagnostic reports.

  • detect_islands(lines_df, tielines_df, node_info, dclines_df) Builds the full network graph using AC lines, tie-lines, and DC lines as edges. Labels each bus with its connected-component index. Returns the components list, updated node_info (with an :island column), and the graph object. Used when CONFIG.enable_plots = true to colour nodes by island in plots.

  • diagnose_islands(lines_df, tielines_df, node_info; dclines_df, top_n) Produces a per-island diagnostic report to distinguish physically-real islands from data-gap artefacts. Each island is classified as:

    • REAL — well-formed AC island
    • SUSPECT — contains buses of multiple voltage levels in the same zone (likely a missing transformer)
    • DC-ONLY — isolated AC island bridged to another island only via DC lines
    • SINGLETON — single bus with no AC connections

    Returns a summary DataFrame sorted largest-first, plus the raw components and node-component vectors.

  • export_island_diagnostics(summary_df, output_path) Writes the island diagnostic summary DataFrame to a CSV file.


4. Network Reduction Logic

These functions implement the core algorithms used to reduce the size of the network while preserving its physical behavior.

  • select_representative_nodes(Ybus, node_info, numbered_lines, numbered_tielines) Identifies representative nodes within each zone. Supports two modes controlled by CONFIG.rep_node_mode:

    • "auto": selects the top CONFIG.rep_node_k_per_zone nodes per zone ranked by interconnection degree (line capacity as tiebreaker). Zones listed in CONFIG.high_res_zones are retained at full bus resolution (all buses become representative nodes). If this leaves an AC island without any representative, the best-ranked bus in that island is added as a forced representative.
    • "manual_excel": reads the IsRepresentative column from the Nodes sheet.

    Falls back to "auto" with a warning if the column is missing or empty in manual mode.

  • kron_reduce_ybus(Ybus, representative_nodes) Applies Kron reduction to eliminate internal nodes while preserving sensitivity relationships between representative nodes. Handles multi-island networks by applying small shunt regularisation ($\varepsilon = 10^{-8}$) before inversion to avoid singularity.

  • calculate_ptdfs_reduced(Y_kron, rep_node_ids; high_res_ids) Calculates PTDFs for the smaller equivalent network using local indices and maps back to original IDs. When high_res_ids is non-empty, intra-high-res zone pairs are skipped to avoid the $O(n_{hires}^2)$ computation.


5. Capacity Optimisation

These functions use mathematical programming to determine synthetic line capacities for the reduced network.

  • optimise_equivalent_capacities(ttc_original, ptdf_reduced_results; Type, lambda, allow_virtual_lines, allowed_synth_pairs, dc_cap_map, high_res_node_ids, phys_line_caps) Primary interface for solving the capacity fitting problem. Dispatches to _solve_qp_model, _solve_lp_model, or _solve_miqp_model based on Type. QP provides a fast accuracy/time balance, LP constructs a deterministic capacity envelope, and MIQP identifies binding synthetic lines with physically consistent capacities. DC capacity is added back in reported total TTC. Intra-high-res synthetic lines are fixed to their physical capacity and excluded from optimisation.

    Returns a tuple (equivalent_capacities_df, ttc_equivalent_df).


6. Workflow and Configuration

These functions and objects control the full end-to-end execution of the model.

  • main_full_analysis(input_dir, output_dir) High-level wrapper that executes the complete 11-step network reduction pipeline, from data loading to result export. Prints a step-by-step timing summary on completion. Returns nothing; all results are written to CSV files in output_dir.

  • CONFIG Global configuration object. All parameters and their defaults:

    ParameterTypeDefaultDescription
    input_filenameString"case118.xlsx"Input file name
    case_studyString"case118"Case study identifier (used in console output)
    optimisation_typeString"QP""QP", "LP", or "MIQP"
    baseFloat64100.0System MVA base
    bus_names_as_intBoolfalsetrue if bus IDs are integers
    in_puBoolfalsetrue if R, X, B already in per-unit
    allow_virtual_linesBoolfalseKeep only physically connected synthetic lines
    lambdaFloat641e-6Regularisation parameter (QP/MIQP)
    ptdf_epsilonFloat641e-6PTDF zero threshold
    suffixString"QP"Suffix for output file names
    miqp_binding_candidates_per_txnInt8Binding candidates retained per transaction in MIQP
    miqp_time_limit_secFloat641800.0MIQP solver time limit
    miqp_mip_rel_gapFloat641e-4MIQP relative MIP gap
    rep_node_modeString"auto""auto" or "manual_excel"
    rep_node_k_per_zoneInt1Nodes per zone in auto mode
    rep_node_degree_thresholdFloat641e-8Minimum susceptance to count as a connection
    high_res_zonesVector{String}[]Zones retained at full bus resolution
    enable_plotsBooltrueGenerate GIS-based PNG plots
    has_dc_linesBoolfalseRead DCLines sheet
    dc_lines_sheetString"DCLines"Name of DC lines sheet
    has_transformersBoolfalseRead Transformers sheet
    transformers_sheetString"Transformers"Name of transformers sheet
    transformers_in_puBooltrueTransformer X already in per-unit
    has_convertersBoolfalseRead Converters sheet
    converters_sheetString"Converters"Name of converters sheet
    parallel_processingBooltrueMulti-threaded TTC enumeration
  • reset_config!() Resets all configuration parameters to their default values. Always call this between case studies in batch runs to avoid state leakage.


7. Visualisation (optional)

Network plots are generated when CONFIG.enable_plots = true. The plotting backend is CairoMakie + GraphMakie, which are regular dependencies installed with the package. Node colours represent zones; edge colours represent line types (gray = AC, red = AC tie-line, blue = DC interconnector).

  • plot_network_gis(g, node_info, lines_df; title, show_names, node_sz) Plots a single network on a lon/lat axis. Uses Latitude/Longitude columns for geographic layout if present; otherwise uses a spring or stress layout. High-resolution zone areas are overlaid with a semi-transparent amber convex-hull polygon and a label. Returns a CairoMakie Figure.

  • plot_original_vs_reduced_gis(g_orig, nodes_orig, lines_orig, g_red, nodes_red, lines_red; main_title) Produces a side-by-side comparison Figure (two panels, shared geographic bounding box). Left panel: full original network with unlabelled nodes. Right panel: reduced network with zone-code labels on external representative nodes; high-res zone buses are shown but not individually labelled. Saves to PNG via CairoMakie.save.

  • plot_network(g, node_info, lines_df; title, n_size, f_size, show_names) Legacy plotting function using Plots.jl + GraphRecipes. Retained for backward compatibility. For new use cases, prefer plot_network_gis.

  • plot_original_vs_reduced(g_orig, nodes_orig, lines_orig, g_red, nodes_red, lines_red, output_path) Legacy side-by-side comparison using Plots.jl. Saves a 1400×700 px PNG. Retained for backward compatibility.


8. Export Utilities

  • export_bus_id_map(node_info, output_path) Writes the original-to-new bus ID mapping to CSV.

  • export_detailed_line_info(lines_df, tielines_df, output_path) Writes comprehensive line information (per-unit parameters, type flags) to CSV.

  • export_island_diagnostics(summary_df, output_path) Writes the island diagnostic summary to CSV.


Internal Module Structure

The package follows a modular architecture, with each file responsible for a specific component of the workflow.

FileResponsibility
config.jlCentralized settings and global CONFIG object
data-loading.jlExcel ingestion, per-unit normalization, DC line and converter handling
export-functions.jlCSV export and reporting utilities
island-detection.jlConnected-component detection, island diagnostics
kron-reduction.jlMathematical node elimination with multi-island regularisation
main-analysis.jl11-step top-level wrapper; timing summary
network-visualisation.jlGIS-based (CairoMakie/GraphMakie) and legacy (Plots.jl) plot functions
optimisation.jlQP fit, LP capacity envelope, MIQP binding-line MILP, TTC reporting
ptdf-calculations.jlDC power flow sensitivity analysis; parallel TTC enumeration
representative-nodes.jlZone grouping, degree-based or manual node selection, high-res zone support
ybus-formation.jlPhysical matrix assembly ($Y_{bus}$)