Pylons looking towards Tarrès, above Sant Bonifaci: a high-voltage line runs downhill, its conductors sweeping from the top of the frame to a row of lattice pylons on a wooded slope, under a band of cloud.
case30, pandapower from PureScript

Grid
Explorer


A demo of Pythia, a Python backend for PureScript. Write PureScript; use pandapower.

pandapower is a power-systems library with no equivalent in JavaScript. The demo runs on your own machine as one Python process: the analysis is PureScript compiled by Pythia, and every power flow is pandapower’s.

1

What it does

A power network is buses, the points where lines meet, loads draw power and generators feed it in, joined by lines. This one is case30, a standard test network as pandapower ships it: 30 buses and 41 lines.

Take one line out and its power moves onto the others. Is another line now carried past its rating, does a bus’s voltage sag below its limit, is any load cut off? Asking that of every line in turn is N-1, a planner’s first screen: 41 outages, each an AC power flow solved by pandapower, each judged in PureScript.

The Lab's N-1 view: the 30-bus network drawn as buses and lines, line 9 and line 39 in red, and beside it the load factor at 0.70 and the count 2 critical, 5 warning, 34 safe.
A recording of the Lab running against pandapower. The load factor moves from 0.70 to 0.90 and back; each time pandapower solves the 41 outages again, PureScript judges them, and the network recolours: 2 critical at 0.70, 20 at 0.90.
2

Bridging PureScript analysis code to pandapower

The analysis code never imports pandapower. It is written against this PureScript interface:

core/src/Grid/Solver.purs
type Solver m =
  { describe :: CaseName -> m CaseData
  , solve :: SolveSpec -> m SolveResult
  , flows :: SolveSpec -> m Flows
  , sweep :: SweepSpec -> m SweepResult
  }

This record provides four operations:

  • describe: a case, its buses, lines, loads and generators
  • solve: one operating point, described in full
  • flows: the same solve, answered narrowly
  • sweep: N-1 over a list of outages, in one call

No mutable handle crosses, so each call stands alone.

Behind this interface are some boilerplate Pythia FFI functions, one for each operation. A single helper encodes each request with its type’s codec, makes the call, and decodes the answer, failing loudly if it does not decode:

columns/python/src/Grid/Pandapower.purs, 44 lines, its imports left out
module Grid.Pandapower
  ( solver
  ) where
…
foreign import describeImpl :: EffectFn1 Json Json

foreign import solveImpl :: EffectFn1 Json Json

foreign import flowsImpl :: EffectFn1 Json Json

foreign import sweepImpl :: EffectFn1 Json Json

solver :: Solver Effect
solver =
  { describe: call "describe" describeImpl caseNameCodec caseDataCodec
  , solve: call "solve" solveImpl solveSpecCodec solveResultCodec
  , flows: call "flows" flowsImpl solveSpecCodec flowsCodec
  , sweep: call "sweep" sweepImpl sweepSpecCodec sweepResultCodec
  }

call :: forall a b. String -> EffectFn1 Json Json -> CA.JsonCodec a -> CA.JsonCodec b -> a -> Effect b
call operation foreignCall requestCodec responseCodec request = do
  answer <- runEffectFn1 foreignCall (CA.encode requestCodec request)
  case CA.decode responseCodec answer of
    Left err -> throw ("the solver's answer to " <> operation <> " does not decode: " <> CA.printJsonDecodeError err)
    Right decoded -> pure decoded

Those connect to the Python code: ordinary Python functions, in a file Pythia copies in beside the compiled code, that call pandapower and copy its result tables out:

columns/python/ffi-py/Grid_Pandapower_foreign.py, excerpts
def _runpp(net, **options):
    """True if the power flow converged. Only non-convergence is an answer;
    any other exception is a fault and propagates."""
    …
    try:
        pp.runpp(net, **options)
        return True
    except pp.LoadflowNotConverged:
        return False
…
def _sweep(sweep):
    …
    run_contingency(net, cases, write_to_net=False,
                    contingency_evaluation_function=evaluate)
…
def _row(net, converged):
    if not converged:
        return {"converged": False, "busVoltagePu": [], "lineLoadingPercent": [],
                "transformerLoadingPercent": []}
    return {
        "converged": True,
        "busVoltagePu": _values(_col(net.res_bus, "vm_pu")),
        "lineLoadingPercent": _values(_col(net.res_line, "loading_percent")),
        "transformerLoadingPercent": _values(_col(net.res_trafo, "loading_percent")),
    }

N-1 is pandapower’s own run_contingency, in one call; its hook for replacing runpp is how each outage’s row is collected. That is all the Python there is: 434 lines, a good part of them comments and the bookkeeping that keeps one solve from depending on the last.

3

What stays on the Python side, and what does not

The Python file says so in its header:

columns/python/ffi-py/Grid_Pandapower_foreign.py, its header
# What is here is library calls and the copying of their tables into JSON.
# What a load factor means, what a branch is called, which bus is the slack,
# what counts as energised, what stands in for a missing result, the totals,
# the limits and the verdict are all in PureScript (`Grid.Dispatch`,
# `Grid.Network`, `Grid.Severity`, `Grid.Contingency`). One decision of ours
# is still here and is the seam's contract: a result pandapower reports as
# NaN (a bus with no source has no voltage) crosses as `null`, never as a
# number. Everything numeric crosses as a Python float.

That one rule is the boundary’s contract. pandapower reports a quantity it could not compute, the voltage of a bus with no source, as NaN. NaN never crosses: it is sent as null,

columns/python/ffi-py/Grid_Pandapower_foreign.py
def _value(x):
    """A finite float, or None. The seam's contract: no NaN crosses."""
    try:
        f = float(x)
    except (TypeError, ValueError):
        return None
    return f if np.isfinite(f) else None

and arrives in PureScript as Nothing, because that is what the type of the answer says:

core/src/Grid/Solver.purs
type Flows =
  { converged :: Boolean
  , busVoltagePu :: Array (Maybe Number)
  , lineLoadingPercent :: Array (Maybe Number)
  , transformerLoadingPercent :: Array (Maybe Number)
  }

Everything here crosses as JSON, encoded and checked by one codec per type. That is a choice for this boundary, which carries whole result tables (a sweep answers about 3,000 numbers). It is not the only way Pythia calls Python: on this backend a PureScript record is a Python dict and a function is a Python callable, and a foreign file can take them as they are. The program’s second library shows it. Flask is handed a PureScript function as each route’s handler, and its app and request are held as opaque foreign types:

columns/python/src/Server/Flask.purs
foreign import getImpl :: Fn3 Flask String (Request -> Effect Response) (Effect Unit)

get :: Flask -> String -> (Request -> Effect Response) -> Effect Unit
get app path handler = runFn3 getImpl app path handler

So a route is PureScript from the request to the answer’s codec:

columns/python/src/Main.purs
  get app contingencyPath \req -> atLoadFactor req \lf -> do
    report <- analyse solver defaultLimits caseData lf
    pure (answer "ContingencyResponse" contingencyReportCodec report)

The whole demo, then: one PureScript source compiled to Python, running in one process beside pandapower on your own machine. The Lab, in your browser, asks it over HTTP.

Your own machine PureScript source analysis and relay simulation Pythia (purepy) to Python Relay machines Glassbox, 2 × JSON API compiled to Python pandapower power flow, N-1 sweep Lab in your browser /api, on localhost Conformance vectors 138, from Glassbox Native reference Python, no PureScript builds, loads, calls held equal by a check Your own machine PureScript source analysis and relay simulation Pythia Relay machines Glassbox JSON API Python pandapower power flow Lab your browser Reference plain Python Vectors 138, Glassbox builds, loads, calls held equal by a check
4

Why not just write it in Python?

For most Python programmers, do. This is for a PureScript programmer who needs a Python library. Their real alternative is a small Python service beside their PureScript, and a JSON contract between the two kept by hand.

What it costs

  • More code

    About five times the plain-Python reference: 4,751 lines of PureScript and 434 of Python, against 1,038. The reference does less, so the comparison is rough.

    Details
    WhatLinesWithout blanks and comments
    Plain Python: the referencenative/grid_native.py, protection_native.py1,038820
    PureScript: the analysis and the relayscore/src, devices/src3,5292,484
    PureScript: the API contract and the serverapi/src, columns/python/src1,222857
    Python behind the bindingGrid_Pandapower_foreign.py434292

    Counted as wc -l counts, every line of every .purs or .py file named; the second figure leaves out blank lines and lines that are only a comment (Python docstrings are counted). The comparison is rough, because the reference does less: no HTTP API, no request validation, no codecs, nothing for the replay. The PureScript’s count includes 567 lines (Grid.Stepper, Grid.Transcript, Grid.Scenarios) that exist for the replay and for checking JavaScript against Python. Even so, the PureScript and the Python behind its binding come to about five times the reference.

  • Some time

    Each request takes 1.07x to 3.12x the reference’s wall clock. pandapower’s own time is unchanged (0.99x to 1.02x): the extra is the compiled PureScript, not the bridge.

    Details
    RequestWhole requestInside pandapowerPureScript share
    N-1, 42 solves1.07x1.01x8.9 %
    Metrics, 1 solve3.12x0.99x74.9 %
    Protection run, line 9 out, 3 solves1.89x1.02x51.8 %
    Protection run, line 27 out at 1.0, 11 solves1.72x1.01x42.8 %

    The whole request is the PureScript program’s wall clock over the reference’s (the README calls it the architecture tax). Inside pandapower is pandapower’s own time here over its time in the reference, for the same answer: near 1.00, the bridge did not change the computation. The PureScript share is the part of the request spent in compiled PureScript. The numbers move a few percent between runs; read the shape, not the third digit. Metrics’ 3x is graph arithmetic done in PureScript that the reference leaves to networkx.

  • A younger toolchain

    Pythia is built from source, and two faults found here were the translation’s, not the program’s: a comparison with NaN that answered true under Pythia and false in JavaScript, and Int arithmetic that wrapped in JavaScript and not in Python. Both are fixed or fenced, and held by a check.

  • A boundary to design and keep

    Everything that crosses needs a type and a codec, on both sides. And the Python behind the binding is still Python you write and debug: keeping solves independent, and the lock without which two requests overwrote each other’s network and both reviewers measured wrong answers marked as successes.

What it buys

  • The same analysis runs in a browser

    The analysis and the relays have no foreign import, so the stock compiler builds them to JavaScript unchanged. The replay on this site is that code, and make check holds the analysis on JavaScript to Python’s answers, byte for byte.

  • One contract for server and page

    The routes, and every answer’s type and codec, are one module, api/src/Grid/Api.purs, compiled into the Python server and into the page. Before it, the page kept its own copies of the shapes. They drifted (the page read data.network.buses where the API sent data.buses) and the page sat broken until the contract was shared.

  • The rule at the boundary is a type

    A missing result is Maybe Number, so no code compares it with a limit without saying what absence means. Before the rule, NaN crossed as a number: under Pythia nan > 100.0 was true and the old cascade tripped dead lines, and the page drew dead islands as healthy. The comparison with the reference found that; the type makes it hard to bring back.

  • A binding per library, not per program

    The pandapower binding is written once against Grid.Solver, and anything written against that interface uses it as it is. The Flask binding knows nothing of power systems.

Example of the costs and benefits

Here’s how this all looks in practice: the code in each language, side by side, showing which limit a loading crosses and how two levels compare.

PureScript: core/src/Grid/Severity.purs
loadingLevel :: Limits -> Number -> Maybe Severity
loadingLevel limits loading
  | loading > limits.criticalLoadingPercent = Just Critical
  | loading > limits.warningLoadingPercent = Just Warning
  | otherwise = Nothing
…
worse :: Maybe Severity -> Maybe Severity -> Boolean
worse a b = rank a < rank b
  where
  rank = case _ of
    Just Critical -> 0
    Just Warning -> 1
    Just Safe -> 2
    Nothing -> 2
Python: native/grid_native.py
def _loading_level(v):
    if v > LIMITS["criticalLoadingPercent"]:
        return "critical"
    if v > LIMITS["warningLoadingPercent"]:
        return "warning"
    return None
…
def _worse(a, b):
    r = {"critical": 0, "warning": 1, None: 2}
    return r[a] < r[b]

About the same size. The difference is in the types. A level in PureScript is Maybe Severity, a closed type, and the compiler checks every case over it, as in rank. In Python it is a string or None, and a misspelt level is found by a test, if one looks.

Holding the two versions to the same answers paid once more. The reference loops over the outages by hand; its answers disagreed with the summary from pandapower’s own run_contingency, which above load factor 1.3 can name a line’s own outage as the cause of its worst loading. That is filed as pandapower issue 3388. The comparison found it, not the type system.

5

The other ways to get here

Compiling to Python is one route to a Python library from another language. These are the others we know of, for anyone choosing.

RouteHow it worksWhat it costs
Embed Python in your programLoad the Python interpreter into your own process and call it: PyO3 from Rust, inline-python from Haskell, PythonCall.jl from Julia. From Node, JSPyBridge runs Python as a child process and talks to it over a pipe.The values at the edge are untyped, or typed by hand; you still ship Python.
A Python serviceThe pandapower part written in Python, behind HTTP, answering JSON.Two languages, and a contract between them kept by hand or generated from a schema.
Compile your language to PythonWhat Pythia does for PureScript. The nearest equivalent elsewhere is Fable, which compiles F# to JavaScript and, in beta, to Python, so F# can have the same arrangement: one source, two targets.A compiler backend that has to exist and be trusted.
Use a different solverOther ecosystems have power-system libraries of their own: PowerModels.jl (optimisation-based power flow and OPF) and JuliaGrid.jl in Julia; PowSyBl in Java, with its Open Load Flow; power-grid-model, a C++ core with Python and C APIs.A different library, with different coverage and different answers to check.
Run Python in the browserPyodide: CPython compiled to WebAssembly, with numpy, scipy and pandas built for it.Untested here for pandapower, which pins an older pandas than Pyodide ships; and some twenty megabytes or more to download before the first answer.
6

Run the demo

The demo is the Python program and its page, the Lab: move the load factor, take out any line, change every relay setting, and read N-1 over all 41 lines, every answer solved by pandapower on your own machine.

The code is public, at github.com/afcondon/grid-explorer.

What you need

  • spago, purs, node and uv
  • a Pythia checkout with purepy built (stack build there); give its path with make PYTHIA=/path/to/Pythia
  • Chrome, for make check only
git clone https://github.com/afcondon/grid-explorer
cd grid-explorer
make          # Python environment, API, JS test column, pages
make check    # the machines; JavaScript against Python; the API
              # against its native reference; the pages
make run      # API on 127.0.0.1:3033, pages on http://localhost:3034

Then open http://localhost:3034/lab/. Nothing built is committed: make produces the Python and the page bundles from the source every time.

7

What is simplified

This is a demo of driving pandapower from PureScript, not a study of a real network. It uses two of pandapower’s tools, its AC power flow and its contingency analysis, on one of the test networks it ships; the rest of the library would be reached the same way, through the same kind of binding. The power flows are pandapower’s, and they are the real thing; the scenario around them is kept deliberately simple.

  • Between events the network is in steady state: there are no faults and no transients. A line is taken out, and the relays act on the overload that follows.
  • The relay settings are illustrative, not any utility’s.
  • The load factor scales every load and generator together, pro rata.
  • Python and JavaScript agreeing says the source means the same on both. It does not say the model is right.
8

Try it in your browser

There is also a version you can try without installing anything: a replay of the demo, on a page called The Relays. pandapower’s answers from the demo were recorded, so you can step through a run as if the solver were on the page. The analysis you interact with is the same PureScript, compiled to JavaScript.

9

Credits

pandapower
The power flow and the N-1 sweep. pandapower.org
case30
MATPOWER’s 30-bus case, a modified IEEE 30-bus system, as pandapower ships it. matpower.org
Pythia
purepy, PureScript to Python. afcondon/Pythia
Flask
The API’s HTTP server, with waitress.
Glassbox
State machines as typed, checkable data, with their conformance generator. afcondon/purescript-glassbox
Pages
Halogen, drawn with Hylograph’s HATS.
Photograph
“Pylons looking towards Tarrès, above Sant Bonifaci”, Andrew Condon.
Type
IBM Plex Sans and IBM Plex Mono, SIL Open Font License 1.1.

Grid Explorer, a Hylograph exhibit. A prototype of this page.