gridplan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gridplan/visualize.py ADDED
@@ -0,0 +1,140 @@
1
+ """
2
+ Visualizes the network topology and (optionally) congestion results from
3
+ dcopf.py, and the build decision from tep.py. Uses networkx for layout
4
+ and matplotlib for rendering - both are general-purpose, not grid-specific,
5
+ so this is easy to adapt if you swap in your own network.
6
+ """
7
+ import os
8
+ import matplotlib
9
+ matplotlib.use("Agg")
10
+ import matplotlib.pyplot as plt
11
+ import matplotlib.patches as mpatches
12
+ import networkx as nx
13
+
14
+ from .network import Network
15
+
16
+ ZONE_COLORS = {"North": "#4C72B0", "Central": "#55A868", "South": "#C44E52"}
17
+
18
+
19
+ def _build_graph(net, include_candidates=False):
20
+ G = nx.Graph()
21
+ for b in net.buses.values():
22
+ G.add_node(b.bus_id, name=b.name, zone=b.zone)
23
+ line_set = net.existing_lines()
24
+ if include_candidates:
25
+ line_set = {**line_set, **net.candidate_lines()}
26
+ for lid, ln in line_set.items():
27
+ G.add_edge(ln.from_bus, ln.to_bus, line_id=lid, status=ln.status,
28
+ capacity=ln.capacity_mw)
29
+ return G
30
+
31
+
32
+ def plot_topology(net, out_path, include_candidates=True, congestion=None,
33
+ build_decision=None, title="Transmission Network"):
34
+ """
35
+ congestion: optional dict of line_id -> loading_pct (e.g. built from
36
+ {lid: lf.loading_pct for lid, lf in result.line_flows.items()}
37
+ where result = congestion.solve_congestion(...))
38
+ used to color existing lines by how loaded they are.
39
+ build_decision: optional dict of candidate line_id -> bool, from
40
+ expansion.solve_expansion(...).build_decision, used to highlight
41
+ recommended new lines in green vs. rejected ones as dashed grey.
42
+ """
43
+ G = _build_graph(net, include_candidates=include_candidates)
44
+ pos = nx.spring_layout(G, seed=7, k=1.3)
45
+
46
+ fig, ax = plt.subplots(figsize=(10, 7))
47
+
48
+ node_colors = [ZONE_COLORS.get(net.buses[n].zone, "#888") for n in G.nodes]
49
+ nx.draw_networkx_nodes(G, pos, node_color=node_colors, node_size=650,
50
+ edgecolors="white", linewidths=1.5, ax=ax)
51
+ labels = {n: net.buses[n].name.replace("_", "\n") for n in G.nodes}
52
+ nx.draw_networkx_labels(G, pos, labels, font_size=7, ax=ax)
53
+
54
+ existing_edges, candidate_built, candidate_rejected = [], [], []
55
+ for u, v, data in G.edges(data=True):
56
+ if data["status"] == "existing":
57
+ existing_edges.append((u, v))
58
+ elif build_decision and build_decision.get(data["line_id"]):
59
+ candidate_built.append((u, v))
60
+ else:
61
+ candidate_rejected.append((u, v))
62
+
63
+ if congestion:
64
+ edge_colors, edge_widths = [], []
65
+ for u, v in existing_edges:
66
+ lid = G[u][v]["line_id"]
67
+ pct = congestion.get(lid, 0)
68
+ edge_widths.append(1.5 + pct / 100 * 4)
69
+ if pct >= 95:
70
+ edge_colors.append("#B22222")
71
+ elif pct >= 70:
72
+ edge_colors.append("#E08214")
73
+ else:
74
+ edge_colors.append("#4C4C4C")
75
+ nx.draw_networkx_edges(G, pos, edgelist=existing_edges, edge_color=edge_colors,
76
+ width=edge_widths, ax=ax)
77
+ else:
78
+ nx.draw_networkx_edges(G, pos, edgelist=existing_edges, edge_color="#4C4C4C",
79
+ width=2, ax=ax)
80
+
81
+ if candidate_built:
82
+ nx.draw_networkx_edges(G, pos, edgelist=candidate_built, edge_color="#2CA02C",
83
+ width=3, style="solid", ax=ax)
84
+ if candidate_rejected:
85
+ nx.draw_networkx_edges(G, pos, edgelist=candidate_rejected, edge_color="#999999",
86
+ width=1.5, style="dashed", ax=ax)
87
+
88
+ edge_labels = {(u, v): d["line_id"] for u, v, d in G.edges(data=True)}
89
+ nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=6, ax=ax)
90
+
91
+ legend_items = [mpatches.Patch(color=c, label=z) for z, c in ZONE_COLORS.items()]
92
+ if congestion:
93
+ legend_items += [
94
+ mpatches.Patch(color="#B22222", label=">=95% loaded"),
95
+ mpatches.Patch(color="#E08214", label="70-95% loaded"),
96
+ mpatches.Patch(color="#4C4C4C", label="<70% loaded"),
97
+ ]
98
+ if include_candidates:
99
+ legend_items.append(mpatches.Patch(color="#2CA02C", label="Recommended new line"))
100
+ legend_items.append(mpatches.Patch(color="#999999", label="Candidate (not built)"))
101
+ ax.legend(handles=legend_items, loc="upper left", fontsize=7, framealpha=0.9)
102
+
103
+ ax.set_title(title, fontsize=13)
104
+ ax.axis("off")
105
+ fig.tight_layout()
106
+ fig.savefig(out_path, dpi=150)
107
+ plt.close(fig)
108
+ return out_path
109
+
110
+
111
+ if __name__ == "__main__":
112
+ import os
113
+ from .congestion import solve_congestion
114
+ from .expansion import solve_expansion
115
+
116
+ data_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
117
+ "examples", "sample_data")
118
+ net = Network.from_csv(data_dir)
119
+ out_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "outputs")
120
+ os.makedirs(out_dir, exist_ok=True)
121
+
122
+ # 1) Plain topology
123
+ plot_topology(net, os.path.join(out_dir, "topology.png"),
124
+ title="Network Topology (existing + candidate lines)")
125
+
126
+ # 2) Congestion snapshot
127
+ r = solve_congestion(net, "summer_peak_h17")
128
+ congestion = {lid: lf.loading_pct for lid, lf in r.line_flows.items()}
129
+ plot_topology(net, os.path.join(out_dir, "congestion_peak.png"),
130
+ congestion=congestion,
131
+ title="Line Loading at Summer Peak (17:00)")
132
+
133
+ # 3) Expansion plan recommendation
134
+ exp_result = solve_expansion(net)
135
+ plot_topology(net, os.path.join(out_dir, "expansion_plan.png"),
136
+ congestion=congestion,
137
+ build_decision=exp_result.build_decision,
138
+ title="Recommended Expansion Plan")
139
+
140
+ print(f"Saved figures to {out_dir}/")
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: gridplan
3
+ Version: 0.1.0
4
+ Summary: DC-OPF congestion analysis and MILP-based transmission expansion planning
5
+ Author: Bonnie Bingham
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/bbplus3/gridplan
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Scientific/Engineering
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pyomo>=6.7
16
+ Requires-Dist: highspy>=1.7
17
+ Provides-Extra: viz
18
+ Requires-Dist: matplotlib; extra == "viz"
19
+ Requires-Dist: networkx; extra == "viz"
20
+ Requires-Dist: pyvis; extra == "viz"
21
+ Provides-Extra: gnn
22
+ Requires-Dist: torch; extra == "gnn"
23
+ Provides-Extra: app
24
+ Requires-Dist: streamlit; extra == "app"
25
+ Requires-Dist: pandas; extra == "app"
26
+ Requires-Dist: matplotlib; extra == "app"
27
+ Requires-Dist: networkx; extra == "app"
28
+ Requires-Dist: pyvis; extra == "app"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Provides-Extra: all
32
+ Requires-Dist: matplotlib; extra == "all"
33
+ Requires-Dist: networkx; extra == "all"
34
+ Requires-Dist: pyvis; extra == "all"
35
+ Requires-Dist: torch; extra == "all"
36
+ Requires-Dist: streamlit; extra == "all"
37
+ Requires-Dist: pandas; extra == "all"
38
+ Requires-Dist: pytest; extra == "all"
39
+ Dynamic: license-file
40
+
41
+ # gridplan
42
+
43
+ DC-OPF congestion analysis and MILP-based transmission expansion planning,
44
+ built on [Pyomo](https://www.pyomo.org/). Answers two questions:
45
+
46
+ 1. **Given today's grid, where's it congested, and what's that costing us?**
47
+ 2. **Given a list of candidate new lines and their price tags, which ones are
48
+ actually worth building?**
49
+
50
+ ```python
51
+ from gridplan import Network, solve_congestion, solve_expansion
52
+
53
+ net = Network.from_csv("examples/sample_data")
54
+
55
+ result = solve_congestion(net, "summer_peak_h17")
56
+ print(result.summary())
57
+ print("Overloaded lines:", result.lines_over(90))
58
+ print("LMPs ($/MWh):", result.lmps)
59
+
60
+ plan = solve_expansion(net)
61
+ print(plan.summary())
62
+ ```
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ git clone https://github.com/bbplus3/gridplan.git
68
+ cd gridplan
69
+ pip install -e . # core: Network, solve_congestion, solve_expansion
70
+ pip install -e ".[viz]" # + static/interactive network diagrams
71
+ pip install -e ".[gnn]" # + GNN power-flow surrogate (needs torch)
72
+ pip install -e ".[app]" # + Streamlit browser app
73
+ pip install -e ".[all]" # everything
74
+ ```
75
+
76
+ No separate solver binary needed — `highspy` (the HiGHS solver, pure pip
77
+ install) is a core dependency, used by default for both the LP congestion
78
+ model and the MILP expansion planning model.
79
+
80
+ ## Quickstart
81
+
82
+ ```bash
83
+ python examples/quickstart.py
84
+ ```
85
+
86
+ or generate a browser diagram / run the full app:
87
+
88
+ ```bash
89
+ pip install -e ".[app]"
90
+ streamlit run app.py
91
+ ```
92
+
93
+ ## How the model works
94
+
95
+ **DC power flow approximation.** Like virtually all transmission planning
96
+ tools (PyPSA, PLEXOS, Google Tapestry, etc.), this uses the linearized "DC"
97
+ power flow model rather than full AC power flow: flow on a line is
98
+ proportional to the voltage-angle difference across it, divided by the
99
+ line's reactance. Standard for planning studies — fast, always solves to a
100
+ clean global optimum, and captures the loop-flow effects that actually
101
+ drive congestion — but not adequate for detailed voltage/operational
102
+ studies (use `pandapower` or `PyPSA` with an AC solver for that).
103
+
104
+ **Congestion model (`gridplan.congestion`).** For a given snapshot, minimizes
105
+ generation cost subject to power balance at every bus and flow limits on
106
+ every existing line — a linear program, solved to global optimality via
107
+ simplex. The dual value on each bus's power-balance constraint is that
108
+ bus's locational marginal price (LMP); this falls straight out of the
109
+ solve, no separate computation needed. `CongestionResult` wraps the answer
110
+ with convenience methods: `.lines_over(pct)`, `.binding_lines()`,
111
+ `.is_feasible`, `.summary()`.
112
+
113
+ **Expansion planning model (`gridplan.expansion`).** Adds a binary
114
+ build/don't-build decision per candidate line, solved jointly across every
115
+ snapshot you give it (a mixed-integer linear program). Uses the standard
116
+ disjunctive/big-M formulation: a candidate line's power-flow equation is
117
+ only enforced when its build variable is 1. The objective weighs one-time
118
+ capital cost against annualized operating + reliability cost.
119
+
120
+ ## Package layout
121
+
122
+ ```
123
+ src/gridplan/
124
+ network.py - Bus, Line, Generator, Network (Network.from_csv(...))
125
+ congestion.py - solve_congestion(), summarize_congestion(), CongestionResult
126
+ expansion.py - solve_expansion(), ExpansionResult
127
+ visualize.py - static PNG network diagrams (needs [viz])
128
+ interactive.py - draggable HTML network diagrams via pyvis (needs [viz])
129
+ gnn.py - GNN power-flow surrogate (needs [gnn]; see module docstring
130
+ for an honest discussion of when this technique actually helps)
131
+ examples/
132
+ sample_data/ - a fictional 9-bus, 3-zone utility system
133
+ generate_sample_data.py
134
+ quickstart.py
135
+ tests/
136
+ test_gridplan.py - hand-checkable 2-bus cases + sanity checks on the sample network
137
+ app.py - Streamlit browser app (needs [app])
138
+ ```
139
+
140
+ ## Bringing your own network
141
+
142
+ Replace `examples/sample_data/*.csv` (or point `Network.from_csv()` at your
143
+ own directory) with four CSVs in this schema:
144
+
145
+ | File | Columns | Notes |
146
+ |---|---|---|
147
+ | `buses.csv` | `bus_id, name, zone, base_kv` | one row per substation/bus |
148
+ | `lines.csv` | `line_id, from_bus, to_bus, reactance_pu, capacity_mw, status, length_km, cost_million_usd` | `status` is `existing` or `candidate`; cost only needed for candidates |
149
+ | `generators.csv` | `gen_id, bus_id, name, capacity_mw, marginal_cost_per_mwh, fuel_type` | one row per generating unit |
150
+ | `loads.csv` | `snapshot, bus_id, hour, season, demand_mw` | one row per (snapshot, bus); a "snapshot" is any label for an hour/condition |
151
+
152
+ `reactance_pu` needs a consistent MVA base across all lines (default 100
153
+ MVA — change `BASE_MVA` in `gridplan/congestion.py` and `gridplan/expansion.py`
154
+ if yours differs). For renewable generators, note `capacity_mw` is treated
155
+ as a hard cap; if you want per-snapshot availability (e.g. wind/solar
156
+ capacity factors), that's a small, contained change to the generator-limit
157
+ constraint in both modules.
158
+
159
+ ## Running tests
160
+
161
+ ```bash
162
+ pip install -e ".[dev]"
163
+ pytest
164
+ ```
165
+
166
+ ## License
167
+
168
+ MIT — see `LICENSE`.
@@ -0,0 +1,12 @@
1
+ gridplan/__init__.py,sha256=orHh6TKCIAW5xp6FuyAmhsCd_aUpQI4BDrVHXMe13hQ,1184
2
+ gridplan/congestion.py,sha256=_v_8U-uI2q5Wn-H1tHm-hMLC4N6LH1G0bURPxTFml6Y,7034
3
+ gridplan/expansion.py,sha256=FHXTUVWmX8va9U1VCXcgkKzeopIIOHnRm7HvuxRH3hQ,6515
4
+ gridplan/gnn.py,sha256=V11JazI01JSOzcP3YYPV7-QXPVs5ZZZO9TdwVOLRH1U,15304
5
+ gridplan/interactive.py,sha256=AMSPeuShge1fTr7oLoD94596CyT9V5NsaFShlgjRe6o,7199
6
+ gridplan/network.py,sha256=SFGgG5u46rEGfTBY7QssOWquKWAVHpDdLFvBjsv-2yY,3947
7
+ gridplan/visualize.py,sha256=hGhxV01yfbqYnFlAFsBwsWSTUyFWKKyZRqChfZ3L1Nc,5828
8
+ gridplan-0.1.0.dist-info/licenses/LICENSE,sha256=6t_ceEQCfmpoIrmcR8IOL-ymlRkGRvh4ZfOXameeW84,1071
9
+ gridplan-0.1.0.dist-info/METADATA,sha256=8r4HdCAbZaiPj7c0O0h5bo5G2DWwv8OH6ivHYdlwDUQ,6611
10
+ gridplan-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
11
+ gridplan-0.1.0.dist-info/top_level.txt,sha256=bCbLC71F6pYJZzXHHehl498Y5ildReKgkCDBRIakvHs,9
12
+ gridplan-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bonnie Bingham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ gridplan