API Reference
ElectricityNetworkReduction._axis_limits — Method
_axis_limits(lons, lats; pad) -> (lon_lo, lon_hi, lat_lo, lat_hi)Return axis limits with pad fractional padding on each side (minimum 1°).
ElectricityNetworkReduction._convex_hull_2d — Method
_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).
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.
ElectricityNetworkReduction._edge_info — Method
_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)
ElectricityNetworkReduction._gis_params — Function
_gis_params(n_orig, n_red) -> NamedTupleCompute 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.
ElectricityNetworkReduction._red_node_sizes — Method
_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.
ElectricityNetworkReduction._solve_miqp_model — Function
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.
ElectricityNetworkReduction._solve_miqp_model_legacy — Function
Linearized MILP formulation using HiGHS that enforces exactly one binding line per transaction. Objective: minimise sum of absolute TTC errors (L1 norm).
ElectricityNetworkReduction.build_converter_map — Method
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.
ElectricityNetworkReduction.build_dc_capacity_map — Method
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)
ElectricityNetworkReduction.calculate_all_ttc_results — Method
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.
ElectricityNetworkReduction.calculate_ptdfs_reduced — Method
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.
ElectricityNetworkReduction.calculate_single_injection_ptdfs — Method
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).
ElectricityNetworkReduction.clean_line_data — Method
clean_line_data(lines_df::DataFrame)Clean line data by removing self-loops and assigning fake EIC codes to missing entries.
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.
ElectricityNetworkReduction.create_ttc_results_from_optimisation — Method
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.
ElectricityNetworkReduction.detect_islands — Function
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.
ElectricityNetworkReduction.diagnose_islands — Method
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 indexn_buses: number of buses in the islandzones: semicolon-separated list of zones with bus counts, e.g. "DE(43);FR(12)"voltage_kv: semicolon-separated sorted unique voltage levelsdc_bridge: true if a DC line links this island to anotherdiagnosis: "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 thetop_nlargest islands in the terminal (0 = all)
ElectricityNetworkReduction.export_bus_id_map — Method
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 columnsexport_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
ElectricityNetworkReduction.export_detailed_line_info — Method
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 datatielines_df::DataFrame: Tie lines dataexport_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
ElectricityNetworkReduction.export_island_diagnostics — Method
export_island_diagnostics(summary_df, output_path)Write the island diagnostic summary DataFrame to a CSV file.
ElectricityNetworkReduction.form_ybus_with_shunt — Method
form_ybus_with_shunt(lines_df, tie_lines_df, node_info, Sbase)Form the network admittance matrix (Y-bus) including shunt elements. Returns a sparse complex matrix representing the network admittance.
ElectricityNetworkReduction.kron_reduce_ybus — Method
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 matrixrep_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
ElectricityNetworkReduction.load_excel_data — Method
load_excel_data(file_path::String)Load network data from Excel file with multiple sheets. Returns a dictionary containing DataFrames for lines, tielines, nodes, and generators.
ElectricityNetworkReduction.main_full_analysis — Method
main_full_analysis(input_data_dir, output_data_dir)Complete eleven-step network reduction analysis workflow:
- Data loading and preprocessing (AC lines, tie-lines, transformers, DC lines, converters)
- Island detection and original network plot (when
CONFIG.enable_plots = true) - Y-bus assembly (AC only) and export of island diagnostics, bus ID map, line details
- Representative node selection (auto by degree, or manual from Excel)
- Virtual line filter and DC capacity map construction
- Original network TTC/PTDF analysis (AC + additive DC, parallelised when
parallel_processing = true) - Kron reduction of non-representative nodes
- Reduced-network PTDF computation
- Optimisation of equivalent line capacities (QP / LP / MIQP via JuMP + Ipopt / HiGHS)
- Reduced network visualisation (when
CONFIG.enable_plots = true) - 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 IDsIsland_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 valuesEquivalent_Capacities_<suffix>.csv: Optimised synthetic line capacities, reactances, and DC flagsTTC_Comparison_<suffix>.csv: Comparison of original vs equivalent TTC valuesNetwork_Original_<suffix>.png: Original network plot (only whenenable_plots = true)Network_Reduced_<suffix>.png: Reduced network plot (only whenenable_plots = true)Network_Original_vs_Reduced_<suffix>.png: Side-by-side comparison plot (only whenenable_plots = true)
ElectricityNetworkReduction.plot_network — Method
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.
ElectricityNetworkReduction.plot_network_gis — Method
plot_network_gis(g, node_info, lines_df; title, show_names, node_sz) -> FigurePlot 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.
ElectricityNetworkReduction.plot_original_vs_reduced — Method
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.
ElectricityNetworkReduction.plot_original_vs_reduced_gis — Method
plot_original_vs_reduced_gis(g_orig, nodes_orig, lines_orig,
g_red, nodes_red, lines_red;
main_title) -> FigureSide-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.
ElectricityNetworkReduction.process_converters — Method
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.
ElectricityNetworkReduction.process_dclines — Method
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)
ElectricityNetworkReduction.process_tielines — Method
process_tielines(tielines_df::DataFrame)Process tie-lines by sorting, removing duplicates, and handling missing EIC codes.
ElectricityNetworkReduction.process_transformers — Method
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.
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.
ElectricityNetworkReduction.rename_buses — Function
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.
ElectricityNetworkReduction.rename_dc_buses — Function
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.
ElectricityNetworkReduction.reset_config! — Method
reset_config!()Resets the global CONFIG object to its default values. Useful for batch testing multiple case studies.
ElectricityNetworkReduction.select_representative_nodes — Method
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_zonenodes 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
IsRepresentativein 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.
ElectricityNetworkReduction.Config — Type
ConfigCentral configuration struct for the entire network reduction workflow. Modify the default values below to run different case studies.
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 mandatoryLines,Tielines,Nodes, andGeneratorssheets from an Excel input file. Also conditionally reads theDCLines,Transformers, andConverterssheets based on the correspondingCONFIG.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 theIsRepresentativecolumn andLatitude/Longitudecolumns 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 theVoltage_levelcolumn, if required. Ifin_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 lineFrom_node/To_nodenames to numerical bus IDs using the map produced byrename_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 asrename_busesso that converter map keys match bus names throughout the pipeline.build_converter_map(converters_df)Returns aDict{String,String}mapping each DC terminal bus name to its connected AC substation bus name. Used byremap_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 beforerename_busesso 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 aDict{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 usingdc_cap_map. Supports multi-threaded execution whenCONFIG.parallel_processing = true. Returns both the TTC DataFrame and aDictof 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 bycalculate_all_ttc_resultsandcalculate_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, updatednode_info(with an:islandcolumn), and the graph object. Used whenCONFIG.enable_plots = trueto 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 islandSUSPECT— 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 linesSINGLETON— 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 byCONFIG.rep_node_mode:"auto": selects the topCONFIG.rep_node_k_per_zonenodes per zone ranked by interconnection degree (line capacity as tiebreaker). Zones listed inCONFIG.high_res_zonesare 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 theIsRepresentativecolumn 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. Whenhigh_res_idsis 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_modelbased onType.QPprovides a fast accuracy/time balance,LPconstructs a deterministic capacity envelope, andMIQPidentifies 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. Returnsnothing; all results are written to CSV files inoutput_dir.CONFIGGlobal configuration object. All parameters and their defaults:Parameter Type Default Description input_filenameString "case118.xlsx"Input file name case_studyString "case118"Case study identifier (used in console output) optimisation_typeString "QP""QP","LP", or"MIQP"baseFloat64 100.0System MVA base bus_names_as_intBool falsetrueif bus IDs are integersin_puBool falsetrueif R, X, B already in per-unitallow_virtual_linesBool falseKeep only physically connected synthetic lines lambdaFloat64 1e-6Regularisation parameter (QP/MIQP) ptdf_epsilonFloat64 1e-6PTDF zero threshold suffixString "QP"Suffix for output file names miqp_binding_candidates_per_txnInt 8Binding candidates retained per transaction in MIQP miqp_time_limit_secFloat64 1800.0MIQP solver time limit miqp_mip_rel_gapFloat64 1e-4MIQP relative MIP gap rep_node_modeString "auto""auto"or"manual_excel"rep_node_k_per_zoneInt 1Nodes per zone in auto mode rep_node_degree_thresholdFloat64 1e-8Minimum susceptance to count as a connection high_res_zonesVector{String} []Zones retained at full bus resolution enable_plotsBool trueGenerate GIS-based PNG plots has_dc_linesBool falseRead DCLines sheet dc_lines_sheetString "DCLines"Name of DC lines sheet has_transformersBool falseRead Transformers sheet transformers_sheetString "Transformers"Name of transformers sheet transformers_in_puBool trueTransformer X already in per-unit has_convertersBool falseRead Converters sheet converters_sheetString "Converters"Name of converters sheet parallel_processingBool trueMulti-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. UsesLatitude/Longitudecolumns 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 CairoMakieFigure.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 viaCairoMakie.save.plot_network(g, node_info, lines_df; title, n_size, f_size, show_names)Legacy plotting function usingPlots.jl+GraphRecipes. Retained for backward compatibility. For new use cases, preferplot_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 usingPlots.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.
| File | Responsibility |
|---|---|
config.jl | Centralized settings and global CONFIG object |
data-loading.jl | Excel ingestion, per-unit normalization, DC line and converter handling |
export-functions.jl | CSV export and reporting utilities |
island-detection.jl | Connected-component detection, island diagnostics |
kron-reduction.jl | Mathematical node elimination with multi-island regularisation |
main-analysis.jl | 11-step top-level wrapper; timing summary |
network-visualisation.jl | GIS-based (CairoMakie/GraphMakie) and legacy (Plots.jl) plot functions |
optimisation.jl | QP fit, LP capacity envelope, MIQP binding-line MILP, TTC reporting |
ptdf-calculations.jl | DC power flow sensitivity analysis; parallel TTC enumeration |
representative-nodes.jl | Zone grouping, degree-based or manual node selection, high-res zone support |
ybus-formation.jl | Physical matrix assembly ($Y_{bus}$) |