freqresponse-screen 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.
@@ -0,0 +1,7 @@
1
+ """FreqResponse-Screen: frequency response screening after a sudden loss of
2
+ generation or load, as inverter-based resources replace synchronous units.
3
+
4
+ A screening tool, not a study. See the README for assumptions and limits.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,324 @@
1
+ """Build the IEEE 39-bus case in ANDES for one frequency-response scenario.
2
+
3
+ The case is edited as tables (one pandas DataFrame per ANDES model) and then
4
+ loaded into ANDES. Replacing a unit removes the machine and every control
5
+ attached to it (governor, exciter, stabilizer), the same approach as
6
+ IBR-FaultScreen.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import os
13
+ import tempfile
14
+
15
+ import andes
16
+ import pandas as pd
17
+
18
+ from .scenario import UNIT_BUSES, Event, Scenario
19
+ from .settings import SYNC_MODEL, ModelSettings
20
+
21
+ CASE_FILE = "ieee39/ieee39_full.xlsx"
22
+ #: REGCA1 + REECA1 + REPCA1 parameters are copied from this ANDES example case.
23
+ IBR_TEMPLATE_CASE = "ieee14/ieee14_solar.xlsx"
24
+ DROOP_KPG = 0.5
25
+ DROOP_KIG = 1.5
26
+ EVENT_SHEETS = ("Toggler", "Toggle", "Alter", "Fault")
27
+ SLACK_BUS = 39
28
+ BASE_MVA = 100.0
29
+
30
+ #: Changes to the ANDES example IBR parameters, applied to every IBR.
31
+ #: Frequency-control fields are set separately from the model settings.
32
+ IBR_OVERRIDES = {
33
+ # Plant voltage control: WECC MVWG Solar PV Plant Modeling and Validation
34
+ # Guideline (Dec 2019), example model invocation (illustrative values).
35
+ "REPCA1": {"Kp": 18.0, "Ki": 5.0, "Tfltr": 0.02, "Tfv": 0.05, "Tft": 0.0,
36
+ "Vfrz": 0.0, "Kc": 0.02, "emax": 0.5, "emin": -0.5,
37
+ "dbd1": 0.0, "dbd2": 0.0, "Qmax": 0.575, "Qmin": -0.575,
38
+ # frequency path: no extra limit on the droop term
39
+ "femax": 99.0, "femin": -99.0},
40
+ }
41
+
42
+
43
+ @functools.lru_cache(maxsize=1)
44
+ def _read_case() -> dict:
45
+ sheets = pd.read_excel(andes.get_case(CASE_FILE), sheet_name=None)
46
+ return {k: v for k, v in sheets.items() if k != "Summary" and not k.startswith("_")}
47
+
48
+
49
+ def read_case() -> dict[str, pd.DataFrame]:
50
+ """The IEEE 39-bus tables as shipped with ANDES (a fresh, editable copy)."""
51
+ return {k: v.copy() for k, v in _read_case().items()}
52
+
53
+
54
+ @functools.lru_cache(maxsize=1)
55
+ def _ibr_template() -> dict:
56
+ t = pd.read_excel(andes.get_case(IBR_TEMPLATE_CASE), sheet_name=None)
57
+ rows = {k: t[k].drop(columns="uid", errors="ignore").iloc[0].to_dict()
58
+ for k in ("REGCA1", "REECA1", "REPCA1")}
59
+ for model, vals in IBR_OVERRIDES.items():
60
+ rows[model].update(vals)
61
+ return rows
62
+
63
+
64
+ def remove_events(sheets) -> list[str]:
65
+ """Drop every event already in the case (the shipped case trips generator 1
66
+ at 12 s); a scenario holds only the event it defines."""
67
+ removed = []
68
+ for name in EVENT_SHEETS:
69
+ df = sheets.pop(name, None)
70
+ if df is not None and not df.empty:
71
+ removed += df["idx"].astype(str).tolist()
72
+ return removed
73
+
74
+
75
+ def unit_row(sheets, bus: int) -> pd.Series:
76
+ df = sheets[SYNC_MODEL]
77
+ hit = df[df["bus"].astype(int) == int(bus)]
78
+ if hit.empty:
79
+ raise ValueError(f"no synchronous machine at bus {bus}")
80
+ return hit.iloc[0]
81
+
82
+
83
+ def unit_dispatch_mw(sheets, bus: int) -> float:
84
+ """Active power of the generator at `bus` from the case data (PV p0), MW."""
85
+ pv = sheets["PV"]
86
+ hit = pv[pv["bus"].astype(int) == int(bus)]
87
+ if hit.empty:
88
+ raise ValueError(f"bus {bus} has no PV generator")
89
+ return float(hit.iloc[0]["p0"]) * BASE_MVA
90
+
91
+
92
+ def fleet_average_h(sheets, exclude_bus: int = SLACK_BUS) -> float:
93
+ """MVA-weighted average inertia constant H (s, machine base) of the units
94
+ other than `exclude_bus`. H = M / 2 (ANDES stores M = 2H on machine base)."""
95
+ df = sheets[SYNC_MODEL]
96
+ df = df[df["bus"].astype(int) != exclude_bus]
97
+ sn = df["Sn"].astype(float)
98
+ h = df["M"].astype(float) / 2.0
99
+ return float((h * sn).sum() / sn.sum())
100
+
101
+
102
+ def set_h39(sheets, mode: str) -> float:
103
+ """Apply the generator 39 inertia mode. Returns H (s, machine base) used."""
104
+ df = sheets[SYNC_MODEL]
105
+ sel = df["bus"].astype(int) == SLACK_BUS
106
+ if mode == "as_published":
107
+ return float(df.loc[sel, "M"].iloc[0]) / 2.0
108
+ h = fleet_average_h(sheets)
109
+ df.loc[sel, "M"] = 2.0 * h
110
+ return h
111
+
112
+
113
+ def add_governor_deadband(sheets, deadband_hz: float, f0: float = 60.0) -> int:
114
+ """Switch the TGOV1N governors to TGOV1NDB with a symmetric deadband.
115
+
116
+ Same parameters; dbL/dbU are in per unit of speed. Returns the number of
117
+ governors changed."""
118
+ if deadband_hz <= 0 or "TGOV1N" not in sheets:
119
+ return 0
120
+ gov = sheets.pop("TGOV1N").copy()
121
+ db = deadband_hz / f0
122
+ gov["dbL"] = -db
123
+ gov["dbU"] = db
124
+ sheets["TGOV1NDB"] = gov
125
+ return len(gov)
126
+
127
+
128
+ def _drop_linked(sheets, column, ids):
129
+ dropped, ids = [], {str(i) for i in ids}
130
+ for name, df in list(sheets.items()):
131
+ if column in df.columns:
132
+ hit = df[column].astype(str).isin(ids)
133
+ if hit.any():
134
+ dropped += df.loc[hit, "idx"].astype(str).tolist()
135
+ sheets[name] = df[~hit]
136
+ return dropped
137
+
138
+
139
+ def _step_up_branch(sheets, bus):
140
+ lines = sheets["Line"]
141
+ at_bus = lines[(lines["bus1"] == bus) | (lines["bus2"] == bus)]
142
+ if at_bus.empty:
143
+ raise ValueError(f"bus {bus} has no branch for plant control")
144
+ xf = at_bus[at_bus["trans"] == 1] if "trans" in at_bus.columns else at_bus.iloc[0:0]
145
+ return (xf if len(xf) == 1 else at_bus).iloc[0]["idx"]
146
+
147
+
148
+ def _busfreq_at(sheets, bus):
149
+ bf = sheets.get("BusFreq")
150
+ if bf is None:
151
+ return None
152
+ hit = bf[bf["bus"].astype(int) == int(bus)]
153
+ return None if hit.empty else hit.iloc[0]["idx"]
154
+
155
+
156
+ def ibr_tag(bus: int) -> str:
157
+ return f"IBR_{int(bus)}"
158
+
159
+
160
+ def replace_with_ibr(sheets, bus: int, model: ModelSettings, f0: float = 60.0) -> dict:
161
+ """Replace the synchronous unit at `bus` with an IBR (REGCA1 + REECA1 + REPCA1).
162
+
163
+ The IBR keeps the unit's MVA rating and active-power dispatch. In droop mode
164
+ its output limit (PMAX, per unit of its rating) is set so it has
165
+ `ibr_headroom` of its rating available above the dispatch.
166
+ """
167
+ bus = int(bus)
168
+ if bus not in UNIT_BUSES:
169
+ raise ValueError(f"bus {bus} is not a replaceable unit")
170
+ m = unit_row(sheets, bus)
171
+ syn, sn, gen = str(m["idx"]), float(m["Sn"]), m["gen"]
172
+ p_pu_own = unit_dispatch_mw(sheets, bus) / sn
173
+ branch = _step_up_branch(sheets, bus)
174
+
175
+ sheets[SYNC_MODEL] = sheets[SYNC_MODEL][sheets[SYNC_MODEL]["idx"].astype(str) != syn]
176
+ controls = _drop_linked(sheets, "syn", [syn])
177
+ controls += _drop_linked(sheets, "avr", controls)
178
+
179
+ tag, t = ibr_tag(bus), _ibr_template()
180
+ droop = model.ibr_support == "droop"
181
+ pmax = min(1.0, p_pu_own + model.ibr_headroom) if droop else 1.0
182
+ kdroop = 100.0 / model.ibr_droop_pct * sn / BASE_MVA
183
+ rows = {
184
+ "REGCA1": {**t["REGCA1"], "idx": f"REG_{tag}", "name": f"REG_{tag}",
185
+ "bus": bus, "gen": gen, "Sn": sn, "Iolim": -1.0},
186
+ "REECA1": {**t["REECA1"], "idx": f"REE_{tag}", "name": f"REE_{tag}",
187
+ "reg": f"REG_{tag}", "Imax": 1.0, "PMIN": 0.0, "PMAX": pmax,
188
+ **{f"I{c}{k}": 1.0 for c in "qp" for k in "1234"}},
189
+ "REPCA1": {**t["REPCA1"], "idx": f"REP_{tag}", "name": f"REP_{tag}",
190
+ "ree": f"REE_{tag}", "line": branch, "busr": bus,
191
+ "Fflag": 1 if droop else 0,
192
+ # Plant power loop closed on the measured branch power so the
193
+ # droop settles (PLflag = 1). Gains are generic: closed-loop
194
+ # time constant (1 + Kpg) / Kig = 1 s.
195
+ "PLflag": 1 if droop else 0, "Kpg": DROOP_KPG, "Kig": DROOP_KIG,
196
+ # ANDES applies Ddn/Dup on the system base (found in testing:
197
+ # the response was Sn/100 times too small on the IBR's own
198
+ # base), so the per-unit droop gain is scaled by Sn / 100 MVA.
199
+ "Ddn": kdroop, "Dup": kdroop,
200
+ "fdbd1": -model.ibr_deadband_hz / f0, "fdbd2": model.ibr_deadband_hz / f0},
201
+ }
202
+ bf = _busfreq_at(sheets, bus)
203
+ if bf is not None:
204
+ rows["REPCA1"]["busf"] = bf
205
+ for name, row in rows.items():
206
+ new = pd.DataFrame([row])
207
+ sheets[name] = new if name not in sheets else pd.concat([sheets[name], new],
208
+ ignore_index=True)
209
+ return {"bus": bus, "mva": sn, "mw": p_pu_own * sn, "pmax_pu": pmax,
210
+ "removed": [syn] + controls}
211
+
212
+
213
+ def bus_vn(sheets, bus: int) -> float:
214
+ b = sheets["Bus"]
215
+ hit = b[b["idx"].astype(int) == int(bus)]
216
+ if hit.empty:
217
+ raise ValueError(f"bus {bus} does not exist")
218
+ return float(hit.iloc[0]["Vn"])
219
+
220
+
221
+ EVENT_LOAD = "EVENT_LOAD"
222
+
223
+
224
+ def add_event_load(sheets, event: Event) -> None:
225
+ """Sized events: an extra PQ load at the event bus (unity power factor).
226
+
227
+ gen_loss: the load starts out of service and is switched on at the event.
228
+ load_trip: the load is served in the pre-event power flow (the slack,
229
+ generator 39, supplies it) and is switched off at the event."""
230
+ if event.kind == "gen_trip":
231
+ return
232
+ row = {"idx": EVENT_LOAD, "u": 1 if event.kind == "load_trip" else 0,
233
+ "name": EVENT_LOAD, "bus": int(event.bus), "Vn": bus_vn(sheets, event.bus),
234
+ "p0": float(event.mw) / BASE_MVA, "q0": 0.0}
235
+ sheets["PQ"] = pd.concat([sheets["PQ"], pd.DataFrame([row])], ignore_index=True)
236
+
237
+
238
+ def event_toggles(sheets, event: Event, ibr_units) -> list[tuple[str, str]]:
239
+ """(model, device idx) pairs switched at the event time."""
240
+ if event.kind != "gen_trip":
241
+ return [("PQ", EVENT_LOAD)]
242
+ bus = int(event.bus)
243
+ if bus in ibr_units:
244
+ tag = ibr_tag(bus)
245
+ return [("REPCA1", f"REP_{tag}"), ("REECA1", f"REE_{tag}"), ("REGCA1", f"REG_{tag}")]
246
+ syn = str(unit_row(sheets, bus)["idx"])
247
+ pairs = [(SYNC_MODEL, syn)]
248
+ ctrl = []
249
+ for name, df in sheets.items():
250
+ if "syn" in df.columns:
251
+ for i in df.loc[df["syn"].astype(str) == syn, "idx"].astype(str):
252
+ pairs.append((name, i))
253
+ ctrl.append(i)
254
+ for name, df in sheets.items():
255
+ if "avr" in df.columns:
256
+ for i in df.loc[df["avr"].astype(str).isin(ctrl), "idx"].astype(str):
257
+ pairs.append((name, i))
258
+ return pairs
259
+
260
+
261
+ def max_load_trip_mw(sheets) -> float:
262
+ """Largest load-trip size the case can serve before the event.
263
+
264
+ The large load is supplied by generator 39 (the slack) in the pre-event
265
+ power flow; its governor must stay below its valve limit (VMAX, per unit of
266
+ its rating) with 2 % margin. About 610 MW for the shipped case."""
267
+ slack_mw = float(sheets["Slack"]["p0"].iloc[0]) * BASE_MVA
268
+ g = unit_row(sheets, SLACK_BUS)
269
+ gov = sheets["TGOV1N"] if "TGOV1N" in sheets else sheets["TGOV1NDB"]
270
+ vmax = float(gov.loc[gov["syn"].astype(str) == str(g["idx"]), "VMAX"].iloc[0])
271
+ return 0.98 * vmax * float(g["Sn"]) - slack_mw
272
+
273
+
274
+ def check_load_trip_size(sheets, mw) -> None:
275
+ cap = max_load_trip_mw(sheets)
276
+ if mw > cap:
277
+ raise ValueError(f"load_trip: {mw:,.0f} MW is more than generator 39 can supply before "
278
+ f"the event in this case (about {cap:,.0f} MW)")
279
+
280
+
281
+ def load_config(model: ModelSettings) -> list[str]:
282
+ if model.load_model == "constant_current":
283
+ return ["PQ.p2p=0", "PQ.p2i=1", "PQ.p2z=0", "PQ.q2q=0", "PQ.q2i=0", "PQ.q2z=1"]
284
+ return ["PQ.p2p=0", "PQ.p2i=0", "PQ.p2z=1", "PQ.q2q=0", "PQ.q2i=0", "PQ.q2z=1"]
285
+
286
+
287
+ def prepare_tables(scenario: Scenario, model: ModelSettings, f0: float = 60.0):
288
+ """All table edits for a scenario. Returns (sheets, info)."""
289
+ sheets = read_case()
290
+ info = {"removed_events": remove_events(sheets)}
291
+ info["h39_s"] = set_h39(sheets, model.h39_mode)
292
+ info["h_fleet_avg_s"] = fleet_average_h(sheets)
293
+ info["dispatch_mw"] = {b: unit_dispatch_mw(sheets, b) for b in UNIT_BUSES}
294
+ if scenario.event.kind == "gen_trip":
295
+ info["event_mw"] = info["dispatch_mw"][int(scenario.event.bus)]
296
+ else:
297
+ info["event_mw"] = float(scenario.event.mw)
298
+ if scenario.event.kind == "load_trip":
299
+ check_load_trip_size(sheets, scenario.event.mw)
300
+ info["governors_with_deadband"] = add_governor_deadband(sheets, model.gov_deadband_hz, f0)
301
+ info["ibrs"] = [replace_with_ibr(sheets, b, model, f0) for b in scenario.ibr_units]
302
+ add_event_load(sheets, scenario.event)
303
+ info["toggles"] = event_toggles(sheets, scenario.event, scenario.ibr_units)
304
+ return sheets, info
305
+
306
+
307
+ def build_system(sheets, toggles, model: ModelSettings):
308
+ """Load the tables into ANDES, add the event toggles, set up, run the power flow."""
309
+ fd, path = tempfile.mkstemp(suffix=".xlsx")
310
+ os.close(fd)
311
+ try:
312
+ with pd.ExcelWriter(path) as writer:
313
+ for name, df in sheets.items():
314
+ df.to_excel(writer, sheet_name=name, index=False)
315
+ system = andes.load(path, no_output=True, default_config=True, setup=False,
316
+ config_option=load_config(model))
317
+ finally:
318
+ os.remove(path)
319
+ for i, (mdl, dev) in enumerate(toggles):
320
+ system.add("Toggle", {"idx": f"EVT_{i + 1}", "model": mdl, "dev": dev,
321
+ "t": model.t_event_s})
322
+ system.setup()
323
+ system.PFlow.run()
324
+ return system
@@ -0,0 +1,173 @@
1
+ """Command line: freqresponse-screen run | render."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ from . import __version__
12
+
13
+ EPILOG = ("Screening only: results are not a study. Thresholds are generic screening values, "
14
+ "not any ISO, RTO, utility or regional UFLS criteria.")
15
+
16
+
17
+ def _settings(args):
18
+ import yaml
19
+
20
+ from .settings import Settings
21
+ data = {}
22
+ if args.settings:
23
+ with open(args.settings, encoding="utf-8") as fh:
24
+ data = yaml.safe_load(fh) or {}
25
+ s = Settings.from_dict(data)
26
+ m, c = s.model, s.criteria
27
+ for name, attr, obj in (("h39", "h39_mode", m), ("ibr_support", "ibr_support", m),
28
+ ("load_model", "load_model", m), ("gov_deadband", "gov_deadband_hz", m),
29
+ ("ibr_droop", "ibr_droop_pct", m), ("ibr_headroom", "ibr_headroom", m),
30
+ ("t_end", "t_end_s", m), ("ufls", "ufls_first_step_hz", c),
31
+ ("overfreq", "overfreq_limit_hz", c)):
32
+ val = getattr(args, name, None)
33
+ if val is not None:
34
+ setattr(obj, attr, val)
35
+ return s.validate()
36
+
37
+
38
+ def _r(x):
39
+ return round(x, 4) if isinstance(x, float) else x
40
+
41
+
42
+ def _write_csv(results, path):
43
+ head = ["record", "event", "event_bus", "event_mw", "ibr_step", "ibr_share_pct", "ibr_units",
44
+ "result", "nadir_or_zenith_hz", "time_to_extreme_s", "rocof_hz_s", "settling_hz",
45
+ "settled", "margin_hz", "ek_mws", "power_step_mw", "sim_status", "notes"]
46
+ recs = [("main", results["main"])] + [("unit_trip", r) for r in results["unit_trips"]]
47
+ for sc in results["scans"]:
48
+ recs += [(f"scan_{sc['kind']}", r) for r in sc["cells"]]
49
+ with open(path, "w", newline="", encoding="utf-8") as fh:
50
+ w = csv.writer(fh)
51
+ w.writerow([f"Screening only - FreqResponse-Screen v{__version__}. Generic thresholds; see report."])
52
+ w.writerow(head)
53
+ for kind, r in recs:
54
+ m = r["metrics"]
55
+ w.writerow([_r(x) for x in [kind, r["event"]["kind"], r["event"]["bus"], r["event"]["mw"], r["step"],
56
+ r["ibr_share_pct"], " ".join(map(str, r["ibr_units"])), m["status"],
57
+ m["extreme_hz"], m["t_extreme_s"], m["rocof_hz_s"], m["settle_hz"],
58
+ m["settled"], m["margin_hz"], r["ek_mws"], r["dp_step_mw"],
59
+ r["status_sim"], " | ".join(m["reasons"])]])
60
+
61
+
62
+ def cmd_run(args) -> int:
63
+ from . import dashboard
64
+ from .scenario import DEFAULT_IBR_ORDER, Event
65
+ from .screen import LOAD_TRIP_SIZES, LOSS_SIZES, screen
66
+
67
+ settings = _settings(args)
68
+ if args.event == "gen_trip":
69
+ event = Event("gen_trip", args.bus or 38)
70
+ else:
71
+ if args.mw is None:
72
+ print("error: --mw is required for gen_loss and load_trip", file=sys.stderr)
73
+ return 2
74
+ event = Event(args.event, args.bus or (16 if args.event == "gen_loss" else 20), args.mw)
75
+ order = tuple(int(x) for x in args.ibr_order.split(",")) if args.ibr_order else DEFAULT_IBR_ORDER
76
+
77
+ def progress(i, n):
78
+ if not args.quiet:
79
+ print(f"\r simulations: {i}/{n}", end="", file=sys.stderr, flush=True)
80
+
81
+ if not args.quiet:
82
+ print(f"FreqResponse-Screen v{__version__}: {event.label()}, IBR step {args.ibr_step}",
83
+ file=sys.stderr)
84
+ results = screen(settings, main_event=event, main_step=args.ibr_step, order=order,
85
+ scans=not args.no_scan, jobs=args.jobs, progress=progress,
86
+ loss_sizes=tuple(args.loss_sizes) if args.loss_sizes else LOSS_SIZES,
87
+ trip_sizes=tuple(args.trip_sizes) if args.trip_sizes else LOAD_TRIP_SIZES)
88
+ if not args.quiet:
89
+ print(file=sys.stderr)
90
+ out = args.out
91
+ with open(out, "w", encoding="utf-8") as fh:
92
+ fh.write(dashboard.render(results))
93
+ if args.json:
94
+ with open(args.json, "w", encoding="utf-8") as fh:
95
+ json.dump(results, fh)
96
+ if args.csv:
97
+ _write_csv(results, args.csv)
98
+ m = results["main"]["metrics"]
99
+ if m["extreme_hz"] is None:
100
+ print(f"{results['main']['event']['label']}: {m['status'].upper()} ({m['reasons'][0]})")
101
+ else:
102
+ print(f"{results['main']['event']['label']}: {m['status'].upper()} "
103
+ f"(extreme {m['extreme_hz']:.3f} Hz, RoCoF {m['rocof_hz_s']:.3f} Hz/s, "
104
+ f"margin {m['margin_hz']:+.3f} Hz)")
105
+ print(f"Dashboard written to {os.path.abspath(out)}")
106
+ return 0
107
+
108
+
109
+ def cmd_render(args) -> int:
110
+ from . import dashboard
111
+ with open(args.results, encoding="utf-8") as fh:
112
+ results = json.load(fh)
113
+ with open(args.out, "w", encoding="utf-8") as fh:
114
+ fh.write(dashboard.render(results))
115
+ print(f"Dashboard written to {os.path.abspath(args.out)}")
116
+ return 0
117
+
118
+
119
+ def build_parser() -> argparse.ArgumentParser:
120
+ p = argparse.ArgumentParser(prog="freqresponse-screen", epilog=EPILOG,
121
+ description="Frequency response screening on the IEEE 39-bus case.")
122
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
123
+ sub = p.add_subparsers(dest="cmd", required=True)
124
+
125
+ r = sub.add_parser("run", help="simulate and write the dashboard", epilog=EPILOG)
126
+ r.add_argument("--event", choices=("gen_trip", "gen_loss", "load_trip"), default="gen_trip",
127
+ help="main event (default gen_trip)")
128
+ r.add_argument("--bus", type=int, help="unit bus for gen_trip (30-38, default 38); "
129
+ "event bus for gen_loss (default 16) or load_trip (default 20)")
130
+ r.add_argument("--mw", type=float, help="event size for gen_loss and load_trip, MW")
131
+ r.add_argument("--ibr-step", type=int, default=0,
132
+ help="units replaced by IBRs for the main event and unit trips (0-9)")
133
+ r.add_argument("--ibr-order", help="replacement order, e.g. 30,31,32,33,34,35,36,37,38")
134
+ r.add_argument("--ibr-support", choices=("none", "droop"))
135
+ r.add_argument("--ibr-droop", type=float, help="IBR droop, %% (default 5)")
136
+ r.add_argument("--ibr-headroom", type=float, help="IBR upward headroom, fraction of rating (default 0.10)")
137
+ r.add_argument("--h39", choices=("standalone", "as_published"), help="generator 39 inertia mode")
138
+ r.add_argument("--load-model", choices=("constant_current", "constant_impedance"))
139
+ r.add_argument("--gov-deadband", type=float, help="governor deadband, Hz (default 0)")
140
+ r.add_argument("--ufls", type=float, help="first UFLS step, Hz (default 59.5)")
141
+ r.add_argument("--overfreq", type=float, help="over-frequency limit, Hz (default 60.5)")
142
+ r.add_argument("--t-end", type=float, help="simulated time, s (default 20)")
143
+ r.add_argument("--settings", help="YAML file with 'criteria' and 'model' sections")
144
+ r.add_argument("--no-scan", action="store_true", help="skip the two heat-map scans")
145
+ r.add_argument("--loss-sizes", type=float, nargs="+", help="generation-loss scan sizes, MW")
146
+ r.add_argument("--trip-sizes", type=float, nargs="+", help="load-trip scan sizes, MW")
147
+ r.add_argument("--jobs", type=int, default=1,
148
+ help="parallel simulations (default 1). Each uses about 0.3-0.5 GB of memory; "
149
+ "about half your processor count is a good start")
150
+ r.add_argument("--out", default="freqresponse_report.html", help="dashboard file")
151
+ r.add_argument("--json", help="also save all results as JSON")
152
+ r.add_argument("--csv", help="also save all results as CSV")
153
+ r.add_argument("--quiet", action="store_true")
154
+ r.set_defaults(func=cmd_run)
155
+
156
+ d = sub.add_parser("render", help="rebuild the dashboard from a saved JSON result")
157
+ d.add_argument("results")
158
+ d.add_argument("--out", default="freqresponse_report.html")
159
+ d.set_defaults(func=cmd_render)
160
+ return p
161
+
162
+
163
+ def main(argv=None) -> int:
164
+ args = build_parser().parse_args(argv)
165
+ try:
166
+ return args.func(args)
167
+ except ValueError as err:
168
+ print(f"error: {err}", file=sys.stderr)
169
+ return 2
170
+
171
+
172
+ if __name__ == "__main__":
173
+ raise SystemExit(main())