import sys
import time
import numpy as np
import pandapower as pp
import pandapower.networks as pn
from lightsim2grid import SolverType
from lightsim2grid.gridmodel import init_from_pandapower
case_name = sys.argv[1] if len(sys.argv) > 1 else "case14"
t0 = time.perf_counter()
net = getattr(pn, case_name)()
pp.runpp(net)
grid = init_from_pandapower(net)
grid.change_solver(SolverType.KLU)
t1 = time.perf_counter()
print(f"model construction: {(t1 - t0) * 1e3:.3f} ms", file=sys.stderr)
n_bus = len(grid.get_bus_vn_kv())
def run_ac_pf():
v_init = np.ones(n_bus, dtype=complex) * grid.get_init_vm_pu()
v = grid.ac_pf(v_init, 20, 1e-6)
if v.shape[0] == 0:
raise RuntimeError(f"lightsim2grid ac_pf diverged for {case_name}")
return v
run_ac_pf()
times = []
v = None
for _ in range(5):
t0 = time.perf_counter()
v = run_ac_pf()
t1 = time.perf_counter()
times.append(t1 - t0)
print(f"nodes={n_bus}")
print(f"ac_pf (warm, 5 runs, ms): {[f'{t * 1e3:.3f}' for t in times]}")
print(f"min={min(times) * 1e3:.3f}ms mean={sum(times) / len(times) * 1e3:.3f}ms")
vm = np.abs(v)
print(f"sample vm[0:5] = {vm[:5]}")
print(f"vm min/max = {vm.min():.6f} / {vm.max():.6f}")
t0 = time.perf_counter()
net2 = getattr(pn, case_name)()
pp.runpp(net2)
grid2 = init_from_pandapower(net2)
grid2.change_solver(SolverType.KLU)
v_init2 = np.ones(n_bus, dtype=complex) * grid2.get_init_vm_pu()
grid2.ac_pf(v_init2, 20, 1e-6)
t1 = time.perf_counter()
print(f"cold (construct+calc): {(t1 - t0) * 1e3:.3f} ms")