diff --git a/docs/schema/pio-ir/2/0.11.7/schema.json b/docs/schema/pio-ir/2/0.11.7/schema.json index 0754c79f6..f58257342 100644 --- a/docs/schema/pio-ir/2/0.11.7/schema.json +++ b/docs/schema/pio-ir/2/0.11.7/schema.json @@ -6337,6 +6337,130 @@ "cutoff_pu" ], "type": "object" + }, + { + "description": "Exponential law inside a voltage band, with nominal-impedance\ncontinuation below `v_low_pu`, current interpolation up to `v_min_pu`,\nand impedance continuation above `v_max_pu`. The continuations apply\nequally to P and Q, independently of their middle-band exponents.\nSee [`Self::power_scale`] for the equations. Arrays follow active branches.", + "properties": { + "gamma_p": { + "items": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "type": "array" + }, + "gamma_q": { + "items": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "type": "array" + }, + "model": { + "const": "bounded_exponential", + "type": "string" + }, + "v_low_pu": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "v_max_pu": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "v_min_pu": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "v_nom": { + "items": { + "anyOf": [ + { + "format": "double", + "type": "number" + }, + { + "enum": [ + "Infinity", + "-Infinity", + "NaN" + ], + "type": "string" + } + ] + }, + "type": "array" + } + }, + "required": [ + "model", + "v_nom", + "gamma_p", + "gamma_q", + "v_low_pu", + "v_min_pu", + "v_max_pu" + ], + "type": "object" } ] }, diff --git a/docs/src/distribution.md b/docs/src/distribution.md index b75c7b451..df9ae3485 100644 --- a/docs/src/distribution.md +++ b/docs/src/distribution.md @@ -60,28 +60,31 @@ returns using exact equivalent circuits. Reimport can introduce auxiliary components, so canonical output is electrically equivalent rather than a text fixed point. Unchanged source replay remains byte exact. -Direct `Open`/`Close` commands and explicit `SwtControl.State` are not yet -lowered and cause a parse error. Active `Action`/`Normal` control execution is -excluded and reported. Deferred geometry remains source-only and blocks -numerical use or canonical conversion. These restrictions are compatibility -gaps; they do not establish complete static OpenDSS support. OpenDSS load models -1, 5 and 8 carry a typed `BoundedZip` law, including low-voltage current -interpolation, upper-voltage impedance continuation and ZIP dropout. Model 2 -remains constant impedance. The Rust `power_scale` method evaluates per-branch -active and reactive multipliers. IR retains this distinct tagged model; readers -without the configuration reject it. Canonical DSS writes the typed limits, including -native defaults, ahead of stale extras or writer defaults. - -BMOPF and PMD currently project these bounded loads to their nominal laws with -a diagnostic. The multiconductor IVR OPF and LinDist3Flow preparations refuse -them by default; each has an explicit opt-in that projects to the nominal law -with a diagnostic (`BoundedLoadLawPolicy::ProjectToNominal`, and the -`approximate` or `permissive` LinDist3Flow policy), described in the -multiconductor IVR guide. Per-phase differences in bounded ZIP coefficients are retained -in the typed model but currently block DSS emission. The legacy C load views -cannot expose the voltage window and reject these loads; additive binding -views remain unfinished. Models 3, 4, 6 and 7 still need complete typed laws. -These are outstanding compatibility tasks, not supported approximations. +Direct `Open`/`Close` commands and explicit `SwtControl.State` on lines +preserve their fixed terminal states through equivalent circuits. Other device +classes remain unresolved. Active `Action`/`Normal` control execution is +excluded and reported. Unsupported geometry blocks numerical use or canonical +conversion. These restrictions do not establish complete static OpenDSS support. + +OpenDSS load models 1, 5 and 8 carry a typed `BoundedZip` law, including +low-voltage current interpolation, upper-voltage impedance continuation and ZIP +dropout. Model 2 remains constant impedance. Models 3 and 4 carry a typed +`BoundedExponential` law: their middle-band P and Q exponents are respectively +`(0, 2)` and the native CVR exponents (default `(1, 2)`). Outside the band, both +powers follow the native fallback independently of those exponents. The Rust +`power_scale` method evaluates these per-branch multipliers. IR retains the +distinct tagged models; readers without a configuration reject it. Canonical DSS +writes the typed exponents and voltage limits ahead of stale extras or writer +defaults. Unequal per-branch parameters emit separate single-phase loads. + +BMOPF and PMD project voltage-bounded loads to their nominal laws with a +diagnostic; PMD also diagnoses its lack of exponential load fields. The +multiconductor IVR OPF and LinDist3Flow preparations refuse these loads by +default; each has an explicit opt-in that projects to the nominal law with a +diagnostic (`BoundedLoadLawPolicy::ProjectToNominal`, and the `approximate` or +`permissive` LinDist3Flow policy), described in the multiconductor IVR guide. Legacy C +load views cannot expose the voltage window and reject these loads; additive +binding views remain unfinished. Models 6 and 7 still need complete typed laws. ```julia emit(feeder, "dss", "copy.dss") # the source bytes, sidecars included @@ -780,7 +783,7 @@ unique physical allocation of branch flows. policy. `Reject` keeps the strict boundary. `Lower` applies audited static neutral, switch, line-shunt and capacitor transformations. `Approximate` also linearizes supported load models and maps IBRs to static generators while -freezing named controls. Bounded ZIP can be projected only when nominal +freezing named controls. Bounded ZIP and exponential laws can be projected only when nominal voltage lies strictly inside its smooth law region, above dropout. The action retains the original `source_voltage_model` and its bounds; strict preparation keeps the complete piecewise law. The source network is not mutated. diff --git a/evals/gridlabd/README.md b/evals/gridlabd/README.md index 0188f955e..ea1f23abb 100644 --- a/evals/gridlabd/README.md +++ b/evals/gridlabd/README.md @@ -773,9 +773,10 @@ qualify triplex cables, OpenDSS CNData/TSData decoding or a complete feeder. ## Bounded load laws `load_voltage_oracle.py --powerio /path/to/powerio --output /new/path` checks -55 static cases for OpenDSS load models 1, 2, 5 and 8 across the voltage band -and dropout transition. It parses through public IR, emits canonical DSS and -compares native complex load voltages, currents and powers. Run the ignored +99 static cases for OpenDSS load models 1, 2, 3, 4, 5 and 8 across the voltage +band and dropout transition, including fractional and negative CVR exponents. +It parses through public IR, emits canonical DSS, repeats the import and output, +and compares native complex load voltages, currents and powers. Run the ignored `typed_laws_match_native_load_currents` test in `powerio/tests/load_voltage_ir.rs` with `POWERIO_LOAD_VOLTAGE_SAMPLES` set to the resulting `report.json` to verify the Rust evaluator against the same independent native samples. The report @@ -1346,3 +1347,415 @@ and asymmetric sequence-source formulas. Only the latter needs compensation for the pinned engine's truncated rotation constants. Using that compensation for symmetric blocks introduced a measurable projection error; the line microcases exercise both branches and catch it. + +### IEEE European low-voltage snapshot + +`european_lv_import_oracle.py` validates the original European LV `Master.dss` +from the pinned `dss-extensions/electricdss-tst` revision in `ieee-corpus.json`. +The catalog pins all 109 companion files, including the load profiles, by byte +count and Git blob hash. Keep this checkout outside the PowerIO repository; +no public dataset bytes are vendored. The original master selects snapshot +mode and sets `useactual=no` on the shapes before creating its loads. + +```sh +cargo build -p powerio --example dist_network +python evals/gridlabd/european_lv_import_oracle.py \ + --source /path/to/electricdss-tst/Version8/Distrib/IEEETestCases/LVTestCase \ + --bridge target/debug/examples/dist_network \ + --output /path/to/new-european-lv-results +``` + +The bridge imports the original, serializes/deserializes its IR with full typed +network equality, and emits canonical output from a fresh module. This prevents +retained-source replay from being mistaken for writer validation. The oracle +compares all 907 original buses, all 906 lines, the transformer, all 55 loads, +and the source's physical feeder port: 14,784 complex voltage/current/power/loss +quantities. It repeats the comparison after a second import and canonical +write, and requires an intentionally changed line length to fail. Both native +and canonical snapshots use the pinned DSS engine, controls off and solver +tolerance `1e-12`; acceptance tolerances remain those in `oracle.py`. + +Canonical static DSS output omits `daily`, `yearly`, and `duty` loadshape +references on loads, generators and voltage sources, with an explicit loss +diagnostic, because their definitions are not regenerated. The original +references remain retained on import; same-format source replay is unaffected. +This result qualifies the feeder's static DSS/IR/DSS path. It does not qualify +its time series or canonical GridLAB-D emission, which still reports unsupported +additional tables and transformer details. + +### Fixed OpenDSS Line terminal states + +`dss_terminal_state_oracle.py` checks 38 synthetic native cases through import, +IR and first/repeated canonical DSS output. It covers one through four +conductors, partial and whole-terminal opens, both ends, reclosure, equal and +changed conductor counts, `LineCode` assignment, `MakeLike`, explicit-neutral +opens, and zero charging. Every opened typed matrix is compared directly with +native `YPrim`; bus voltages and physical line-port currents and powers are +compared after both canonical cycles. A separately initialized native circuit +with the wrong fixed state must fail the electrical comparison. + +```sh +cargo build -p powerio --example dist_network +python evals/gridlabd/dss_terminal_state_oracle.py \ + --bridge target/debug/examples/dist_network \ + --output /path/to/new-terminal-state-results +``` + +Ordinary Line `Open`/`Close` commands bind at execution time and replay in +property/copy/solve order. Native conductor-count changes reset the contacts; +a same-size `MakeLike` keeps the destination's contacts. Fixed open ports use +the native zero-current Schur complement, including the pinned engine's +`1e-12 S` diagonal stabilization, represented by an existing typed shunt and +ideal external contacts. Effective linecodes remain available, contact ratings +are retained, and unsupported line metadata is diagnosed as source-only. +No new IR type or solver dependency is introduced. + +The DSS writer preserves reciprocal coupled/unequal shunts with scalar +impedance branches and diagonal corrections; nonreciprocal matrices use the +existing coupled-source equivalent. This avoids collapsing a symmetric matrix +to one scalar and avoids unnecessary cancellation in reciprocal circuits. +Already-exact scalar delta shunts keep their compact native expression. +Geometry-derived lines still require calculated impedances before conversion. +Commands on other device classes, omitted/invalid terminal indices, and +out-of-range conductor indices remain explicit refusals. Active switching and +protection execution remain outside this static profile. + +### OpenDSS overhead geometry calculation checkpoint + +`dss_overhead_geometry_oracle.py` captures native series impedance and total +shunt susceptance for 150 synthetic cases: Carson, FullCarson and Deri; 40, 50, +60, 1000 and 3000 Hz; one and three phase arrangements, an explicit fourth +conductor, and four/five-conductor neutral reduction; two resistance/earth +resistivity profiles including strong skin effect. These are explicit SI +inputs to a private evaluator, not feeder-import qualification. + +```sh +python evals/gridlabd/dss_overhead_geometry_oracle.py \ + --output /path/to/new-dss-overhead-matrices +POWERIO_GEOMETRY_ORACLE=/path/to/new-dss-overhead-matrices/matrices.json \ + cargo test -p powerio-dist --lib \ + dss::geometry::tests::pinned_overhead_matrices -- --ignored --nocapture +``` + +Both steps are required: native capture alone does not compare PowerIO. The +Rust comparison checks every matrix entry, with absolute tolerances of +`1e-12 ohm/m` and `1e-18 S/m`, plus `1e-10` relative tolerance. Generated decks, +SHA-256 hashes and native observations remain outside the repository. + +The calculation follows pinned DSS C-API +[`LineConstants.pas`](https://github.com/dss-extensions/dss_capi/blob/87d85c2622c8281b92255335bc7c09b11191b21d/src/General/LineConstants.pas), +including its rounded physical constants, frequency-boundary behavior and +Deri Bessel-series calculation. Neutral reduction eliminates the neutral +impedance block but retains the phase block of the full inverted potential +matrix for capacitance. The native C API reports capacitance in nF using a +different, full-precision `TwoPi`; the observation script converts that +quantity back to susceptance with the corresponding constant. + +The public reader now uses this calculation together with ordered definitions +and native shared-cache history, as described below. The kernel comparison +alone does not qualify a feeder; whole-feeder qualification uses the public +reader, IR round trips and canonical output. Spacing and cable models remain +unresolved in the OpenDSS reader. + +### Ordered OpenDSS overhead definitions + +`dss_wiredata_oracle.py` checks 49 native conductor-definition cases, including +positional/abbreviated properties, RPN values, default backfilling, unit changes, +repeated radius assignments and historical/self `MakeLike`. A radius assignment +initializes capacitance radius only while the latter is negative; later radius +edits leave it alone. A GMR-only definition can leave capacitance radius negative, +in which case the geometry calculation uses the physical radius. + +`dss_geometry_definition_oracle.py` checks 27 synthetic geometry-definition +cases. Conductor selectors, sticky units, equal-size and changed-size resets, +wire arrays and copied definitions follow native order. Wire assignment binds +an existing identity and copies its current scalar ratings, while calculation +reads the wire values visible at that later time. A later declaration does not +repair a missing reference. Both resolvers reuse bounded append-only property +and copy histories; no new public model or IR type is introduced. Seasonal +ratings remain source metadata. Assigning `LineSpacing` to `LineGeometry` copies +its coordinates and units at that point; later spacing edits do not change the +geometry until reassignment. The geometry keeps its own phase count and conductor +selector. Spacing copies, self-copies, partial coordinate arrays and size changes +follow the pinned engine. Missing references, mismatched conductor counts and +uninitialized coordinates remain errors. Direct `Line.spacing` and cable +conductor definitions remain unresolved. + +```sh +python evals/gridlabd/dss_wiredata_oracle.py --output /tmp/new-wire-observations +POWERIO_WIRE_ORACLE=/tmp/new-wire-observations/wires.json \ + cargo test -p powerio-dist --lib \ + dss::geometry::wire::tests::pinned_wire_definitions -- --ignored +python evals/gridlabd/dss_geometry_definition_oracle.py \ + --output /tmp/new-geometry-definitions +POWERIO_GEOMETRY_DEFINITION_ORACLE=/tmp/new-geometry-definitions/definitions.json \ + cargo test -p powerio-dist --lib \ + dss::geometry::definition::tests::pinned_geometry_definitions -- --ignored +``` + +For public data, the same oracle checks the 32 geometry objects in the 17 +CIMHub IEEE4 cases that declare `LineGeometry`. It verifies source byte counts +and Git blob hashes against `ieee-corpus.json` before execution. Keep the pinned +CIMHub checkout and generated observations outside the PowerIO repository. + +```sh +python evals/gridlabd/dss_geometry_definition_oracle.py \ + --ieee4-base /path/to/CIMHub/ieee4/base --output /tmp/new-ieee4-geometries +POWERIO_GEOMETRY_DEFINITION_ORACLE=/tmp/new-ieee4-geometries/definitions.json \ + cargo test -p powerio-dist --lib \ + dss::geometry::definition::tests::pinned_geometry_definitions -- --ignored +``` + +This compares definition fields and the Carson impedance/admittance matrices +at 60 Hz, including unbalanced, single-phase and center-tapped case inputs. +Definition checks alone do **not** qualify transformer models or full power +flows. The following checks exercise shared-cache history and public import. + +### Public OpenDSS overhead import and IEEE4 qualification + +The reader lowers supported overhead `WireData`/`LineGeometry` lines to the +existing effective line matrices. It replays source-order assignments and +calculation commands because native OpenDSS shares geometry calculations while +each line caches its own primitive. Default and active earth models differ; +geometry edits, `MakeLike`, length/units changes, frequency changes and `Clear` +do not all invalidate the same caches. Unsupported geometry remains an explicit +electrical readiness blocker. This introduces no public model or IR type. + +`dss_geometry_cache_oracle.py` captures twelve synthetic histories. The Rust +comparison checks native line primitives after each recorded state, with +`1e-10 S` absolute plus `1e-10` relative tolerance. Histories include shared +geometries, earth-model inheritance, definition edits, `MakeLike`, and replacing +a geometry binding with a `LineCode` or sequence parameters. + +```sh +python evals/gridlabd/dss_geometry_cache_oracle.py \ + --output /tmp/new-geometry-cache +POWERIO_GEOMETRY_CACHE_ORACLE=/tmp/new-geometry-cache/observations.json \ + cargo test -p powerio-dist --lib \ + dss::geometry::timeline::tests::pinned_calculation_history -- --ignored +cargo build -p powerio --example dist_network +python evals/gridlabd/ieee4_import_oracle.py \ + --ieee4-base /path/to/CIMHub/ieee4/base \ + --bridge target/debug/examples/dist_network --output /tmp/new-ieee4-import +``` + +The IEEE4 harness checks all twenty-seven pinned CIMHub cases, including +transformer-code, autotransformer, four-wire and geometry variants. It also +verifies and stages the pinned `ieee4xy.dat` coordinate companion. Each qualification requires typed import, IR equality, native +versus canonical electrical comparison, repeated import/emission, and rejection +of a deliberately changed line. It compares every original bus voltage and +Line/Transformer/AutoTrans/Load/Capacitor/Reactor terminal current, power and loss, plus the physical +source feeder port. Source bytes and generated evidence stay external. + +Fourteen cases qualify: `DDBal`, `DDUnBal`, `DYBal`, `DYUnBal`, `GYDBal`, +`GYDUnBal`, `OYODBal`, `OnePh`, `SCTBal`, `SCTUnBal`, `YDBal`, `YDUnBal`, +`YYBal`, and `YYUnBal`. Together they provide 953 complex observables per +conversion pass. These are IEEE4 variants, not fourteen distinct feeder +families. Thirteen remain unqualified. The three geometry cases retain these +failures: + +- `YYD` retains delta-side voltage/power mismatches (maximum about + `1.37e-4 V` and `0.0788 VA`). +- `YYD1Tank` does not converge in the converted native solve. +- `YYDXn` retains eighteen electrical mismatches, including a maximum voltage + difference of about `4.53e-6 V` and power difference of `0.00261 VA`. + +For these three cases, native and canonical transformer admittance matrices +are identical, and the largest line admittance difference is `7.95e-15 S`. +The delta-side voltage differences are a common offset across phases; removing +that offset leaves less than `2.3e-12 V`. This diagnostic does not change the +qualification criteria or excuse nonconvergence. + +The ten additional cases exposed by the wider scan are also reported: + +- `Auto1bus`, `Auto3bus`, `AutoHLT`, and `AutoHLTCode` retain strict electrical + mismatches, particularly at the very short connecting lines. +- `AutoAuto` loses the native `AutoTrans` component during conversion. +- `IMODOD`, `IMOYODlag`, and `IMOYODlead` retain substantive four-wire + voltage/current/power mismatches. +- `IMYD` fails import on an inconsistent LineCode capacitance dimension. +- `OYODUnBal` passes its first comparison but its repeated conversion fails + native convergence, so it does not qualify. + +The broader external script audit recognizes both `New Circuit` and +`New object=Circuit` spellings: 53 of 61 entry points parse and retain typed +network equality through IR. The expanded inventory includes IEEE34, IEEE37 +and IEEE123 master cases previously missed by that scan. It also includes +auxiliary and fault-study scripts; these counts are not qualified-feeder totals. + +The native and generated solves all use controls off, at most 1,000 iterations, +and tolerance `1e-11`, stricter than the original files' `1e-8`. The balanced +delta-delta native case stalls at `1e-12`; nonconverged runs never qualify. +Observable acceptance thresholds in `oracle.compare` remain unchanged. + +### OpenDSS transformer-code assignment + +`XfmrCode` properties use their native ordered table, including positional and +abbreviated input. A transformer binds the code state available at assignment; +later code edits do not change it. The reader uses bounded existing property +and copy histories, materializing winding connections, voltage/rating/tap, +resistance and neutral impedance, reactances, excitation and antifloat values. +Missing references and unresolved code properties produce an error instead of +a transformer with factory defaults. Code definitions remain retained metadata. +Seasonal ratings, tap bounds and DC resistance are not newly projected into +typed fields by this AC snapshot work. + +Native `MakeLike` omits excitation and antifloat fields; self-copy resets winding +records. Scalar kVA setters propagate between windings, while arrays assign +individual winding values. End-of-edit scalar reactances can override an array. +Fifteen native state probes cover these distinctions and historical bindings. +The public IEEE4 checks above additionally qualify the balanced and unbalanced +center-tapped feeders, including excitation and unequal winding resistance. +Canonical output keeps typed winding resistances authoritative: replaying a +stored total load loss after them would replace unequal values with an equal +split. A mutation round-trip regression exercises this behavior. + +```sh +python evals/gridlabd/dss_xfmrcode_oracle.py --output /tmp/new-xfmrcode-states +POWERIO_XFMRCODE_ORACLE=/tmp/new-xfmrcode-states/observations.json \ + cargo test -p powerio-dist --test dss_xfmrcode -- --include-ignored +``` + + +## Public IEEE13, IEEE34, IEEE37, IEEE123, IEEE9500 and North American LV profiles + +`ieee_distribution_import_oracle.py` compares nine public feeder entries with +canonical output and repeated conversion. Sources and dependencies are pinned +in `ieee-corpus.json`; public bytes remain in an external checkout. Run: + +```sh +python evals/gridlabd/ieee_distribution_import_oracle.py \ + --source-root /path/to/electricdss-tst \ + --bridge /path/to/dist_network --output /new/path +``` + +The profile inserts `Set ControlMode=Off` before every solve or voltage-base +calculation in the selected entry files. The report retains each insertion, +the original bytes and hashes, and the adjusted hashes. It compares the written +fixed device states; it does not reproduce actively regulated published results. +The common IEEE4 comparator checks complex bus voltages and device terminal +currents, powers and losses, source ports, IR equality, repeated conversion and +a changed-line negative control. Missing ports and nonconvergence fail. Each +case reports its result independently; a parser success is not qualification. + + +### Public North American spacing definitions + +`dss_spacing_oracle.py` verifies the pinned North American master before selecting +its conductor and geometry definitions. It puts the `Trans` overhead geometry, +`Pri` concentric-neutral cables and reduced four-conductor `Sec` bundle into +controlled, unbalanced circuits. +The report records the source line range and hashes; generated source files +show the complete circuit additions. These are geometry probes, not full-feeder +qualification. + +```sh +python evals/gridlabd/dss_spacing_oracle.py \ + --north-american-master /path/to/LVTestCaseNorthAmerican/Master.dss \ + --bridge /path/to/dist_network --output /new/path +``` + +All three probes compare complex bus voltages, terminal currents, powers and losses, +source ports, IR equality and repeated canonical conversion. A changed line +length must fail the comparison. Public input bytes and generated results stay +outside the repository. + + +### Concentric-neutral cable geometry + +The reader resolves `CNData` and `LineGeometry.CNCable`/`CNCables` through the +existing conductor histories. It preserves native unit interpretation, strand +GMR defaults, historical copies, live electrical edits and copied ratings. +Cable phases may have trailing bare neutrals; concentric strands are always +eliminated before optional reduction of those bare neutrals. The resulting +impedance and capacitance use the existing typed line model and IR layout. +Direct `Line.spacing` is covered below. Tape-shield cables and mixed bare/cable +phase positions remain unqualified. The pinned engine rejects `LineGeometry like=` when copying +a CN geometry with an invalid type cast; PowerIO reports that case explicitly. + +```sh +python evals/gridlabd/dss_cn_geometry_oracle.py --output /tmp/new-cn-geometry +POWERIO_GEOMETRY_ORACLE=/tmp/new-cn-geometry/matrices.json \ + cargo test -p powerio-dist --lib pinned_overhead_matrices -- --ignored +POWERIO_GEOMETRY_DEFINITION_ORACLE=/tmp/new-cn-geometry/definitions.json \ + cargo test -p powerio-dist --lib pinned_geometry_definitions -- --ignored +python evals/gridlabd/dss_geometry_cache_oracle.py --output /tmp/new-geometry-cache +POWERIO_GEOMETRY_CACHE_ORACLE=/tmp/new-geometry-cache/observations.json \ + cargo test -p powerio-dist --lib pinned_calculation_history -- --ignored +``` + +The cable oracle checks 75 native matrices across three earth models, five +frequencies and five conductor/phase/reduction configurations. It records +convergence separately: the unloaded high-frequency circuits are matrix probes, +not feeder qualifications. Nine successful definition probes and the native +copy failure are recorded separately. Sixteen cache histories cover both +conductor families, including live cable edits and an overhead-to-cable change. + +The complete North American master now imports with no electrical-readiness +blockers and survives IR and repeated canonical conversion. Native and emitted +solves converge, but the 21,671-observable comparison still fails: maximum +errors are approximately 26 microvolts, 57 microamps and 7.9 VA. Its `SecPar` +variant also remains unqualified. These residuals remain visible under the +unchanged acceptance thresholds. The three controlled public-geometry probes +pass independently; their success does not qualify the complete feeder. + + +### Direct Line.spacing and IEEE9500 + +Direct spacing retains live `LineSpacing`, `WireData` and `CNData` references. +The reader preserves assignment-time dimensions and ratings, later edits, +copied definitions and the native per-Line frequency cache. Unlike a +`LineGeometry.spacing` assignment, this path reads current coordinates when it +recalculates. Missing historical bindings and unsafe live conductor-count +changes remain explicit errors. The calculation also preserves the native +order of earth-model selection; the temporary geometry is first calculated +with the previous active earth model. + +```sh +python evals/gridlabd/dss_direct_spacing_oracle.py --output /tmp/new-direct-spacing +POWERIO_GEOMETRY_CACHE_ORACLE=/tmp/new-direct-spacing/observations.json \ + cargo test -p powerio-dist --lib pinned_calculation_history -- --ignored +python evals/gridlabd/ieee9500_spacing_oracle.py \ + --master /path/to/ieee9500dss/ieee9500_base.dss \ + --bridge /path/to/dist_network --output /tmp/new-ieee9500-spacing +``` + +Twenty native histories compare line primitives and current ratings. The public +spacing oracle selects one original line for each overhead/cable and phase-count +combination, keeps its definitions and length, and replaces its endpoints with +a controlled source and unequal loads. All five selections pass: overhead +single-, two- and three-phase lines and single- and three-phase CN cables. +Together they compare 150 complex quantities, IR, repeated canonical output +and changed-line negative controls. They are line probes, not full-feeder +qualifications. + +The `electricdss-tst` IEEE9500 master and its coordinate and UUID companions are +now pinned in the catalog. Its 2,622 unresolved geometry entries are eliminated; +import and IR equality succeed. The complete source does not converge in the +pinned native engine under the written fixed-state profile. Normal and Newton +methods both fail within 1,000 iterations at tolerances from `1e-11` to `1e-8`; +the original source with controls enabled also fails. Canonical convergence +alone cannot qualify that conversion. The separately pinned CIMHub balanced +and unbalanced archives remain distinct cases. +The full-feeder comparator also includes Generator, PVSystem and Storage ports; +missing converted ports are reported, not silently omitted. UUID resolution +uses the source directory while native automatic directory changes remain off. + + +Both CIMHub archives are exercised by: + +```sh +python evals/gridlabd/ieee9500_archive_import_oracle.py \ + --archives /path/to/pinned/archives --bridge /path/to/dist_network \ + --output /tmp/new-ieee9500-archives +``` + +The archive bytes are checked against the catalog before extraction. Both +fixed-state native cases converge, but their first converted comparisons left +almost every downstream bus de-energized. The source path contains a series +`Reactor.hvmv_sub_hsb` with `r=0` and `x=14.798307` ohms; that reactor was +retained untyped and omitted from canonical electrical equipment. These are +failed comparisons, not valid all-zero solutions. The readiness audit now +blocks active untyped reactors explicitly, so these feeder imports correctly +remain incomplete after their line geometry is resolved. Series-reactor +conversion is the next required electrical feature for these public cases. diff --git a/evals/gridlabd/dss_cn_geometry_oracle.py b/evals/gridlabd/dss_cn_geometry_oracle.py new file mode 100644 index 000000000..92044f7ce --- /dev/null +++ b/evals/gridlabd/dss_cn_geometry_oracle.py @@ -0,0 +1,124 @@ +"""Native CN cable matrix and definition evidence, before public feeder checks.""" + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np +import opendssdirect as dss +from dss_geometry_definition_oracle import observe +from dss_overhead_geometry_oracle import deck, wires +from oracle import LOCK + + +def generate(output): + output.mkdir(parents=True, exist_ok=False) + cases = {} + for model in ("carson", "fullcarson", "deri"): + for frequency in (40.0, 50.0, 60.0, 1000.0, 3000.0): + for count, phases, reduced in ( + (1, 1, False), + (3, 3, False), + (4, 3, False), + (4, 3, True), + (3, 2, True), + ): + conductors = wires(count, False) + for i, wire in enumerate(conductors): + wire.update(x=i * 0.1, height=-1.0 - 0.05 * (i % 2)) + if i < phases: + wire["cable"] = dict( + k=13 + i, + diastrand=0.0015, + gmrstrand=0.0006, + rstrand=0.0008, + epsr=2.3 + i * 0.1, + inslayer=0.004, + diains=0.026, + diacable=0.031, + ) + key = f"{model}-{frequency}-{count}-{phases}-{reduced}" + geometry = dict( + wires=conductors, + phases=phases, + reduce=reduced, + earth_model=model, + rho=37.0, + ) + script = deck(geometry, frequency) + path = output / f"{key}.dss" + path.write_text(script) + engine = dss.NewContext() + for flag in ( + "AllowChangeDir", + "AllowDOScmd", + "AllowEditor", + "AllowForms", + ): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Text.Command(f'redirect "{path.resolve()}"') + engine.LineGeometries.Name("g") + n = phases if reduced else count + data = dict( + # Matrix qualification does not require the unloaded circuit to solve. + native_unloaded_converged=engine.Solution.Converged(), + geometry=geometry, + frequency=frequency, + engine=engine.Basic.Version(), + script_sha256=hashlib.sha256(script.encode()).hexdigest(), + ) + for name, getter, scale in ( + ("r", engine.LineGeometries.Rmatrix, 1), + ("x", engine.LineGeometries.Xmatrix, 1), + ("b", engine.LineGeometries.Cmatrix, 1e-9 * math.tau * frequency), + ): + data[name] = ( + np.array(getter(frequency, 1, 4)).reshape((n, n), order="F") + * scale + ).tolist() + cases[key] = data + (output / "matrices.json").write_text(json.dumps(cases, indent=2) + "\n") + definitions = ( + "new cndata.a rac=.1214 diam=1.124 gmrunits=ft runits=mi radunits=in normamps=615\n" + "~ diacable=2.08 k=21 diastrand=.1285 inslayer=.25 diains=1.64 rstrand=.1809\n" + "new cndata.b like=a gmrac=.04683 gmrstrand=.00417\n" + "new wiredata.n radius=.005 rac=.0002 radunits=m runits=m\n" + "new linespacing.s nconds=3 nphases=3 units=in x=[0 3 6] h=[-48 -48 -48]\n" + "new linegeometry.g nconds=3 nphases=3 spacing=s cncables=[b b b]\n" + ) + variants = { + "base": "", + "cn_defaults_and_sticky_units": "edit linegeometry.g cncables=[a a a]\n", + "cn_copy_snapshot": "edit cndata.a rac=.3 diastrand=.15\n", + "cn_self_copy": "edit cndata.b like=b\n", + "cn_live_edit": "edit cndata.b rac=.3 diastrand=.15\n", + "cn_array_selector": "edit linegeometry.g cond=2 cncables=[b a b] x=3.5\n", + "cn_single_selector": "edit linegeometry.g cond=2 cncable=a x=3.5\n", + "cn_ratings": "edit cndata.b normamps=700\nedit linegeometry.g normamps=0 cncables=[b b b]\n", + "cn_copy": "new linegeometry.c like=g\n", + "cn_bare_neutral": "edit linegeometry.g nconds=4 cond=1 cncable=b units=in x=0 h=-48 cond=2 cncable=b x=3 h=-48 cond=3 cncable=b x=6 h=-48 wires=[n] cond=4 x=9 h=-48 reduce=yes\n", + } + records, errors = {}, {} + for name, edit in variants.items(): + script = "clear\nnew circuit.c\n" + definitions + edit + try: + records[name] = observe(script, matrices="fresh") + except Exception as exc: + if name != "cn_copy": + raise + errors[name] = dict(script=script, native_error=str(exc)) + (output / "native-errors.json").write_text(json.dumps(errors, indent=2) + "\n") + (output / "definitions.json").write_text(json.dumps(records, indent=2) + "\n") + print( + f"Captured {len(cases)} matrices and {len(records)} definitions; Rust comparison is required." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + generate(parser.parse_args().output) diff --git a/evals/gridlabd/dss_direct_spacing_oracle.py b/evals/gridlabd/dss_direct_spacing_oracle.py new file mode 100644 index 000000000..af54f7d87 --- /dev/null +++ b/evals/gridlabd/dss_direct_spacing_oracle.py @@ -0,0 +1,177 @@ +"""Native direct Line.spacing history, electrical primitives and current ratings.""" + +import argparse +import json +from pathlib import Path + +import opendssdirect as dss +from oracle import LOCK + +DEFINITIONS = """new wiredata.w rac=.0002 radius=.01 radunits=m runits=m normamps=100 +new wiredata.n rac=.0004 radius=.005 radunits=m runits=m normamps=70 +new linespacing.s nconds=2 nphases=1 units=m x=[0 1] h=[10 9] +new cndata.c rac=.0002 radius=.01 radunits=m runits=m normamps=150 k=13 diastrand=.0015 rstrand=.0008 inslayer=.004 diains=.028 diacable=.033 +""" +LINES = """new line.a bus1=sourcebus.1 bus2=a.1 spacing=s wires=[w n] length=100 units=m earthmodel=carson +new line.b bus1=sourcebus.1 bus2=b.1 spacing=s wires=[w n] length=100 units=m earthmodel=deri +set controlmode=off +solve +""" +BASE = "clear\nnew circuit.c basekv=12.47\n" + DEFINITIONS + LINES + + +def cases(): + result = { + "overhead": (BASE, []), + "live_wire": ( + BASE, + [ + "edit wiredata.w rac=.0005 normamps=200", + "edit line.a length=200", + "set frequency=50", + ], + ), + "live_spacing": ( + BASE, + [ + "edit linespacing.s x=[0 2] h=[15 14]", + "edit line.a spacing=s wires=[w n]", + "set frequency=50", + ], + ), + "wire_reassign": (BASE, ["edit line.a wires=[n w]", "set frequency=50"]), + "spacing_reassign": ( + BASE, + [ + "new linespacing.t like=s h=[20 19]\nedit line.a spacing=t wires=[w n]", + "set frequency=50", + ], + ), + "rho": ( + BASE, + ["edit line.a rho=37", "edit line.a length=101", "set frequency=50"], + ), + "earth": ( + BASE, + [ + "edit line.a earthmodel=fullcarson", + "set frequency=50", + "set frequency=60", + ], + ), + "units": (BASE, ["edit line.a units=ft", "set frequency=50"]), + "ratings": ( + BASE, + [ + "edit line.a normamps=300 emergamps=500", + "set frequency=50", + "edit line.a wires=[w n]", + "set frequency=60", + ], + ), + "line_copy": ( + BASE, + [ + "edit line.b length=200", + "edit line.a like=b", + "edit line.a length=150", + "set frequency=50", + ], + ), + "sequence_override": ( + BASE, + ["edit line.a r1=.02 x1=.01 c1=0", "edit line.a spacing=s wires=[w n]"], + ), + "linecode_override": ( + BASE, + [ + "new linecode.c nphases=1 rmatrix=[.02] xmatrix=[.01] cmatrix=[0] units=km\nedit line.a linecode=c", + "edit line.a spacing=s wires=[w n]", + ], + ), + } + for rho in (100, 37): + result[f"initial_rho_{rho}"] = ( + BASE.replace("length=100", f"rho={rho} length=100"), + [], + ) + result["live_before_first_calculation"] = ( + BASE.replace( + "set controlmode=off", + "edit wiredata.w rac=.0006\nedit linespacing.s h=[12 11]\nset controlmode=off", + ), + [], + ) + result["geometry_to_spacing"] = ( + BASE.replace( + "new line.a", + "new linegeometry.g nconds=1 nphases=1 cond=1 wire=w x=0 h=10 units=m\nnew line.a", + ).replace("bus2=a.1 spacing=s wires=[w n]", "bus2=a.1 geometry=g"), + ["edit line.a spacing=s wires=[w n]"], + ) + result["spacing_to_geometry"] = ( + BASE, + [ + "new linegeometry.g nconds=1 nphases=1 cond=1 wire=w x=0 h=10 units=m\nedit line.a geometry=g", + "edit line.a spacing=s wires=[w n]", + ], + ) + cn = BASE.replace("x=[0 1] h=[10 9]", "x=[0 .1] h=[-1 -1]").replace( + "wires=[w n]", "cncables=[c] wires=[n]" + ) + result["cn_bare_neutral"] = ( + cn, + ["edit cndata.c rstrand=.001 normamps=250", "set frequency=50"], + ) + result["cn_full_array_then_neutral"] = ( + cn.replace("cncables=[c]", "cncables=[c c]"), + [], + ) + result["cn_only"] = ( + cn.replace("nconds=2", "nconds=1") + .replace("x=[0 .1] h=[-1 -1]", "x=[0] h=[-1]") + .replace(" wires=[n]", ""), + ["set frequency=50"], + ) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + results = {} + for name, (base, commands) in cases().items(): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Basic.DataPath(str(args.output.resolve())) + engine.Text.Commands(base) + observations = [] + for command in ["initial", *commands]: + if command != "initial": + engine.Text.Commands(command + "\nsolve\n") + if not engine.Solution.Converged(): + raise ValueError(f"native solve failed: {name}/{command}") + primitives, ratings = {}, {} + for line in ("a", "b"): + engine.Lines.Name(line) + primitives[line] = list(engine.CktElement.YPrim()) + ratings[line] = [engine.Lines.NormAmps(), engine.Lines.EmergAmps()] + observations.append( + dict(command=command, primitives=primitives, ratings=ratings) + ) + results[name] = dict( + base=base, engine=engine.Basic.Version(), observations=observations + ) + (args.output / "observations.json").write_text(json.dumps(results, indent=2) + "\n") + print( + f"Captured {len(results)} native direct-spacing histories; Rust comparison is required." + ) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_geometry_cache_oracle.py b/evals/gridlabd/dss_geometry_cache_oracle.py new file mode 100644 index 000000000..8b411b8f3 --- /dev/null +++ b/evals/gridlabd/dss_geometry_cache_oracle.py @@ -0,0 +1,184 @@ +"""Observe native shared geometry and per-Line cache history (one-phase probes).""" + +import argparse +import json +from pathlib import Path + +import opendssdirect as dss +from oracle import LOCK + +DEFINITIONS = """new wiredata.w rac=0.0002 radius=0.01 radunits=m runits=m +new linegeometry.g nconds=1 nphases=1 cond=1 wire=w x=0 h=10 units=m +""" +LINES = """new line.a bus1=sourcebus.1 bus2=a.1 geometry=g length=100 units=m earthmodel=carson +new line.b bus1=sourcebus.1 bus2=b.1 geometry=g length=100 units=m earthmodel=deri +set controlmode=off +solve +""" +BASE = "clear\nnew circuit.c basekv=12.47\n" + DEFINITIONS + LINES + + +def cases(): + result = { + "wire_geometry_line": ( + BASE, + [ + "edit wiredata.w rac=0.0004", + "edit linegeometry.g h=11", + "edit line.a length=100", + "edit line.b geometry=g", + ], + ), + "earth_reassign": ( + BASE, + [ + "edit line.a earthmodel=deri", + "edit line.a geometry=g", + "edit linegeometry.g h=11", + "edit line.a geometry=g", + ], + ), + "length_units": ( + BASE, + [ + "edit line.a length=200", + "edit line.a units=ft", + "edit line.a geometry=g", + ], + ), + "frequency": (BASE, ["set frequency=50", "set frequency=60"]), + "rho_shared": ( + BASE, + ["edit line.b rho=37", "edit line.a geometry=g", "edit line.b geometry=g"], + ), + "copy_after_solve": ( + BASE, + ["new linegeometry.h like=g", "edit line.a geometry=h"], + ), + "line_copy": ( + BASE, + [ + "edit line.b length=200 geometry=g", + "edit line.a like=b", + "edit line.a length=150", + ], + ), + "sequence_override": ( + BASE, + ["edit line.a r1=0.02 x1=0.01 c1=0", "edit line.a geometry=g"], + ), + "linecode_override": ( + BASE, + [ + "new linecode.lc nphases=1 rmatrix=[0.02] xmatrix=[0.01] cmatrix=[0] units=km\nedit line.a linecode=lc", + "edit line.a geometry=g", + ], + ), + } + result["copy_before_line"] = ( + "clear\nnew circuit.c basekv=12.47\n" + + DEFINITIONS + + "new linegeometry.h like=g\nedit wiredata.w rac=0.0004\n" + + LINES.replace("geometry=g", "geometry=h"), + ["edit linegeometry.h h=11", "edit line.a geometry=h"], + ) + result["clear_active_earth"] = ( + BASE.replace("earthmodel=deri", "earthmodel=carson"), + [ + "clear\nnew circuit.d basekv=12.47\n" + + DEFINITIONS + + "new linegeometry.h like=g\n" + + LINES.replace("geometry=g", "geometry=h").replace( + "earthmodel=carson", "earthmodel=deri" + ) + ], + ) + result["default_earth"] = ( + "clear\nnew circuit.c basekv=12.47\nset earthmodel=carson\n" + + DEFINITIONS + + LINES.replace(" earthmodel=carson", ""), + ["set earthmodel=fullcarson", "edit line.a geometry=g"], + ) + cn = ( + "new cndata.c rac=.0002 radius=.01 radunits=m runits=m k=13 " + "diastrand=.0015 rstrand=.0008 inslayer=.004 diains=.028 diacable=.033\n" + ) + cn_base = ( + "clear\nnew circuit.c basekv=12.47\n" + + cn + + "new linegeometry.g nconds=1 nphases=1 cond=1 cncable=c x=0 h=-1 units=m\n" + + LINES + ) + result["cn_live_definition"] = ( + cn_base, + [ + "edit cndata.c rac=.0004 diastrand=.002", + "edit linegeometry.g h=-1.1", + "edit line.a geometry=g", + "edit line.b geometry=g", + ], + ) + result["cn_frequency_and_rho"] = ( + cn_base, + [ + "set frequency=50", + "edit line.b rho=37", + "edit line.a geometry=g", + "set frequency=60", + ], + ) + result["cn_reset_same_size"] = ( + cn_base, + [ + "edit linegeometry.g nconds=1 cond=1 cncable=c x=0 h=-2 units=m", + "edit line.a geometry=g", + "edit line.b geometry=g", + ], + ) + result["overhead_to_cn"] = ( + BASE, + [ + cn + "edit linegeometry.g cond=1 cncable=c h=-1", + "edit line.a geometry=g", + "edit line.b geometry=g", + ], + ) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + results = {} + for name, (base, commands) in cases().items(): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Basic.DataPath(str(args.output.resolve())) + engine.Text.Commands(base) + observations = [] + for command in ["initial", *commands]: + if command != "initial": + engine.Text.Commands(command + "\nsolve\n") + if not engine.Solution.Converged(): + raise ValueError(f"native solve failed: {name}/{command}") + primitives = {} + for line in ("a", "b"): + engine.Circuit.SetActiveElement("Line." + line) + primitives[line] = list(engine.CktElement.YPrim()) + observations.append(dict(command=command, primitives=primitives)) + results[name] = dict( + base=base, engine=engine.Basic.Version(), observations=observations + ) + (args.output / "observations.json").write_text(json.dumps(results, indent=2) + "\n") + print( + f"Captured {len(results)} native histories; run the Rust comparison separately." + ) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_geometry_definition_oracle.py b/evals/gridlabd/dss_geometry_definition_oracle.py new file mode 100644 index 000000000..92ec0a513 --- /dev/null +++ b/evals/gridlabd/dss_geometry_definition_oracle.py @@ -0,0 +1,191 @@ +"""Check overhead definition ordering separately from shared calculation caches.""" + +import argparse +import hashlib +import json +import math +import re +from pathlib import Path + +import numpy as np +import opendssdirect as dss +from oracle import LOCK + +WIRE = "new wiredata.a rac=0.0002 radius=0.01 radunits=m runits=m normamps=100\nnew wiredata.b rac=0.0004 radius=0.005 radunits=m runits=m emergamps=90\n" +GEOMETRY = "new linegeometry.g nconds=2 nphases=1 reduce=yes\n~ cond=1 wire=a units=m x=0 h=10\n~ cond=2 wire=b x=1 h=9\n" + + +def scripts(): + variants = { + "base": "", + "gmr_only": "new wiredata.g rac=0.0002 gmrac=0.007 gmrunits=m runits=m\nedit linegeometry.g cond=1 wire=g\n", + "sticky_units": "edit linegeometry.g cond=1 units=ft cond=2 x=2\n", + "unset_units": "edit linegeometry.g nconds=2 wires=[a b] h=10 x=1 cond=1 h=11 x=0\n", + "reset_same_size": "edit linegeometry.g nconds=2 cond=1 wire=a x=0 h=30 cond=2 wire=b x=2 h=28\n", + "reset_resize": "edit linegeometry.g nconds=3 cond=1 wire=a x=0 h=30 cond=2 wire=a x=2 h=30 cond=3 wire=b x=1 h=28\n", + "wire_array": "edit linegeometry.g wires=[b a] x=2 h=8\n", + "wire_edit": "edit wiredata.a radius=0.02 rac=0.0003 normamps=200\n", + "wire_rebind": "edit wiredata.a normamps=200 emergamps=300\nedit linegeometry.g normamps=0 emergamps=0 cond=1 wire=a\n", + "reduce_no": "edit linegeometry.g reduce=no\n", + "copy": "new linegeometry.c like=g\nedit linegeometry.g cond=1 x=2\n", + "copy_units": "new linegeometry.c like=g\nedit linegeometry.c nconds=2 cond=1 wire=a x=0 h=30 cond=2 wire=b x=2 h=28\n", + "copy_wire_live": "new linegeometry.c like=g\nedit wiredata.a rac=0.0003 radius=0.02\n", + "historical_rating": "new wiredata.c like=a\nedit wiredata.a normamps=500\nedit linegeometry.g normamps=0 cond=1 wire=c\n", + "geometry_abbreviations": "edit linegeometry.g cond=1 wir=b uni=ft h=30 norm=120 emerg=180 red=no\n", + } + spacing = "new linespacing.s nconds=2 nphases=1 units=m x=[0 2] h=[12 11]\n" + variants.update( + { + "spacing": spacing + "edit linegeometry.g spacing=s\n", + "spacing_later_edit": spacing + + "edit linegeometry.g spacing=s\nedit linespacing.s x=[3 4] h=[13 14]\n", + "spacing_reassign": spacing + + "edit linegeometry.g spacing=s\nedit linespacing.s x=[3 4] h=[13 14]\nedit linegeometry.g spacing=s\n", + "spacing_partial": spacing + + "edit linespacing.s x=[3]\nedit linegeometry.g spacing=s\n", + "spacing_same_size": spacing + + "edit linespacing.s nconds=2\nedit linegeometry.g spacing=s\n", + "spacing_shrink": "new linespacing.s nconds=3 units=m x=[0 2 3] h=[12 11 13]\nedit linespacing.s nconds=2\nedit linegeometry.g spacing=s\n", + "spacing_grow_initialized": "new linespacing.s nconds=1 x=[0] h=[12]\nedit linespacing.s nconds=2 x=[0 2] h=[12 11]\nedit linegeometry.g spacing=s\n", + "spacing_self_like": spacing + + "edit linespacing.s like=s\nedit linegeometry.g spacing=s\n", + "spacing_like": spacing + + "new linespacing.t like=s\nedit linespacing.s x=[3 4]\nedit linegeometry.g spacing=t\n", + "spacing_selector": spacing + + "edit linegeometry.g cond=2 spacing=s x=3 cond=1 h=14\n", + "spacing_keeps_geometry_phases": spacing + + "edit linegeometry.g nphases=2 reduce=no spacing=s\n", + "spacing_abbreviations": "new linespacing.s nc=2 np=1 x=[0 2] h=[12 11] u=m\nedit linegeometry.g spac=s\n", + } + ) + return { + name: "clear\nnew circuit.c\n" + WIRE + GEOMETRY + edit + for name, edit in variants.items() + } + + +def observe(script, matrices="fresh", data_path=None): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + if data_path is not None: + engine.Basic.DataPath(str(data_path.resolve())) + engine.Text.Commands(script) + geometries = {} + api = engine.LineGeometries + for name in api.AllNames(): + api.Name(name) + # OpenDSSDirect's enum conversion refuses native -1 (unset units). + # Use the same C API getter without converting those integers. + api._check_for_error(api._lib.LineGeometries_Get_Units_GR()) + units = api._get_int32_gr_array() + data = dict( + units=[int(v) for v in units], + wires=[ + v.removeprefix("WireData.") + .removeprefix("wiredata.") + .removeprefix("CNData.") + .removeprefix("cndata.") + for v in api.Conductors() + ], + x=list(api.Xcoords()), + height=list(api.Ycoords()), + phases=api.Phases(), + reduce=api.Reduce(), + normamps=api.NormAmps(), + emergamps=api.EmergAmps(), + ) + engine.Text.Command(f"? linegeometry.{name}.cond") + data["active"] = int(engine.Text.Result()) + if matrices: + # Each synthetic case has one geometry and no earlier calculation. + # MakeLike cases are definition-only: MakeLike itself computes and + # shares cached values, which this comparison does not qualify. + if matrices == "fresh": + engine.Text.Command( + f"new line._oracle bus1=sourcebus bus2=end geometry={name} length=1 units=m earthmodel=carson" + ) + engine.Text.Command("set controlmode=off") + engine.Text.Command("solve") + if not engine.Solution.Converged(): + raise ValueError("native geometry circuit did not converge") + api.Name(name) + n = data["phases"] if data["reduce"] else len(data["wires"]) + data["matrices"] = { + "r": np.array(api.Rmatrix(60, 1, 4)) + .reshape((n, n), order="F") + .tolist(), + "x": np.array(api.Xmatrix(60, 1, 4)) + .reshape((n, n), order="F") + .tolist(), + "b": ( + np.array(api.Cmatrix(60, 1, 4)).reshape((n, n), order="F") + * 1e-9 + * math.tau + * 60 + ).tolist(), + } + geometries[name] = data + return dict( + script=script, + script_sha256=hashlib.sha256(script.encode()).hexdigest(), + engine=engine.Basic.Version(), + geometries=geometries, + ) + + +def public_ieee4(base, output): + catalog = json.loads(Path(__file__).with_name("ieee-corpus.json").read_text()) + family = next(f for f in catalog["families"] if f["id"] == "ieee4") + source = next(s for s in family["sources"] if s["repository"].endswith("/CIMHub")) + results = {} + for record in source["files"]: + if not record["path"].lower().endswith(".dss"): + continue + path = base / Path(record["path"]).name + content = path.read_bytes() + blob = hashlib.sha1(f"blob {len(content)}\0".encode() + content).hexdigest() + if len(content) != record["bytes"] or blob != record["git_blob_sha1"]: + raise ValueError(f"public source differs from pinned catalog: {path}") + script = content.decode("utf-8-sig") + if not re.search(r"(?im)^\s*new\s+linegeometry\.", script): + continue + data_path = output / path.stem + data_path.mkdir() + result = observe(script, matrices="existing", data_path=data_path) + result["source"] = dict( + repository=source["repository"], commit=source["commit"], **record + ) + results[path.name] = result + if not results: + raise ValueError("no public geometry definitions observed") + return results + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument( + "--ieee4-base", + type=Path, + help="external pinned CIMHub ieee4/base directory; select public geometry cases instead of synthetic cases", + ) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + if args.ieee4_base is not None: + results = public_ieee4(args.ieee4_base, args.output) + else: + results = { + name: observe(script, matrices="fresh" if "copy" not in name else None) + for name, script in scripts().items() + } + (args.output / "definitions.json").write_text(json.dumps(results, indent=2) + "\n") + print( + f"Captured {len(results)} native geometry definition cases; Rust comparison is required separately." + ) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_overhead_geometry_oracle.py b/evals/gridlabd/dss_overhead_geometry_oracle.py new file mode 100644 index 000000000..c1d736df0 --- /dev/null +++ b/evals/gridlabd/dss_overhead_geometry_oracle.py @@ -0,0 +1,139 @@ +"""Pinned native overhead impedance/admittance matrices for the staged evaluator. + +This is geometry-kernel evidence, not PowerIO feeder-import qualification. +Wire values are explicit SI data; ordered definition/default/cache behavior is +validated separately before the public reader can activate geometry support. +""" + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np +import opendssdirect as dss +from oracle import LOCK + + +def wires(count, skin): + return [ + dict( + x=float(i * 2 - 3), + height=10.0 - (i % 2), + radius=0.008 + i * 0.0005, + capacitance_radius=0.01 + i * 0.0005, + gmr=0.006 + i * 0.0003, + rdc=(1e-6 if skin else 0.0002) * (1 + i / 5), + rac=0.00021 * (1 + i / 5), + ) + for i in range(count) + ] + + +def deck(geometry, frequency): + text = [ + "clear", + f"set defaultbasefrequency={frequency:.17g}", + "new circuit.c basekv=12.47", + f"set earthmodel={geometry['earth_model']}", + ] + for i, wire in enumerate(geometry["wires"]): + cable = wire.get("cable") + kind = "cndata" if cable else "wiredata" + text.append( + f"new {kind}.w{i} runits=m gmrunits=m radunits=m " + f"rdc={wire['rdc']:.17g} rac={wire['rac']:.17g} gmrac={wire['gmr']:.17g} " + f"radius={wire['radius']:.17g} capradius={wire['capacitance_radius']:.17g}" + ) + if cable: + text.append("~ " + " ".join(f"{k}={v:.17g}" for k, v in cable.items())) + text.append( + f"new linegeometry.g nconds={len(geometry['wires'])} nphases={geometry['phases']} reduce={'yes' if geometry['reduce'] else 'no'}" + ) + for i, wire in enumerate(geometry["wires"]): + text.append( + f"~ cond={i + 1} {'cncable' if wire.get('cable') else 'wire'}=w{i} units=m x={wire['x']:.17g} h={wire['height']:.17g}" + ) + text += [ + f"new line.l bus1=sourcebus bus2=end geometry=g length=1 units=m rho={geometry['rho']:.17g}", + "set controlmode=off", + "solve", + ] + return "\n".join(text) + "\n" + + +def generate(output): + output.mkdir(parents=True, exist_ok=False) + cases = {} + for model in ("carson", "fullcarson", "deri"): + for frequency in (40.0, 50.0, 60.0, 1000.0, 3000.0): + for count, phases, reduced in ( + (1, 1, False), + (3, 3, False), + (4, 3, False), + (4, 3, True), + (5, 3, True), + ): + for skin in (False, True): + key = f"{model}-{frequency}-{count}-{phases}-{reduced}-{skin}" + geometry = dict( + wires=wires(count, skin), + phases=phases, + reduce=reduced, + earth_model=model, + rho=100.0 if not skin else 37.0, + ) + script = deck(geometry, frequency) + path = output / f"{key}.dss" + path.write_text(script) + engine = dss.NewContext() + for flag in ( + "AllowChangeDir", + "AllowDOScmd", + "AllowEditor", + "AllowForms", + ): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Text.Command(f'redirect "{path.resolve()}"') + if not engine.Solution.Converged(): + raise ValueError( + f"native geometry circuit did not converge: {key}" + ) + engine.LineGeometries.Name("g") + n = phases if reduced else count + resistance = np.array( + engine.LineGeometries.Rmatrix(frequency, 1.0, 4) + ).reshape((n, n), order="F") + reactance = np.array( + engine.LineGeometries.Xmatrix(frequency, 1.0, 4) + ).reshape((n, n), order="F") + capacitance = np.array( + engine.LineGeometries.Cmatrix(frequency, 1.0, 4) + ).reshape((n, n), order="F") + cases[key] = dict( + geometry=geometry, + frequency=frequency, + r=resistance.tolist(), + x=reactance.tolist(), + b=(capacitance * 1e-9 * math.tau * frequency).tolist(), + engine=engine.Basic.Version(), + script_sha256=hashlib.sha256(script.encode()).hexdigest(), + ) + (output / "matrices.json").write_text(json.dumps(cases, indent=2) + "\n") + print( + f"Captured {len(cases)} pinned native matrices; Rust comparison is a separate required step." + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + generate(args.output.resolve()) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_spacing_oracle.py b/evals/gridlabd/dss_spacing_oracle.py new file mode 100644 index 000000000..5cdc09d38 --- /dev/null +++ b/evals/gridlabd/dss_spacing_oracle.py @@ -0,0 +1,79 @@ +"""Check pinned public geometry definitions in controlled static circuits. + +This qualifies the selected LineSpacing/LineGeometry definitions, not the full +North American feeder. Direct Line.spacing remains separate compatibility work. +""" + +import argparse +import hashlib +import json +import re +from pathlib import Path + +from ieee4_import_oracle import evaluate +from oracle import HERE + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--north-american-master", required=True, type=Path) + parser.add_argument("--bridge", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + catalog = json.loads((HERE / "ieee-corpus.json").read_text()) + family = next( + f for f in catalog["families"] if f["id"] == "north_american_lv_network" + ) + pin = family["sources"][0] + record = next(f for f in pin["files"] if f["path"].endswith("/Master.dss")) + data = args.north_american_master.read_bytes() + if ( + len(data) != record["bytes"] + or hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + != record["git_blob_sha1"] + ): + raise ValueError("public input differs from pinned master") + lines = data.decode("utf-8-sig").splitlines(keepends=True) + start = next( + i for i, line in enumerate(lines) if re.match(r"(?i)^new linespacing\.", line) + ) + end = next(i for i, line in enumerate(lines) if re.match(r"(?i)^new line\.", line)) + definitions = "".join(lines[start:end]) + args.output.mkdir(parents=True, exist_ok=False) + report = dict( + scope=__doc__, + source=dict(repository=pin["repository"], commit=pin["commit"], **record), + selected_source_lines=[start + 1, end], + definitions_sha256=hashlib.sha256(definitions.encode()).hexdigest(), + bridge_sha256=hashlib.sha256(args.bridge.read_bytes()).hexdigest(), + cases={}, + ) + for geometry, length in (("Trans", 150), ("Pri", 300), ("Sec", 30)): + folder = args.output / geometry.lower() + folder.mkdir() + source = folder / "input.dss" + source.write_text( + "Clear\nNew Circuit.c phases=3 bus1=sourcebus basekv=12.47 pu=1.02 " + "r1=.01 x1=.02 r0=.02 x0=.03\n" + + definitions + + f"New Line.probe bus1=sourcebus.1.2.3 bus2=end.1.2.3 geometry={geometry} " + f"length={length} units=ft earthmodel=carson\n" + + "\n".join( + f"New Load.l{i} phases=1 bus1=end.{i}.0 kv=7.199557856794634 " + f"kw={kw} kvar={kw / 2} model=1" + for i, kw in enumerate((80, 120, 65), 1) + ) + + "\nSet controlmode=off tolerance=1e-11 maxiterations=1000\nSolve\n" + ) + row = evaluate(source.resolve(), args.bridge.resolve(), folder.resolve(), 1e-11) + row["profile_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest() + report["cases"][geometry] = row + print(geometry, "PASS" if row["passed"] else "FAIL", row["stage"], flush=True) + report["passed"] = all(row["passed"] for row in report["cases"].values()) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if not report["passed"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_terminal_state_oracle.py b/evals/gridlabd/dss_terminal_state_oracle.py new file mode 100644 index 000000000..155b18a22 --- /dev/null +++ b/evals/gridlabd/dss_terminal_state_oracle.py @@ -0,0 +1,227 @@ +"""Native fixed Line terminal states through PowerIO import, IR and fresh DSS. + +Covers 1/2/3/4 conductors, partial and complete opens at both ends, reclosure, +MakeLike, conductor resizing, LineCode reassignment, explicit neutral and zero +charging. Every opened typed admittance is independently compared to native +YPrim. Every case compares original bus voltages and physical line-port +currents/powers after both first and repeated canonical conversion. A wrong +fixed state must fail. No source echoes or external dataset files are used. +""" + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import numpy as np +import opendssdirect as dss +from oracle import LOCK, add, compare + +cases = { + "from_all": "open line.main 1", + "to_one": "open line.main 2 1", + "both_one": "open line.main 1 1\nopen line.main 2 1", + "all": "open line.main 1\nopen line.main 2", + "reclose": "open line.main 1\nclose line.main 1", + "same_phases": "open line.main 2 1\nedit line.main phases={n}", + "resize": "open line.main 2 1\nedit line.main phases=2\nedit line.main phases={n}", + "code_same": "open line.main 2 1\nnew linecode.c nphases={n} r1=.2 x1=.4 r0=.6 x0=.9 c1=100 c0=70\nedit line.main linecode=c", + "copy_same": "new line.other phases={n} enabled=no\nopen line.main 2 1\nedit line.main like=other", +} + + +def pairs(a): + return np.array(a[::2]) + 1j * np.array(a[1::2]) + + +def run(p): + e = dss.NewContext() + for k in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(e.Basic, k)(False) + assert LOCK["dss"]["version"] in e.Basic.Version() + e.Text.Command(f'redirect "{p}"') + assert e.Solution.Converged() + return e + + +def snap(e, n, ports): + s = {} + for bus in ("sourcebus", "sink"): + e.Circuit.SetActiveBus(bus) + for node, v in zip(e.Bus.Nodes(), pairs(e.Bus.Voltages()), strict=True): + add(s, f"{bus}.{node}", "V", v) + for term, (name, start) in enumerate(ports): + e.Circuit.SetActiveElement(name) + for q, u, a in [ + ("current", "A", e.CktElement.Currents()), + ("power", "VA", np.array(e.CktElement.Powers()) * 1000), + ]: + for i, v in enumerate(pairs(a)[start : start + n]): + add(s, f"main.{term}.{i}.{q}", u, v) + return s + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bridge", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + bridge = args.bridge.resolve() + out = args.output.resolve() + out.mkdir(parents=True, exist_ok=False) + report = { + "scope": __doc__, + "bridge_sha256": hashlib.sha256(bridge.read_bytes()).hexdigest(), + "cases": {}, + } + for n in (1, 2, 3, 4): + for name, commands in list(cases.items()) + ( + [ + ("neutral_open", "open line.main 2 4"), + ("neutral_all", "open line.main 1"), + ("zero_cap", "edit line.main c1=0 c0=0\nopen line.main 2 1"), + ] + if n == 4 + else [] + ): + if name == "resize" and n == 2: + continue + folder = out / f"{n}-{name}" + folder.mkdir() + path = folder / "input.dss" + deck = f"clear\nnew circuit.c phases={n} basekv=12.47 bus1=sourcebus\nnew line.main phases={n} bus1=sourcebus bus2=sink r1=.2 x1=.4 r0=.6 x0=.9 c1=100 c0=70 length=1\n" + for i in range(1, n + 1): + deck += f"new load.l{i} phases=1 bus1=sink.{i}.0 kv=7.2 kw={10 + i} kvar=3 model=2\n" + if name.startswith("neutral_"): + deck = deck.replace("circuit.c phases=4", "circuit.c phases=3").replace( + "bus1=sourcebus bus2=sink", + "bus1=sourcebus.1.2.3.4 bus2=sink.1.2.3.4", + ) + deck = ( + "\n".join( + line + for line in deck.splitlines() + if not line.startswith("new load.l4") + ) + + "\n" + ) + for i in (1, 2, 3): + deck = deck.replace(f"bus1=sink.{i}.0", f"bus1=sink.{i}.4") + deck += "new line.ground phases=1 bus1=sourcebus.4 bus2=sourcebus.0 r1=.3 x1=0 r0=.3 x0=0 c1=0 c0=0 length=1\n" + deck += ( + commands.format(n=n) + + "\nset controlmode=off tolerance=1e-12 maxiterations=1000\nsolve\n" + ) + path.write_text(deck) + row = {"input_sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + try: + native = run(path) + row["engine"] = native.Basic.Version() + result = subprocess.run( + [str(bridge), str(path), str(folder / "import")], + text=True, + capture_output=True, + check=False, + timeout=120, + ) + (folder / "stderr.txt").write_text(result.stderr) + result.check_returncode() + j = json.loads(result.stdout) + (folder / "bridge.json").write_text(result.stdout) + assert j["targets"]["dss"]["ok"], j["targets"]["dss"] + actual = run(folder / "import/dss/case.dss") + sh = [ + s + for s in j["network"]["shunts"] + if s["name"].startswith("_pio_open_line_main") + ] + ports = ( + [("line.main", 0), ("line.main", n)] + if not sh + else [ + (f"line.{sh[0]['name']}_from", 0), + (f"line.{sh[0]['name']}_to", 0), + ] + ) + expected = snap(native, n, [("line.main", 0), ("line.main", n)]) + got = snap(actual, n, ports) + row["comparison"] = compare(expected, got) + if sh: + native.Circuit.SetActiveElement("line.main") + yp = pairs(native.CktElement.YPrim()).reshape( + (2 * n, 2 * n), order="F" + ) + typed = np.array(sh[0]["g"]) + 1j * np.array(sh[0]["b"]) + er, ar = {}, {} + for i in range(2 * n): + for k in range(2 * n): + add(er, f"{i}.{k}", "S", yp[i, k]) + add(ar, f"{i}.{k}", "S", typed[i, k]) + row["primitive"] = compare(er, ar) + repeated = subprocess.run( + [ + str(bridge), + str(folder / "import/dss/case.dss"), + str(folder / "reimport"), + ], + text=True, + capture_output=True, + check=False, + timeout=120, + ) + (folder / "reimport.stderr.txt").write_text(repeated.stderr) + repeated.check_returncode() + row["reimport_comparison"] = compare( + expected, snap(run(folder / "reimport/dss/case.dss"), n, ports) + ) + native.Circuit.SetActiveElement("line.main") + was_open = any( + native.CktElement.IsOpen(t, c) + for t in (1, 2) + for c in range(1, n + 1) + ) + wrong_commands = ( + "close line.main 1\nclose line.main 2" + if was_open + else "open line.main 2 1" + ) + wrong_path = folder / "wrong-state.dss" + wrong_path.write_text( + deck.removesuffix("solve\n") + wrong_commands + "\nsolve\n" + ) + native = run(wrong_path) + negative = compare( + expected, snap(native, n, [("line.main", 0), ("line.main", n)]) + ) + row["wrong_state_negative"] = { + "passed": not negative["passed"], + "comparison": negative, + } + row["passed"] = ( + row["comparison"]["passed"] + and row.get("primitive", {"passed": True})["passed"] + and row["reimport_comparison"]["passed"] + and row["wrong_state_negative"]["passed"] + ) + (folder / "expected.json").write_text(json.dumps(expected, indent=2)) + (folder / "actual.json").write_text(json.dumps(got, indent=2)) + except Exception as e: + row = {"passed": False, "error": str(e)} + report["cases"][folder.name] = row + (out / "report.json").write_text(json.dumps(report, indent=2)) + print( + folder.name, + row["passed"], + row.get("error", row.get("comparison", {}).get("failures", [])[:1]), + flush=True, + ) + report["passed"] = all(c["passed"] for c in report["cases"].values()) + (out / "report.json").write_text(json.dumps(report, indent=2)) + + if not report["passed"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_wiredata_oracle.py b/evals/gridlabd/dss_wiredata_oracle.py new file mode 100644 index 000000000..798f74c3b --- /dev/null +++ b/evals/gridlabd/dss_wiredata_oracle.py @@ -0,0 +1,97 @@ +"""Observe ordered WireData defaults and MakeLike in the pinned native engine. + +This checks conductor definition state only; feeder electrical qualification +also needs LineGeometry binding and canonical circuit comparisons. +""" + +import argparse +import hashlib +import itertools +import json +from pathlib import Path + +import opendssdirect as dss +from oracle import LOCK + +FIELDS = { + "rdc": "Rdc", + "rac": "Rac", + "runits": "ResistanceUnits", + "gmr": "GMRac", + "gmrunits": "GMRUnits", + "radius": "Radius", + "radunits": "RadiusUnits", + "capacitance_radius": "CapRadius", + "normamps": "NormAmps", + "emergamps": "EmergAmps", +} + + +def scripts(): + cases = { + "empty": "new wiredata.a", + "radius_only": "new wiredata.a radius=0.1", + "gmr_only": "new wiredata.a gmrac=0.1", + "rdc_first": "new wiredata.a rdc=0.2 rac=0.3 rdc=0.4", + "rac_first": "new wiredata.a rac=0.3 rdc=0.2 rac=0.4", + "rating_normal": "new wiredata.a normamps=100 emergamps=170 normamps=110", + "rating_emergency": "new wiredata.a emergamps=150 normamps=110 emergamps=180", + "diameter_sticky": "new wiredata.a diam=0.2 diam=0.4 radius=0.5", + "explicit_cap": "new wiredata.a capradius=0.3 radius=0.2 radius=0.4", + "copy": "new wiredata.a radius=0.2 rac=0.3 radunits=cm\nnew wiredata.b radius=4 like=a\nedit wiredata.a radius=0.5 rac=0.7\nedit wiredata.b radius=0.4", + "empty_copy": "new wiredata.a\nnew wiredata.b radius=0.2 like=a rac=0.3", + "self_copy": "new wiredata.a radius=0.2 rac=0.3\nedit wiredata.a like=a radius=0.4", + "positional": "new wiredata.a 0.2 0.3 km 0.008 m 0.01 m 100 160 0.03 1 [120] 0.04", + "abbreviated": "new wiredata.a rac=0.2 run=km gmra=0.008 gmru=m rad=0.01 radu=m norm=100 emerg=170 capr=0.012", + "rpn": "new wiredata.a rac=(0.2 2 *) radius=(0.01 2 *) radunits=m", + "negative_backfill": "new wiredata.a rac=-1 rdc=0.2 normamps=-1 emergamps=150", + } + setters = ("gmrac=0.007", "radius=0.01", "gmrunits=ft", "radunits=in") + for i, order in enumerate(itertools.permutations(setters)): + cases[f"order_{i}"] = "new wiredata.a " + " ".join(order) + for unit in ("none", "mi", "kft", "km", "m", "ft", "in", "cm", "mm"): + cases[f"unit_{unit}"] = ( + f"new wiredata.a rac=0.3 runits={unit} radius=0.01 radunits={unit}" + ) + return { + name: "clear\nnew circuit.c\n" + script + "\n" for name, script in cases.items() + } + + +def observe(script): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Text.Commands(script) + wires = {} + for name in engine.WireData.AllNames(): + engine.WireData.Name(name) + wires[name] = { + key: getattr(engine.WireData, getter)() for key, getter in FIELDS.items() + } + if not wires: + raise ValueError("no native wires observed") + return { + "script": script, + "script_sha256": hashlib.sha256(script.encode()).hexdigest(), + "engine": engine.Basic.Version(), + "wires": wires, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + results = {name: observe(script) for name, script in scripts().items()} + (args.output / "wires.json").write_text(json.dumps(results, indent=2) + "\n") + print( + f"Captured {len(results)} native definition cases; run the Rust comparison separately." + ) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/dss_xfmrcode_oracle.py b/evals/gridlabd/dss_xfmrcode_oracle.py new file mode 100644 index 000000000..b2cf629f8 --- /dev/null +++ b/evals/gridlabd/dss_xfmrcode_oracle.py @@ -0,0 +1,95 @@ +"""Capture assignment-time transformer-code states with the pinned native engine.""" + +import argparse +import json +import re +from pathlib import Path + +import opendssdirect as dss +from oracle import LOCK + + +def cases(): + common = "new xfmrcode.c phases=1 windings=3 kvs=[7.2 .12 .12] kvas=[2000 2000 2000] %rs=[.6 1.2 1.2] xhl=2.04 xht=2.04 xlt=1.36 %imag=.5 %noloadloss=.2\n" + cases = { + "center_tap": common, + "connection_abbreviations": "new xfmrcode.c windings=3 conns=[w wy del] xhl=5\n", + "scalar_connection_abbreviations": "new xfmrcode.c conn=delt wdg=2 conn=y xhl=6\n", + "positional": "new xfmrcode.c 1 2 1 delta 12.47 1500 1.02 .35 2 3\n~ wdg=2 conn=wye kv=.48\n~ xhl=4\n", + "scalar_rating": "new xfmrcode.c windings=3 wdg=1 kva=500 wdg=3 kva=100\n~ wdg=2 %r=.7 rneut=2 xneut=3\n~ xhl=5\n", + "two_winding_rating": "new xfmrcode.c wdg=2 kva=300 xhl=6\n", + "array_order": "new xfmrcode.c windings=3 xhl=5 xscarray=[1 2 3]\n~ xscarray=[4 5 6]\n", + "windings_reset": common + "edit xfmrcode.c windings=3\n", + "changed_size": common + + "edit xfmrcode.c windings=4\n~ xscarray=[1 2 3 4 5 6] kvs=[12 4 2 1]\n", + "copy_defaults": common + + "new xfmrcode.empty xhl=7\nedit xfmrcode.c like=empty\n", + "copy_omissions": common + + "new xfmrcode.target %imag=.9 ppm_antifloat=7 wdg=2\n~ like=c kv=.24\nnew transformer.other xfmrcode=target buses=[a b c]\n", + "self_copy": common + "edit xfmrcode.c like=c\n", + "historical": common + + "new transformer.early xfmrcode=c buses=[a b c]\nedit xfmrcode.c kvs=[12 .24 .24] %imag=.8\n", + "zero_default": "new xfmrcode.c\n", + "scalar_zero": "new xfmrcode.c xhl=0\n", + } + return { + k: "clear\nnew circuit.c\n" + v + "new transformer.final xfmrcode=c\n" + for k, v in cases.items() + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + observations = {} + for name, script in cases().items(): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Basic.DataPath(str(args.output.resolve())) + engine.Text.Commands(script) + transformers = {} + for transformer in engine.Transformers.AllNames(): + engine.Transformers.Name(transformer) + windings = [] + for i in range(1, engine.Transformers.NumWindings() + 1): + engine.Transformers.Wdg(i) + windings.append( + dict( + kv=engine.Transformers.kV(), + kva=engine.Transformers.kVA(), + tap=engine.Transformers.Tap(), + r=engine.Transformers.R(), + rneut=engine.Transformers.Rneut(), + xneut=engine.Transformers.Xneut(), + delta=bool(engine.Transformers.IsDelta()), + ) + ) + engine.Circuit.SetActiveElement("transformer." + transformer) + xsc = re.split( + r"[,\s]+", engine.Properties.Value("xscarray").strip("[]() ") + ) + transformers[transformer] = dict( + phases=engine.CktElement.NumPhases(), + windings=windings, + xsc=[float(v) for v in xsc if v.strip()], + extras={ + k: float(engine.Properties.Value(k)) + for k in ("%imag", "%noloadloss", "ppm_antifloat") + }, + ) + observations[name] = dict( + script=script, engine=engine.Basic.Version(), transformers=transformers + ) + (args.output / "observations.json").write_text( + json.dumps(observations, indent=2) + "\n" + ) + print(f"Captured {len(observations)} cases; run the Rust comparison separately.") + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/european_lv_import_oracle.py b/evals/gridlabd/european_lv_import_oracle.py new file mode 100644 index 000000000..64720da6d --- /dev/null +++ b/evals/gridlabd/european_lv_import_oracle.py @@ -0,0 +1,183 @@ +"""Pinned IEEE European LV snapshot through import, IR and canonical OpenDSS. + +The original master selects snapshot mode. All loadshape definitions have +useactual=no before loads are created. No time-series or active-control result +is claimed. Dataset bytes stay external; every input file is checked against +the catalog's Git blob pin before copying it to a fresh output directory. +""" + +import argparse +import hashlib +import json +from pathlib import Path + +import opendssdirect as dss +from oracle import HERE, LOCK, add, command, compare + + +def pairs(values): + return [complex(a, b) for a, b in zip(values[::2], values[1::2], strict=True)] + + +def run(path): + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned OpenDSS engine") + engine.Text.Command(f'redirect "{path.resolve()}"') + engine.Text.Command( + "set mode=snapshot controlmode=off tolerance=1e-12 maxiterations=1000" + ) + engine.Text.Command("solve") + if not engine.Solution.Converged(): + raise ValueError("OpenDSS did not converge") + return engine + + +def snapshot(engine, buses, elements, *, canonical): + result = {} + known_buses = {bus.lower() for bus in engine.Circuit.AllBusNames()} + known_elements = {name.lower() for name in engine.Circuit.AllElementNames()} + for bus in buses: + if bus not in known_buses: + continue # compare reports every missing original observable. + engine.Circuit.SetActiveBus(bus) + for node, voltage in zip( + engine.Bus.Nodes(), pairs(engine.Bus.Voltages()), strict=True + ): + add(result, f"bus.{bus}.{node}.voltage", "V", voltage) + for name in elements: + if name not in known_elements: + continue + engine.Circuit.SetActiveElement(name) + if not engine.CktElement.Enabled(): + continue + nodes = engine.CktElement.NodeOrder() + nc = engine.CktElement.NumConductors() + for quantity, unit, values in [ + ("current", "A", engine.CktElement.Currents()), + ("power", "VA", [1000 * x for x in engine.CktElement.Powers()]), + ]: + for i, value in enumerate(pairs(values)): + key = f"{name}.terminal{i // nc + 1}.conductor{i % nc + 1}.node{nodes[i]}.{quantity}" + add(result, key, unit, value) + add(result, f"{name}.loss", "VA", complex(*engine.CktElement.Losses())) + # Observe the source's physical feeder port. Its internal equivalent has + # auxiliary EMF buses; those are not original circuit observables. + source = "line._pio_vsource_source_impedance" if canonical else "vsource.source" + if source in known_elements: + engine.Circuit.SetActiveElement(source) + if engine.CktElement.NumConductors() != 3: + raise ValueError("source conductor inventory changed") + for quantity, unit, values in [ + ("current", "A", engine.CktElement.Currents()), + ("power", "VA", [1000 * x for x in engine.CktElement.Powers()]), + ]: + port = pairs(values)[3:6] if canonical else pairs(values)[:3] + for i, value in enumerate(port): + add(result, f"source.feeder.{i + 1}.{quantity}", unit, value) + return result + + +def evaluate(source, bridge, output): + catalog = json.loads((HERE / "ieee-corpus.json").read_text()) + pin = next(f for f in catalog["families"] if f["id"] == "european_lv")["sources"][0] + prefix = "Version8/Distrib/IEEETestCases/LVTestCase/" + output.mkdir(parents=True, exist_ok=False) + hashes = {} + for item in pin["files"]: + relative = Path(item["path"].removeprefix(prefix)) + data = (source / relative).read_bytes() + blob = hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + if len(data) != item["bytes"] or blob != item["git_blob_sha1"]: + raise ValueError(f"source pin mismatch: {relative}") + destination = output / "native" / relative + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(data) + hashes[str(relative)] = hashlib.sha256(data).hexdigest() + imported = output / "imported" + bridge_result = json.loads( + command( + [str(bridge.resolve()), str(output / "native/Master.dss"), str(imported)], + output, + ) + ) + (output / "bridge.json").write_text(json.dumps(bridge_result, indent=2) + "\n") + if ( + not bridge_result["ir_network_equal"] + or not bridge_result["targets"]["dss"]["ok"] + ): + raise ValueError("import/IR/canonical DSS failed") + native = run(output / "native/Master.dss") + buses = [bus.lower() for bus in native.Circuit.AllBusNames()] + elements = [ + name.lower() + for name in native.Circuit.AllElementNames() + if name.lower().startswith(("line.", "transformer.", "load.")) + ] + if len(buses) != 907 or len(elements) != 961: + raise ValueError("native feeder inventory changed") + expected = snapshot(native, buses, elements, canonical=False) + canonical = run(imported / "dss/case.dss") + actual = snapshot(canonical, buses, elements, canonical=True) + # A second canonical import must also solve and match the original. + reimported = output / "reimported" + command( + [str(bridge.resolve()), str(imported / "dss/case.dss"), str(reimported)], output + ) + again = snapshot(run(reimported / "dss/case.dss"), buses, elements, canonical=True) + canonical.Text.Command("edit line.line1 length=20") + canonical.Text.Command("solve") + if not canonical.Solution.Converged(): + raise ValueError("negative-control circuit did not converge") + wrong = snapshot(canonical, buses, elements, canonical=True) + comparison, repeated, negative = ( + compare(expected, values) for values in (actual, again, wrong) + ) + report = { + "scope": __doc__, + "repository": pin["repository"], + "commit": pin["commit"], + "input_sha256": hashes, + "bridge_sha256": hashlib.sha256(bridge.read_bytes()).hexdigest(), + "engine": native.Basic.Version(), + "buses": len(buses), + "elements": len(elements), + "comparison": comparison, + "reimport_comparison": repeated, + "wrong_line_negative": { + "passed": not negative["passed"], + "comparison": negative, + }, + "passed": comparison["passed"] + and repeated["passed"] + and not negative["passed"], + } + for name, data in [ + ("native", expected), + ("canonical", actual), + ("reimported", again), + ("wrong-line", wrong), + ("report", report), + ]: + (output / f"{name}.json").write_text(json.dumps(data, indent=2) + "\n") + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", required=True, type=Path) + parser.add_argument("--bridge", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + report = evaluate( + args.source.resolve(), args.bridge.resolve(), args.output.resolve() + ) + print(json.dumps({key: report[key] for key in ("passed", "buses", "elements")})) + if not report["passed"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/ieee-corpus.json b/evals/gridlabd/ieee-corpus.json index ced170aaa..c31aac544 100644 --- a/evals/gridlabd/ieee-corpus.json +++ b/evals/gridlabd/ieee-corpus.json @@ -26,6 +26,32 @@ "bytes": 14065 } ] + }, + { + "repository": "https://github.com/dss-extensions/electricdss-tst", + "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", + "files": [ + { + "path": "Version8/Distrib/IEEETestCases/13Bus/IEEE13Node_BusXY.csv", + "git_blob_sha1": "26cd6f484e910e03ec196318f8692266421c9f2a", + "bytes": 243 + }, + { + "path": "Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss", + "git_blob_sha1": "f02bc852ff50fc03632a7efe9cead633a237a66a", + "bytes": 8354 + }, + { + "path": "Version8/Distrib/IEEETestCases/13Bus/IEEELineCodes.DSS", + "git_blob_sha1": "519a228cf1907f551a6b38c1522da651d1322c26", + "bytes": 30 + }, + { + "path": "Version8/Distrib/IEEETestCases/IEEELineCodes.DSS", + "git_blob_sha1": "eba8d904eb8f0aa1b8fa69faa0fdbc6afa10c3dd", + "bytes": 12032 + } + ] } ], "note": "Keep solver variants distinct; do not substitute NR for FBS implicitly." @@ -53,6 +79,52 @@ "bytes": 2873 } ] + }, + { + "repository": "https://github.com/dss-extensions/electricdss-tst", + "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", + "files": [ + { + "path": "Version8/Distrib/IEEETestCases/34Bus/IEEE34_BusXY.csv", + "git_blob_sha1": "da24689018a460a25c7d973fa56d92f2b33d951d", + "bytes": 506 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/IEEELineCodes.DSS", + "git_blob_sha1": "519a228cf1907f551a6b38c1522da651d1322c26", + "bytes": 30 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/Run_IEEE34Mod1.dss", + "git_blob_sha1": "b01299250d68acde03317822fac0e86e020f8bc6", + "bytes": 1565 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/Run_IEEE34Mod2.dss", + "git_blob_sha1": "7bca2e2f0c389e023901f63db71bc2d0458685a4", + "bytes": 1691 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/ieee34Mod1.dss", + "git_blob_sha1": "2e4c35226bcf35008f73620e5926854b96437e34", + "bytes": 14341 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/ieee34Mod2.dss", + "git_blob_sha1": "1a6297718368277ff8d8dd689cb00bf55e5525ae", + "bytes": 14329 + }, + { + "path": "Version8/Distrib/IEEETestCases/34Bus/nmsu_linecode2_ABC.txt", + "git_blob_sha1": "cbafbe5d0616493d3ea5c3cb3842001bbfd5fdd5", + "bytes": 1281 + }, + { + "path": "Version8/Distrib/IEEETestCases/IEEELineCodes.DSS", + "git_blob_sha1": "eba8d904eb8f0aa1b8fa69faa0fdbc6afa10c3dd", + "bytes": 12032 + } + ] } ], "note": "Keep solver variants distinct; do not substitute NR for FBS implicitly." @@ -80,6 +152,32 @@ "bytes": 2637 } ] + }, + { + "repository": "https://github.com/dss-extensions/electricdss-tst", + "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", + "files": [ + { + "path": "Version8/Distrib/IEEETestCases/37Bus/IEEE37_BusXY.csv", + "git_blob_sha1": "48c6bc6bdb3ea8d3f4209c9a596bc6a4cf565fa1", + "bytes": 755 + }, + { + "path": "Version8/Distrib/IEEETestCases/37Bus/IEEELineCodes.DSS", + "git_blob_sha1": "519a228cf1907f551a6b38c1522da651d1322c26", + "bytes": 30 + }, + { + "path": "Version8/Distrib/IEEETestCases/37Bus/ieee37.dss", + "git_blob_sha1": "938b6843f3e025f223194d32072503a017191bf8", + "bytes": 7427 + }, + { + "path": "Version8/Distrib/IEEETestCases/IEEELineCodes.DSS", + "git_blob_sha1": "eba8d904eb8f0aa1b8fa69faa0fdbc6afa10c3dd", + "bytes": 12032 + } + ] } ], "note": "Keep solver variants distinct; do not substitute NR for FBS implicitly." @@ -122,6 +220,127 @@ "bytes": 57032 } ] + }, + { + "repository": "https://github.com/dss-extensions/electricdss-tst", + "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", + "files": [ + { + "path": "Version8/Distrib/IEEETestCases/123Bus/BusCoords.dat", + "git_blob_sha1": "1bced02d1de85454674d6b0a4a263ffd7bbbee5a", + "bytes": 2858 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/CircuitPlottingScripts.dss", + "git_blob_sha1": "e65fd37cdc1a1aa7480970647bb14c22de5e6412", + "bytes": 1165 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/IEEE123Loads.DSS", + "git_blob_sha1": "452974187c8dcc05e387e1d83cf798db373ed1d7", + "bytes": 8289 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/IEEE123Master.dss", + "git_blob_sha1": "1f234a8615253c8891ac2530f3f2803fca34915f", + "bytes": 17096 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/IEEE123Regulators.DSS", + "git_blob_sha1": "f695011c017946feadcd0f5280f833d8d9680ac4", + "bytes": 1861 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/IEEE123Switches.dss", + "git_blob_sha1": "f42cde72efe27a43fc39eba21925066979b8d666", + "bytes": 16925 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/IEEELineCodes.DSS", + "git_blob_sha1": "519a228cf1907f551a6b38c1522da651d1322c26", + "bytes": 30 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/P174_Run_SolarRamp.DSS", + "git_blob_sha1": "b9003175125afc623d07938afc899dc4d833f375", + "bytes": 1439 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/P174_Run_VoltageProfile.DSS", + "git_blob_sha1": "43a71343404dec1e2edb4f094f8f464b0bf64709", + "bytes": 1034 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/PV5sdata1.csv", + "git_blob_sha1": "cc5609a244f6c829fb967b2a438e285bfd6c69b6", + "bytes": 28794 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/PVShape.dss", + "git_blob_sha1": "4c0469a76186fbba90201ccfe9c292a056c2c71f", + "bytes": 14521 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/PaperLoadShape.txt", + "git_blob_sha1": "5f42b2bb14e55c8b3954ff6df2f0772f9aba1a87", + "bytes": 61318 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/RevRegTest.dss", + "git_blob_sha1": "c22706e56ba0f29d988528b4bed5c8a846edf0c8", + "bytes": 1753 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/Run_IEEE123Bus.DSS", + "git_blob_sha1": "84d74a943d99195b7c8f0f4fcaa45d1674eadeaf", + "bytes": 4766 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/Run_YearlySim.dss", + "git_blob_sha1": "25d503322862a8e08f9b3ade012e8bf006cf0ec3", + "bytes": 1717 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/SetDailyLoadShape.DSS", + "git_blob_sha1": "6ca22a83376142f320d5bf2dbe98c1291fa21a93", + "bytes": 2277 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/SolarRamp-Mack.DSS", + "git_blob_sha1": "c16caecade45949ca7c29c42a194824fdbcc1ead", + "bytes": 2230 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/SolarRamp.DSS", + "git_blob_sha1": "180127226edae02d46c6b38e21f7df4e75dcec50", + "bytes": 1940 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/SolarRamp.csv", + "git_blob_sha1": "2e55be78f8f81a3235aaac72eb54779864c008da", + "bytes": 1202 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/StorageRamp.CSV", + "git_blob_sha1": "9e3ece25ef79dd28888e9583bfa67d0df21185fb", + "bytes": 1202 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/WindRamp.DSS", + "git_blob_sha1": "50c76a79256fdc7bdaaf9765b1c0aa39aa7a3369", + "bytes": 1432 + }, + { + "path": "Version8/Distrib/IEEETestCases/123Bus/WindRampRevRegTest.DSS", + "git_blob_sha1": "caf901d9c517daf5f3dced2f239d564154859e36", + "bytes": 1992 + }, + { + "path": "Version8/Distrib/IEEETestCases/IEEELineCodes.DSS", + "git_blob_sha1": "eba8d904eb8f0aa1b8fa69faa0fdbc6afa10c3dd", + "bytes": 12032 + } + ] } ], "note": "Zero-voltage regression assertions cover absent phases, not a complete positive load-flow reference. Switching schedules require an explicitly selected static state." @@ -278,6 +497,11 @@ "path": "ieee4/base/YYUnBal.dss", "git_blob_sha1": "79a824e44a9293ea26c106451f92b33e5423a257", "bytes": 1258 + }, + { + "path": "ieee4/base/ieee4xy.dat", + "git_blob_sha1": "f71a07ed2dd0e36d34e2821ae1c9f79310055680", + "bytes": 208 } ] } @@ -516,6 +740,27 @@ "bytes": 1445129 } ] + }, + { + "repository": "https://github.com/dss-extensions/electricdss-tst", + "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", + "files": [ + { + "path": "Version8/Distrib/IEEETestCases/ieee9500dss/ieee9500_base.dss", + "git_blob_sha1": "bb5d8745d98a808e2d2c5478bc9b24611401100e", + "bytes": 1064633 + }, + { + "path": "Version8/Distrib/IEEETestCases/ieee9500dss/ieee9500_busxy.dss", + "git_blob_sha1": "892fcdfecf58c188a801e55587ea64e7642b752a", + "bytes": 165083 + }, + { + "path": "Version8/Distrib/IEEETestCases/ieee9500dss/ieee9500_uuid.dss", + "git_blob_sha1": "12ad8f0fdcd6b72aad3ecc1170019f0aa4f8c49b", + "bytes": 381690 + } + ] } ], "note": "Archives include paired engine results. GLM wrappers include climate/generator/reliability modules; do not silently discard their effects." @@ -527,15 +772,555 @@ "repository": "https://github.com/dss-extensions/electricdss-tst", "commit": "3b208397160213cae4a9e2d0a7d1aa3528ce26e1", "files": [ + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Buscoords.txt", + "git_blob_sha1": "8cc819e53e8fab2fbb20dda97e2e330c2fbcd727", + "bytes": 23723 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_1.txt", + "git_blob_sha1": "f08762073aced1f6eebd6c110eaa2c7c300f5a19", + "bytes": 12803 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_10.txt", + "git_blob_sha1": "6a36b211d6bcd38a1e64c7d01fe7ef29b12463af", + "bytes": 12933 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_100.txt", + "git_blob_sha1": "ebdebc7bef085ef10d45239173d4c2df00fb11ed", + "bytes": 12891 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_11.txt", + "git_blob_sha1": "6242023c7c272cdc389dc5ed0592d2e83f007897", + "bytes": 12931 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_12.txt", + "git_blob_sha1": "4c47d41a9c7808fcbae28bed103addc16adcc841", + "bytes": 12937 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_13.txt", + "git_blob_sha1": "10b91ea876fc2ae1e0a37e98068a7e7174457a9c", + "bytes": 12903 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_14.txt", + "git_blob_sha1": "a26c66055796b045635ca0b5fe62b3f5466c3533", + "bytes": 12687 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_15.txt", + "git_blob_sha1": "679490c5b522c63c5e3a7ff42967205fcd421918", + "bytes": 12960 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_16.txt", + "git_blob_sha1": "745d3d3118800e7a179a73e51bb959f8fe456f97", + "bytes": 12744 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_17.txt", + "git_blob_sha1": "fc29e229d2ba0ecea83f654710209e61340d67c5", + "bytes": 12851 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_18.txt", + "git_blob_sha1": "2af17bc3056c214736406e4b7349a674c6a66970", + "bytes": 12556 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_19.txt", + "git_blob_sha1": "419d6700d10d92fd468289940e6a6e2bb5bf3eca", + "bytes": 12773 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_2.txt", + "git_blob_sha1": "386be3ce43aaf37858875e7c493e79a10e8b85ac", + "bytes": 12881 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_20.txt", + "git_blob_sha1": "30e2c2f19a6eabbda67fc6bcc38905cd606f7e9e", + "bytes": 12854 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_21.txt", + "git_blob_sha1": "771f437c01402460ea97231bff3023f9a62e443a", + "bytes": 12632 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_22.txt", + "git_blob_sha1": "09fbd29fed9bf87803c065fd71d38033edbb4cc3", + "bytes": 12807 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_23.txt", + "git_blob_sha1": "feed4f1eb1ce278aa4651897a071f681785649e4", + "bytes": 12941 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_24.txt", + "git_blob_sha1": "8eda61b9db1e013eff3d105427ca4d6a237ada59", + "bytes": 12906 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_25.txt", + "git_blob_sha1": "8f26a996dbd3ce8eccf590adf63a81129f445464", + "bytes": 12179 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_26.txt", + "git_blob_sha1": "4583c293c03fdcacc771f81adf5cdf1388fefffa", + "bytes": 12941 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_27.txt", + "git_blob_sha1": "47a1cc33ceef328332ab3c45410f16101d507e92", + "bytes": 12893 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_28.txt", + "git_blob_sha1": "3c948e9b8b087fb85bbfa37f93c277e2c1b12cf2", + "bytes": 12948 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_29.txt", + "git_blob_sha1": "d36fcb6d68d6d3f7f2924ca1f49a64fa60485c23", + "bytes": 12818 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_3.txt", + "git_blob_sha1": "c105c37e1387f5bf448bb9cc89e23b10051170a1", + "bytes": 12943 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_30.txt", + "git_blob_sha1": "da112b221aa20150f3927485f133fd297faf6aa7", + "bytes": 12899 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_31.txt", + "git_blob_sha1": "8f8468a7dcaaf17602a6883781f48b6d1b61c223", + "bytes": 12819 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_32.txt", + "git_blob_sha1": "1972f910670a06b8323e7940b014171004fda18c", + "bytes": 12867 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_33.txt", + "git_blob_sha1": "370935c3320330b501f81bef83b93546f1859820", + "bytes": 12794 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_34.txt", + "git_blob_sha1": "48d8dec7647020b5123202960646134ec5382750", + "bytes": 12920 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_35.txt", + "git_blob_sha1": "dc71cbd1e298512866a941754cd2fe1f4f26735b", + "bytes": 12918 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_36.txt", + "git_blob_sha1": "58429739b6bd10d31e8a9ac51c71a46ec0c8e0d2", + "bytes": 12954 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_37.txt", + "git_blob_sha1": "644d45775f7e5dc9820274829e3c77bfda198218", + "bytes": 12838 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_38.txt", + "git_blob_sha1": "43d575ade058ce0e6825d572f8cfe5f8fd9a1321", + "bytes": 12863 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_39.txt", + "git_blob_sha1": "96a917a8a4e24a7d26fd86076da51ef2f4b72ad3", + "bytes": 12857 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_4.txt", + "git_blob_sha1": "7bf9c1011191e308c03c3905224cad488c4f654d", + "bytes": 12884 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_40.txt", + "git_blob_sha1": "5cef11afc2f30f407de1784d5e1117e8efd072d4", + "bytes": 12924 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_41.txt", + "git_blob_sha1": "2cbb2eb779b9324e43d7c1c53e427f93d2487c6a", + "bytes": 12911 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_42.txt", + "git_blob_sha1": "98f5b5a61f9aeaf6e852fef8e2f14a8a02bdb4ef", + "bytes": 12750 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_43.txt", + "git_blob_sha1": "42d1a743587d38360db20247d947ee641b7b26c9", + "bytes": 11876 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_44.txt", + "git_blob_sha1": "bf738e0bb0f2e9bf9d667950c474dce38a9a5ecd", + "bytes": 12872 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_45.txt", + "git_blob_sha1": "39337b3c043b7480c004f002f08eb399e7c3dce1", + "bytes": 12887 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_46.txt", + "git_blob_sha1": "17857c14b2a863b268b23d04fd39d334f19b5aff", + "bytes": 12905 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_47.txt", + "git_blob_sha1": "c8a46e2218cea50e8c729e66e5c6812a0359fc0a", + "bytes": 12928 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_48.txt", + "git_blob_sha1": "9fce7100f7009bde3582bf737e4b778116f78219", + "bytes": 12854 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_49.txt", + "git_blob_sha1": "50de96e669c9a24d62986f5df9f933410ec66251", + "bytes": 12879 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_5.txt", + "git_blob_sha1": "6b8f4c92e153b840a279f78b5974fc1ef3fd73bb", + "bytes": 12865 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_50.txt", + "git_blob_sha1": "80b093d196a80f40cb7dac82d88269e16df673b1", + "bytes": 12734 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_51.txt", + "git_blob_sha1": "454f0bcbe8c34d397ea8d30b73a16ae0f4d0d476", + "bytes": 12915 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_52.txt", + "git_blob_sha1": "404eb8b17c5a35de7a81dcf84b02aa7e71db6c1e", + "bytes": 12923 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_53.txt", + "git_blob_sha1": "62c029148f28bfdb041cb73f3a24d67b49e8595f", + "bytes": 12829 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_54.txt", + "git_blob_sha1": "8cf96b44a183326646125bd191780372db943679", + "bytes": 12908 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_55.txt", + "git_blob_sha1": "30e9905cad35fc2aedfc4bbf48f01ccdaa697ae6", + "bytes": 12778 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_56.txt", + "git_blob_sha1": "db4ee2e2ce5c450d1613011ddfa59c3b2a168e2f", + "bytes": 12286 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_57.txt", + "git_blob_sha1": "6c5d42d24c5c065329154485c644c986f0ad82e8", + "bytes": 12956 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_58.txt", + "git_blob_sha1": "4b0fcd7b2383fef4dc7e8bf2e40fa71de3645f0d", + "bytes": 11970 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_59.txt", + "git_blob_sha1": "d32c95d68d024006348da0d14475dab07d195fe6", + "bytes": 12888 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_6.txt", + "git_blob_sha1": "73988fd802083e57ed81bd747d17e2493fb68e14", + "bytes": 12939 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_60.txt", + "git_blob_sha1": "98dad3c86495dd1379799ed0587eb6747b5c2d88", + "bytes": 12932 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_61.txt", + "git_blob_sha1": "cce954342c91a5681a44c387c253191f066edcca", + "bytes": 12893 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_62.txt", + "git_blob_sha1": "93d55688dd8fa2156de23af4467dec81b94b41a3", + "bytes": 12903 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_63.txt", + "git_blob_sha1": "30bc3de2a9845a09ab14e759f1f879d5b8ef13be", + "bytes": 12553 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_64.txt", + "git_blob_sha1": "c0f54e35147a67fe636f0b434f466706bf523752", + "bytes": 12890 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_65.txt", + "git_blob_sha1": "5039eb6dca57d2c82c02bd5fec76edc8b9c5c803", + "bytes": 12925 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_66.txt", + "git_blob_sha1": "91081a7e9d88ff6fdc7ca408f76ed1dc9a9c5f74", + "bytes": 12917 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_67.txt", + "git_blob_sha1": "7252405b880e263819556015a15abae13af1a75f", + "bytes": 12469 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_68.txt", + "git_blob_sha1": "5a8beb7a210cb8ad265a601e00e23f8be51522eb", + "bytes": 12776 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_69.txt", + "git_blob_sha1": "b0e085ffb35325c33424368bb0660bac73ac2e12", + "bytes": 12799 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_7.txt", + "git_blob_sha1": "26e88e6dfe7b64600c49b06e6149bf0a9ab0bf3b", + "bytes": 12928 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_70.txt", + "git_blob_sha1": "97fd982ce690aca2037a4e258b4b938eae251157", + "bytes": 12881 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_71.txt", + "git_blob_sha1": "a33adfb72e15e222de6cecbcd12931ffcd5d50c4", + "bytes": 12911 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_72.txt", + "git_blob_sha1": "f81a09543599208543caf7c6c419f264fd0f8911", + "bytes": 12762 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_73.txt", + "git_blob_sha1": "83f8b98c14c93d0674815c5a9252e25f03a48e4a", + "bytes": 12848 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_74.txt", + "git_blob_sha1": "177c04e643508dcb31b129df1e8f501a463fd342", + "bytes": 12904 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_75.txt", + "git_blob_sha1": "839e9ee9a7c56acd3182a01fb87dfcf9e821532b", + "bytes": 12858 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_76.txt", + "git_blob_sha1": "0adc49eee74abb9524bbadf82e83a2efb5dd3976", + "bytes": 12896 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_77.txt", + "git_blob_sha1": "df89893825e2c6d81869683b65ca614b8cb316fc", + "bytes": 12864 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_78.txt", + "git_blob_sha1": "f61e64632962cecea0ba1a179439af02bcbb8969", + "bytes": 12837 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_79.txt", + "git_blob_sha1": "df0871fd5ed2db4db9c38e88cf8b9c24f9fef74a", + "bytes": 12945 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_8.txt", + "git_blob_sha1": "121128ea2e8dc5b539ecbb2f421d9ee412e94588", + "bytes": 12850 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_80.txt", + "git_blob_sha1": "b396823fc6a5873e96a37e3cb7ac935eb2c59332", + "bytes": 12890 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_81.txt", + "git_blob_sha1": "b9f38d6fefa857bac465fe72cec9b35262492969", + "bytes": 12205 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_82.txt", + "git_blob_sha1": "0846073ff3e4356b896c2a2dae9de66243fb3434", + "bytes": 12903 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_83.txt", + "git_blob_sha1": "79a235d3f8460ec629104b0d0b44f2f9957e7e47", + "bytes": 12914 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_84.txt", + "git_blob_sha1": "24d36a09cfd50b2e7cccf0e2bee096f12106b2e1", + "bytes": 12921 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_85.txt", + "git_blob_sha1": "644aef20ab04680f6b6bd19dcb80b1067848161b", + "bytes": 12915 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_86.txt", + "git_blob_sha1": "b4389d0247e16f49128c1900a887e14b069b5ab9", + "bytes": 12912 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_87.txt", + "git_blob_sha1": "c96ea601b36f7bbd7d3e9542ad649554affcec87", + "bytes": 12928 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_88.txt", + "git_blob_sha1": "dcb048b995d9d0445736be0c92d854182df18f22", + "bytes": 12854 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_89.txt", + "git_blob_sha1": "1ddcafce91c0077d1b474851c23c0d8bfd3e3be9", + "bytes": 12765 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_9.txt", + "git_blob_sha1": "c4045068b940106a09bb67ff60835f23f796431c", + "bytes": 12862 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_90.txt", + "git_blob_sha1": "70811de84fdde77c23c58bcb7c893344a267f1eb", + "bytes": 12772 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_91.txt", + "git_blob_sha1": "1c8f6e15935790f515ee8c393e05470c9bb1c374", + "bytes": 12945 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_92.txt", + "git_blob_sha1": "6d0f34196455e92f3115f2a9b4f386ea0634b01b", + "bytes": 12266 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_93.txt", + "git_blob_sha1": "00822106724c84bc5f908cd028b2b095bbadaf07", + "bytes": 12900 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_94.txt", + "git_blob_sha1": "32f327c5672633ff504dc975016f7cb6e2eb1430", + "bytes": 12947 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_95.txt", + "git_blob_sha1": "618d9c6747acc44205d1673285ab68e506498bd0", + "bytes": 12879 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_96.txt", + "git_blob_sha1": "29f1e106cc9178270a9c4a9d0b51cba2470ec0b4", + "bytes": 12878 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_97.txt", + "git_blob_sha1": "a388bc3f2f7fda143407d4cce60c0ac1d191a591", + "bytes": 12903 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_98.txt", + "git_blob_sha1": "79c6d94850015f04ed708a6398575666a5baa65b", + "bytes": 12852 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Daily_1min_100profiles/load_profile_99.txt", + "git_blob_sha1": "ce760afa068eda60abbcf424da86f8502c1b36d0", + "bytes": 12896 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Generators.txt", + "git_blob_sha1": "d9bd27384ae2c4b19848f288b93b47572c183c5a", + "bytes": 56 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/LineCode.txt", + "git_blob_sha1": "264bd68fede735712030e76af1d0f2a461c748df", + "bytes": 864 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Lines.txt", + "git_blob_sha1": "dc52c03ca9e262e0534a2f22136da47f065b32a9", + "bytes": 74784 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/LoadShapes.txt", + "git_blob_sha1": "b085affedf28f4e0cd0b272e7e177c29197cddb2", + "bytes": 6362 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Loads.txt", + "git_blob_sha1": "2cf6a1aba083ef8945f36c11fe1e1cf22fa7afb8", + "bytes": 4046 + }, { "path": "Version8/Distrib/IEEETestCases/LVTestCase/Master.dss", "git_blob_sha1": "21e4d7f3610558718da7b4f94d3352878ed6cbfd", "bytes": 1600 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Monitors.txt", + "git_blob_sha1": "922798c64cd36ced81e43f913b959e76a920161a", + "bytes": 109069 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCase/Transformers.txt", + "git_blob_sha1": "4f46319b644cd103282cdf6876a9b4fd9901f857", + "bytes": 101 } ] } ], - "note": "OpenDSS corpus source; this catalog does not imply an available GLM equivalent or validated PowerIO support." + "note": "Original snapshot entrypoint and all companion files pinned; european_lv_import_oracle.py checks native DSS against import, IR and fresh canonical DSS. Time-series simulation and GLM emission remain separate qualifications." }, { "id": "north_american_lv_network", @@ -563,6 +1348,11 @@ "path": "Version8/Distrib/IEEETestCases/LVTestCaseNorthAmerican/network_protectors.dss", "git_blob_sha1": "8c6b9412fc96b2cd811aacb85f7c2ff75df5a48a", "bytes": 12448 + }, + { + "path": "Version8/Distrib/IEEETestCases/LVTestCaseNorthAmerican/buscoords.dat", + "git_blob_sha1": "0f7ef3cd175d46fc6beb1810efc9ffe44b28da4c", + "bytes": 6023 } ] } diff --git a/evals/gridlabd/ieee4_import_oracle.py b/evals/gridlabd/ieee4_import_oracle.py new file mode 100644 index 000000000..1c4da8d5d --- /dev/null +++ b/evals/gridlabd/ieee4_import_oracle.py @@ -0,0 +1,202 @@ +"""Pinned IEEE4 cases through import, IR and repeated canonical DSS. + +Reports every failure. Definition-only, retained-source or nonconverged results +never count as electrical qualification. Public dataset bytes remain external. +""" + +import argparse +import hashlib +import json +import os +import re +from pathlib import Path + +import opendssdirect as dss +from european_lv_import_oracle import snapshot +from oracle import HERE, LOCK, command, compare + + +def run(path, tolerance): + path = path.resolve() + engine = dss.NewContext() + for flag in ("AllowChangeDir", "AllowDOScmd", "AllowEditor", "AllowForms"): + getattr(engine.Basic, flag)(False) + if LOCK["dss"]["version"] not in engine.Basic.Version(): + raise ValueError("unpinned engine") + engine.Basic.DataPath(str(path.parent.resolve())) + # UUIDs uses the process directory even when native AllowChangeDir is off. + previous = Path.cwd() + try: + os.chdir(path.parent) + engine.Text.Command(f'redirect "{path.resolve()}"') + finally: + os.chdir(previous) + engine.Text.Command( + f"set mode=snapshot controlmode=off tolerance={tolerance} maxiterations=1000" + ) + engine.Text.Command("solve") + if not engine.Solution.Converged(): + raise ValueError("OpenDSS did not converge") + return engine + + +def imported(bridge, source, folder, acquisition_root=None): + args = [str(bridge), str(source), str(folder)] + if acquisition_root is not None: + args.append(str(acquisition_root)) + result = json.loads(command(args, folder.parent)) + (folder / "bridge.json").write_text(json.dumps(result, indent=2) + "\n") + if not result["ir_network_equal"] or not result["targets"]["dss"]["ok"]: + raise ValueError("IR equality or canonical DSS emission failed") + if any(f["severity"] == "Blocker" for f in result["readiness"]): + raise ValueError("import retains electrical readiness blockers") + return folder / "dss/case.dss" + + +def evaluate(source, bridge, folder, tolerance, acquisition_root=None): + row = {"passed": False, "solver_tolerance": tolerance} + try: + row["stage"] = "import" + canonical_path = imported(bridge, source, folder / "imported", acquisition_root) + row["stage"] = "native solve" + native = run(source, tolerance) + row["engine"] = native.Basic.Version() + buses = [b.lower() for b in native.Circuit.AllBusNames()] + elements = [ + n.lower() + for n in native.Circuit.AllElementNames() + if n.lower().startswith( + ( + "line.", + "transformer.", + "load.", + "autotrans.", + "capacitor.", + "reactor.", + "generator.", + "pvsystem.", + "storage.", + ) + ) + ] + expected = snapshot(native, buses, elements, canonical=False) + (folder / "native.json").write_text(json.dumps(expected, indent=2) + "\n") + row["stage"] = "canonical solve" + canonical = run(canonical_path, tolerance) + actual = snapshot(canonical, buses, elements, canonical=True) + row["comparison"] = compare(expected, actual) + (folder / "canonical.json").write_text(json.dumps(actual, indent=2) + "\n") + row["stage"] = "reimport" + reimported_path = imported(bridge, canonical_path, folder / "reimported") + repeated = snapshot( + run(reimported_path, tolerance), buses, elements, canonical=True + ) + row["reimport_comparison"] = compare(expected, repeated) + (folder / "reimported.json").write_text(json.dumps(repeated, indent=2) + "\n") + row["stage"] = "wrong line negative control" + canonical.Lines.Name( + "line1" + if "line.line1" in elements + else next( + n.removeprefix("line.") for n in elements if n.startswith("line.") + ) + ) + line = canonical.Lines.Name() + length = canonical.Lines.Length() + # Initialize the changed model independently, avoiding the previous + # solution's floating-node state as a hidden input to the control. + text = canonical_path.read_text() + pattern = ( + r"(?im)^(\s*new\s+line\." + re.escape(line) + r"\s+[^\n]*?\blength=)(\S+)" + ) + text, count = re.subn(pattern, lambda m: m[1] + f"{length * 1.25:.17g}", text) + if count != 1: + raise ValueError( + "negative control could not identify exactly one Line declaration" + ) + wrong_path = canonical_path.with_name("wrong-line.dss") + wrong_path.write_text(text) + wrong = snapshot(run(wrong_path, tolerance), buses, elements, canonical=True) + negative = compare(expected, wrong) + row["wrong_line_negative"] = { + "passed": not negative["passed"], + "comparison": negative, + } + (folder / "wrong-line.json").write_text(json.dumps(wrong, indent=2) + "\n") + row["passed"] = ( + row["comparison"]["passed"] + and row["reimport_comparison"]["passed"] + and not negative["passed"] + ) + row["stage"] = "compared" + except Exception as error: + row["error"] = str(error) + return row + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ieee4-base", type=Path, required=True) + parser.add_argument("--bridge", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + pin = next( + s + for f in json.loads((HERE / "ieee-corpus.json").read_text())["families"] + if f["id"] == "ieee4" + for s in f["sources"] + if s["repository"].endswith("/CIMHub") + ) + report = { + "scope": __doc__, + "bridge_sha256": hashlib.sha256(args.bridge.read_bytes()).hexdigest(), + "cases": {}, + } + verified = {} + for record in pin["files"]: + name = Path(record["path"]).name + data = (args.ieee4_base / name).read_bytes() + if ( + len(data) != record["bytes"] + or hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + != record["git_blob_sha1"] + ): + raise ValueError(f"source pin mismatch: {name}") + verified[name] = (record, data) + report["companions"] = { + name: dict(record, sha256=hashlib.sha256(data).hexdigest()) + for name, (record, data) in verified.items() + if not name.lower().endswith(".dss") + } + for name, (record, data) in verified.items(): + if not name.lower().endswith(".dss"): + continue + folder = args.output / Path(name).stem + folder.mkdir() + source = folder / "native.dss" + source.write_bytes(data) + for companion in report["companions"]: + (folder / companion).write_bytes(verified[companion][1]) + # Floating delta cases and edited controls can stall below 1e-11. + # Use one pinned solve criterion, stricter than the files' 1e-8; + # observable acceptance in oracle.compare remains unchanged. + tolerance = 1e-11 + row = evaluate( + source.resolve(), args.bridge.resolve(), folder.resolve(), tolerance + ) + row["source"] = dict( + repository=pin["repository"], commit=pin["commit"], **record + ) + row["source_sha256"] = hashlib.sha256(data).hexdigest() + report["cases"][name] = row + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(name, "PASS" if row["passed"] else "FAIL", row["stage"], flush=True) + report["qualified_cases"] = sum(c["passed"] for c in report["cases"].values()) + report["passed"] = all(c["passed"] for c in report["cases"].values()) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"Qualified {report['qualified_cases']}/{len(report['cases'])} cases.") + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/ieee9500_archive_import_oracle.py b/evals/gridlabd/ieee9500_archive_import_oracle.py new file mode 100644 index 000000000..49031381d --- /dev/null +++ b/evals/gridlabd/ieee9500_archive_import_oracle.py @@ -0,0 +1,112 @@ +"""Pinned CIMHub balanced/unbalanced IEEE9500 DSS static import comparisons. + +The two archive cases remain distinct from the electricdss-tst IEEE9500 case. +ControlMode=Off is inserted before voltage-base calculations and solves. The +original archive members and adjusted profiles are retained with hashes. +""" + +import argparse +import hashlib +import io +import json +import re +import zipfile +from pathlib import Path, PurePosixPath + +from ieee4_import_oracle import evaluate +from oracle import HERE + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archives", type=Path, required=True) + parser.add_argument("--bridge", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + catalog = json.loads((HERE / "ieee-corpus.json").read_text()) + family = next(f for f in catalog["families"] if f["id"] == "ieee9500") + pin = next(s for s in family["sources"] if s["repository"].endswith("/CIMHub")) + report = dict( + scope=__doc__, + source_commit=pin["commit"], + repository=pin["repository"], + bridge_sha256=hashlib.sha256(args.bridge.read_bytes()).hexdigest(), + cases={}, + ) + for variant in ("bal", "unbal"): + prefix = f"ieee9500{variant}" + record = next( + f for f in pin["files"] if f["path"].endswith(prefix + "_dss.zip") + ) + data = (args.archives / Path(record["path"]).name).read_bytes() + if ( + len(data) != record["bytes"] + or hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + != record["git_blob_sha1"] + ): + raise ValueError("archive does not match pinned source") + folder = args.output / variant + folder.mkdir() + hashes, patches = {}, [] + with zipfile.ZipFile(io.BytesIO(data)) as archive: + if sum(info.file_size for info in archive.infolist()) > 50_000_000: + raise ValueError("archive exceeds extraction limit") + for info in archive.infolist(): + relative = PurePosixPath(info.filename) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError("unsafe archive member") + if info.is_dir(): + continue + content = archive.read(info) + original, fixed = ( + folder / kind / relative for kind in ("original", "fixed") + ) + original.parent.mkdir(parents=True, exist_ok=True) + fixed.parent.mkdir(parents=True, exist_ok=True) + original.write_bytes(content) + adjusted = content + if relative.name == prefix + "_base.dss": + lines = [] + for number, line in enumerate( + content.decode("utf-8-sig").splitlines(keepends=True), 1 + ): + code = re.split(r"!|//", line)[0].strip() + if re.match( + r"(?i)^(solve|calcv|calcvoltagebases)(?:\s|$)", code + ): + lines.append("Set ControlMode=Off\n") + patches.append( + dict( + before_line=number, + original_command=code, + insertion="Set ControlMode=Off", + ) + ) + lines.append(line) + adjusted = "".join(lines).encode() + fixed.write_bytes(adjusted) + hashes[str(relative)] = dict( + bytes=len(content), + original_sha256=hashlib.sha256(content).hexdigest(), + profile_sha256=hashlib.sha256(adjusted).hexdigest(), + ) + if not patches: + raise ValueError("archive master has no recognized calculation") + row = evaluate( + (folder / "fixed/dss" / (prefix + "_base.dss")).resolve(), + args.bridge.resolve(), + folder.resolve(), + 1e-11, + (folder / "fixed").resolve(), + ) + row.update(archive=record, files=hashes, profile_patches=patches) + report["cases"][variant] = row + print(variant, "PASS" if row["passed"] else "FAIL", row["stage"], flush=True) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + report["passed"] = all(row["passed"] for row in report["cases"].values()) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/ieee9500_spacing_oracle.py b/evals/gridlabd/ieee9500_spacing_oracle.py new file mode 100644 index 000000000..f1042bd29 --- /dev/null +++ b/evals/gridlabd/ieee9500_spacing_oracle.py @@ -0,0 +1,104 @@ +"""Pinned IEEE9500 direct-spacing definitions in controlled unbalanced circuits. + +These selected line probes do not qualify the complete feeder. +""" + +import argparse +import hashlib +import json +import re +from pathlib import Path + +from ieee4_import_oracle import evaluate +from oracle import HERE + + +def blocks(text): + lines = text.splitlines(keepends=True) + starts = [i for i, line in enumerate(lines) if re.match(r"(?i)^new\s", line)] + for a, b in zip(starts, [*starts[1:], len(lines)], strict=True): + yield a + 1, "".join(lines[a:b]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--master", required=True, type=Path) + parser.add_argument("--bridge", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + catalog = json.loads((HERE / "ieee-corpus.json").read_text()) + family = next(f for f in catalog["families"] if f["id"] == "ieee9500") + pin = next( + s for s in family["sources"] if s["repository"].endswith("/electricdss-tst") + ) + record = next(f for f in pin["files"] if f["path"].endswith("ieee9500_base.dss")) + data = args.master.read_bytes() + if ( + len(data) != record["bytes"] + or hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + != record["git_blob_sha1"] + ): + raise ValueError("IEEE9500 master differs from source pin") + source_blocks = list(blocks(data.decode("utf-8-sig"))) + definitions = "".join( + block + for _, block in source_blocks + if re.match(r"(?i)^new (wiredata|cndata|linespacing)\.", block) + ) + selected = {} + for line, block in source_blocks: + if not re.match(r"(?i)^new line\.", block) or not re.search( + r"\bspacing=", block, re.I + ): + continue + phases = int(re.search(r"(?i)\bphases=(\d+)", block)[1]) + kind = "cn" if re.search(r"(?i)\bcncables=", block) else "overhead" + selected.setdefault((kind, phases), (line, block)) + if not selected: + raise ValueError("no direct-spacing lines found") + args.output.mkdir(parents=True, exist_ok=False) + report = dict( + scope=__doc__, + source=dict(repository=pin["repository"], commit=pin["commit"], **record), + definitions_sha256=hashlib.sha256(definitions.encode()).hexdigest(), + bridge_sha256=hashlib.sha256(args.bridge.read_bytes()).hexdigest(), + cases={}, + ) + for (kind, phases), (line, original) in selected.items(): + name = f"{kind}-{phases}ph" + folder = args.output / name + folder.mkdir() + circuit_line = re.sub(r"(?i)^(new line\.)\S+", r"\1probe", original) + nodes = re.search(r"(?i)\bbus1=\S+?\.([\d.]+)", original)[1] + circuit_line = re.sub( + r"(?i)\bbus1=\S+", "bus1=sourcebus." + nodes, circuit_line + ) + circuit_line = re.sub(r"(?i)\bbus2=\S+", "bus2=end." + nodes, circuit_line) + path = folder / "input.dss" + path.write_text( + "clear\nnew circuit.c bus1=sourcebus basekv=12.47 r1=.01 x1=.02 r0=.02 x0=.03\n" + + definitions + + circuit_line + + "\n".join( + f"new load.l{i} phases=1 bus1=end.{node}.0 kv=7.199557856794634 kw={40 + 15 * i} kvar={20 + 5 * i}" + for i, node in enumerate(nodes.split(".")) + if node != "0" + ) + + "\nset controlmode=off tolerance=1e-11 maxiterations=1000\nsolve\n" + ) + row = evaluate(path.resolve(), args.bridge.resolve(), folder.resolve(), 1e-11) + row.update( + source_line=line, + original_line_block=original, + profile_sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + ) + report["cases"][name] = row + print(name, "PASS" if row["passed"] else "FAIL", row["stage"], flush=True) + report["passed"] = all(row["passed"] for row in report["cases"].values()) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if not report["passed"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/ieee_distribution_import_oracle.py b/evals/gridlabd/ieee_distribution_import_oracle.py new file mode 100644 index 000000000..34d9aada0 --- /dev/null +++ b/evals/gridlabd/ieee_distribution_import_oracle.py @@ -0,0 +1,140 @@ +"""Public IEEE13/34/37/123/9500 and North American LV DSS feeders at their written, fixed device states. + +Every solve and voltage-base calculation in the selected entry files is +preceded by ControlMode=Off. Original bytes are pinned and retained separately; +this is an explicit static profile, not a claim about active regulator results. +""" + +import argparse +import hashlib +import json +import re +from pathlib import Path + +from ieee4_import_oracle import evaluate +from oracle import HERE + +PREFIX = "Version8/Distrib/IEEETestCases/" +CASES = { + "ieee13": "13Bus/IEEE13Nodeckt.dss", + "ieee34_mod1": "34Bus/ieee34Mod1.dss", + "ieee34_mod2": "34Bus/ieee34Mod2.dss", + "ieee37": "37Bus/ieee37.dss", + "ieee123": "123Bus/IEEE123Master.dss", + "ieee123_switches": "123Bus/IEEE123Switches.dss", + "ieee9500": "ieee9500dss/ieee9500_base.dss", + "north_american": "LVTestCaseNorthAmerican/Master.dss", + "north_american_secpar": "LVTestCaseNorthAmerican/SecPar.dss", +} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--source-root", + type=Path, + required=True, + help="pinned electricdss-tst checkout", + ) + parser.add_argument("--bridge", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + catalog = json.loads((HERE / "ieee-corpus.json").read_text()) + records = {} + commits = set() + for family in catalog["families"]: + if family["id"] not in ( + "ieee13", + "ieee34", + "ieee37", + "ieee123", + "north_american_lv_network", + "ieee9500", + ): + continue + for pin in family["sources"]: + if not pin["repository"].endswith("/electricdss-tst"): + continue + commits.add(pin["commit"]) + for record in pin["files"]: + if record["path"] in records and records[record["path"]] != record: + raise ValueError("inconsistent source pins") + records[record["path"]] = record + if len(commits) != 1: + raise ValueError("expected one pinned source revision") + original = args.output / "original" + fixed = args.output / "fixed" + patches = {} + hashes = {} + for relative, record in records.items(): + data = (args.source_root / relative).read_bytes() + if ( + len(data) != record["bytes"] + or hashlib.sha1(f"blob {len(data)}\0".encode() + data).hexdigest() + != record["git_blob_sha1"] + ): + raise ValueError(f"source pin mismatch: {relative}") + a, b = original / relative, fixed / relative + a.parent.mkdir(parents=True, exist_ok=True) + b.parent.mkdir(parents=True, exist_ok=True) + a.write_bytes(data) + adjusted = data + if relative in {PREFIX + value for value in CASES.values()}: + lines = data.decode("utf-8-sig").splitlines(keepends=True) + result = [] + edits = [] + for number, line in enumerate(lines, 1): + code = re.split(r"!|//", line)[0].strip() + if re.match(r"(?i)^(solve|calcv|calcvoltagebases)(?:\s|$)", code): + result.append("Set ControlMode=Off\n") + edits.append( + dict( + before_line=number, + original_command=code, + insertion="Set ControlMode=Off", + ) + ) + result.append(line) + if not edits: + raise ValueError( + f"selected feeder has no recognized calculation: {relative}" + ) + adjusted = "".join(result).encode() + patches[relative] = edits + b.write_bytes(adjusted) + hashes[relative] = dict( + record, + original_sha256=hashlib.sha256(data).hexdigest(), + profile_sha256=hashlib.sha256(adjusted).hexdigest(), + ) + report = dict( + scope=__doc__, + source_commit=commits.pop(), + files=hashes, + profile_patches=patches, + bridge_sha256=hashlib.sha256(args.bridge.read_bytes()).hexdigest(), + cases={}, + ) + for name, relative in CASES.items(): + folder = args.output / name + folder.mkdir() + row = evaluate( + (fixed / PREFIX / relative).resolve(), + args.bridge.resolve(), + folder.resolve(), + 1e-11, + fixed.resolve(), + ) + row["entry"] = PREFIX + relative + report["cases"][name] = row + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(name, "PASS" if row["passed"] else "FAIL", row["stage"], flush=True) + report["qualified_cases"] = sum(v["passed"] for v in report["cases"].values()) + report["passed"] = all(v["passed"] for v in report["cases"].values()) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(f"Qualified {report['qualified_cases']}/{len(CASES)} fixed-state cases.") + + +if __name__ == "__main__": + main() diff --git a/evals/gridlabd/load_voltage_oracle.py b/evals/gridlabd/load_voltage_oracle.py index 72850e82a..f37cbbe67 100644 --- a/evals/gridlabd/load_voltage_oracle.py +++ b/evals/gridlabd/load_voltage_oracle.py @@ -44,6 +44,10 @@ def main(): models = { "power": "model=1", "current": "model=5", + "motor": "model=3", + "cvr": "model=4", + "cvr_fractional": "model=4 cvrwatts=.7 cvrvars=1.8", + "cvr_negative": "model=4 cvrwatts=-.5 cvrvars=3", "impedance": "model=2", "zip": "model=8 zipv=[.2 .3 .5 .1 .4 .5 0]", "dropout": "model=8 zipv=[0 0 1 0 0 1 .8]", @@ -64,17 +68,24 @@ def main(): ) ir = case / "input.pio.json" canonical = case / "canonical.dss" + repeated_ir = case / "reimported.pio.json" + repeated = case / "reimported.dss" for command in ( ["serialize", str(source), "-o", str(ir)], ["convert", str(ir), "--to", "opendss", "-o", str(canonical)], + ["serialize", str(canonical), "-o", str(repeated_ir)], + ["convert", str(repeated_ir), "--to", "opendss", "-o", str(repeated)], ): run = subprocess.run( [str(cli), *command], text=True, capture_output=True, check=False ) - (case / f"{command[0]}.log").write_text(run.stdout + run.stderr) + (case / f"{Path(command[-1]).name}.log").write_text( + run.stdout + run.stderr + ) run.check_returncode() original = snapshot(source) actual = snapshot(canonical) + reimported = snapshot(repeated) # Same voltage/current/power thresholds as the established engine # microcase suite. No angle alignment or magnitude-only comparison. absolute = dict(voltage=1e-6, current=1e-7, power=1e-4) @@ -82,8 +93,13 @@ def main(): key: abs(complex(*original[key]) - complex(*actual[key])) for key in original } + repeat_errors = { + key: abs(complex(*original[key]) - complex(*reimported[key])) + for key in original + } passed = all( - errors[key] <= absolute[key] + 1e-9 * abs(complex(*original[key])) + max(errors[key], repeat_errors[key]) + <= absolute[key] + 1e-9 * abs(complex(*original[key])) for key in original ) cases.append( @@ -93,12 +109,14 @@ def main(): input_sha256=hashlib.sha256(source.read_bytes()).hexdigest(), original=original, canonical=actual, + reimported=reimported, + reimported_errors=repeat_errors, errors=errors, passed=passed, ) ) report = dict( - scope="Models 1, 2, 5, 8; explicit static state; public IR and canonical DSS", + scope="Models 1, 2, 3, 4, 5, 8; explicit static state; public IR and canonical DSS", version=dss.Basic.Version(), cli_sha256=hashlib.sha256(cli.read_bytes()).hexdigest(), cases=cases, diff --git a/powerio-capi/src/lib.rs b/powerio-capi/src/lib.rs index f971b5e36..b2a9e67e6 100644 --- a/powerio-capi/src/lib.rs +++ b/powerio-capi/src/lib.rs @@ -8185,7 +8185,11 @@ pub unsafe extern "C" fn pio_calculation_instance_initial_point( fn require_legacy_load_voltage_model( model: &powerio_dist::DistLoadVoltageModel, ) -> Result<(), *mut PioError> { - if matches!(model, powerio_dist::DistLoadVoltageModel::BoundedZip { .. }) { + if matches!( + model, + powerio_dist::DistLoadVoltageModel::BoundedZip { .. } + | powerio_dist::DistLoadVoltageModel::BoundedExponential { .. } + ) { return Err(boundary_error( &codes::REQUEST_CAPI_TYPE_MISMATCH, "legacy load view cannot describe voltage-band transitions or dropout", @@ -21245,7 +21249,13 @@ mod tests { #[test] fn legacy_load_views_refuse_unrepresented_voltage_bands() { - let source = powerio_core::Source::from_memory("load.dss", b"New Circuit.c phases=1 bus1=b.1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model=1\n".to_vec()).unwrap(); + for model in [1, 3, 4] { + check_legacy_load_voltage_refusal(model); + } + } + + fn check_legacy_load_voltage_refusal(model: u8) { + let source = powerio_core::Source::from_memory("load.dss", format!("New Circuit.c phases=1 bus1=b.1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model={model}\n").into_bytes()).unwrap(); let parsed = powerio_dist::parse(source).unwrap(); let pf = powerio_prob::McAcPfInstance::from_network(parsed.value().clone()).unwrap(); unsafe { diff --git a/powerio-dist/examples/bmopf/README.md b/powerio-dist/examples/bmopf/README.md index 7de850e64..3663c3a06 100644 --- a/powerio-dist/examples/bmopf/README.md +++ b/powerio-dist/examples/bmopf/README.md @@ -7,7 +7,7 @@ rather than editing by hand. | Case | Source `.dss` | Size | Write diagnostics | |---|---|---|---| -| IEEE 34 | `tests/data/dist/opendss/ieee34/ieee34Mod1.dss` (vendored) | 99,676 bytes | 102 | +| IEEE 34 | `tests/data/dist/opendss/ieee34/ieee34Mod1.dss` (vendored) | 99,830 bytes | 104 | | IEEE 123 | `tests/data/dist/opendss/ieee123/IEEE123Master.dss` (vendored) | 247,716 bytes | 143 | | 4 bus delta wye | `4Bus-DY-Bal/4Bus-DY-Bal.DSS` from the OpenDSS distribution | 15,976 bytes | 0 | diff --git a/powerio-dist/examples/bmopf/ieee34.json b/powerio-dist/examples/bmopf/ieee34.json index 2e89827ab..d2dd4b732 100644 --- a/powerio-dist/examples/bmopf/ieee34.json +++ b/powerio-dist/examples/bmopf/ieee34.json @@ -2596,7 +2596,13 @@ "D808_810rb": { "bus": "810", "configuration": "SINGLE_PHASE", - "model": "CONSTANT_POWER", + "gamma_p": [ + 1.0 + ], + "gamma_q": [ + 2.0 + ], + "model": "EXPONENTIAL", "p_nom": [ 8000.0 ], @@ -2614,7 +2620,13 @@ "D808_810sb": { "bus": "808", "configuration": "SINGLE_PHASE", - "model": "CONSTANT_POWER", + "gamma_p": [ + 1.0 + ], + "gamma_q": [ + 2.0 + ], + "model": "EXPONENTIAL", "p_nom": [ 8000.0 ], diff --git a/powerio-dist/src/bmopf/write.rs b/powerio-dist/src/bmopf/write.rs index e827c50fd..c802ae6bc 100644 --- a/powerio-dist/src/bmopf/write.rs +++ b/powerio-dist/src/bmopf/write.rs @@ -1143,7 +1143,8 @@ impl Writer { what: &str, ) { match model { - DistLoadVoltageModel::BoundedZip { .. } => { + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } => { self.warn(&C::EMIT_BMOPF_VALUE_SUBSTITUTED, format!("{what}: voltage-band transitions and dropout have no BMOPF load-law field; emitted the nominal law")); self.load_voltage_model(o, &model.without_voltage_bounds(), what); } diff --git a/powerio-dist/src/diagnostics.rs b/powerio-dist/src/diagnostics.rs index 1055fd679..9097cb77d 100644 --- a/powerio-dist/src/diagnostics.rs +++ b/powerio-dist/src/diagnostics.rs @@ -139,6 +139,8 @@ pub mod codes { "a disabled source is retained without electrical contributions"; READ_DSS_SOURCE_UNRESOLVED = "READ.DSS.SOURCE_UNRESOLVED", Error, "a voltage source is invalid or outside the qualified static profile", category = Data; + READ_DSS_TRANSFORMER_UNRESOLVED = "READ.DSS.TRANSFORMER_UNRESOLVED", Error, + "a transformer definition could not be resolved into the static electrical snapshot"; READ_DSS_LINE_UNRESOLVED = "READ.DSS.LINE_UNRESOLVED", Error, "a line is invalid or outside the qualified static electrical profile", category = Data; READ_DSS_PROPERTY_UNKNOWN = "READ.DSS.PROPERTY_UNKNOWN", Warning, diff --git a/powerio-dist/src/dss/frequency.rs b/powerio-dist/src/dss/frequency.rs index 919769311..48507330f 100644 --- a/powerio-dist/src/dss/frequency.rs +++ b/powerio-dist/src/dss/frequency.rs @@ -6,8 +6,8 @@ use super::lex::{Value, VarMap}; -// Native option order through the final frequency-setting option. Later -// options cannot advance positionally back into one of these three slots. +// Native option order through the last state-setting option interpreted here. +// Later options cannot advance positionally back into these slots. const OPTIONS: &[&str] = &[ "type", "element", @@ -82,6 +82,14 @@ const OPTIONS: &[&str] = &[ "showexport", "numallociterations", "defaultbasefrequency", + "markswitches", + "switchmarkercode", + "daisysize", + "marktransformers", + "transmarkercode", + "transmarkersize", + "loadshapeclass", + "earthmodel", ]; pub(super) fn option_position(name: &str) -> usize { diff --git a/powerio-dist/src/dss/geometry/cache.rs b/powerio-dist/src/dss/geometry/cache.rs new file mode 100644 index 000000000..f9f1b97ed --- /dev/null +++ b/powerio-dist/src/dss/geometry/cache.rs @@ -0,0 +1,192 @@ +//! Shared native geometry calculation state; line caches are separate. +use super::{EarthModel, Geometry, definition, wire}; +use crate::dss::{line_history::Snapshot, linecode::LineMatrices, raw::RawDss}; +use std::collections::BTreeMap; + +#[derive(Debug)] +struct Entry { + point: Snapshot, + allocated: usize, + cable_allocations: usize, + dirty: bool, + rho: f64, + rho_changed: bool, + input: Option, + matrices: Option<(f64, LineMatrices)>, +} + +pub(in crate::dss) struct Context<'a> { + raw: &'a RawDss, + visible: BTreeMap, + entries: BTreeMap, + pub active_earth: Result, +} + +impl<'a> Context<'a> { + pub fn new(raw: &'a RawDss) -> Self { + Self { + raw, + visible: BTreeMap::new(), + entries: BTreeMap::new(), + active_earth: raw.geometry_earth.clone().unwrap_or(Ok(EarthModel::Deri)), + } + } + + pub fn observe(&mut self, point: Snapshot, key: Option<&str>) -> Result<(), String> { + self.visible.insert(point.object, point); + if self.raw.objects[point.object].class != "linegeometry" { + return Ok(()); + } + let entry = self.entries.entry(point.object).or_insert_with(|| Entry { + point, + allocated: 0, + cable_allocations: 0, + dirty: true, + rho: 100.0, + rho_changed: true, + input: None, + matrices: None, + }); + entry.point = point; + if matches!(key, Some("nconds" | "like" | "cncable" | "cncables")) { + let definition = definition::resolve(self.raw, point)?; + if definition.cable_allocations != entry.cable_allocations { + entry.cable_allocations = definition.cable_allocations; + entry.input = None; + entry.matrices = None; + } + if definition.conductors.len() != entry.allocated { + entry.allocated = definition.conductors.len(); + entry.rho = 100.0; + entry.input = None; + entry.matrices = None; + entry.rho_changed = true; + } + } + if key == Some("nphases") + && let Some(input) = &mut entry.input + { + // Native changes the cable phase count immediately, but does not + // invalidate a matrix already calculated at this frequency. + input.phases = definition::resolve(self.raw, point)? + .phases + .min(input.wires.len()); + } + if matches!( + key, + Some( + "nconds" + | "wire" + | "x" + | "h" + | "units" + | "spacing" + | "wires" + | "cncable" + | "tscable" + | "cncables" + | "tscables" + | "like" + ) + ) { + entry.dirty = true; + } + Ok(()) + } + + pub fn spacing(&self, object: usize) -> Result { + let point = self + .visible + .get(&object) + .ok_or("LineSpacing is not visible")?; + super::spacing::resolve_with_budget(self.raw, *point, &mut (1_usize << 22)) + } + + pub fn conductor(&self, object: usize) -> Result { + let point = self + .visible + .get(&object) + .ok_or("conductor is not visible")?; + wire::resolve_with_budget(self.raw, *point, &mut (1_usize << 22)) + } + + pub fn definition(&self, object: usize) -> Result { + let point = self + .entries + .get(&object) + .ok_or("LineGeometry did not exist at assignment")? + .point; + definition::resolve(self.raw, point) + } + + pub fn set_rho(&mut self, object: usize, rho: f64) -> Result<(), String> { + let entry = self + .entries + .get_mut(&object) + .ok_or("missing geometry cache")?; + if !rho.is_finite() || rho <= 0.0 { + return Err("geometry earth resistivity must be positive finite".into()); + } + entry.rho_changed |= entry.rho.to_bits() != rho.to_bits(); + entry.rho = rho; + Ok(()) + } + + pub fn calculate(&mut self, object: usize, frequency: f64) -> Result { + let entry = self + .entries + .get_mut(&object) + .ok_or("missing geometry cache")?; + if entry.dirty { + let definition = definition::resolve(self.raw, entry.point)?; + let mut input = definition.materialize( + self.raw, + self.active_earth.clone()?, + entry.rho, + |object| self.visible[&object], + )?; + let n = input.wires.len(); + // Calc retains any previous Kron order. Reduce can replace that + // order, but turning Reduce off does not discard a cached reduction. + let old_keep = entry + .matrices + .as_ref() + .map(|(_, m)| m.r.len()) + .filter(|&keep| keep < n); + let keep = if definition.reduce && definition.phases > 0 && definition.phases < n { + Some(definition.phases) + } else { + old_keep + }; + input.reduction_order = keep; + entry.input = Some(input); + } + if entry.dirty + || entry.rho_changed + || entry + .matrices + .as_ref() + .is_none_or(|(f, _)| f.to_bits() != frequency.to_bits()) + { + let input = entry + .input + .as_mut() + .ok_or("geometry has no calculated conductor data")?; + input.rho = entry.rho; + input.earth_model = self.active_earth.clone()?; + entry.matrices = Some((frequency, input.calculate(frequency)?)); + entry.dirty = false; + entry.rho_changed = false; + } + Ok(entry.matrices.as_ref().unwrap().1.clone()) + } + + pub fn scale(matrix: &mut LineMatrices, length: f64, units: usize) { + let factor = length * wire::meters(units); + for values in [&mut matrix.r, &mut matrix.x, &mut matrix.b] { + for value in values.iter_mut().flatten() { + *value *= factor; + } + } + } +} diff --git a/powerio-dist/src/dss/geometry/cn.rs b/powerio-dist/src/dss/geometry/cn.rs new file mode 100644 index 000000000..10a6d770a --- /dev/null +++ b/powerio-dist/src/dss/geometry/cn.rs @@ -0,0 +1,255 @@ +//! Concentric-neutral cable constants, matching the pinned DSS CNLineConstants. +use super::{EPSILON_0, EarthModel, Geometry, MU_0, TWO_PI, bessel_ratio, wire::meters}; +use crate::dss::linecode::LineMatrices; +use num_complex::Complex64 as Complex; +use serde::{Deserialize, Serialize}; +use std::f64::consts::PI; + +/// Native definition values; `si` converts the lengths and resistance once. +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +pub(in crate::dss) struct Data { + pub k: usize, + pub diastrand: f64, + pub gmrstrand: f64, + pub rstrand: f64, + pub epsr: f64, + pub inslayer: f64, + pub diains: f64, + pub diacable: f64, +} + +impl Default for Data { + fn default() -> Self { + Self { + k: 2, + diastrand: -1.0, + gmrstrand: -1.0, + rstrand: -1.0, + epsr: 2.3, + inslayer: -1.0, + diains: -1.0, + diacable: -1.0, + } + } +} + +impl Data { + pub fn apply(&mut self, key: &str, value: f64) -> Result<(), String> { + match key { + "k" => { + if value.fract() != 0.0 || !(2.0..=f64::from(i32::MAX)).contains(&value) { + return Err("CNData needs at least two neutral strands".into()); + } + self.k = value as usize; + } + "diastrand" => { + self.diastrand = value; + // This default remains in GMRUnits, even when RadiusUnits differ. + if self.gmrstrand <= 0.0 { + self.gmrstrand = 0.7788 * 0.5 * value; + } + } + "gmrstrand" => self.gmrstrand = value, + "rstrand" => self.rstrand = value, + "epsr" => self.epsr = value, + "inslayer" => self.inslayer = value, + "diains" => self.diains = value, + "diacable" => self.diacable = value, + _ => return Err(format!("unqualified CNData property {key}")), + } + if value <= 0.0 || (key == "epsr" && value < 1.0) { + return Err(format!("invalid CNData {key}")); + } + Ok(()) + } + + pub fn si(mut self, radius_units: usize, gmr_units: usize, resistance_units: usize) -> Self { + let length = meters(radius_units); + self.diastrand *= length; + self.inslayer *= length; + self.diains *= length; + self.diacable *= length; + self.gmrstrand *= meters(gmr_units); + self.rstrand /= meters(resistance_units); + self + } + + fn validate(self) -> Result<(), String> { + if self.k < 2 + || self.epsr < 1.0 + || [ + self.diastrand, + self.gmrstrand, + self.rstrand, + self.epsr, + self.inslayer, + self.diains, + self.diacable, + ] + .iter() + .any(|v| !v.is_finite() || *v <= 0.0) + || self.diains <= 2.0 * self.inslayer + || self.diacable <= self.diastrand + { + return Err("invalid or incomplete concentric-neutral cable data".into()); + } + Ok(()) + } +} + +fn validate(input: &Geometry, frequency: f64) -> Result<(), String> { + let n = input.wires.len(); + if n == 0 + || n > 32 + || input.phases == 0 + || input.phases > n + || !frequency.is_finite() + || frequency <= 0.0 + || !input.rho.is_finite() + || input.rho <= 0.0 + { + return Err( + "invalid concentric-neutral geometry dimensions, frequency or resistivity".into(), + ); + } + for (i, wire) in input.wires.iter().enumerate() { + if !wire.x.is_finite() + || !wire.height.is_finite() + || [wire.radius, wire.gmr, wire.rdc, wire.rac] + .iter() + .any(|v| !v.is_finite() || *v <= 0.0) + { + return Err("invalid concentric-neutral geometry conductor data".into()); + } + // The native CN model adds one neutral ring for every phase position. + // Bare conductors are supported only in the trailing neutral positions. + if (i < input.phases) != wire.cable.is_some() { + return Err( + "CN geometry requires cables in all phase positions and bare trailing neutrals" + .into(), + ); + } + if let Some(cable) = wire.cable { + cable.validate()?; + } + for (j, other) in input.wires[..i].iter().enumerate() { + let radius = if i < input.phases { wire.radius } else { 0.0 }; + let other_radius = if j < input.phases { other.radius } else { 0.0 }; + if (wire.x - other.x).hypot(wire.height - other.height) < radius + other_radius { + return Err("cable conductors occupy the same space".into()); + } + } + } + Ok(()) +} + +fn internal(input: &Geometry, i: usize, frequency: f64) -> Complex { + let wire = &input.wires[i]; + match input.earth_model { + EarthModel::Carson | EarthModel::FullCarson => { + Complex::new(wire.rac, TWO_PI * frequency * MU_0 / (8.0 * PI)) + } + EarthModel::Deri => { + let alpha = Complex::new(1.0, 1.0) * (frequency * MU_0 / wire.rdc).sqrt(); + Complex::new(1.0, 1.0) * bessel_ratio(alpha) * (wire.rdc * frequency * MU_0).sqrt() + / 2.0 + } + } +} + +pub(super) fn calculate(input: &Geometry, frequency: f64) -> Result { + validate(input, frequency)?; + let n = input.wires.len(); + let phases = input.phases; + let order = n + phases; + let factor = Complex::new(0.0, TWO_PI * frequency * MU_0 / TWO_PI); + let mut z = vec![vec![Complex::default(); order]; order]; + for (i, wire) in input.wires.iter().enumerate() { + let mut zi = internal(input, i, frequency); + let radius = if frequency > 40.0 && frequency < 1000.0 { + zi.im = 0.0; + wire.gmr + } else { + wire.radius + }; + z[i][i] = zi + factor * (1.0 / radius).ln() + input.earth(i, i, frequency); + for (j, other) in input.wires.iter().enumerate().take(i) { + let distance = (wire.x - other.x).hypot(wire.height - other.height); + z[i][j] = factor * (1.0 / distance).ln() + input.earth(i, j, frequency); + z[j][i] = z[i][j]; + } + } + for i in 0..phases { + let wire = &input.wires[i]; + let cable = wire.cable.unwrap(); + let k = cable.k as f64; + let radius = 0.5 * (cable.diacable - cable.diastrand); + let gmr = (cable.gmrstrand * k * radius.powf(k - 1.0)).powf(1.0 / k); + let index = n + i; + z[index][index] = + cable.rstrand / k + factor * (1.0 / gmr).ln() + input.earth(i, i, frequency); + for (j, other) in input.wires.iter().enumerate().take(i) { + let distance = (wire.x - other.x).hypot(wire.height - other.height); + z[index][n + j] = factor * (1.0 / distance).ln() + input.earth(i, j, frequency); + z[n + j][index] = z[index][n + j]; + } + for (j, other) in input.wires.iter().enumerate() { + let distance = if i == j { + radius + } else { + let d = (wire.x - other.x).hypot(wire.height - other.height); + (d.powf(k) - radius.powf(k)).powf(1.0 / k) + }; + z[index][j] = factor * (1.0 / distance).ln() + input.earth(i, j, frequency); + z[j][index] = z[index][j]; + } + } + let keep = input + .reduction_order + .unwrap_or(if input.reduce { phases } else { n }); + if keep == 0 || keep > n { + return Err("invalid cable reduction order".into()); + } + // Concentric neutrals are always eliminated, before optional bare neutrals. + for k in (keep..order).rev() { + if z[k][k] == Complex::default() { + return Err("cable reduction has a zero pivot".into()); + } + for i in 0..k { + for j in 0..k { + let correction = z[i][k] * z[k][j] / z[k][k]; + z[i][j] -= correction; + } + } + } + let mut b = vec![vec![0.0; keep]; keep]; + for (i, row) in b.iter_mut().enumerate().take(phases) { + let cable = input.wires[i].cable.unwrap(); + let outer = 0.5 * cable.diains; + let inner = outer - cable.inslayer; + row[i] = TWO_PI * EPSILON_0 * cable.epsr * (TWO_PI * frequency) / (outer / inner).ln(); + } + let result = LineMatrices { + r: z.iter() + .take(keep) + .map(|row| row.iter().take(keep).map(|v| v.re).collect()) + .collect(), + x: z.iter() + .take(keep) + .map(|row| row.iter().take(keep).map(|v| v.im).collect()) + .collect(), + b, + }; + if [&result.r, &result.x, &result.b] + .into_iter() + .flatten() + .flatten() + .any(|v| !v.is_finite()) + { + return Err("cable calculation became nonfinite".into()); + } + Ok(result) +} + +#[cfg(test)] +mod tests; diff --git a/powerio-dist/src/dss/geometry/cn/tests.rs b/powerio-dist/src/dss/geometry/cn/tests.rs new file mode 100644 index 000000000..ab3054b34 --- /dev/null +++ b/powerio-dist/src/dss/geometry/cn/tests.rs @@ -0,0 +1,96 @@ +use super::*; + +fn geometry() -> Geometry { + Geometry { + wires: (0..4) + .map(|i| { + let j = f64::from(i); + super::super::Wire { + x: j * 0.1, + height: -1.0 - 0.05 * f64::from(i % 2), + radius: 0.008 + j * 0.0005, + capacitance_radius: 0.01 + j * 0.0005, + gmr: 0.006 + j * 0.0003, + rdc: 0.0002 * (1.0 + j / 5.0), + rac: 0.00021 * (1.0 + j / 5.0), + cable: (i < 3).then_some(Data { + k: (13 + i) as usize, + diastrand: 0.0015, + gmrstrand: 0.0006, + rstrand: 0.0008, + epsr: 2.3 + j * 0.1, + inslayer: 0.004, + diains: 0.026, + diacable: 0.031, + }), + } + }) + .collect(), + phases: 3, + reduce: true, + reduction_order: None, + earth_model: EarthModel::Carson, + rho: 37.0, + } +} + +#[test] +fn cable_and_bare_neutral_reduction_matches_pinned_native_values() { + // DSS C-API 87d85c2, dss_cn_geometry_oracle.py carson-60.0-4-3-True. + let matrices = calculate(&geometry(), 60.0).unwrap(); + let r = [ + 0.000_265_503_608_882_421_4, + 3.519_501_778_096_733e-6, + 6.498_786_398_968_169e-7, + 3.519_501_778_096_733e-6, + 0.000_302_151_139_117_561_83, + 2.374_709_548_094_71e-6, + 6.498_786_398_968_169e-7, + 2.374_709_548_094_71e-6, + 0.000_341_845_252_252_206_93, + ]; + let x = [ + 8.428_299_081_358_696e-5, + -5.959_678_010_096_394e-6, + -3.215_202_146_906_68e-6, + -5.959_678_010_096_394e-6, + 8.041_560_706_820_995e-5, + -5.162_644_883_651_848e-6, + -3.215_202_146_906_68e-6, + -5.162_644_883_651_848e-6, + 7.349_568_921_535_918e-5, + ]; + for (actual, expected) in matrices + .r + .iter() + .flatten() + .zip(r) + .chain(matrices.x.iter().flatten().zip(x)) + { + assert!((actual - expected).abs() < 1e-15); + } + assert!((matrices.b[0][0] - 1.311_763_202_020_904_5e-7).abs() < 1e-17); + assert_eq!(matrices.b[0][1].to_bits(), 0.0_f64.to_bits()); + let mut unreduced = geometry(); + unreduced.reduce = false; + let matrices = calculate(&unreduced, 60.0).unwrap(); + assert_eq!(matrices.r.len(), 4); + assert_eq!(matrices.b[3], vec![0.0; 4]); +} + +#[test] +fn incomplete_and_mixed_phase_cables_are_explicitly_refused() { + let mut input = geometry(); + input.wires[0].cable.as_mut().unwrap().diains = 0.001; + assert!(calculate(&input, 60.0).unwrap_err().contains("incomplete")); + input = geometry(); + input.wires[0].cable = None; + assert!( + calculate(&input, 60.0) + .unwrap_err() + .contains("all phase positions") + ); + input = geometry(); + input.wires[0].height = f64::NAN; + assert!(calculate(&input, 60.0).is_err()); +} diff --git a/powerio-dist/src/dss/geometry/definition.rs b/powerio-dist/src/dss/geometry/definition.rs new file mode 100644 index 000000000..c3ab5bbee --- /dev/null +++ b/powerio-dist/src/dss/geometry/definition.rs @@ -0,0 +1,368 @@ +//! Ordered LineGeometry definitions, retaining live conductor identities. +use super::{EarthModel, Geometry, wire}; +use crate::dss::{ + line_history::Snapshot, + raw::{RawDss, RawProp}, +}; +use std::collections::{HashMap, HashSet}; + +#[derive(Clone, Debug, serde::Serialize)] +pub(in crate::dss) struct Conductor { + pub wire: Option, + pub x: f64, + pub height: f64, + // Native -1 means not assigned. Selecting the conductor replaces it + // with the last assigned unit, initially feet. + pub units: Option, +} + +#[derive(Clone, Debug)] +pub(in crate::dss) struct Definition { + pub conductors: Vec, + pub phases: usize, + pub reduce: bool, + pub normamps: f64, + pub emergamps: f64, + pub cable_allocations: usize, + cn_choices: Vec, + active: usize, + last_unit: usize, +} + +impl Default for Definition { + fn default() -> Self { + Self { + conductors: Vec::new(), + phases: 0, + reduce: false, + normamps: 0.0, + emergamps: 0.0, + cable_allocations: 0, + cn_choices: Vec::new(), + active: 0, + last_unit: 5, + } + } +} + +impl Definition { + fn resize(&mut self, n: usize) { + if self.cn_choices.iter().any(|v| *v) { + self.cable_allocations += 1; + } + self.cn_choices = vec![false; n]; + self.conductors = vec![ + Conductor { + wire: None, + x: 0.0, + height: 0.0, + units: None + }; + n + ]; + self.active = 0; + self.last_unit = 5; + } + + fn copy(&mut self, source: &Self) { + // NConds resets both selection fields even when the size is equal. + self.resize(source.conductors.len()); + self.conductors.clone_from(&source.conductors); + self.phases = source.phases; + self.reduce = source.reduce; + self.normamps = source.normamps; + self.emergamps = source.emergamps; + } + + fn bind( + &mut self, + index: usize, + point: Snapshot, + raw: &RawDss, + budget: &mut usize, + ) -> Result<(), String> { + self.conductors + .get_mut(index) + .ok_or("invalid geometry conductor selector")? + .wire = Some(point.object); + // Native copies ratings from the conductor's state NOW, while the + // eventual matrix calculation reads the live conductor object. + if index == 0 { + let source = wire::resolve_with_budget(raw, point, budget)?; + if self.normamps == 0.0 && source.normamps > 0.0 { + self.normamps = source.normamps; + } + if self.emergamps == 0.0 && source.emergamps > 0.0 { + self.emergamps = source.emergamps; + } + } + Ok(()) + } + + fn bind_property( + &mut self, + raw: &RawDss, + object: usize, + offset: usize, + key: &str, + budget: &mut usize, + ) -> Result<(), String> { + let refs = raw.line_history[&object] + .wires + .get(&offset) + .ok_or("missing WireData binding")?; + let single = matches!(key, "wire" | "cncable"); + if key == "wire" && self.cn_choices.get(self.active) == Some(&true) { + return Err("replacing a CN cable with a bare phase wire is unqualified".into()); + } + let start = if single { + self.active + } else if key == "wires" && self.cn_choices.get(self.active) == Some(&true) { + self.phases + } else { + 0 + }; + let count = if single { + 1 + } else if key == "cncables" { + self.phases + } else { + self.conductors.len().saturating_sub(start) + }; + if refs.len() != count || count == 0 { + return Err("geometry wire array has wrong length".into()); + } + for (index, point) in refs.iter().enumerate() { + self.bind( + start + index, + point.ok_or("WireData did not exist at assignment")?, + raw, + budget, + )?; + } + if key == "wires" { + self.active = start + count - 1; + } else if key.starts_with("cn") { + let choice = self + .cn_choices + .get_mut(self.active) + .ok_or("invalid CN selector")?; + if !*choice { + self.cable_allocations += 1; + *choice = true; + } + } + Ok(()) + } + + fn apply( + &mut self, + raw: &RawDss, + object: usize, + offset: usize, + prop: &RawProp, + budget: &mut usize, + ) -> Result<(), String> { + let key = prop + .name + .as_deref() + .ok_or("unnamed LineGeometry property")?; + let number = || -> Result { + let value = prop + .value + .to_f64(Some(&raw.vars)) + .map_err(|e| e.to_string())?; + if value.is_finite() { + Ok(value) + } else { + Err(format!("nonfinite LineGeometry {key}")) + } + }; + let count = |minimum: usize| -> Result { + let value = number()?; + if value.fract() != 0.0 || !(minimum as f64..=32.0).contains(&value) { + return Err(format!("invalid LineGeometry {key}")); + } + Ok(value as usize) + }; + match key { + "nconds" => self.resize(count(1)?), + "nphases" => self.phases = count(0)?, + "cond" => { + self.active = count(1)? - 1; + self.conductors + .get_mut(self.active) + .ok_or("invalid geometry conductor selector")? + .units + .get_or_insert(self.last_unit); + } + "x" | "h" | "units" => { + let conductor = self + .conductors + .get_mut(self.active) + .ok_or("geometry has no active conductor")?; + match key { + "x" => conductor.x = number()?, + "h" => conductor.height = number()?, + _ => { + let units = crate::dss::linecode::units(&prop.value.text); + conductor.units = Some(units); + self.last_unit = units; + } + } + } + "wire" | "wires" | "cncable" | "cncables" => { + self.bind_property(raw, object, offset, key, budget)?; + } + "spacing" => { + let point = raw.line_history[&object] + .spacings + .get(&offset) + .ok_or("missing LineSpacing binding")? + .ok_or("LineSpacing did not exist at assignment")?; + let spacing = super::spacing::resolve_with_budget(raw, point, budget)?; + if spacing.x.len() != self.conductors.len() { + return Err("LineSpacing has the wrong number of conductors".into()); + } + self.last_unit = spacing.units; + for (i, conductor) in self.conductors.iter_mut().enumerate() { + if !spacing.x[i].is_finite() || !spacing.height[i].is_finite() { + return Err("LineSpacing coordinates were not initialized".into()); + } + conductor.x = spacing.x[i]; + conductor.height = spacing.height[i]; + conductor.units = Some(spacing.units); + } + // Spacing changes neither the geometry's phase count nor its selector. + } + "normamps" => self.normamps = number()?, + "emergamps" => self.emergamps = number()?, + "reduce" => self.reduce = prop.value.text.starts_with(['y', 'Y', 't', 'T']), + // These are retained metadata, not inputs to static impedance. + "seasons" | "ratings" | "linetype" => {} + _ => return Err(format!("unqualified LineGeometry property {key}")), + } + Ok(()) + } + + /// The caller chooses the WireData prefixes visible at this calculation. + /// Matrix/cache replay must not substitute final wire values for a past + /// native calculation. Definition identity and coordinates remain separate. + pub fn materialize( + &self, + raw: &RawDss, + earth_model: EarthModel, + rho: f64, + mut visible_wire: impl FnMut(usize) -> Snapshot, + ) -> Result { + let mut budget = 1_usize << 22; + let wires = self + .conductors + .iter() + .map(|conductor| { + let object = conductor.wire.ok_or("geometry conductor has no WireData")?; + let state = wire::resolve_with_budget(raw, visible_wire(object), &mut budget)?; + let meters = wire::meters(conductor.units.unwrap_or(0)); + Ok(state.at(conductor.x * meters, conductor.height * meters)) + }) + .collect::, String>>()?; + if self.cn_choices.iter().any(|v| *v) && !wires.iter().any(|w| w.cable.is_some()) { + return Err("replacing all CN cables with bare phase wires is unqualified".into()); + } + Ok(Geometry { + wires, + phases: self.phases, + reduce: self.reduce, + reduction_order: None, + earth_model, + rho, + }) + } +} + +pub(super) fn resolve(raw: &RawDss, point: Snapshot) -> Result { + let mut cache = HashMap::new(); + let mut visiting = HashSet::new(); + let mut pending = vec![(point, false)]; + let mut budget = 1_usize << 22; + while let Some((point, ready)) = pending.pop() { + if cache.contains_key(&point) { + continue; + } + let object = raw + .objects + .get(point.object) + .ok_or("missing LineGeometry object")?; + if object.class != "linegeometry" { + return Err("expected LineGeometry history".into()); + } + let history = raw + .line_history + .get(&point.object) + .ok_or("missing LineGeometry history")?; + let copies = history + .copies + .get(..point.copies) + .ok_or("invalid LineGeometry copy prefix")?; + budget = budget + .checked_sub(1) + .ok_or("LineGeometry evaluation work limit exceeded")?; + if ready { + let mut state = Definition::default(); + let props = object + .props + .get(..point.properties) + .ok_or("invalid LineGeometry property prefix")?; + let mut offset = 0; + for copy in copies { + if copy.source.object == point.object { + return Err( + "native LineGeometry self-copy resets its own conductor data".into(), + ); + } + for (i, prop) in props + .get(offset..copy.start) + .ok_or("invalid geometry copy span")? + .iter() + .enumerate() + { + state.apply(raw, point.object, offset + i, prop, &mut budget)?; + } + budget = budget + .checked_sub(copy.start - offset + 32) + .ok_or("LineGeometry evaluation work limit exceeded")?; + let source: &Definition = cache + .get(©.source) + .ok_or("unresolved LineGeometry copy")?; + if source.cn_choices.iter().any(|v| *v) { + return Err("pinned native engine cannot copy a CN LineGeometry".into()); + } + state.copy(source); + offset = copy.end; + } + let remaining = props.get(offset..).ok_or("invalid geometry copy span")?; + budget = budget + .checked_sub(remaining.len()) + .ok_or("LineGeometry evaluation work limit exceeded")?; + for (i, prop) in remaining.iter().enumerate() { + state.apply(raw, point.object, offset + i, prop, &mut budget)?; + } + cache.insert(point, state); + visiting.remove(&point); + } else { + if !visiting.insert(point) { + return Err("cyclic LineGeometry history".into()); + } + pending.push((point, true)); + for copy in copies.iter().rev() { + pending.push((copy.source, false)); + } + } + } + cache + .remove(&point) + .ok_or_else(|| "missing resolved LineGeometry".into()) +} + +#[cfg(test)] +mod tests; diff --git a/powerio-dist/src/dss/geometry/definition/tests.rs b/powerio-dist/src/dss/geometry/definition/tests.rs new file mode 100644 index 000000000..57a35ae9c --- /dev/null +++ b/powerio-dist/src/dss/geometry/definition/tests.rs @@ -0,0 +1,191 @@ +use super::*; +fn raw(text: &str) -> RawDss { + crate::dss::raw::__parse_raw_with(text, "geometry.dss", &mut |_: &std::path::Path| { + Err(std::io::Error::other("no includes")) + }) +} + +#[test] +fn wire_reference_is_bound_at_assignment_not_repaired_by_later_declaration() { + let raw = raw( + "New LineGeometry.g nconds=1 nphases=1 cond=1 wire=later x=0 h=10\nNew WireData.later radius=0.01 rac=0.0002\n", + ); + assert!( + resolve(&raw, raw.line_snapshot(0)) + .unwrap_err() + .contains("did not exist") + ); +} + +#[test] +fn rating_copies_and_live_wire_values_have_different_time_semantics() { + let raw = raw( + "New WireData.a radius=0.01 rac=0.0002 normamps=100\nNew LineGeometry.g nconds=1 nphases=1 cond=1 wire=a units=m x=0 h=10\nEdit WireData.a radius=0.02 rac=0.0004 normamps=200\n", + ); + let definition = resolve(&raw, raw.line_snapshot(1)).unwrap(); + assert!((definition.normamps - 100.0).abs() < 1e-12); + let geometry = definition + .materialize(&raw, EarthModel::Carson, 100.0, |object| { + raw.line_snapshot(object) + }) + .unwrap(); + assert!((geometry.wires[0].radius - 0.02).abs() < 1e-12); + assert!((geometry.wires[0].rac - 0.0004).abs() < 1e-12); + assert!((geometry.wires[0].capacitance_radius - 0.01).abs() < 1e-12); +} + +#[test] +#[ignore = "requires pinned native geometry definition observations"] +fn pinned_geometry_definitions() { + #[derive(serde::Deserialize)] + struct Matrices { + r: Vec>, + x: Vec>, + b: Vec>, + } + #[derive(serde::Deserialize)] + struct Expected { + units: Vec, + wires: Vec, + x: Vec, + height: Vec, + phases: usize, + reduce: bool, + normamps: f64, + emergamps: f64, + active: usize, + matrices: Option, + } + #[derive(serde::Deserialize)] + struct Case { + script: String, + geometries: std::collections::BTreeMap, + } + let path = std::env::var("POWERIO_GEOMETRY_DEFINITION_ORACLE").expect("native observations"); + let cases: std::collections::BTreeMap = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert!(!cases.is_empty()); + for (case, expected) in cases { + let raw = raw(&expected.script); + for (name, expected) in expected.geometries { + let index = raw + .objects + .iter() + .position(|o| o.class == "linegeometry" && o.name.eq_ignore_ascii_case(&name)) + .unwrap(); + let actual = resolve(&raw, raw.line_snapshot(index)) + .unwrap_or_else(|e| panic!("{case}/{name}: {e}")); + assert_eq!(actual.phases, expected.phases, "{case}/{name}/phases"); + assert_eq!(actual.reduce, expected.reduce, "{case}/{name}/reduce"); + assert_eq!(actual.active + 1, expected.active, "{case}/{name}/active"); + assert!( + (actual.normamps - expected.normamps).abs() < 1e-12, + "{case}/{name}/normamps" + ); + assert!( + (actual.emergamps - expected.emergamps).abs() < 1e-12, + "{case}/{name}/emergamps" + ); + assert_eq!(actual.conductors.len(), expected.wires.len()); + for (i, conductor) in actual.conductors.iter().enumerate() { + assert_eq!( + conductor.units.map_or(-1, |u| i32::try_from(u).unwrap()), + expected.units[i], + "{case}/{name}/units/{i}" + ); + assert!( + conductor + .wire + .map_or("", |idx| raw.objects[idx].name.as_str()) + .eq_ignore_ascii_case(&expected.wires[i]), + "{case}/{name}/wire/{i}" + ); + assert!( + (conductor.x - expected.x[i]).abs() < 1e-12, + "{case}/{name}/x/{i}" + ); + assert!( + (conductor.height - expected.height[i]).abs() < 1e-12, + "{case}/{name}/h/{i}" + ); + } + if let Some(expected) = expected.matrices { + let got = actual + .materialize(&raw, EarthModel::Carson, 100.0, |idx| { + raw.line_snapshot(idx) + }) + .unwrap() + .calculate(60.0) + .unwrap(); + for (label, got, expected, absolute) in [ + ("r", got.r, expected.r, 1e-12), + ("x", got.x, expected.x, 1e-12), + ("b", got.b, expected.b, 1e-18), + ] { + assert_eq!(got.len(), expected.len()); + for (a, b) in got.iter().flatten().zip(expected.iter().flatten()) { + assert!( + (a - b).abs() <= absolute + 1e-10 * b.abs(), + "{case}/{name}/{label}: {a} != {b}" + ); + } + } + } + } + } +} + +#[test] +fn spacing_missing_at_assignment_cannot_be_repaired_later() { + let raw = raw( + "New LineGeometry.g nconds=1 nphases=1 spacing=missing\nNew LineSpacing.missing nconds=1 x=[0] h=[10]\n", + ); + assert!( + resolve(&raw, raw.line_snapshot(0)) + .unwrap_err() + .contains("did not exist") + ); +} + +#[test] +fn spacing_dimension_mismatch_and_uninitialized_growth_are_refused() { + for text in [ + "New LineSpacing.s nconds=2 x=[0 1] h=[10 11]\nNew LineGeometry.g nconds=1 nphases=1 spacing=s\n", + "New LineSpacing.s nconds=4\nNew LineGeometry.g nconds=4 nphases=3 spacing=s\n", + ] { + let raw = raw(text); + assert!(resolve(&raw, raw.line_snapshot(1)).is_err()); + } +} + +#[test] +fn copied_spacing_is_a_snapshot_and_geometry_ignores_its_phase_count() { + let raw = raw( + "New LineSpacing.s nconds=2 nphases=1 units=m x=[0 2] h=[10 11]\nNew LineSpacing.t like=s\nEdit LineSpacing.s x=[3 4]\nNew LineGeometry.g nconds=2 nphases=2 spacing=t\nEdit LineSpacing.t x=[5 6]\n", + ); + let g = resolve(&raw, raw.line_snapshot(2)).unwrap(); + assert_eq!(g.phases, 2); + assert_eq!( + g.conductors.iter().map(|c| c.x).collect::>(), + [0., 2.] + ); +} + +#[test] +fn cn_forward_references_and_native_geometry_copy_failure_are_explicit() { + let missing = + raw("New LineGeometry.g nconds=1 nphases=1 cncables=[later]\nNew CNData.later rac=.001\n"); + assert!( + resolve(&missing, missing.line_snapshot(0)) + .unwrap_err() + .contains("did not exist") + ); + let copied = raw( + "New CNData.a rac=.001\nNew LineGeometry.g nconds=1 nphases=1 cncables=[a]\nNew LineGeometry.h like=g\n", + ); + assert!( + resolve(&copied, copied.line_snapshot(2)) + .unwrap_err() + .contains("cannot copy") + ); +} diff --git a/powerio-dist/src/dss/geometry/direct.rs b/powerio-dist/src/dss/geometry/direct.rs new file mode 100644 index 000000000..595e7d13a --- /dev/null +++ b/powerio-dist/src/dss/geometry/direct.rs @@ -0,0 +1,62 @@ +//! Live direct Line.spacing inputs; the Line owns its calculation-frequency cache. +use super::{EarthModel, Geometry, cache::Context, wire}; +use crate::dss::linecode::LineMatrices; + +#[derive(Clone, Debug)] +pub(in crate::dss) struct Binding { + pub object: usize, + pub conductors: Vec>, + pub cable: bool, +} + +impl Binding { + pub fn calculate( + &self, + context: &mut Context<'_>, + frequency: f64, + earth: EarthModel, + rho: Option, + ) -> Result<(LineMatrices, f64, f64), String> { + let spacing = context.spacing(self.object)?; + if spacing.x.len() != self.conductors.len() { + return Err("live LineSpacing size differs from its assigned conductor slots".into()); + } + let mut normamps = 0.0; + let mut emergamps = 0.0; + let meters = wire::meters(spacing.units); + let wires = self + .conductors + .iter() + .enumerate() + .map(|(i, object)| { + let state = context + .conductor(object.ok_or("direct LineSpacing has an unassigned conductor")?)?; + if i == 0 { + normamps = state.normamps; + emergamps = state.emergamps; + } + Ok(state.at(spacing.x[i] * meters, spacing.height[i] * meters)) + }) + .collect::, String>>()?; + let mut input = Geometry { + wires, + phases: spacing.phases, + reduce: spacing.phases < spacing.x.len(), + reduction_order: None, + earth_model: context.active_earth.clone()?, + rho: 100.0, + }; + // LoadSpacingAndWires calculates immediately using the PREVIOUS active + // earth model. FMakeZFromSpacing selects the Line earth model afterwards. + let mut result = input.calculate(frequency)?; + context.active_earth = Ok(earth); + if let Some(rho) = rho + && rho.to_bits() != 100.0_f64.to_bits() + { + input.rho = rho; + input.earth_model = earth; + result = input.calculate(frequency)?; + } + Ok((result, normamps, emergamps)) + } +} diff --git a/powerio-dist/src/dss/geometry/mod.rs b/powerio-dist/src/dss/geometry/mod.rs new file mode 100644 index 000000000..684934f02 --- /dev/null +++ b/powerio-dist/src/dss/geometry/mod.rs @@ -0,0 +1,324 @@ +//! Pinned OpenDSS overhead and concentric-neutral geometry calculations in SI units. +//! +//! Ordered conductor definitions and shared native calculation caches feed +//! conductor-resolved Line snapshots. Unqualified cable paths retain +//! explicit unresolved-geometry diagnostics. +pub(super) mod cache; +mod cn; +pub(super) mod definition; +pub(super) mod direct; +mod spacing; +pub(super) mod timeline; +mod wire; + +use super::linecode::LineMatrices; +use num_complex::Complex64 as Complex; +use serde::Deserialize; +use std::f64::consts::PI; + +// These deliberately match LineConstants.pas in the pinned engine. Replacing +// them with higher-precision physical constants changes the source model. +#[expect( + clippy::approx_constant, + reason = "match the pinned OpenDSS engine constant" +)] +const TWO_PI: f64 = 6.283_185_307; +const MU_0: f64 = 12.566_37e-7; +const EPSILON_0: f64 = 8.854e-12; + +#[derive(Clone, Copy, Debug, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(in crate::dss) enum EarthModel { + Carson, + FullCarson, + Deri, +} + +impl EarthModel { + pub fn parse(text: &str) -> Result { + match text.to_ascii_lowercase().as_str() { + "carson" => Ok(Self::Carson), + "fullcarson" => Ok(Self::FullCarson), + "deri" => Ok(Self::Deri), + _ => Err(format!("unqualified earth model {text:?}")), + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize)] +pub(super) struct Wire { + #[serde(default)] + pub cable: Option, + pub x: f64, + pub height: f64, + pub radius: f64, + pub capacitance_radius: f64, + pub gmr: f64, + pub rdc: f64, + pub rac: f64, +} + +#[derive(Clone, Debug, Deserialize)] +pub(super) struct Geometry { + pub wires: Vec, + pub phases: usize, + pub reduce: bool, + #[serde(default)] + pub reduction_order: Option, + pub earth_model: EarthModel, + pub rho: f64, +} + +fn bessel_ratio(alpha: Complex) -> Complex { + if alpha.norm() > 35.0 { + return Complex::new(1.0, 0.0); + } + // Same bounded series and absolute term criterion as native mathutil. + let z = alpha * alpha * 0.25; + let mut term = z; + let mut zero = Complex::new(1.0, 0.0) + term; + for i in 2..=1001 { + term = z * term / f64::from(i * i); + zero += term; + if term.norm_sqr() < 1e-20 { + break; + } + } + let mut term = alpha / 2.0; + let mut one = term; + let mut increment = term; + for i in (4..=1000).step_by(2) { + let next = alpha / f64::from(i); + term *= increment * next; + one += term; + increment = next; + if term.norm_sqr() < 1e-20 { + break; + } + } + zero / one +} + +impl Geometry { + fn validate(&self, frequency: f64) -> Result<(), String> { + let n = self.wires.len(); + if n == 0 + || n > 32 + || self.phases == 0 + || self.phases > n + || !frequency.is_finite() + || frequency <= 0.0 + || !self.rho.is_finite() + || self.rho <= 0.0 + { + return Err("overhead geometry needs 1..32 conductors, a valid phase count, positive frequency and earth resistivity".into()); + } + for (i, wire) in self.wires.iter().enumerate() { + if !wire.x.is_finite() + || [ + wire.height, + wire.radius, + wire.capacitance_radius, + wire.gmr, + wire.rdc, + wire.rac, + ] + .iter() + .any(|v| !v.is_finite() || *v <= 0.0) + { + return Err(format!("overhead conductor {} has invalid SI data", i + 1)); + } + for other in &self.wires[..i] { + if (wire.x - other.x).hypot(wire.height - other.height) < wire.radius + other.radius + { + return Err("overhead conductors occupy the same space".into()); + } + } + } + Ok(()) + } + + fn earth(&self, i: usize, j: usize, frequency: f64) -> Complex { + let first = &self.wires[i]; + let second = &self.wires[j]; + let omega_mu = TWO_PI * frequency * MU_0; + match self.earth_model { + EarthModel::Carson => Complex::new( + omega_mu / 8.0, + omega_mu / TWO_PI * (658.5 * (self.rho / frequency).sqrt()).ln(), + ), + EarthModel::Deri => { + let depth = 1.0 / Complex::new(0.0, omega_mu / self.rho).sqrt(); + let height = first.height.abs() + second.height.abs() + 2.0 * depth; + let argument = if i == j { + height + } else { + (height * height + (first.x - second.x).powi(2)).sqrt() + }; + Complex::new(0.0, omega_mu / TWO_PI) * argument.ln() + } + EarthModel::FullCarson => { + let distance = (first.height.abs() + second.height.abs()).hypot(first.x - second.x); + let theta = if i == j { + 0.0 + } else { + ((first.height.abs() + second.height.abs()) / distance).acos() + }; + let scaled_distance = 2.8099e-3 * distance * (frequency / self.rho).sqrt(); + let b1 = 1.0 / (3.0 * 2.0_f64.sqrt()); + let b2 = 1.0 / 16.0; + let b3 = b1 / 15.0; + let b4 = b2 / 24.0; + let c2 = 1.365_931_5_f64; + let c4 = c2 + 1.0 / 4.0 + 1.0 / 6.0; + let real = PI / 8.0 - b1 * scaled_distance * theta.cos() + + b2 * scaled_distance + * scaled_distance + * ((c2.exp() / scaled_distance).ln() * (2.0 * theta).cos() + + theta * (2.0 * theta).sin()) + + b3 * scaled_distance.powi(3) * (3.0 * theta).cos() + - b4 * PI / 4.0 * scaled_distance.powi(4) * (4.0 * theta).cos(); + let imaginary = 0.5 * (1.85138 / scaled_distance).ln() + + b1 * scaled_distance * theta.cos() + - b2 * PI / 4.0 * scaled_distance * scaled_distance * (2.0 * theta).cos() + + b3 * scaled_distance.powi(3) * (3.0 * theta).cos() + - b4 * scaled_distance.powi(4) + * ((c4.exp() / scaled_distance).ln() * (4.0 * theta).cos() + + theta * (4.0 * theta).sin()) + + 0.5 * distance.ln(); + Complex::new(real, imaginary) * (omega_mu / PI) + } + } + } + + pub fn calculate(&self, frequency: f64) -> Result { + if self.wires.iter().any(|w| w.cable.is_some()) { + return cn::calculate(self, frequency); + } + self.validate(frequency)?; + let n = self.wires.len(); + let omega = TWO_PI * frequency; + let factor = omega * MU_0 / TWO_PI; + let mut z = vec![vec![Complex::default(); n]; n]; + let mut potential = vec![vec![0.0; n]; n]; + for i in 0..n { + let wire = &self.wires[i]; + let mut internal = match self.earth_model { + EarthModel::Carson | EarthModel::FullCarson => { + Complex::new(wire.rac, omega * MU_0 / (8.0 * PI)) + } + EarthModel::Deri => { + let alpha = Complex::new(1.0, 1.0) * (frequency * MU_0 / wire.rdc).sqrt(); + Complex::new(1.0, 1.0) + * bessel_ratio(alpha) + * (wire.rdc * frequency * MU_0).sqrt() + / 2.0 + } + }; + let radius = if frequency > 40.0 && frequency < 1000.0 { + internal.im = 0.0; + wire.gmr + } else { + wire.radius + }; + z[i][i] = internal + + Complex::new(0.0, factor * (1.0 / radius).ln()) + + self.earth(i, i, frequency); + potential[i][i] = (2.0 * wire.height / wire.capacitance_radius).ln(); + for j in 0..i { + let other = &self.wires[j]; + let distance = (wire.x - other.x).hypot(wire.height - other.height); + z[i][j] = + Complex::new(0.0, factor * (1.0 / distance).ln()) + self.earth(i, j, frequency); + z[j][i] = z[i][j]; + potential[i][j] = + ((wire.x - other.x).hypot(wire.height + other.height) / distance).ln(); + potential[j][i] = potential[i][j]; + } + } + let inverse = inverse(potential)?; + let keep = self + .reduction_order + .unwrap_or(if self.reduce { self.phases } else { n }); + for k in (keep..n).rev() { + if z[k][k] == Complex::default() { + return Err("geometry neutral reduction has a zero pivot".into()); + } + for i in 0..k { + for j in 0..k { + let correction = z[i][k] * z[k][j] / z[k][k]; + z[i][j] -= correction; + } + } + } + let result = LineMatrices { + r: z.iter() + .take(keep) + .map(|row| row.iter().take(keep).map(|v| v.re).collect()) + .collect(), + x: z.iter() + .take(keep) + .map(|row| row.iter().take(keep).map(|v| v.im).collect()) + .collect(), + // Native reduction retains the phase block of the inverted full + // potential matrix; it does not Kron-reduce that admittance. + b: inverse + .iter() + .take(keep) + .map(|row| { + row.iter() + .take(keep) + .map(|v| v * TWO_PI * EPSILON_0 * omega) + .collect() + }) + .collect(), + }; + if [&result.r, &result.x, &result.b] + .into_iter() + .flatten() + .flatten() + .any(|v| !v.is_finite()) + { + return Err("geometry calculation became nonfinite".into()); + } + Ok(result) + } +} + +fn inverse(mut a: Vec>) -> Result>, String> { + let n = a.len(); + let mut inverse = vec![vec![0.0; n]; n]; + for (i, row) in inverse.iter_mut().enumerate() { + row[i] = 1.0; + } + for k in 0..n { + let pivot = (k..n) + .max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs())) + .unwrap(); + if a[pivot][k] == 0.0 { + return Err("geometry potential matrix is singular".into()); + } + a.swap(k, pivot); + inverse.swap(k, pivot); + let diagonal = a[k][k]; + for j in 0..n { + a[k][j] /= diagonal; + inverse[k][j] /= diagonal; + } + let row = a[k].clone(); + let inverse_row = inverse[k].clone(); + for i in 0..n { + if i != k { + let factor = a[i][k]; + for j in 0..n { + a[i][j] -= factor * row[j]; + inverse[i][j] -= factor * inverse_row[j]; + } + } + } + } + Ok(inverse) +} + +#[cfg(test)] +mod tests; diff --git a/powerio-dist/src/dss/geometry/spacing.rs b/powerio-dist/src/dss/geometry/spacing.rs new file mode 100644 index 000000000..a91aaaa43 --- /dev/null +++ b/powerio-dist/src/dss/geometry/spacing.rs @@ -0,0 +1,156 @@ +//! LineSpacing snapshots. Geometry assignment copies coordinates; units are metadata. +use crate::dss::{ + line_history::Snapshot, + raw::{RawDss, RawProp}, +}; +use std::collections::{HashMap, HashSet}; + +#[derive(Clone, Debug)] +pub(in crate::dss) struct State { + pub x: Vec, + pub height: Vec, + pub phases: usize, + pub units: usize, +} + +impl Default for State { + fn default() -> Self { + Self { + x: vec![0.0; 3], + height: vec![0.0; 3], + phases: 3, + units: 5, + } + } +} + +impl State { + fn apply(&mut self, prop: &RawProp, raw: &RawDss) -> Result<(), String> { + let key = prop.name.as_deref().ok_or("unnamed LineSpacing property")?; + match key { + "nconds" | "nphases" => { + let value = prop + .value + .to_f64(Some(&raw.vars)) + .map_err(|e| e.to_string())?; + let minimum = usize::from(key == "nconds"); + if !value.is_finite() + || value.fract() != 0.0 + || !(minimum as f64..=32.0).contains(&value) + { + return Err(format!("invalid LineSpacing {key}")); + } + if key == "nphases" { + self.phases = value as usize; + } else { + // Native realloc retains existing entries but does not initialize + // newly allocated positions. Require them to be set before use. + self.x.resize(value as usize, f64::NAN); + self.height.resize(value as usize, f64::NAN); + self.units = 5; + } + } + "x" | "h" => { + let values = prop + .value + .to_vector(Some(&raw.vars)) + .map_err(|e| e.to_string())?; + let target = if key == "x" { + &mut self.x + } else { + &mut self.height + }; + for (i, entry) in target.iter_mut().enumerate() { + *entry = values.get(i).copied().unwrap_or(0.0); + if !entry.is_finite() { + return Err(format!("nonfinite LineSpacing {key}")); + } + } + } + "units" => self.units = crate::dss::linecode::units(&prop.value.text), + _ => return Err(format!("unqualified LineSpacing property {key}")), + } + Ok(()) + } +} + +pub(super) fn resolve_with_budget( + raw: &RawDss, + point: Snapshot, + budget: &mut usize, +) -> Result { + let mut cache = HashMap::new(); + let mut visiting = HashSet::new(); + let mut pending = vec![(point, false)]; + while let Some((point, ready)) = pending.pop() { + if cache.contains_key(&point) { + continue; + } + let object = raw + .objects + .get(point.object) + .ok_or("missing LineSpacing object")?; + if object.class != "linespacing" { + return Err("expected LineSpacing history".into()); + } + let history = raw + .line_history + .get(&point.object) + .ok_or("missing LineSpacing history")?; + let copies = history + .copies + .get(..point.copies) + .ok_or("invalid LineSpacing copy prefix")?; + *budget = budget + .checked_sub(32) + .ok_or("LineSpacing evaluation work limit exceeded")?; + if ready { + let mut state = State::default(); + let props = object + .props + .get(..point.properties) + .ok_or("invalid LineSpacing property prefix")?; + let mut offset = 0; + for copy in copies { + let before = props + .get(offset..copy.start) + .ok_or("invalid LineSpacing copy span")?; + *budget = budget + .checked_sub(before.len()) + .ok_or("LineSpacing evaluation work limit exceeded")?; + for prop in before { + state.apply(prop, raw)?; + } + state = cache + .get(©.source) + .cloned() + .ok_or("unresolved LineSpacing copy")?; + if copy.source.object == point.object { + // Native self-copy resets Units before reading the aliased source. + state.units = 5; + } + offset = copy.end; + } + let remaining = props.get(offset..).ok_or("invalid LineSpacing copy span")?; + *budget = budget + .checked_sub(remaining.len()) + .ok_or("LineSpacing evaluation work limit exceeded")?; + for prop in remaining { + state.apply(prop, raw)?; + } + cache.insert(point, state); + visiting.remove(&point); + } else { + if !visiting.insert(point) { + return Err("cyclic LineSpacing history".into()); + } + pending.push((point, true)); + for c in copies.iter().rev() { + pending.push((c.source, false)); + } + } + } + cache + .remove(&point) + .ok_or_else(|| "missing resolved LineSpacing".into()) +} diff --git a/powerio-dist/src/dss/geometry/tests.rs b/powerio-dist/src/dss/geometry/tests.rs new file mode 100644 index 000000000..25b036137 --- /dev/null +++ b/powerio-dist/src/dss/geometry/tests.rs @@ -0,0 +1,74 @@ +use super::*; + +fn sample() -> Geometry { + Geometry { + wires: vec![Wire { + cable: None, + x: 0.0, + height: 10.0, + radius: 0.01, + capacitance_radius: 0.01, + gmr: 0.007_788, + rdc: 0.0001, + rac: 0.000_102, + }], + phases: 1, + reduce: false, + reduction_order: None, + earth_model: EarthModel::Carson, + rho: 100.0, + } +} +#[test] +fn single_wire_matches_closed_form_and_rejects_invalid_geometry() { + let mut input = sample(); + let result = input.calculate(60.0).unwrap(); + let omega = TWO_PI * 60.0; + assert!((result.r[0][0] - (0.000_102 + omega * MU_0 / 8.0)).abs() < 1e-15); + assert!((result.b[0][0] - TWO_PI * EPSILON_0 * omega / (2000.0_f64.ln())).abs() < 1e-20); + input.wires.push(input.wires[0]); + assert!(input.calculate(60.0).unwrap_err().contains("same space")); + input.wires.pop(); + input.wires[0].height = 0.0; + assert!(input.calculate(60.0).is_err()); + assert!(sample().calculate(f64::NAN).is_err()); +} +#[test] +#[ignore = "requires pinned native geometry matrix observations"] +fn pinned_overhead_matrices() { + #[derive(Deserialize)] + struct Case { + geometry: Geometry, + frequency: f64, + r: Vec>, + x: Vec>, + b: Vec>, + } + let path = std::env::var("POWERIO_GEOMETRY_ORACLE").unwrap(); + let cases: std::collections::BTreeMap = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert!(!cases.is_empty()); + for (name, case) in cases { + let result = case + .geometry + .calculate(case.frequency) + .unwrap_or_else(|e| panic!("{name}: {e}")); + for (label, got, expected, absolute) in [ + ("r", result.r, case.r, 1e-12), + ("x", result.x, case.x, 1e-12), + ("b", result.b, case.b, 1e-18), + ] { + assert_eq!(got.len(), expected.len(), "{name}/{label}"); + for (row, reference) in got.iter().zip(&expected) { + assert_eq!(row.len(), reference.len()); + for (a, b) in row.iter().zip(reference) { + assert!( + (a - b).abs() <= absolute + 1e-10 * b.abs(), + "{name}/{label}: {a} != {b}; error {}", + (a - b).abs() + ); + } + } + } + } +} diff --git a/powerio-dist/src/dss/geometry/timeline.rs b/powerio-dist/src/dss/geometry/timeline.rs new file mode 100644 index 000000000..956bdae60 --- /dev/null +++ b/powerio-dist/src/dss/geometry/timeline.rs @@ -0,0 +1,215 @@ +//! Source-order electrical actions required by shared geometry calculations. +use super::{EarthModel, cache::Context}; +use crate::dss::{line, line_history::Snapshot, linecode, raw::RawDss}; +use std::collections::BTreeMap; + +#[derive(Debug)] +pub(in crate::dss) enum Action { + New { + point: Snapshot, + earth: Option, + }, + Property { + point: Snapshot, + offset: usize, + }, + Copy { + point: Snapshot, + frequency: f64, + }, + Solve { + frequency: f64, + }, + Terminal { + object: usize, + terminal: usize, + conductor: usize, + closed: bool, + }, +} + +type States = BTreeMap>; + +pub(in crate::dss) fn resolve(raw: &RawDss) -> States { + execute(raw, true).0 +} + +pub(in crate::dss) fn earth_before_clear(raw: &RawDss) -> Result { + execute(raw, false).1 +} + +#[expect( + clippy::too_many_lines, + reason = "source-order actions share one calculation context" +)] +fn execute(raw: &RawDss, finalize: bool) -> (States, Result) { + let mut context = Context::new(raw); + let mut states = States::new(); + let mut faults = BTreeMap::new(); + let mut budget = 1_usize << 24; + for action in &raw.geometry_timeline { + match *action { + Action::New { point, ref earth } => { + if raw.objects[point.object].class == "line" { + let state = + EarthModel::parse(earth.as_deref().unwrap_or("deri")).map(|earth| { + let mut state = line::State::new( + raw.line_history[&point.object].constructor_frequency, + &raw.objects[point.object].name, + ); + state.earth_model = earth; + state + }); + states.insert(point.object, state); + } else if let Err(e) = context.observe(point, None) { + faults.insert(point.object, e); + } + } + Action::Property { point, offset } => { + let prop = &raw.objects[point.object].props[offset]; + if let Some(result) = states.get_mut(&point.object) { + if let Ok(state) = result { + let change = (|| match prop.name.as_deref() { + Some("geometry") => { + let source = raw.line_history[&point.object] + .geometries + .get(&offset) + .ok_or("missing LineGeometry binding")? + .ok_or("LineGeometry did not exist at assignment")?; + if let Some(e) = faults.get(&source.object) { + return Err(e.clone()); + } + let definition = context.definition(source.object)?; + state.fetch_geometry(source.object, &definition, &mut context) + } + Some("spacing") => { + let source = raw.line_history[&point.object] + .spacings + .get(&offset) + .ok_or("missing LineSpacing binding")? + .ok_or("LineSpacing did not exist at assignment")?; + state.fetch_spacing(source.object, &context) + } + Some("wires" | "cncables") => { + let objects = raw.line_history[&point.object] + .wires + .get(&offset) + .ok_or("missing conductor bindings")? + .iter() + .map(|p| { + p.map(|s| s.object) + .ok_or("conductor did not exist at assignment") + }) + .collect::, _>>()?; + state.bind_conductors( + prop.name.as_deref() == Some("cncables"), + &objects, + &context, + ) + } + Some("linecode") => { + let source = raw.line_history[&point.object] + .linecodes + .get(&offset) + .ok_or("missing LineCode binding")? + .ok_or("LineCode did not exist at assignment")?; + let code = linecode::resolve_with_budget(raw, source, &mut budget)?; + state.fetch_code(&code); + Ok(()) + } + _ => { + state.apply(prop, raw)?; + if prop.name.as_deref() == Some("rho") { + state.update_geometry_rho(&mut context)?; + } + Ok(()) + } + })(); + if let Err(e) = change { + *result = Err(e); + } + } + } else if let Err(e) = context.observe(point, prop.name.as_deref()) { + faults.insert(point.object, e); + } + } + Action::Copy { point, frequency } => { + if raw.objects[point.object].class == "line" { + let source = raw.line_history[&point.object].copies[point.copies - 1] + .source + .object; + let source = states + .get(&source) + .cloned() + .unwrap_or_else(|| Err("missing source Line".into())); + if let Some(result) = states.get_mut(&point.object) { + match (result.as_mut(), source) { + (Ok(state), Ok(source)) => state.make_like(&source), + (Ok(_), Err(e)) => *result = Err(e), + (Err(_), _) => {} + } + } + } else { + let result = context.observe(point, Some("like")).and_then(|()| { + if raw.objects[point.object].class == "linegeometry" { + context.calculate(point.object, frequency)?; + } + Ok(()) + }); + if let Err(e) = result { + faults.insert(point.object, e); + } + } + } + Action::Solve { frequency } => solve(&mut states, &mut context, frequency, &mut budget), + Action::Terminal { + object, + terminal, + conductor, + closed, + } => { + if let Some(result) = states.get_mut(&object) + && let Ok(state) = result + && let Err(e) = state.set_closed(terminal, conductor, closed) + { + *result = Err(e); + } + } + } + } + if finalize { + solve( + &mut states, + &mut context, + raw.snapshot_frequency(), + &mut budget, + ); + } + (states, context.active_earth) +} + +fn solve(states: &mut States, context: &mut Context<'_>, frequency: f64, budget: &mut usize) { + for result in states.values_mut() { + if let Err(error) = result { + context.active_earth = Err(format!( + "prior unresolved Line calculation may affect active earth model: {error}" + )); + } + if let Ok(state) = result { + let Some(remaining) = budget.checked_sub(state.n * state.n * 6 + 1) else { + *result = Err("geometry Line evaluation work limit exceeded".into()); + continue; + }; + *budget = remaining; + } + if let Ok(state) = result + && state.enabled + && let Err(e) = state.primitive_with_geometry(frequency, context) + { + *result = Err(e); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/powerio-dist/src/dss/geometry/timeline/tests.rs b/powerio-dist/src/dss/geometry/timeline/tests.rs new file mode 100644 index 000000000..9631dc0d6 --- /dev/null +++ b/powerio-dist/src/dss/geometry/timeline/tests.rs @@ -0,0 +1,107 @@ +use super::*; +use num_complex::Complex64 as Complex; +use std::fmt::Write as _; + +#[test] +#[ignore = "requires pinned native geometry cache trace"] +fn pinned_calculation_history() { + #[derive(serde::Deserialize)] + struct Observation { + command: String, + primitives: BTreeMap>, + #[serde(default)] + ratings: BTreeMap, + } + #[derive(serde::Deserialize)] + struct Case { + base: String, + observations: Vec, + } + let path = std::env::var("POWERIO_GEOMETRY_CACHE_ORACLE").expect("native cache trace"); + let cases: BTreeMap = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert!(!cases.is_empty()); + for (name, case) in cases { + let mut script = case.base; + for observation in case.observations { + if observation.command != "initial" { + writeln!(script, "{}\nsolve", observation.command).unwrap(); + } + let raw = crate::dss::raw::__parse_raw_with( + &script, + "geometry-cache.dss", + &mut |_: &std::path::Path| Err(std::io::Error::other("no includes")), + ); + let mut states = resolve(&raw); + for (line, expected) in observation.primitives { + let object = raw + .objects + .iter() + .position(|o| o.class == "line" && o.name == line) + .unwrap(); + let state = states + .get_mut(&object) + .unwrap() + .as_mut() + .unwrap_or_else(|e| panic!("{name}/{line}: {e}")); + if let Some(expected) = observation.ratings.get(&line) { + for (actual, expected) in [state.normamps, state.emergamps].iter().zip(expected) + { + assert!( + (actual - expected).abs() < 1e-10, + "{name}/{line}/{}/rating: {actual} != {expected}", + observation.command + ); + } + } + let m = state.primitive(raw.snapshot_frequency()).unwrap(); + assert_eq!(m.r.len(), 1); + let y = Complex::new(1.0, 0.0) / Complex::new(m.r[0][0], m.x[0][0]); + let diagonal = y + Complex::new(0.0, m.b[0][0] / 2.0); + let actual = [diagonal, -y, -y, diagonal]; + assert_eq!(expected.len(), 8); + for (actual, expected) in actual.iter().zip(expected.as_chunks::<2>().0.iter()) { + let expected = Complex::new(expected[0], expected[1]); + assert!( + (*actual - expected).norm() <= 1e-10 + 1e-10 * expected.norm(), + "{name}/{line}/{}: {actual} != {expected}", + observation.command + ); + } + } + } + } +} + +#[test] +fn direct_spacing_uses_previous_active_earth_model_and_first_wire_rating() { + let script = "clear\nnew circuit.c basekv=12.47\nnew wiredata.w rac=.0002 radius=.01 radunits=m runits=m normamps=100\nnew wiredata.n rac=.0004 radius=.005 radunits=m runits=m normamps=70\nnew linespacing.s nconds=2 nphases=1 units=m x=[0 1] h=[10 9]\nnew line.a bus1=sourcebus.1 bus2=a.1 spacing=s wires=[w n] length=100 units=m earthmodel=carson\nnew line.b bus1=sourcebus.1 bus2=b.1 spacing=s wires=[w n] length=100 units=m earthmodel=deri\nset controlmode=off\nsolve\n"; + let raw = + crate::dss::raw::__parse_raw_with(script, "direct.dss", &mut |_: &std::path::Path| { + Err(std::io::Error::other("no includes")) + }); + let mut states = resolve(&raw); + // Pinned native DSS C-API87d85c2 observations. The first line computes with + // Deri, then sets Carson, which the second line uses for its calculation. + for (name, expected) in [ + ( + "a", + Complex::new(5.867_598_074_966_158, -12.584_981_620_131_156), + ), + ( + "b", + Complex::new(5.931_475_775_215_832, -12.543_154_948_714_399), + ), + ] { + let index = raw + .objects + .iter() + .position(|o| o.class == "line" && o.name == name) + .unwrap(); + let state = states.get_mut(&index).unwrap().as_mut().unwrap(); + let matrix = state.primitive(60.0).unwrap(); + let y = Complex::new(1.0, 0.0) / Complex::new(matrix.r[0][0], matrix.x[0][0]); + assert!((y - expected).norm() < 1e-10); + assert!((state.normamps - 100.0).abs() < 1e-10); + } +} diff --git a/powerio-dist/src/dss/geometry/wire.rs b/powerio-dist/src/dss/geometry/wire.rs new file mode 100644 index 000000000..c3baf8c4b --- /dev/null +++ b/powerio-dist/src/dss/geometry/wire.rs @@ -0,0 +1,251 @@ +//! Ordered native WireData values, before conversion to SI. +use crate::dss::{ + line_history::Snapshot, + raw::{RawDss, RawProp}, +}; +use std::collections::{HashMap, HashSet}; + +#[derive(Clone, Debug, serde::Serialize)] +pub(in crate::dss) struct State { + #[serde(skip_serializing_if = "Option::is_none")] + pub cable: Option, + pub rdc: f64, + pub rac: f64, + pub runits: usize, + pub gmr: f64, + pub gmrunits: usize, + pub radius: f64, + pub radunits: usize, + pub capacitance_radius: f64, + pub normamps: f64, + pub emergamps: f64, +} + +impl Default for State { + fn default() -> Self { + Self { + cable: None, + rdc: -1.0, + rac: -1.0, + runits: 0, + gmr: -1.0, + gmrunits: 0, + radius: -1.0, + radunits: 0, + capacitance_radius: -1.0, + normamps: -1.0, + emergamps: -1.0, + } + } +} + +impl State { + fn apply(&mut self, prop: &RawProp, raw: &RawDss) -> Result<(), String> { + let key = prop.name.as_deref().ok_or("unnamed WireData property")?; + let number = || -> Result { + let value = prop + .value + .to_f64(Some(&raw.vars)) + .map_err(|e| e.to_string())?; + if !value.is_finite() { + return Err(format!("nonfinite WireData {key}")); + } + Ok(value) + }; + let units = || crate::dss::linecode::units(&prop.value.text); + match key { + "rdc" => { + self.rdc = number()?; + if self.rac < 0.0 { + self.rac = self.rdc * 1.02; + } + } + "rac" => { + self.rac = number()?; + if self.rdc < 0.0 { + self.rdc = self.rac / 1.02; + } + } + "runits" => self.runits = units(), + "gmrac" => { + self.gmr = number()?; + if self.gmr <= 0.0 { + return Err("WireData GMR must be positive".into()); + } + if self.radius < 0.0 { + self.radius = self.gmr / 0.7788; + } + } + "gmrunits" => { + self.gmrunits = units(); + if self.radunits == 0 { + self.radunits = self.gmrunits; + } + } + "radius" | "diam" => { + self.radius = number()? / if key == "diam" { 2.0 } else { 1.0 }; + if self.radius <= 0.0 { + return Err("WireData radius must be positive".into()); + } + if self.gmr < 0.0 { + self.gmr = 0.7788 * self.radius; + } + if self.capacitance_radius < 0.0 { + self.capacitance_radius = self.radius; + } + } + "radunits" => { + self.radunits = units(); + if self.gmrunits == 0 { + self.gmrunits = self.radunits; + } + } + "capradius" => { + self.capacitance_radius = number()?; + if self.capacitance_radius == 0.0 { + return Err("WireData capacitance radius cannot be zero".into()); + } + } + "normamps" => { + self.normamps = number()?; + if self.emergamps < 0.0 { + self.emergamps = 1.5 * self.normamps; + } + } + "emergamps" => { + self.emergamps = number()?; + if self.normamps < 0.0 { + self.normamps = self.emergamps / 1.5; + } + } + // Seasonal ratings are retained in the source; they do not alter + // this static conductor impedance or the two scalar ratings. + "seasons" | "ratings" => {} + _ => { + if let Some(cable) = &mut self.cable { + cable.apply(key, number()?)?; + } else { + return Err(format!("unqualified WireData property {key}")); + } + } + } + Ok(()) + } + + pub fn at(&self, x: f64, height: f64) -> super::Wire { + super::Wire { + cable: self + .cable + .map(|c| c.si(self.radunits, self.gmrunits, self.runits)), + x, + height, + radius: self.radius * meters(self.radunits), + // LineConstants uses physical radius when the stored capradius + // remains negative (e.g. a GMR-only conductor definition). + capacitance_radius: if self.capacitance_radius < 0.0 { + self.radius + } else { + self.capacitance_radius + } * meters(self.radunits), + gmr: self.gmr * meters(self.gmrunits), + rdc: self.rdc / meters(self.runits), + rac: self.rac / meters(self.runits), + } + } +} + +pub(super) fn meters(units: usize) -> f64 { + // DSS To_Meters interprets unspecified units as meters. Unit setters + // change interpretation, not the stored numeric values. + [ + 1.0, 1609.344, 304.8, 1000.0, 1.0, 0.3048, 0.0254, 0.01, 0.001, + ][units] +} + +#[cfg(test)] +pub(super) fn resolve(raw: &RawDss, point: Snapshot) -> Result { + resolve_with_budget(raw, point, &mut (1_usize << 22)) +} + +pub(super) fn resolve_with_budget( + raw: &RawDss, + point: Snapshot, + budget: &mut usize, +) -> Result { + let mut cache = HashMap::new(); + let mut visiting = HashSet::new(); + let mut pending = vec![(point, false)]; + while let Some((point, ready)) = pending.pop() { + if cache.contains_key(&point) { + continue; + } + let object = raw + .objects + .get(point.object) + .ok_or("missing WireData object")?; + if !matches!(object.class.as_str(), "wiredata" | "cndata") { + return Err("expected WireData history".into()); + } + let history = raw + .line_history + .get(&point.object) + .ok_or("missing WireData history")?; + let copies = history + .copies + .get(..point.copies) + .ok_or("invalid WireData copy prefix")?; + *budget = budget + .checked_sub(1) + .ok_or("WireData evaluation work limit exceeded")?; + if ready { + let mut state = State::default(); + if object.class == "cndata" { + state.cable = Some(super::cn::Data::default()); + } + let props = object + .props + .get(..point.properties) + .ok_or("invalid WireData property prefix")?; + let mut offset = 0; + for copy in copies { + let before = props + .get(offset..copy.start) + .ok_or("invalid WireData copy span")?; + *budget = budget + .checked_sub(before.len()) + .ok_or("WireData evaluation work limit exceeded")?; + for prop in before { + state.apply(prop, raw)?; + } + state = cache + .get(©.source) + .cloned() + .ok_or("unresolved WireData copy")?; + offset = copy.end; + } + let remaining = props.get(offset..).ok_or("invalid WireData copy span")?; + *budget = budget + .checked_sub(remaining.len()) + .ok_or("WireData evaluation work limit exceeded")?; + for prop in remaining { + state.apply(prop, raw)?; + } + cache.insert(point, state); + visiting.remove(&point); + } else { + if !visiting.insert(point) { + return Err("cyclic WireData history".into()); + } + pending.push((point, true)); + for c in copies.iter().rev() { + pending.push((c.source, false)); + } + } + } + cache + .remove(&point) + .ok_or_else(|| "missing resolved WireData".into()) +} + +#[cfg(test)] +mod tests; diff --git a/powerio-dist/src/dss/geometry/wire/tests.rs b/powerio-dist/src/dss/geometry/wire/tests.rs new file mode 100644 index 000000000..84e4cfaa6 --- /dev/null +++ b/powerio-dist/src/dss/geometry/wire/tests.rs @@ -0,0 +1,78 @@ +use super::*; +use std::fmt::Write as _; +fn raw(text: &str) -> RawDss { + crate::dss::raw::__parse_raw_with(text, "wire.dss", &mut |_: &std::path::Path| { + Err(std::io::Error::other("no includes")) + }) +} + +#[test] +fn historical_copy_and_sticky_radius_survive_source_edits() { + let raw = raw( + "New WireData.a rac=0.306 runits=mi gmrac=0.0244 gmrunits=ft diam=0.721 radunits=in\nNew WireData.b radius=2 like=a\nEdit WireData.a radius=1\nEdit WireData.b radius=0.5\n", + ); + let b = resolve(&raw, raw.line_snapshot(1)).unwrap(); + assert!((b.capacitance_radius - 0.3605).abs() < 1e-15); + assert!((b.radius - 0.5).abs() < 1e-15); + let wire = b.at(0.0, 10.0); + assert!((wire.radius - 0.0127).abs() < 1e-15); + assert!((wire.gmr - 0.0244 * 0.3048).abs() < 1e-15); + assert!((wire.rac - 0.306 / 1609.344).abs() < 1e-15); + assert!((wire.rdc - wire.rac / 1.02).abs() < 1e-15); +} + +#[test] +fn empty_and_self_copies_keep_native_defaults_without_recursion() { + let mut text = + "New WireData.a radius=0.1\nEdit WireData.a like=a\nNew WireData.b like=a\n".to_owned(); + for i in 0..512 { + writeln!( + text, + "New WireData.c{i} like={}", + if i == 0 { + "b".into() + } else { + format!("c{}", i - 1) + } + ) + .unwrap(); + } + let raw = raw(&text); + let wire = resolve(&raw, raw.line_snapshot(raw.objects.len() - 1)).unwrap(); + assert!((wire.capacitance_radius - 0.1).abs() < 1e-15); + assert!((wire.rac + 1.0).abs() < 1e-15); +} + +#[test] +#[ignore = "requires pinned native WireData observations"] +fn pinned_wire_definitions() { + #[derive(serde::Deserialize)] + struct Case { + script: String, + wires: std::collections::BTreeMap, + } + let path = std::env::var("POWERIO_WIRE_ORACLE").expect("native observations"); + let cases: std::collections::BTreeMap = + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + assert!(!cases.is_empty()); + for (case, expected) in cases { + let raw = raw(&expected.script); + for (name, fields) in expected.wires { + let index = raw + .objects + .iter() + .position(|o| o.class == "wiredata" && o.name.eq_ignore_ascii_case(&name)) + .unwrap(); + let actual = + serde_json::to_value(resolve(&raw, raw.line_snapshot(index)).unwrap()).unwrap(); + for (field, value) in fields.as_object().unwrap() { + let expected = value.as_f64().unwrap(); + let actual = actual[field].as_f64().unwrap(); + assert!( + (actual - expected).abs() <= 1e-14 + 1e-12 * expected.abs(), + "{case}/{name}/{field}: {actual} != {expected}" + ); + } + } + } +} diff --git a/powerio-dist/src/dss/line.rs b/powerio-dist/src/dss/line.rs index 4cdea1165..90b83a17f 100644 --- a/powerio-dist/src/dss/line.rs +++ b/powerio-dist/src/dss/line.rs @@ -90,7 +90,9 @@ fn replay( }) { charge(budget, state.n * state.n * 6)?; // Native BuildY marks SystemYChanged, not each Line YPrim. - if !e.rebuild_only { + if let Some((terminal, conductor, closed)) = e.terminal_state { + state.set_closed(terminal, conductor, closed)?; + } else if !e.rebuild_only { state.solve(e.frequency)?; } event += 1; diff --git a/powerio-dist/src/dss/line/state.rs b/powerio-dist/src/dss/line/state.rs index e152ed003..eb79d05b4 100644 --- a/powerio-dist/src/dss/line/state.rs +++ b/powerio-dist/src/dss/line/state.rs @@ -1,14 +1,20 @@ use std::f64::consts::TAU; +use crate::dss::geometry::{EarthModel, cache::Context, definition::Definition, direct::Binding}; use crate::dss::{linecode, raw::RawDss, raw::RawProp}; use linecode::LineMatrices; #[derive(Clone, Debug)] +#[expect( + clippy::struct_excessive_bools, + reason = "independent native enable, switch, invalidation and explicit-property flags" +)] pub(in crate::dss) struct State { pub n: usize, pub frequency: f64, pub bus: [String; 2], pub enabled: bool, + pub closed: [Vec; 2], pub is_switch: bool, pub normamps: f64, pub emergamps: f64, @@ -24,6 +30,15 @@ pub(in crate::dss) struct State { kxg: f64, dirty: bool, cached: Option<(f64, LineMatrices)>, + geometry: Option, + spacing: Option, + ratings_specified: bool, + geometry_frequency: Option, + // Native Zinv survives MakeLike and LineCode assignment while geometry + // remains bound; those operations copy Z/Yc without copying Zinv. + geometry_impedance: Option, + pub earth_model: EarthModel, + rho_specified: bool, } #[derive(Clone, Debug)] @@ -42,6 +57,7 @@ impl State { frequency, bus: [format!("{name}_1"), format!("{name}_2")], enabled: true, + closed: [vec![true; 3], vec![true; 3]], is_switch: false, normamps: 400.0, emergamps: 600.0, @@ -66,12 +82,48 @@ impl State { kxg: 0.0, dirty: true, cached: None, + geometry: None, + spacing: None, + ratings_specified: false, + geometry_frequency: None, + geometry_impedance: None, + earth_model: EarthModel::Deri, + rho_specified: false, }; state.update_kxg(); state.recalc(); state } + fn resize_terminals(&mut self, n: usize) { + if self.n != n { + self.closed = [vec![true; n], vec![true; n]]; + } + self.n = n; + } + + pub fn set_closed( + &mut self, + terminal: usize, + conductor: usize, + closed: bool, + ) -> Result<(), String> { + let end = self + .closed + .get_mut(terminal.wrapping_sub(1)) + .ok_or("invalid Line terminal")?; + if conductor > self.n { + return Err("Line terminal command conductor exceeds its current count".into()); + } + if conductor == 0 { + end.fill(closed); + } else { + end[conductor - 1] = closed; + } + self.dirty = true; + Ok(()) + } + fn update_kxg(&mut self) { self.kxg = self.xg / (658.5 * (self.rho / self.frequency).sqrt()).ln(); } @@ -101,6 +153,8 @@ impl State { } pub fn fetch_code(&mut self, code: &linecode::State) { + self.kill_geometry(); + self.kill_spacing(); self.frequency = code.frequency; self.rg = code.rg; self.xg = code.xg; @@ -110,7 +164,7 @@ impl State { self.units_convert = conversion(code.units, self.units); self.normamps = code.normamps; self.emergamps = code.emergamps; - self.n = code.n; + self.resize_terminals(code.n); self.sequence.model = code.sequence; if code.sequence { self.sequence.values = code.seq; @@ -132,7 +186,7 @@ impl State { if self.n != source.n { self.dirty = true; } - self.n = source.n; + self.resize_terminals(source.n); self.frequency = source.frequency; self.enabled = true; self.normamps = source.normamps; @@ -212,6 +266,8 @@ impl State { self.matrices.x = matrix; } self.sequence.model = false; + self.kill_geometry(); + self.kill_spacing(); self.reset_units(); self.dirty = true; } @@ -226,29 +282,41 @@ impl State { } "rho" => { self.rho = number()?; + self.rho_specified = true; self.update_kxg(); } + "earthmodel" => self.earth_model = EarthModel::parse(&prop.value.text)?, "enabled" => self.enabled = yes(&prop.value.text), - "switch" => { - self.is_switch = yes(&prop.value.text); - if self.is_switch { - self.sequence.values = [1.0, 1.0, 1.0, 1.0, 1.1e-9, 1e-9]; - self.length = 0.001; - self.reset_units(); - self.sequence.changed = true; - self.dirty = true; + "switch" => self.set_switch(yes(&prop.value.text)), + "normamps" | "emergamps" => { + if key == "normamps" { + self.normamps = number()?; + } else { + self.emergamps = number()?; } + self.ratings_specified = true; } - "normamps" => self.normamps = number()?, - "emergamps" => self.emergamps = number()?, + "seasons" | "ratings" => self.ratings_specified = true, // These fields do not alter an ordinary matrix/sequence primitive. - "faultrate" | "pctperm" | "repair" | "seasons" | "ratings" | "linetype" - | "earthmodel" => {} + "faultrate" | "pctperm" | "repair" | "linetype" => {} _ => return Err(format!("unqualified Line property {key}")), } Ok(()) } + fn set_switch(&mut self, enabled: bool) { + self.is_switch = enabled; + if enabled { + self.sequence.values = [1.0, 1.0, 1.0, 1.0, 1.1e-9, 1e-9]; + self.length = 0.001; + self.reset_units(); + self.kill_geometry(); + self.kill_spacing(); + self.sequence.changed = true; + self.dirty = true; + } + } + fn set_phases(&mut self, n: f64) -> Result<(), String> { if !(1.0..=32.0).contains(&n) || n.fract() != 0.0 { return Err("invalid Line conductor count".into()); @@ -258,7 +326,7 @@ impl State { if !self.sequence.model { return Err("illegal matrix-mode Line phase change (native error 18101)".into()); } - self.n = n; + self.resize_terminals(n); self.recalc(); } self.dirty = true; @@ -266,6 +334,8 @@ impl State { } fn set_sequence(&mut self, key: &str, value: f64) { + self.kill_geometry(); + self.kill_spacing(); let (index, scale) = match key { "r1" => (0, 1.0), "x1" => (1, 1.0), @@ -289,6 +359,189 @@ impl State { } } + fn kill_geometry(&mut self) { + if self.geometry.take().is_some() { + self.geometry_frequency = None; + } + } + + fn kill_spacing(&mut self) { + if self.spacing.take().is_some() { + self.geometry_frequency = None; + } + } + + pub fn fetch_spacing(&mut self, object: usize, context: &Context<'_>) -> Result<(), String> { + let spacing = context.spacing(object)?; + if spacing.phases == 0 || spacing.phases > spacing.x.len() { + return Err("invalid direct LineSpacing phase count".into()); + } + // Reassignment allocates new conductor slots but retains FZFrequency + // and the previous cable choice unless a geometry was bound. + let cable = self.spacing.as_ref().is_some_and(|b| b.cable); + self.kill_geometry(); + self.code_units = None; + self.spacing = Some(Binding { + object, + conductors: vec![None; spacing.x.len()], + cable, + }); + self.resize_terminals(spacing.phases); + self.sequence.model = false; + self.sequence.changed = false; + self.ratings_specified = false; + self.dirty = true; + Ok(()) + } + + pub fn bind_conductors( + &mut self, + cable: bool, + objects: &[usize], + context: &Context<'_>, + ) -> Result<(), String> { + let binding = self + .spacing + .as_mut() + .ok_or("LineSpacing must precede conductor assignment")?; + let spacing = context.spacing(binding.object)?; + if spacing.x.len() != binding.conductors.len() { + return Err("live LineSpacing size differs from its assigned conductor slots".into()); + } + let start = if !cable && binding.cable { + spacing.phases + } else { + 0 + }; + let count = binding.conductors.len().saturating_sub(start); + if objects.is_empty() || objects.len() > count || (!cable && objects.len() != count) { + return Err("direct spacing conductor array has wrong length".into()); + } + for (i, object) in objects.iter().enumerate() { + binding.conductors[start + i] = Some(*object); + if !cable { + let state = context.conductor(*object)?; + self.normamps = state.normamps; + self.emergamps = state.emergamps; + } + } + if cable { + binding.cable = true; + } + self.ratings_specified = false; + self.dirty = true; + Ok(()) + } + + pub fn fetch_geometry( + &mut self, + object: usize, + definition: &Definition, + context: &mut Context<'_>, + ) -> Result<(), String> { + let n = if definition.reduce { + definition.phases + } else { + definition.conductors.len() + }; + if n == 0 || n > 32 { + return Err("invalid geometry Line conductor count".into()); + } + self.kill_spacing(); + self.geometry = Some(object); + self.geometry_frequency = None; + self.code_units = None; + self.resize_terminals(n); + self.normamps = definition.normamps; + self.emergamps = definition.emergamps; + self.sequence.model = false; + self.sequence.changed = false; + self.dirty = true; + if self.rho_specified { + context.set_rho(object, self.rho)?; + } + Ok(()) + } + + pub fn update_geometry_rho(&mut self, context: &mut Context<'_>) -> Result<(), String> { + if let Some(object) = self.geometry { + context.set_rho(object, self.rho)?; + self.dirty = true; + } + Ok(()) + } + + pub fn primitive_with_geometry( + &mut self, + frequency: f64, + context: &mut Context<'_>, + ) -> Result { + if self.geometry.is_none() && self.spacing.is_none() { + return self.primitive(frequency); + } + if let Some((f, matrix)) = &self.cached + && !self.dirty + && f.to_bits() == frequency.to_bits() + { + return Ok(matrix.clone()); + } + if !frequency.is_finite() || frequency <= 0.51 { + return Err("Line AC frequency must exceed 0.51 Hz".into()); + } + if self + .geometry_frequency + .is_none_or(|f| f.to_bits() != frequency.to_bits()) + { + let mut matrix = if let Some(object) = self.geometry { + context.active_earth = Ok(self.earth_model); + context.calculate(object, frequency)? + } else { + let (matrix, normamps, emergamps) = self.spacing.as_ref().unwrap().calculate( + context, + frequency, + self.earth_model, + self.rho_specified.then_some(self.rho), + )?; + if !self.ratings_specified { + self.normamps = normamps; + self.emergamps = emergamps; + } + matrix + }; + Context::scale(&mut matrix, self.length, self.units); + self.geometry_impedance = Some(matrix.clone()); + self.matrices = matrix; + self.geometry_frequency = Some(frequency); + } + let mut effective = self.matrices.clone(); + if let Some(impedance) = &self.geometry_impedance { + effective.r.clone_from(&impedance.r); + effective.x.clone_from(&impedance.x); + } + if [&effective.r, &effective.x, &effective.b] + .iter() + .any(|m| m.len() != self.n || m.iter().any(|row| row.len() != self.n)) + { + return Err("geometry calculation dimension differs from the Line terminals".into()); + } + let impedance: Vec> = self + .matrices + .r + .iter() + .zip(&effective.x) + .map(|(r, x)| { + r.iter() + .zip(x) + .map(|(&r, &x)| num_complex::Complex64::new(r, x)) + .collect() + }) + .collect(); + crate::dss::primitive::validate(&impedance, "Line", 183)?; + self.cached = Some((frequency, effective.clone())); + self.dirty = false; + Ok(effective.clone()) + } + pub fn physical_length(&self) -> Option { let units = if self.units == 0 { self.code_units? @@ -316,6 +569,9 @@ impl State { { return Ok(matrix.clone()); } + if self.geometry.is_some() || self.spacing.is_some() { + return Err("geometry Line requires a resolved shared calculation context".into()); + } if !frequency.is_finite() || frequency <= 0.51 { return Err("Line AC frequency must exceed 0.51 Hz".into()); } diff --git a/powerio-dist/src/dss/line/tests.rs b/powerio-dist/src/dss/line/tests.rs index 4f3225f4d..3d49f13b8 100644 --- a/powerio-dist/src/dss/line/tests.rs +++ b/powerio-dist/src/dss/line/tests.rs @@ -190,3 +190,60 @@ fn pinned_line_states() { ) .unwrap(); } + +#[test] +fn fixed_terminal_history_follows_native_copy_and_resize_rules() { + for (commands, expected) in [ + ("open line.a 1 2", [vec![true, false, true], vec![true; 3]]), + ( + "open line.a 1\nclose line.a 1 2", + [vec![false, true, false], vec![true; 3]], + ), + ( + "open line.a 2 1\nedit line.a phases=3", + [vec![true; 3], vec![false, true, true]], + ), + ( + "open line.a 2 1\nedit line.a phases=2\nedit line.a phases=3", + [vec![true; 3], vec![true; 3]], + ), + ( + "open line.a 2 1\nnew line.b\nedit line.a like=b", + [vec![true; 3], vec![false, true, true]], + ), + ( + "new line.b\nopen line.b 1\nedit line.a like=b", + [vec![true; 3], vec![true; 3]], + ), + ( + "open line.a 2\nclose line.a term=2 cond=0", + [vec![true; 3], vec![true; 3]], + ), + ] { + let raw = read(&format!("new circuit.c\nnew line.a\n{commands}\nsolve")); + assert_eq!( + resolve(&raw, point(&raw, "a")).unwrap().closed, + expected, + "{commands}" + ); + } +} + +#[test] +fn terminal_command_binds_before_later_declarations_and_selects_the_line() { + let raw = read("new circuit.c\nopen line.a 1\nnew line.a"); + assert!( + raw.warnings + .iter() + .any(|w| w.contains("requires an existing ordinary Line")) + ); + let raw = read("new circuit.c\nnew line.a\nnew line.b\nopen line.a 1 2\n~ length=7"); + assert_eq!( + resolve(&raw, point(&raw, "a")).unwrap().length.to_bits(), + 7.0_f64.to_bits() + ); + assert_eq!( + resolve(&raw, point(&raw, "b")).unwrap().length.to_bits(), + 1.0_f64.to_bits() + ); +} diff --git a/powerio-dist/src/dss/line_history.rs b/powerio-dist/src/dss/line_history.rs index 52b2f1838..7bf67e20c 100644 --- a/powerio-dist/src/dss/line_history.rs +++ b/powerio-dist/src/dss/line_history.rs @@ -1,4 +1,4 @@ -//! Immutable references to the line/linecode state visible at an assignment. +//! Immutable references to electrical definition state at an assignment. //! //! The property and edit vectors only append. Prefix lengths therefore retain //! past state without cloning matrix literals or retaining another object tree. @@ -24,6 +24,7 @@ pub(super) struct Event { pub position: Snapshot, pub frequency: f64, pub rebuild_only: bool, + pub terminal_state: Option<(usize, usize, bool)>, } #[cfg_attr(not(test), allow(dead_code))] @@ -47,6 +48,12 @@ pub(super) struct LineHistory { // Property offset -> referenced linecode prefix. None records a missing // reference at assignment, even if that name is declared later. pub linecodes: BTreeMap>, + pub xfmrcodes: BTreeMap>, + pub geometries: BTreeMap>, + pub spacings: BTreeMap>, + // Geometry conductor assignments bind identities immediately; their + // snapshots also preserve the ratings copied at that assignment. + pub wires: BTreeMap>>, } impl LineHistory { @@ -56,6 +63,10 @@ impl LineHistory { copies: Vec::new(), events: Vec::new(), linecodes: BTreeMap::new(), + geometries: BTreeMap::new(), + spacings: BTreeMap::new(), + xfmrcodes: BTreeMap::new(), + wires: BTreeMap::new(), } } } diff --git a/powerio-dist/src/dss/mod.rs b/powerio-dist/src/dss/mod.rs index 7dfd5daee..0e2886c40 100644 --- a/powerio-dist/src/dss/mod.rs +++ b/powerio-dist/src/dss/mod.rs @@ -7,6 +7,7 @@ pub mod defaults; mod frequency; +mod geometry; pub mod lex; mod line; mod line_history; @@ -19,6 +20,7 @@ mod rpn; mod solution_mode; mod source; mod write; +mod xfmrcode; pub use lex::{BusSpec, Param, Scanner, Value, VarMap}; pub use raw::{BusCoord, RawCommand, RawDss, RawObject, RawProp}; diff --git a/powerio-dist/src/dss/prop.rs b/powerio-dist/src/dss/prop.rs index 64932dd62..9a651c7bb 100644 --- a/powerio-dist/src/dss/prop.rs +++ b/powerio-dist/src/dss/prop.rs @@ -217,6 +217,54 @@ class!( ] ); +// Pinned DSS C-API XfmrCode.pas; codes have no bus or circuit-element fields. +class!( + XFMR_CODE, + "xfmrcode", + [ + "phases", + "windings", + "wdg", + "conn", + "kv", + "kva", + "tap", + "%r", + "rneut", + "xneut", + "conns", + "kvs", + "kvas", + "taps", + "xhl", + "xht", + "xlt", + "xscarray", + "thermal", + "n", + "m", + "flrise", + "hsrise", + "%loadloss", + "%noloadloss", + "normhkva", + "emerghkva", + "maxtap", + "mintap", + "numtaps", + "%imag", + "ppm_antifloat", + "%rs", + "x12", + "x13", + "x23", + "rdcohms", + "seasons", + "ratings", + "like", + ] +); + class!( VSOURCE, "vsource", @@ -543,13 +591,102 @@ class!( ] ); -/// The Phase A classes with property tables. Anything else parses into the -/// raw layer untyped. +// Pinned DSS C-API ConductorData.pas (WireData adds no own fields). +class!( + WIRE_DATA, + "wiredata", + [ + "rdc", + "rac", + "runits", + "gmrac", + "gmrunits", + "radius", + "radunits", + "normamps", + "emergamps", + "diam", + "seasons", + "ratings", + "capradius", + "like", + ] +); + +// CNData inherits CableData and then ConductorData in the pinned engine. +class!( + CN_DATA, + "cndata", + [ + "k", + "diastrand", + "gmrstrand", + "rstrand", + "epsr", + "inslayer", + "diains", + "diacable", + "rdc", + "rac", + "runits", + "gmrac", + "gmrunits", + "radius", + "radunits", + "normamps", + "emergamps", + "diam", + "seasons", + "ratings", + "capradius", + "like" + ] +); + +class!( + LINE_GEOMETRY, + "linegeometry", + [ + "nconds", + "nphases", + "cond", + "wire", + "x", + "h", + "units", + "normamps", + "emergamps", + "reduce", + "spacing", + "wires", + "cncable", + "tscable", + "cncables", + "tscables", + "seasons", + "ratings", + "linetype", + "like", + ] +); + +class!( + LINE_SPACING, + "linespacing", + ["nconds", "nphases", "x", "h", "units", "like"] +); + +/// Classes with ordered property tables; other classes remain untyped. static CLASSES: &[&DssClass] = &[ &LINE, &LINECODE, + &WIRE_DATA, + &CN_DATA, + &LINE_GEOMETRY, + &LINE_SPACING, &LOAD, &TRANSFORMER, + &XFMR_CODE, &VSOURCE, &CAPACITOR, &REACTOR, @@ -627,7 +764,7 @@ mod tests { assert!(class_by_name("Line").is_some()); assert!(class_by_name("LINECODE").is_some()); assert!(class_by_name("reactor").is_some()); - assert!(class_by_name("xfmrcode").is_none()); + assert_eq!(class_by_name("xfmrcode").unwrap().props[3], "conn"); } #[test] diff --git a/powerio-dist/src/dss/raw.rs b/powerio-dist/src/dss/raw.rs index 5e5f8b2a5..43deaecab 100644 --- a/powerio-dist/src/dss/raw.rs +++ b/powerio-dist/src/dss/raw.rs @@ -257,6 +257,9 @@ pub struct RawDss { // to offsets in the existing flattened history; no extra history tree. source_replay: BTreeMap, pub(super) line_history: BTreeMap, + pub(super) geometry_timeline: Vec, + earth_model: Option, + pub(super) geometry_earth: Option>, frequency: super::frequency::FrequencyState, solution_mode: super::solution_mode::SolutionMode, /// Diagnostic records retained, against `MAX_TOTAL_DIAGNOSTICS`. Survives @@ -306,6 +309,9 @@ impl RawDss { fn option_assignment(&mut self, position: &mut usize, name: &str, value: &Value) { self.frequency.assignment(position, name, value, &self.vars); + if *position == 81 { + self.earth_model = Some(value.text.clone()); + } if *position == 8 { self.solution_mode.assign(&value.text); } @@ -390,6 +396,7 @@ impl RawDss { } fn clear(&mut self) { + let geometry_earth = Some(super::geometry::timeline::earth_before_clear(self)); // `Clear` resets the circuit, not the record of how the script was // read. A warning or an `Error` finding already emitted describes input // the caller wrote, and no later command un-writes it — dropping them @@ -404,10 +411,13 @@ impl RawDss { let vars_generation = self.vars_generation.wrapping_add(1); let mut frequency = std::mem::take(&mut self.frequency); frequency.clear(); + let earth_model = self.earth_model.take(); *self = RawDss { vars_generation, warnings, diagnostics, + earth_model, + geometry_earth, frequency, total_diagnostics, halted, @@ -622,6 +632,7 @@ impl Executor<'_, L> { Some("edit") => self.do_edit(scan, ctx), Some("more" | "m" | "~") => self.do_more(scan, ctx), Some("select") => self.do_select(scan, ctx), + Some(canonical @ ("open" | "close")) => self.do_terminal_state(canonical, scan, ctx), Some("set") => self.do_set(scan), Some("redirect") => self.do_redirect(scan, false, ctx), Some("compile") => self.do_redirect(scan, true, ctx), @@ -880,6 +891,90 @@ impl Executor<'_, L> { self.consume_and_apply(idx, scan, ctx); } + fn do_terminal_state( + &mut self, + verb: &str, + scan: &mut Scanner, + ctx: &dyn Fn(String) -> String, + ) { + if !self.raw.charge_preserved() { + return; + } + self.raw.commands.push(RawCommand { + verb: verb.into(), + args: scan.remainder().into(), + }); + let Some((class, name)) = self.object_spec(scan, ctx) else { + self.raw.warn( + &C::READ_DSS_LINE_UNRESOLVED, + ctx("terminal command requires an explicit element".into()), + ); + return; + }; + let key = (class.to_ascii_lowercase(), name.to_ascii_lowercase()); + let Some(&idx) = self + .raw + .index + .get(&key) + .filter(|_| class.eq_ignore_ascii_case("line")) + else { + self.raw.warn(&C::READ_DSS_LINE_UNRESOLVED, ctx(format!("{verb} {class}.{name}: terminal state requires an existing ordinary Line; other classes remain unresolved"))); + return; + }; + // The native command consumes positional values even when they have + // parameter names. Bind the object now, not after later declarations. + let mut integer = || { + scan.next_param() + .map(|p| p.value.to_f64(Some(&self.raw.vars))) + }; + let terminal = integer(); + let conductor = integer(); + let number = |v: Option>, default: usize| -> Option { + match v { + None => Some(default), + Some(Ok(n)) if n.is_finite() && (0.0..=32.0).contains(&n) && n.fract() == 0.0 => { + Some(n as usize) + } + _ => None, + } + }; + let (Some(terminal @ 1..=2), Some(conductor)) = (number(terminal, 0), number(conductor, 0)) + else { + self.raw.warn(&C::READ_DSS_LINE_UNRESOLVED, ctx(format!("{verb} Line.{name}: explicit terminal 1 or 2 and a nonnegative conductor index are required"))); + return; + }; + if self.raw.total_props >= MAX_TOTAL_PROPS + || self.retained_property_count(idx) >= MAX_OBJECT_PROPS + { + self.raw.halt(ctx( + "line terminal history exceeds the supported work budget".into(), + )); + return; + } + let event = super::line_history::Event { + position: self.raw.line_snapshot(idx), + frequency: self.raw.snapshot_frequency(), + rebuild_only: false, + terminal_state: Some((terminal, conductor, verb == "close")), + }; + self.raw.total_props += 1; + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .events + .push(event); + self.raw + .geometry_timeline + .push(super::geometry::timeline::Action::Terminal { + object: idx, + terminal, + conductor, + closed: verb == "close", + }); + self.raw.active = Some(idx); + } + fn do_select(&mut self, scan: &mut Scanner, ctx: &dyn Fn(String) -> String) { let Some((class, name)) = self.object_spec(scan, ctx) else { return; @@ -1363,11 +1458,32 @@ impl Executor<'_, L> { props: Vec::new(), edits: Vec::new(), }); - if matches!(self.raw.objects[idx].class.as_str(), "line" | "linecode") { + if matches!( + self.raw.objects[idx].class.as_str(), + "line" + | "linecode" + | "wiredata" + | "cndata" + | "linegeometry" + | "linespacing" + | "xfmrcode" + | "transformer" + ) { self.raw.line_history.insert( idx, super::line_history::LineHistory::new(self.raw.frequency.constructor()), ); + if matches!( + self.raw.objects[idx].class.as_str(), + "line" | "wiredata" | "cndata" | "linegeometry" | "linespacing" + ) { + self.raw + .geometry_timeline + .push(super::geometry::timeline::Action::New { + point: self.raw.line_snapshot(idx), + earth: self.raw.earth_model.clone(), + }); + } } if self.raw.objects[idx].class == "vsource" { let frequency = self.raw.frequency.constructor(); @@ -1404,7 +1520,11 @@ impl Executor<'_, L> { self.raw.objects[idx].props.len() + self.raw.line_history.get(&idx).map_or(0, |h| { // Include the current command's pending closing checkpoint. - h.copies.len() + h.events.len() + self.raw.objects[idx].edits.len() + 1 + h.copies.len() + + h.events.len() + + h.wires.values().map(Vec::len).sum::() + + self.raw.objects[idx].edits.len() + + 1 }) + self .raw @@ -1432,11 +1552,19 @@ impl Executor<'_, L> { return; } self.raw.total_props += indices.len(); + if !rebuild_only { + self.raw + .geometry_timeline + .push(super::geometry::timeline::Action::Solve { + frequency: self.raw.snapshot_frequency(), + }); + } for idx in indices { let event = super::line_history::Event { position: self.raw.line_snapshot(idx), frequency: self.raw.snapshot_frequency(), rebuild_only, + terminal_state: None, }; self.raw .line_history @@ -1503,6 +1631,22 @@ impl Executor<'_, L> { } } + fn copy_transformer_bindings(&mut self, idx: usize, src: usize, base: usize) { + if self.raw.objects[idx].class == "transformer" { + let bindings = self.raw.line_history[&src].xfmrcodes.clone(); + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .xfmrcodes + .extend( + bindings + .into_iter() + .map(|(offset, point)| (base + offset, point)), + ); + } + } + fn apply_like(&mut self, idx: usize, value: &Value, ctx: &dyn Fn(String) -> String) { let class = self.raw.objects[idx].class.clone(); let key = (class.clone(), value.text.to_ascii_lowercase()); @@ -1579,6 +1723,7 @@ impl Executor<'_, L> { }, ); } + self.copy_transformer_bindings(idx, src, base); self.append_source_resets(idx, src, base); let cloned = self.raw.objects[src].props.clone(); let bounds: Vec = self.raw.objects[src] @@ -1587,6 +1732,17 @@ impl Executor<'_, L> { .collect(); self.raw.objects[idx].props.extend(cloned); self.raw.objects[idx].edits.extend(bounds); + if matches!( + class.as_str(), + "line" | "wiredata" | "cndata" | "linegeometry" | "linespacing" + ) { + self.raw + .geometry_timeline + .push(super::geometry::timeline::Action::Copy { + point: self.raw.line_snapshot(idx), + frequency: self.raw.snapshot_frequency(), + }); + } } None => self.raw.warn( &C::READ_DSS_REFERENCE_DROPPED, @@ -1595,6 +1751,94 @@ impl Executor<'_, L> { } } + fn bind_geometry_references( + &mut self, + idx: usize, + p: &RawProp, + ctx: &dyn Fn(String) -> String, + ) -> bool { + if matches!( + self.raw.objects[idx].class.as_str(), + "linegeometry" | "line" + ) && matches!( + p.name.as_deref(), + Some("wire" | "wires" | "cncable" | "cncables") + ) { + let names = if matches!(p.name.as_deref(), Some("wire" | "cncable")) { + vec![p.value.text.clone()] + } else { + p.value.to_string_list(Some(&self.raw.vars)) + }; + if names.len() > 32 + || self + .retained_property_count(idx) + .saturating_add(names.len()) + > MAX_OBJECT_PROPS + || self.raw.total_props.saturating_add(names.len()) > MAX_TOTAL_PROPS + { + self.raw.halt(ctx( + "geometry conductor bindings exceed the supported count/work budget".into(), + )); + return false; + } + self.raw.total_props += names.len(); + let class = if p.name.as_deref().unwrap().starts_with("cn") { + "cndata" + } else { + "wiredata" + }; + let references = names + .iter() + .map(|name| { + self.raw + .index + .get(&(class.into(), name.to_ascii_lowercase())) + .map(|&object| self.raw.line_snapshot(object)) + }) + .collect(); + let offset = self.raw.objects[idx].props.len(); + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .wires + .insert(offset, references); + } + if matches!( + self.raw.objects[idx].class.as_str(), + "linegeometry" | "line" + ) && p.name.as_deref() == Some("spacing") + { + let referenced = self + .raw + .index + .get(&("linespacing".into(), p.value.text.to_ascii_lowercase())) + .map(|&object| self.raw.line_snapshot(object)); + let offset = self.raw.objects[idx].props.len(); + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .spacings + .insert(offset, referenced); + } + if self.raw.objects[idx].class == "line" && p.name.as_deref() == Some("geometry") { + let referenced = self + .raw + .index + .get(&("linegeometry".into(), p.value.text.to_ascii_lowercase())) + .map(|&object| self.raw.line_snapshot(object)); + let offset = self.raw.objects[idx].props.len(); + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .geometries + .insert(offset, referenced); + } + true + } + fn apply_props(&mut self, idx: usize, props: Vec, ctx: &dyn Fn(String) -> String) { self.raw.active = Some(idx); if self.raw.line_history.contains_key(&idx) { @@ -1653,11 +1897,40 @@ impl Executor<'_, L> { .linecodes .insert(offset, referenced); } + if self.raw.objects[idx].class == "transformer" && p.name.as_deref() == Some("xfmrcode") + { + let referenced = self + .raw + .index + .get(&("xfmrcode".into(), p.value.text.to_ascii_lowercase())) + .map(|&index| self.raw.line_snapshot(index)); + let offset = self.raw.objects[idx].props.len(); + self.raw + .line_history + .get_mut(&idx) + .unwrap() + .xfmrcodes + .insert(offset, referenced); + } + if !self.bind_geometry_references(idx, &p, ctx) { + return; + } self.source_reference(idx, &p); if let Some(replay) = self.raw.source_replay.get_mut(&idx) { replay.record_property(&p); } self.raw.objects[idx].props.push(p); + if matches!( + self.raw.objects[idx].class.as_str(), + "line" | "wiredata" | "cndata" | "linegeometry" | "linespacing" + ) { + self.raw + .geometry_timeline + .push(super::geometry::timeline::Action::Property { + point: self.raw.line_snapshot(idx), + offset: self.raw.objects[idx].props.len() - 1, + }); + } } // This command line was one engine Edit; it ends in // RecalcElementData, so record the boundary. diff --git a/powerio-dist/src/dss/read.rs b/powerio-dist/src/dss/read.rs index 07c97a9f0..8db9806d9 100644 --- a/powerio-dist/src/dss/read.rs +++ b/powerio-dist/src/dss/read.rs @@ -31,6 +31,7 @@ use crate::model::{ }; mod lines; +mod open_lines; mod sources; /// Upper bound on any count property (`phases`, conductors, `windings`, tap @@ -132,15 +133,6 @@ fn snapshot_network(raw: &RawDss) -> (MulticonductorNetwork, Vec (MulticonductorNetwork, Vec rd.net.transformers_mut().push(t), + Err(e) => rd.warn( + &C::READ_DSS_TRANSFORMER_UNRESOLVED, + format!("Transformer.{}: {e}", obj.name), + ), + } } for obj in raw.of_class("load") { let l = rd.load(obj); @@ -674,7 +676,7 @@ impl Reader<'_> { } fn load_voltage_model( - &self, + &mut self, props: &Props<'_>, phases: usize, model: i64, @@ -684,6 +686,24 @@ impl Reader<'_> { if model == 2 { return DistLoadVoltageModel::ConstantImpedance { v_nom }; } + if matches!(model, 3 | 4) { + let (p, q) = if model == 3 { + (0.0, 2.0) + } else { + ( + self.f64_prop(props.get("cvrwatts")).unwrap_or(1.0), + self.f64_prop(props.get("cvrvars")).unwrap_or(2.0), + ) + }; + return DistLoadVoltageModel::BoundedExponential { + v_nom, + gamma_p: vec![p; phases], + gamma_q: vec![q; phases], + v_low_pu, + v_min_pu, + v_max_pu, + }; + } if !matches!(model, 1 | 5 | 8) { return DistLoadVoltageModel::ConstantPower { v_nom }; } @@ -773,7 +793,7 @@ impl Reader<'_> { // fields hold explicit power per phase. phases rides too: a 2 // phase delta load also has 3 conductors, so the terminal map // alone cannot reconstruct `phases=`. - let (v_low_pu, v_min_pu, v_max_pu) = if matches!(model, 1 | 5 | 8) { + let (v_low_pu, v_min_pu, v_max_pu) = if matches!(model, 1 | 3 | 4 | 5 | 8) { ( self.f64_prop(props.get("vlowpu")).unwrap_or(0.5), self.f64_prop(props.get("vminpu")).unwrap_or(0.95), @@ -798,6 +818,10 @@ impl Reader<'_> { let v_nom = vec![v_phase; phases]; let voltage_model = self.load_voltage_model(&props, phases, model, v_nom, (v_low_pu, v_min_pu, v_max_pu)); + if model == 4 { + extras.remove("cvrwatts"); + extras.remove("cvrvars"); + } DistLoad { name: obj.name.clone(), bus: spec.name, @@ -813,7 +837,12 @@ impl Reader<'_> { // ----- transformer --------------------------------------------------- #[allow(clippy::too_many_lines)] // OpenDSS transformer edits must be replayed in order - fn transformer(&mut self, obj: &RawObject) -> DistTransformer { + fn transformer( + &mut self, + obj: &RawObject, + raw: &RawDss, + index: usize, + ) -> std::result::Result { // Order matters: wdg= switches the winding under edit, windings= // reallocates. Walk assignments sequentially. let mut phases = dd::transformer::PHASES; @@ -831,10 +860,39 @@ impl Reader<'_> { let mut begin = 0; for end in obj.edit_bounds() { let mut scalar_reactance_changed = false; - for p in &obj.props[begin..end] { + for (offset, p) in obj.props.iter().enumerate().take(end).skip(begin) { let Some(name) = &p.name else { continue }; let v = &p.value; match name.as_str() { + "xfmrcode" => { + let point = raw.line_history[&index].xfmrcodes.get(&offset) + .ok_or("missing XfmrCode binding")? + .ok_or("XfmrCode did not exist at assignment")?; + let code = super::xfmrcode::resolve(raw, point)?; + phases = code.phases; + n_windings = code.windings.len(); + let buses: Vec<_> = windings.iter().map(|w| w.bus.clone()).collect(); + windings = code.windings.iter().enumerate().map(|(i, w)| WindingRaw { + bus: buses.get(i).cloned().flatten(), + conn_delta: w.delta, kv: w.kv, kva: w.kva, tap: w.tap, + r_pct: w.r, r_neutral: Some(w.rneut), x_neutral: Some(w.xneut), + kv_specified: true, kva_specified: true, + }).collect(); + if active >= n_windings { return Err("XfmrCode leaves an invalid winding selector".into()); } + [xhl, xht, xlt] = code.x; + xsc_pct = code.xsc; + xhl_specified = true; + // FetchXfmrCode immediately calls RecalcElementData. + if scalar_reactance_changed && n_windings <= 3 { + let count = xsc_pct.len(); + xsc_pct.clone_from_slice(&code.x[..count]); + } + scalar_reactance_changed = false; + for (key, value) in code.extras { + extras.insert(key, value.into()); + } + } + "phases" => { phases = self.usize_prop(Some(v)).unwrap_or(phases); } @@ -977,13 +1035,13 @@ impl Reader<'_> { } let out = self.finish_windings(&windings, phases, &obj.name); - DistTransformer { + Ok(DistTransformer { name: obj.name.clone(), windings: out, xsc_pct, phases, extras, - } + }) } /// Resolves winding bus specs, terminal maps, and SI ratings, recording @@ -2144,7 +2202,7 @@ mod tests { } #[test] - fn terminal_commands_cannot_silently_leave_the_circuit_closed() { + fn terminal_commands_materialize_fixed_electrical_states() { for command in ["Open", "Close"] { let source = powerio_core::Source::from_memory( "state.dss", @@ -2153,7 +2211,12 @@ mod tests { ) .unwrap(); let mut diagnostics = crate::collect::Diagnostics::new(); - assert!(parse_dss_collecting(&source, &mut diagnostics).is_err()); + let net = parse_dss_collecting(&source, &mut diagnostics).unwrap(); + assert_eq!(net.shunts().len(), usize::from(command == "Open")); + assert_eq!( + net.lines().iter().any(|l| l.name == "l"), + command == "Close" + ); } } diff --git a/powerio-dist/src/dss/read/lines.rs b/powerio-dist/src/dss/read/lines.rs index c08f49174..25fe82340 100644 --- a/powerio-dist/src/dss/read/lines.rs +++ b/powerio-dist/src/dss/read/lines.rs @@ -49,7 +49,7 @@ impl Reader<'_> { } if [ "like", "linecode", "rmatrix", "xmatrix", "cmatrix", "r1", "r0", "x1", "x0", "c1", - "c0", "b1", "b0", "switch", + "c0", "b1", "b0", "switch", "geometry", "spacing", ] .iter() .all(|key| object.get(key).is_none()) @@ -59,22 +59,31 @@ impl Reader<'_> { } } - fn retain_deferred_line(&mut self, object: &super::RawObject) -> bool { + fn retain_deferred_line(&mut self, object: &super::RawObject, reason: Option<&str>) -> bool { if !crate::readiness::DEFERRED_GEOMETRY_KEYS .iter() .any(|key| object.get(key).is_some()) { return false; } - self.warn(&C::READ_DSS_GEOMETRY_UNRESOLVED, format!( - "line {}: geometry-derived conductor impedances are unresolved; the source object is retained and electrical readiness is blocked", object.name, - )); + self.warn( + &C::READ_DSS_GEOMETRY_UNRESOLVED, + format!( + "line {}: {}; the source object is retained and electrical readiness is blocked", + object.name, + reason.unwrap_or("geometry-derived conductor impedances are unresolved"), + ), + ); self.net .untyped_objects_mut() .push(UntypedObject::from(object)); true } + #[expect( + clippy::too_many_lines, + reason = "ordered line resolution and typed lowering stay in one pass" + )] pub(super) fn resolved_lines(&mut self, raw: &RawDss) -> LineResult<()> { self.retain_line_definitions(raw); let mut used: BTreeSet<_> = raw @@ -82,17 +91,31 @@ impl Reader<'_> { .map(|o| o.name.to_ascii_lowercase()) .collect(); let mut resolved = Vec::new(); + let mut joint = raw + .of_class("line") + .any(|o| o.get("geometry").is_some() || o.get("spacing").is_some()) + .then(|| crate::dss::geometry::timeline::resolve(raw)); for (index, object) in raw .objects .iter() .enumerate() .filter(|(_, o)| o.class == "line") { - if self.retain_deferred_line(object) { - continue; - } - let mut state = line::resolve(raw, raw.line_snapshot(index)) - .map_err(|e| format!("Line.{}: {e}", object.name))?; + let result = if let Some(joint) = &mut joint { + joint.remove(&index).ok_or("missing ordered Line state")? + } else { + if self.retain_deferred_line(object, None) { + continue; + } + line::resolve(raw, raw.line_snapshot(index)) + }; + let mut state = match result { + Ok(state) => state, + Err(error) if self.retain_deferred_line(object, Some(&error)) => { + continue; + } + Err(error) => return Err(format!("Line.{}: {error}", object.name)), + }; if state.enabled { let matrices = state .primitive(self.net.base_frequency()) @@ -169,8 +192,12 @@ impl Reader<'_> { "Line.{} has no declared length unit: a one-meter electrical equivalent is used and the source length is retained in extras; no geographic distance is inferred",object.name, )); } + if state.closed.iter().flatten().any(|closed| !closed) { + self.open_line(raw, &line, &code, &state.closed)?; + } else { + self.net.lines_mut().push(line); + } self.net.line_codes_mut().push(code); - self.net.lines_mut().push(line); } Ok(()) } diff --git a/powerio-dist/src/dss/read/open_lines.rs b/powerio-dist/src/dss/read/open_lines.rs new file mode 100644 index 000000000..a0e117ea9 --- /dev/null +++ b/powerio-dist/src/dss/read/open_lines.rs @@ -0,0 +1,192 @@ +//! Fixed open Line ports use the native zero-current Schur complement. +use super::{BusSpec, C, DistLine, DistLineCode, RawDss, Reader}; +use crate::{DistShunt, DistSwitch}; +use num_complex::Complex64 as Complex; + +type Matrix = Vec>; + +fn inverse(mut matrix: Matrix) -> Result { + let n = matrix.len(); + let mut result = vec![vec![Complex::default(); n]; n]; + for (i, row) in result.iter_mut().enumerate() { + row[i] = Complex::new(1.0, 0.0); + } + for k in 0..n { + let pivot = (k..n) + .max_by(|&a, &b| matrix[a][k].norm_sqr().total_cmp(&matrix[b][k].norm_sqr())) + .unwrap(); + if matrix[pivot][k] == Complex::default() { + return Err("open Line series impedance is singular".into()); + } + matrix.swap(k, pivot); + result.swap(k, pivot); + let diagonal = matrix[k][k]; + for j in 0..n { + matrix[k][j] /= diagonal; + result[k][j] /= diagonal; + } + let row = matrix[k].clone(); + let inv_row = result[k].clone(); + for i in 0..n { + if i == k { + continue; + } + let factor = matrix[i][k]; + for j in 0..n { + matrix[i][j] -= factor * row[j]; + result[i][j] -= factor * inv_row[j]; + } + } + } + Ok(result) +} + +fn primitive(code: &DistLineCode, length: f64, closed: &[Vec; 2]) -> Result { + let n = code.r_series.len(); + let impedance = (0..n) + .map(|i| { + (0..n) + .map(|j| Complex::new(code.r_series[i][j], code.x_series[i][j]) * length) + .collect() + }) + .collect(); + let series = inverse(impedance)?; + let mut matrix = vec![vec![Complex::default(); 2 * n]; 2 * n]; + for i in 0..n { + for j in 0..n { + // Native TCMatrix is symmetric. Avoid introducing roundoff + // asymmetry from a general inverse into the typed model. + let y = series[i.max(j)][i.min(j)]; + matrix[i][j] = y + Complex::new(code.g_from[i][j], code.b_from[i][j]) * length; + matrix[n + i][n + j] = y + Complex::new(code.g_to[i][j], code.b_to[i][j]) * length; + matrix[i][n + j] = -y; + matrix[n + i][j] = -y; + } + } + let mut eliminated = vec![false; 2 * n]; + // TDSSCktElement.DoYprimCalcs eliminates terminals then conductors, + // and adds EPSILON=1e-12 S on every external diagonal when any opens. + for k in 0..2 * n { + if closed[k / n][k % n] { + continue; + } + let diagonal = if matrix[k][k] == Complex::default() { + Complex::new(1e-12, 0.0) + } else { + matrix[k][k] + }; + eliminated[k] = true; + for i in 0..2 * n { + if eliminated[i] { + continue; + } + for j in i..2 * n { + if !eliminated[j] { + let reduction = matrix[i][k] * matrix[k][j] / diagonal; + matrix[i][j] -= reduction; + matrix[j][i] = matrix[i][j]; + } + } + } + matrix[k].fill(Complex::default()); + for row in &mut matrix { + row[k] = Complex::default(); + } + } + for (i, row) in matrix.iter_mut().enumerate() { + row[i] += 1e-12; + } + if matrix + .iter() + .flatten() + .any(|v| !v.re.is_finite() || !v.im.is_finite()) + { + return Err("open Line admittance is nonfinite".into()); + } + Ok(matrix) +} + +impl Reader<'_> { + pub(super) fn open_line( + &mut self, + raw: &RawDss, + line: &DistLine, + code: &DistLineCode, + closed: &[Vec; 2], + ) -> Result<(), String> { + let matrix = primitive(code, line.length, closed)?; + let n = line.terminal_map_from.len(); + let base = format!("_pio_open_line_{}", line.name); + let mut stem = base.clone(); + let mut suffix = 0; + // Reserve the whole generated family against declared identifiers and + // bus literals, including devices that the reader has not visited yet. + while self + .buses + .keys() + .any(|s| s.contains(&stem.to_ascii_lowercase())) + || raw.objects.iter().any(|o| { + o.name + .to_ascii_lowercase() + .contains(&stem.to_ascii_lowercase()) + || o.props.iter().any(|p| { + p.value + .text + .to_ascii_lowercase() + .contains(&stem.to_ascii_lowercase()) + }) + }) + || raw.buscoords.iter().any(|b| { + b.bus + .to_ascii_lowercase() + .contains(&stem.to_ascii_lowercase()) + }) + { + suffix += 1; + stem = format!("{base}_{suffix}"); + } + let bus = format!("{stem}_ports"); + let nodes = (1..=2 * n) + .map(|i| i32::try_from(i).expect("Line has at most 32 conductors")) + .collect(); + let terms = self.terminals( + &BusSpec { + name: bus.clone(), + nodes, + }, + 2 * n, + 2 * n, + 2 * n, + ); + self.net.shunts_mut().push(DistShunt::new( + &stem, + &bus, + terms.clone(), + matrix + .iter() + .map(|r| r.iter().map(|v| v.re).collect()) + .collect(), + matrix + .iter() + .map(|r| r.iter().map(|v| v.im).collect()) + .collect(), + )); + for (label, endpoint, original, offset) in [ + ("from", &line.bus_from, &line.terminal_map_from, 0), + ("to", &line.bus_to, &line.terminal_map_to, n), + ] { + let mut contact = DistSwitch::new( + format!("{stem}_{label}"), + endpoint, + &bus, + original.clone(), + terms[offset..offset + n].to_vec(), + false, + ); + contact.i_max.clone_from(&line.i_max); + self.net.switches_mut().push(contact); + } + self.warn(&C::READ_DSS_RETAINED_SOURCE_ONLY,format!("Line.{}: fixed open ports use the native zero-current reduced admittance, including 1e-12 S diagonal stabilization, with ideal external contacts; effective linecode retained and line metadata remains source-only",line.name)); + Ok(()) + } +} diff --git a/powerio-dist/src/dss/write.rs b/powerio-dist/src/dss/write.rs index d833a2ae1..669695f9a 100644 --- a/powerio-dist/src/dss/write.rs +++ b/powerio-dist/src/dss/write.rs @@ -28,8 +28,8 @@ use crate::model::{ use super::read::delta_edges; use super::{lex, prop}; +mod admittance_shunts; mod asymmetric_pair; -mod asymmetric_shunts; mod ideal_switches; mod ideal_transformers; mod loads; @@ -644,6 +644,20 @@ impl DssWriter { if matches!(key.as_str(), "bmopf_subtype") || key.starts_with("pmd_") { continue; // converter bookkeeping } + // Canonical output is a static snapshot and does not regenerate + // loadshape objects. Replaying these references creates dangling + // native dependencies even when the snapshot never uses a shape. + if matches!(class, "load" | "generator" | "vsource") + && matches!(key.as_str(), "daily" | "yearly" | "duty") + { + self.warn( + &C::EMIT_DSS_EXTRAS_DROPPED, + format!( + "{class} {name}: extra `{key}` loadshape reference omitted from the static snapshot; its definition is not regenerated" + ), + ); + continue; + } let known = table.is_some_and(|t| t.props.contains(&key.as_str())); let text = value .as_str() @@ -1452,6 +1466,9 @@ impl DssWriter { let _ = write!(s, " %Rs=({}) taps=({})", rs.join(", "), taps.join(", ")); self.transformer_reactances(t, &mut s); let mut extras = t.extras.clone(); + // Winding resistances are authoritative; replaying the derived + // total would overwrite unequal first/second winding values. + extras.remove("%loadloss"); // Typed reactances determine output after an IR load or mutation. if t.xsc_pct.len() == nw * (nw - 1) / 2 { extras.remove("xscarray"); @@ -1725,8 +1742,6 @@ impl DssWriter { }); let mut extras = l.extras.clone(); strip_emitted_extras(&mut extras, &["kv", "phases", "conn"]); - let retained_model = extras.remove("model"); - let retained_zipv = extras.remove("zipv"); // q that came from a power factor goes back as pf=, so the // engine recomputes its own kvar bit for bit. let reactive = match extras.remove("pf").and_then(|v| v.as_f64()) { @@ -1740,8 +1755,17 @@ impl DssWriter { num(kv), num(kw), ); + self.write_load_voltage_model(l, &mut extras, &mut s); + self.add_default_load_voltage_bounds(&mut extras); + s.push_str(&self.extras_tail("load", &l.name, &extras)); + self.line_out(&s); + } + + fn write_load_voltage_model(&mut self, l: &DistLoad, extras: &mut Extras, s: &mut String) { + let retained_model = extras.remove("model"); + let retained_zipv = extras.remove("zipv"); let nominal_model = l.voltage_model.without_voltage_bounds(); - let bounded_cutoff = load_voltage_bounds(&l.voltage_model, &mut extras); + let bounded_cutoff = load_voltage_bounds(&l.voltage_model, extras); match &nominal_model { DistLoadVoltageModel::ConstantPower { .. } => { if bounded_cutoff.is_none() @@ -1789,7 +1813,26 @@ impl DssWriter { ); } } - DistLoadVoltageModel::BoundedZip { .. } => unreachable!("bounds handled above"), + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } => { + unreachable!("bounds handled above") + } + DistLoadVoltageModel::Exponential { + gamma_p, gamma_q, .. + } if matches!( + l.voltage_model, + DistLoadVoltageModel::BoundedExponential { .. } + ) => + { + extras.remove("cvrwatts"); + extras.remove("cvrvars"); + let _ = write!( + s, + " model=4 cvrwatts={} cvrvars={}", + num(gamma_p[0]), + num(gamma_q[0]) + ); + } DistLoadVoltageModel::Exponential { .. } => { self.warn(&C::EMIT_DSS_VALUE_SUBSTITUTED, format!( "load {}: exponential voltage model has no OpenDSS load model code; emitted constant power", @@ -1797,9 +1840,6 @@ impl DssWriter { )); } } - self.add_default_load_voltage_bounds(&mut extras); - s.push_str(&self.extras_tail("load", &l.name, &extras)); - self.line_out(&s); } fn add_default_load_voltage_bounds(&self, extras: &mut Extras) { @@ -2186,7 +2226,7 @@ impl DssWriter { fn shunts(&mut self, net: &MulticonductorNetwork) { for (index, sh) in net.shunts().iter().enumerate() { - if self.asymmetric_shunt(net, sh, index) { + if self.full_admittance_shunt(net, sh, index) { continue; } let stashed_delta = shunt_stashed_delta(sh); @@ -2945,6 +2985,18 @@ fn shunt_kvar( } fn load_voltage_bounds(model: &DistLoadVoltageModel, extras: &mut Extras) -> Option { + if let DistLoadVoltageModel::BoundedExponential { + v_low_pu, + v_min_pu, + v_max_pu, + .. + } = model + { + extras.insert("vlowpu".into(), (*v_low_pu).into()); + extras.insert("vminpu".into(), (*v_min_pu).into()); + extras.insert("vmaxpu".into(), (*v_max_pu).into()); + return Some(0.0); + } if let DistLoadVoltageModel::BoundedZip { v_low_pu, v_min_pu, @@ -4322,23 +4374,21 @@ mod tests { ..MulticonductorNetworkTables::default() }); let out = emit_dss_text(&net); - let line = out - .text - .lines() - .find(|l| l.contains("Capacitor.capx")) - .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text)); - assert!(line.contains("conn=wye"), "{line}"); + assert!(out.text.contains("_pio_shunt_0_pair_")); assert!( out.render_diagnostics() .iter() - .any(|w| w.contains("off diagonal")), - "{:?}", - out.render_diagnostics() + .any(|w| w.contains("full admittance")) + ); + assert!( + !out.render_diagnostics() + .iter() + .any(|w| w.contains("only the diagonal")) ); } #[test] - fn stashed_delta_matrix_warns_when_scalar_emission_is_lossy() { + fn stashed_delta_matrix_preserves_unequal_branches() { let (b, vs) = three_phase_source(2400.0); let bmat = vec![ vec![0.003, -0.001, -0.002], @@ -4364,18 +4414,16 @@ mod tests { ..MulticonductorNetworkTables::default() }); let out = emit_dss_text(&net); - let line = out - .text - .lines() - .find(|l| l.contains("Capacitor.capx")) - .unwrap_or_else(|| panic!("no capacitor emitted in:\n{}", out.text)); - assert!(line.contains("conn=delta"), "{line}"); + assert!(out.text.contains("_pio_shunt_0_pair_")); assert!( out.render_diagnostics() .iter() - .any(|w| w.contains("no scalar capacitor expression")), - "{:?}", - out.render_diagnostics() + .any(|w| w.contains("full admittance")) + ); + assert!( + !out.render_diagnostics() + .iter() + .any(|w| w.contains("only the average")) ); } @@ -4438,7 +4486,7 @@ mod tests { let (b, vs) = three_phase_source(2400.0); let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye); load.extras - .insert("daily".into(), serde_json::json!("a ) b")); + .insert("spectrum".into(), serde_json::json!("a ) b")); let net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables { base_frequency: 60.0, buses: vec![b], @@ -4448,8 +4496,8 @@ mod tests { }); let (first, second) = roundtrip(&net); // A paren wrapper would close at the `)` and land `b)` on the next - // positional property (duty); brackets survive. - assert!(first.contains("daily=[a ) b]"), "{first}"); + // positional property; brackets survive. + assert!(first.contains("spectrum=[a ) b]"), "{first}"); assert_eq!( first.lines().find(|line| line.starts_with("New Load.ld ")), second @@ -4462,7 +4510,7 @@ mod tests { assert_eq!( back.loads()[0] .extras - .get("daily") + .get("spectrum") .and_then(serde_json::Value::as_str), Some("a ) b") ); @@ -4475,7 +4523,8 @@ mod tests { let bad = "a )]}\"' b"; let (b, vs) = three_phase_source(2400.0); let mut load = load_on("sb", &["1", "2", "3", "4"], Configuration::Wye); - load.extras.insert("daily".into(), serde_json::json!(bad)); + load.extras + .insert("spectrum".into(), serde_json::json!(bad)); let mut net = MulticonductorNetwork::from_tables(MulticonductorNetworkTables { base_frequency: 60.0, buses: vec![b], @@ -4486,39 +4535,43 @@ mod tests { net.options_mut().push(("foo".into(), bad.into())); let out = emit_dss_text(&net); assert!(out.text.contains(&format!("Set foo={bad}")), "{}", out.text); - assert!(out.text.contains(&format!("daily={bad}")), "{}", out.text); + assert!( + out.text.contains(&format!("spectrum={bad}")), + "{}", + out.text + ); let warned = |needle: &str| { out.render_diagnostics() .iter() .any(|w| w.contains(needle) && w.contains("emitted as written")) }; assert!(warned("option `foo`"), "{:?}", out.render_diagnostics()); - assert!(warned("`daily`"), "{:?}", out.render_diagnostics()); + assert!(warned("`spectrum`"), "{:?}", out.render_diagnostics()); } #[test] - fn empty_extras_values_wrap_instead_of_eating_the_next_token() { + fn canonical_snapshot_omits_loadshape_references_with_diagnostics() { let dss = "clear\nnew circuit.c basekv=12.47 bus1=sb\n\ - new load.ld bus1=sb.1 phases=1 kv=7.2 kw=10 daily=() duty=sh\nsolve\n"; + new load.ld bus1=sb.1 phases=1 kv=7.2 kw=10 daily=() duty=sh yearly=annual\nsolve\n"; let net = parse_dss_str(dss); - let load = &net.loads()[0]; - assert_eq!(load.extras.get("daily").and_then(|v| v.as_str()), Some("")); - let w1 = emit_dss_text(&net).text; - let again = parse_dss_str(&w1); - let load2 = &again.loads()[0]; - assert_eq!(load2.extras.get("daily").and_then(|v| v.as_str()), Some("")); assert_eq!( - load2.extras.get("duty").and_then(|v| v.as_str()), + net.loads()[0].extras.get("duty").and_then(|v| v.as_str()), Some("sh") ); - let second = emit_dss_text(&again); - assert_eq!( - w1.lines().find(|line| line.starts_with("New Load.ld ")), - second - .text - .lines() - .find(|line| line.starts_with("New Load.ld ")) - ); + let emitted = emit_dss_text(&net); + for key in ["daily", "duty", "yearly"] { + assert!(!emitted.text.contains(&format!(" {key}="))); + assert!( + emitted + .render_diagnostics() + .iter() + .any(|d| d.contains(&format!("`{key}` loadshape reference omitted"))) + ); + } + let again = parse_dss_str(&emitted.text); + assert_eq!(again.loads()[0].p_nom, net.loads()[0].p_nom); + assert_eq!(again.loads()[0].q_nom, net.loads()[0].q_nom); + assert_eq!(again.loads()[0].voltage_model, net.loads()[0].voltage_model); } #[test] diff --git a/powerio-dist/src/dss/write/asymmetric_shunts.rs b/powerio-dist/src/dss/write/admittance_shunts.rs similarity index 60% rename from powerio-dist/src/dss/write/asymmetric_shunts.rs rename to powerio-dist/src/dss/write/admittance_shunts.rs index 0a3cfa2ca..a663a298a 100644 --- a/powerio-dist/src/dss/write/asymmetric_shunts.rs +++ b/powerio-dist/src/dss/write/admittance_shunts.rs @@ -1,18 +1,77 @@ -//! Full nonreciprocal admittances as diagonally shifted two-port blocks. +//! Full admittances: reciprocal branches or shifted nonreciprocal two-port blocks. use super::asymmetric_pair::{self, PairPorts}; use super::{C, DssWriter, num}; use crate::{DistLineCode, DistShunt, MulticonductorNetwork}; use num_complex::Complex64; pub(super) fn needed(shunt: &DistShunt) -> bool { - [&shunt.g, &shunt.b].into_iter().any(|m| { - m.iter().enumerate().any(|(i, row)| { - row.iter() + let n = shunt.terminal_map.len(); + let phases = super::extras_usize(&shunt.extras, "phases").unwrap_or(n); + if symmetric(shunt) + && !super::has_nonzero(&shunt.g) + && (super::shunt_stashed_delta(shunt) || super::looks_like_delta_shunt(&shunt.b, n, phases)) + && super::delta_branch_susceptance(&shunt.b, &super::delta_edges(n, phases), n).is_some() + { + return false; // Existing scalar delta expression is already exact. + } + // Scalar native shunts cannot preserve coupling or unequal diagonal + // values, even when the full matrix is reciprocal. + [&shunt.g, &shunt.b].into_iter().any(|matrix| { + matrix.iter().enumerate().any(|(i, row)| { + row.iter().enumerate().any(|(j, value)| { + if i == j { + matrix.first().and_then(|r| r.first()) != Some(value) + } else { + *value != 0.0 + } + }) + }) + }) +} +fn symmetric(shunt: &DistShunt) -> bool { + [&shunt.g, &shunt.b].into_iter().all(|m| { + m.iter().enumerate().all(|(i, r)| { + r.iter() .enumerate() - .any(|(j, v)| m.get(j).and_then(|r| r.get(i)) != Some(v)) + .all(|(j, v)| m.get(j).and_then(|r| r.get(i)) == Some(v)) }) }) } +struct ReciprocalProjection { + branches: Vec<(usize, usize, Complex64)>, + diagonal: Vec>, +} +fn reciprocal_projection(shunt: &DistShunt) -> Option { + let n = shunt.terminal_map.len(); + let value = |i: usize, j: usize| Complex64::new(shunt.g[i][j], shunt.b[i][j]); + let impedance = |y: Complex64| -> Option { + let z = 1.0 / y; + (z.re.is_finite() && z.im.is_finite() && z != Complex64::default()).then_some(z) + }; + let mut diagonal = (0..n).map(|i| value(i, i)).collect::>(); + let mut branches = Vec::new(); + for i in 0..n { + for j in i + 1..n { + let off = value(i, j); + if off != Complex64::default() { + branches.push((i, j, impedance(-off)?)); + diagonal[i] += off; + diagonal[j] += off; + } + } + } + let diagonal = diagonal + .into_iter() + .map(|y| { + if y == Complex64::default() { + Some(None) + } else { + impedance(y).map(Some) + } + }) + .collect::>>()?; + Some(ReciprocalProjection { branches, diagonal }) +} struct Pair { first: usize, second: usize, @@ -89,9 +148,10 @@ pub(super) fn validate(net: &MulticonductorNetwork) -> Result<(), String> { b.id.eq_ignore_ascii_case(&shunt.bus) && shunt.terminal_map.iter().all(|t| b.terminals.contains(t)) }) || projection(shunt).is_none() + || (symmetric(shunt) && reciprocal_projection(shunt).is_none()) { return Err(format!( - "shunt {}: asymmetric admittance requires declared terminals and a finite exact DSS projection", + "shunt {}: full admittance requires declared terminals and a finite exact DSS projection", shunt.name )); } @@ -99,7 +159,7 @@ pub(super) fn validate(net: &MulticonductorNetwork) -> Result<(), String> { Ok(()) } impl DssWriter { - pub(super) fn asymmetric_shunt( + pub(super) fn full_admittance_shunt( &mut self, net: &MulticonductorNetwork, shunt: &DistShunt, @@ -108,7 +168,7 @@ impl DssWriter { if !needed(shunt) { return false; } - let projection = projection(shunt).expect("validated asymmetric admittance"); + let mut projection = projection(shunt).expect("validated full admittance"); let mut prefix = format!("_pio_shunt_{index}_"); let mut names = super::ideal_transformers::used_names(net); names.extend(net.shunts().iter().map(|s| s.name.to_ascii_lowercase())); @@ -119,6 +179,16 @@ impl DssWriter { while names.iter().any(|n| n.contains(&prefix)) { prefix.push('_'); } + if symmetric(shunt) { + let reciprocal = reciprocal_projection(shunt).expect("validated reciprocal admittance"); + for (k, (i, j, z)) in reciprocal.branches.iter().enumerate() { + let from = self.bus_ref(&shunt.bus, std::slice::from_ref(&shunt.terminal_map[*i])); + let to = self.bus_ref(&shunt.bus, std::slice::from_ref(&shunt.terminal_map[*j])); + self.line_out(&format!("New Line.{prefix}pair_{k} phases=1 bus1={from} bus2={to} length=1 units=m r1={} x1={} r0={} x0={} c1=0 c0=0 basefreq={}",num(z.re),num(z.im),num(z.re),num(z.im),num(net.base_frequency()))); + } + projection.pairs.clear(); + projection.diagonal = reciprocal.diagonal; + } let ground = format!("{}.0.0", shunt.bus); for (k, pair) in projection.pairs.iter().enumerate() { let name = format!("{prefix}pair_{k}"); @@ -147,7 +217,7 @@ impl DssWriter { self.line_out(&format!("New Reactor.{prefix}diagonal_{k} phases=1 bus1={bus} bus2={}.0 r={} x={} basefreq={}",shunt.bus,num(z.re),num(z.im),num(net.base_frequency()))); } } - self.warn(&C::EMIT_DSS_IMPEDANCE_EQUIVALENT,format!("shunt {}: full asymmetric admittance uses {} coupled two-port blocks and exact diagonal corrections under prefix {prefix}; aggregate external terminal currents instead of interpreting internal negative-element losses",shunt.name,projection.pairs.len())); + self.warn(&C::EMIT_DSS_IMPEDANCE_EQUIVALENT,format!("shunt {}: full admittance uses reciprocal impedance branches or {} coupled two-port blocks and exact diagonal corrections under prefix {prefix}; aggregate external terminal currents instead of interpreting internal negative-element losses",shunt.name,projection.pairs.len())); for key in shunt.extras.keys() { self.warn( &C::EMIT_DSS_EXTRAS_DROPPED, diff --git a/powerio-dist/src/dss/write/loads.rs b/powerio-dist/src/dss/write/loads.rs index 14316ed94..2bc9d0e14 100644 --- a/powerio-dist/src/dss/write/loads.rs +++ b/powerio-dist/src/dss/write/loads.rs @@ -12,6 +12,12 @@ fn parameters(model: &DistLoadVoltageModel) -> Vec<&[f64]> { v_nom, gamma_p, gamma_q, + } + | DistLoadVoltageModel::BoundedExponential { + v_nom, + gamma_p, + gamma_q, + .. } => vec![v_nom, gamma_p, gamma_q], DistLoadVoltageModel::Zip { v_nom, @@ -45,6 +51,12 @@ pub(super) fn phase_model(model: &DistLoadVoltageModel, phase: usize) -> DistLoa v_nom, gamma_p, gamma_q, + } + | DistLoadVoltageModel::BoundedExponential { + v_nom, + gamma_p, + gamma_q, + .. } => vec![v_nom, gamma_p, gamma_q], DistLoadVoltageModel::Zip { v_nom, @@ -141,7 +153,11 @@ pub(super) fn validate(net: &MulticonductorNetwork) -> Result<(), String> { for (i, array) in parameters(&load.voltage_model).iter().enumerate() { let legacy_scalar_voltage = i == 0 && array.len() == 1 - && !matches!(load.voltage_model, DistLoadVoltageModel::BoundedZip { .. }); + && !matches!( + load.voltage_model, + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } + ); if (i != 0 || !array.is_empty()) && array.len() != n && !legacy_scalar_voltage { return Err(format!( "load {}: voltage-law array must align with its {n} power branches", diff --git a/powerio-dist/src/dss/write/sources.rs b/powerio-dist/src/dss/write/sources.rs index c43f3d0ab..04129187b 100644 --- a/powerio-dist/src/dss/write/sources.rs +++ b/powerio-dist/src/dss/write/sources.rs @@ -75,7 +75,7 @@ pub(super) fn validate(net: &MulticonductorNetwork) -> Result<(), String> { } } loads::validate(net)?; - super::asymmetric_shunts::validate(net)?; + super::admittance_shunts::validate(net)?; ideal_transformers::validate(net)?; for code in net.line_codes().iter().filter(|c| asymmetric(c)) { if sequence_impedance(code, 1.0).is_none() diff --git a/powerio-dist/src/dss/xfmrcode.rs b/powerio-dist/src/dss/xfmrcode.rs new file mode 100644 index 000000000..6c2fad0d8 --- /dev/null +++ b/powerio-dist/src/dss/xfmrcode.rs @@ -0,0 +1,360 @@ +//! Assignment-time OpenDSS transformer-code state (pinned DSS C-API). +//! +//! XfmrCode.pas at 87d85c2622c8281b92255335bc7c09b11191b21d is the +//! behavioral reference. Winding voltage/rating use kV/kVA; R and X use +//! percent. Source-order copy prefixes reuse the bounded raw history. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use super::{ + line_history::Snapshot, + raw::{RawDss, RawProp}, +}; + +#[derive(Clone, Debug)] +pub(super) struct Winding { + pub delta: bool, + pub kv: f64, + pub kva: f64, + pub tap: f64, + pub r: f64, + pub rneut: f64, + pub xneut: f64, +} + +impl Default for Winding { + fn default() -> Self { + Self { + delta: false, + kv: 12.47, + kva: 1000.0, + tap: 1.0, + r: 0.2, + rneut: -1.0, + xneut: 0.0, + } + } +} + +#[derive(Clone, Debug)] +pub(super) struct State { + pub phases: usize, + pub windings: Vec, + active: usize, + pub x: [f64; 3], + pub xsc: Vec, + changed: bool, + pub extras: BTreeMap, +} + +impl Default for State { + fn default() -> Self { + Self { + phases: 3, + windings: vec![Winding::default(); 2], + active: 0, + x: [7.0, 35.0, 30.0], + xsc: vec![0.0], + changed: false, + extras: [ + ("thermal", 2.0), + ("n", 0.8), + ("m", 0.8), + ("flrise", 65.0), + ("hsrise", 15.0), + ("%loadloss", 0.4), + ("%noloadloss", 0.0), + ("%imag", 0.0), + ("ppm_antifloat", 1.0), + ("normhkva", 1100.0), + ("emerghkva", 1500.0), + ] + .into_iter() + .map(|(k, v)| (k.into(), v.to_string())) + .collect(), + } + } +} + +impl State { + fn finish_edit(&mut self) { + if self.changed && self.windings.len() <= 3 { + let n = self.xsc.len(); + self.xsc.copy_from_slice(&self.x[..n]); + } + self.changed = false; + } + + fn make_like(&mut self, source: &Self) { + // Native MakeLike omits excitation/antifloat and the selector. + let (active, changed) = (self.active, self.changed); + let retained: Vec<_> = ["%imag", "ppm_antifloat"] + .iter() + .map(|&k| (k.to_owned(), self.extras[k].clone())) + .collect(); + *self = source.clone(); + self.active = active; + self.changed = changed; + self.extras.extend(retained); + } + + fn load_loss(&mut self) { + self.extras.insert( + "%loadloss".into(), + (self.windings[0].r + self.windings[1].r).to_string(), + ); + } + + fn ratings(&mut self) { + self.extras + .insert("normhkva".into(), (1.1 * self.windings[0].kva).to_string()); + self.extras + .insert("emerghkva".into(), (1.5 * self.windings[0].kva).to_string()); + } + + fn set_count(&mut self, key: &str, value: f64) -> Result<(), String> { + if !(1.0..=64.0).contains(&value) || value.fract() != 0.0 { + return Err(format!("invalid XfmrCode {key}")); + } + let n = value as usize; + match key { + "phases" => self.phases = n, + "windings" if n >= 2 => { + self.windings = vec![Winding::default(); n]; + self.xsc.resize(n * (n - 1) / 2, 30.0); + } + "wdg" if n <= self.windings.len() => self.active = n - 1, + _ => return Err(format!("invalid XfmrCode {key}")), + } + Ok(()) + } + + fn apply_array(&mut self, key: &str, p: &RawProp, raw: &RawDss) -> Result<(), String> { + let values = p + .value + .to_vector(Some(&raw.vars)) + .map_err(|e| e.to_string())?; + let n = if key == "xscarray" { + self.xsc.len() + } else { + self.windings.len() + }; + if values.len() != n || values.iter().any(|v| !v.is_finite()) { + return Err(format!("invalid XfmrCode {key} array")); + } + if key == "xscarray" { + self.xsc = values; + } else { + let scalar = match key { + "kvs" => "kv", + "kvas" => "kva", + "taps" => "tap", + _ => "%r", + }; + for (w, v) in self.windings.iter_mut().zip(values) { + set_number(w, scalar, v); + } + if key == "kvas" { + self.ratings(); + } + if key == "%rs" { + self.load_loss(); + } + } + Ok(()) + } + + fn apply(&mut self, p: &RawProp, raw: &RawDss) -> Result<(), String> { + let key = p.name.as_deref().ok_or("unnamed XfmrCode property")?; + let number = || { + let v = p.value.to_f64(Some(&raw.vars)).map_err(|e| e.to_string())?; + if v.is_finite() { + Ok(v) + } else { + Err(format!("nonfinite XfmrCode {key}")) + } + }; + match key { + "phases" | "windings" | "wdg" => self.set_count(key, number()?)?, + "conn" => { + let w = self + .windings + .get_mut(self.active) + .ok_or("invalid XfmrCode winding selector")?; + w.delta = connection(&p.value.text)?; + } + "kv" | "kva" | "tap" | "%r" | "rneut" | "xneut" => { + let v = number()?; + let w = self + .windings + .get_mut(self.active) + .ok_or("invalid XfmrCode winding selector")?; + set_number(w, key, v); + if key == "kva" { + if self.active == 0 { + for w in &mut self.windings[1..] { + w.kva = v; + } + self.ratings(); + } else if self.windings.len() == 2 { + self.windings[0].kva = v; + } + } else if key == "%r" { + self.load_loss(); + } + } + "conns" => { + let items = p.value.to_string_list(Some(&raw.vars)); + if items.len() != self.windings.len() { + return Err("XfmrCode connection array has wrong length".into()); + } + for (w, v) in self.windings.iter_mut().zip(items) { + w.delta = connection(&v)?; + } + } + "kvs" | "kvas" | "taps" | "%rs" | "xscarray" => self.apply_array(key, p, raw)?, + "xhl" | "xht" | "xlt" | "x12" | "x13" | "x23" => { + let i = match key { + "xhl" | "x12" => 0, + "xht" | "x13" => 1, + _ => 2, + }; + self.x[i] = number()?; + self.changed = true; + } + "%loadloss" => { + let v = number()?; + self.windings[0].r = v / 2.0; + self.windings[1].r = v / 2.0; + self.extras.insert(key.into(), v.to_string()); + } + "thermal" | "n" | "m" | "flrise" | "hsrise" | "%noloadloss" | "%imag" + | "ppm_antifloat" | "normhkva" | "emerghkva" => { + self.extras.insert(key.into(), number()?.to_string()); + } + // These definition properties do not change the AC primitive or + // fixed tap. The original code object remains retained metadata. + "maxtap" | "mintap" | "numtaps" | "rdcohms" | "seasons" | "ratings" => {} + _ => return Err(format!("unqualified XfmrCode property {key}")), + } + Ok(()) + } +} + +fn set_number(w: &mut Winding, key: &str, value: f64) { + match key { + "kv" => w.kv = value, + "kva" => w.kva = value, + "tap" => w.tap = value, + "%r" => w.r = value, + "rneut" => w.rneut = value, + "xneut" => w.xneut = value, + _ => unreachable!(), + } +} + +fn connection(text: &str) -> Result { + let text = text.to_ascii_lowercase(); + if text == "y" || text == "ln" || (!text.is_empty() && "wye".starts_with(&text)) { + Ok(false) + } else if text == "ll" || (!text.is_empty() && "delta".starts_with(&text)) { + Ok(true) + } else { + Err("invalid XfmrCode winding connection".into()) + } +} + +pub(super) fn resolve(raw: &RawDss, point: Snapshot) -> Result { + let mut cache = HashMap::new(); + let mut pending = vec![(point, false)]; + let mut visiting = HashSet::new(); + let mut budget = 1_usize << 22; + while let Some((point, ready)) = pending.pop() { + if cache.contains_key(&point) { + continue; + } + let history = raw + .line_history + .get(&point.object) + .ok_or("missing XfmrCode history")?; + if raw.objects[point.object].class != "xfmrcode" { + return Err("expected XfmrCode history".into()); + } + let copies = history + .copies + .get(..point.copies) + .ok_or("invalid XfmrCode copy prefix")?; + if ready { + let state = replay(raw, point, &cache, &mut budget)?; + visiting.remove(&point); + cache.insert(point, state); + } else { + if !visiting.insert(point) { + return Err("cyclic XfmrCode history".into()); + } + charge(&mut budget, 1)?; + pending.push((point, true)); + for copy in copies.iter().rev() { + pending.push((copy.source, false)); + } + } + } + cache + .remove(&point) + .ok_or_else(|| "missing resolved XfmrCode".into()) +} + +fn charge(budget: &mut usize, amount: usize) -> Result<(), String> { + *budget = budget + .checked_sub(amount) + .ok_or("XfmrCode evaluation work limit exceeded")?; + Ok(()) +} + +fn replay( + raw: &RawDss, + point: Snapshot, + cache: &HashMap, + budget: &mut usize, +) -> Result { + let object = &raw.objects[point.object]; + let props = object + .props + .get(..point.properties) + .ok_or("invalid XfmrCode property prefix")?; + let edits = object + .edits + .get(..point.edits) + .ok_or("invalid XfmrCode edit prefix")?; + let copies = &raw.line_history[&point.object].copies[..point.copies]; + let mut state = State::default(); + let (mut property, mut edit, mut copy) = (0, 0, 0); + loop { + let next = copies.get(copy); + charge(budget, state.windings.len() * state.windings.len() + 1)?; + if edit < edits.len() && edits[edit] == property && next.is_none_or(|c| edit < c.edit_start) + { + state.finish_edit(); + edit += 1; + } else if let Some(c) = next.filter(|c| c.start == property && c.edit_start == edit) { + state.make_like(cache.get(&c.source).ok_or("unresolved XfmrCode copy")?); + if c.source.object == point.object { + // MakeLike(self) reallocates its own winding records before + // copying them, so the native source records are defaults. + state.windings.fill(Winding::default()); + } + property = c.end; + edit = c.edit_end; + copy += 1; + } else if property < props.len() { + state.apply(&props[property], raw)?; + property += 1; + } else { + break; + } + } + if edit != edits.len() || copy != copies.len() { + return Err("unconsumed XfmrCode history".into()); + } + Ok(state) +} diff --git a/powerio-dist/src/lindist3flow.rs b/powerio-dist/src/lindist3flow.rs index 66fc7190c..11f02a46a 100644 --- a/powerio-dist/src/lindist3flow.rs +++ b/powerio-dist/src/lindist3flow.rs @@ -479,56 +479,48 @@ fn lower_capacitors( Ok(()) } -// Bounded ZIP is projected only by the explicit approximation policy. -// Strict preparation retains the complete law and its transition bounds. -fn nominal_bounded_zip(load: &crate::DistLoad) -> Result> { - let DistLoadVoltageModel::BoundedZip { - v_nom, - alpha_z, - alpha_i, - alpha_p, - beta_z, - beta_i, - beta_p, - v_low_pu, - v_min_pu, - v_max_pu, - cutoff_pu, - } = &load.voltage_model - else { - return Ok(None); +// Select only a smooth nominal branch. The existing nominal-law projection +// handles the coefficients; the source law and bounds remain in the audit. +fn nominal_bounded_load(load: &crate::DistLoad) -> Result> { + let model = &load.voltage_model; + let (low, min, max) = match model { + DistLoadVoltageModel::BoundedZip { + v_low_pu, + v_min_pu, + v_max_pu, + cutoff_pu, + .. + } if cutoff_pu.is_finite() && (0.0..1.0).contains(cutoff_pu) => { + (*v_low_pu, *v_min_pu, *v_max_pu) + } + DistLoadVoltageModel::BoundedExponential { + v_low_pu, + v_min_pu, + v_max_pu, + .. + } => (*v_low_pu, *v_min_pu, *v_max_pu), + _ => return Ok(None), }; - if ![*v_low_pu, *v_min_pu, *v_max_pu, *cutoff_pu] - .iter() - .all(|x| x.is_finite()) - || !(0.0..1.0).contains(v_low_pu) - || *v_min_pu >= 1.0 - || *v_max_pu <= 1.0 - || !(0.0..1.0).contains(cutoff_pu) + if ![low, min, max].iter().all(|value| value.is_finite()) + || !(0.0..1.0).contains(&low) + || min >= 1.0 + || max <= 1.0 { return Ok(None); } let n = load.p_nom.len(); - if n == 0 || load.q_nom.len() != n || v_nom.len() != n { + if n == 0 || load.q_nom.len() != n || model.v_nom().len() != n { return Err(fail(format!( "load `{}` bounded law has invalid channel dimensions", load.name ))); } - for (channel, &voltage) in v_nom.iter().enumerate() { - load.voltage_model + for (channel, &voltage) in model.v_nom().iter().enumerate() { + model .power_scale(channel, voltage) .map_err(|error| fail(format!("load `{}`: {error}", load.name)))?; } - Ok(Some(DistLoadVoltageModel::Zip { - v_nom: v_nom.clone(), - alpha_z: alpha_z.clone(), - alpha_i: alpha_i.clone(), - alpha_p: alpha_p.clone(), - beta_z: beta_z.clone(), - beta_i: beta_i.clone(), - beta_p: beta_p.clone(), - })) + Ok(Some(model.without_voltage_bounds())) } fn approximate_loads( @@ -545,7 +537,7 @@ fn approximate_loads( } }; for load in network.loads_mut() { - let nominal = nominal_bounded_zip(load)?; + let nominal = nominal_bounded_load(load)?; let model = nominal.as_ref().unwrap_or(&load.voltage_model); let approximation = match model { DistLoadVoltageModel::ConstantCurrent { v_nom } => Some(DistLoadVoltageModel::Zip { diff --git a/powerio-dist/src/load_voltage.rs b/powerio-dist/src/load_voltage.rs index bfcac8a23..c135181df 100644 --- a/powerio-dist/src/load_voltage.rs +++ b/powerio-dist/src/load_voltage.rs @@ -16,6 +16,12 @@ impl DistLoadVoltageModel { /// Above the low threshold, a positive cutoff multiplies the result by /// `(1 + tanh(500 * (u - cutoff_pu))) / 2`. /// + /// For a bounded exponential law the middle-band factors are + /// `u^gamma_p` and `u^gamma_q`. Both factors become `u²` below the low + /// threshold, `u * (low + (1/min - low) * (u-low)/(min-low))` between + /// low and min, and `(u/max)²` above max (using `u²` when max is zero). + /// These continuations need not join the exponential law continuously. + /// /// Returns an error for missing coefficients, invalid parameters or /// nonfinite evaluation instead of manufacturing a nominal load law. #[expect( @@ -50,6 +56,18 @@ impl DistLoadVoltageModel { Self::Exponential { gamma_p, gamma_q, .. } => [voltage_pu.powf(at(gamma_p)?), voltage_pu.powf(at(gamma_q)?)], + Self::BoundedExponential { + gamma_p, + gamma_q, + v_low_pu, + v_min_pu, + v_max_pu, + .. + } => bounded_exponential_scale( + voltage_pu, + [at(gamma_p)?, at(gamma_q)?], + [*v_low_pu, *v_min_pu, *v_max_pu], + )?, Self::Zip { alpha_z, alpha_i, @@ -144,6 +162,19 @@ impl DistLoadVoltageModel { #[must_use] #[allow(clippy::float_cmp)] // Only exact coefficient identities permit this projection. pub fn without_voltage_bounds(&self) -> Self { + if let Self::BoundedExponential { + v_nom, + gamma_p, + gamma_q, + .. + } = self + { + return Self::Exponential { + v_nom: v_nom.clone(), + gamma_p: gamma_p.clone(), + gamma_q: gamma_q.clone(), + }; + } let Self::BoundedZip { v_nom, alpha_z, @@ -182,3 +213,25 @@ impl DistLoadVoltageModel { } } } + +fn bounded_exponential_scale( + u: f64, + gamma: [f64; 2], + bounds: [f64; 3], +) -> Result<[f64; 2], String> { + if bounds.iter().any(|v| !v.is_finite() || *v < 0.0) { + return Err("load voltage thresholds must be finite and nonnegative".into()); + } + let [low, min, max] = bounds; + // Preserve the native branch order even when thresholds overlap. + let scale = if u <= low { + u * u + } else if u <= min { + u * (low + (1.0 / min - low) * (u - low) / (min - low)) + } else if u > max { + u * u / if max == 0.0 { 1.0 } else { max * max } + } else { + return Ok(gamma.map(|exponent| u.powf(exponent))); + }; + Ok([scale; 2]) +} diff --git a/powerio-dist/src/model.rs b/powerio-dist/src/model.rs index 3f04f5911..db2ba3ade 100644 --- a/powerio-dist/src/model.rs +++ b/powerio-dist/src/model.rs @@ -435,6 +435,19 @@ pub enum DistLoadVoltageModel { v_max_pu: f64, cutoff_pu: f64, }, + /// Exponential law inside a voltage band, with nominal-impedance + /// continuation below `v_low_pu`, current interpolation up to `v_min_pu`, + /// and impedance continuation above `v_max_pu`. The continuations apply + /// equally to P and Q, independently of their middle-band exponents. + /// See [`Self::power_scale`] for the equations. Arrays follow active branches. + BoundedExponential { + v_nom: Vec, + gamma_p: Vec, + gamma_q: Vec, + v_low_pu: f64, + v_min_pu: f64, + v_max_pu: f64, + }, } impl Default for DistLoadVoltageModel { @@ -452,7 +465,8 @@ impl DistLoadVoltageModel { | Self::ConstantImpedance { v_nom } | Self::Zip { v_nom, .. } | Self::Exponential { v_nom, .. } - | Self::BoundedZip { v_nom, .. } => v_nom, + | Self::BoundedZip { v_nom, .. } + | Self::BoundedExponential { v_nom, .. } => v_nom, } } } diff --git a/powerio-dist/src/pmd/write.rs b/powerio-dist/src/pmd/write.rs index bb88b80a4..8d75e04eb 100644 --- a/powerio-dist/src/pmd/write.rs +++ b/powerio-dist/src/pmd/write.rs @@ -726,11 +726,18 @@ impl Writer { } }; let nominal_model = l.voltage_model.without_voltage_bounds(); - if matches!(l.voltage_model, DistLoadVoltageModel::BoundedZip { .. }) { + if matches!( + l.voltage_model, + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } + ) { self.warn(&C::EMIT_PMD_VALUE_SUBSTITUTED, format!("{what}: voltage-band transitions and dropout have no PMD load-law field; emitted the nominal law")); } let model = match &nominal_model { - DistLoadVoltageModel::BoundedZip { .. } => unreachable!("bounds handled above"), + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } => { + unreachable!("bounds handled above") + } DistLoadVoltageModel::ConstantImpedance { v_nom } => { insert_vm_nom(v_nom); "IMPEDANCE" diff --git a/powerio-dist/src/readiness.rs b/powerio-dist/src/readiness.rs index 544d57bf9..11d07b5cd 100644 --- a/powerio-dist/src/readiness.rs +++ b/powerio-dist/src/readiness.rs @@ -2,8 +2,8 @@ //! //! Parsing and electrical readiness are deliberately separate. A source can be //! syntactically valid while the resulting typed network is not safe to hand -//! to a solver or semantic writer. In particular, OpenDSS line geometry is -//! still deferred: until Carson/geometry lowering exists, a geometry-defined +//! to a solver or semantic writer. Unresolved OpenDSS geometry metadata +//! must remain blocked: a geometry-defined //! line must not be treated as electrically complete merely because the //! parser has a placeholder linecode. @@ -157,11 +157,10 @@ impl ElectricalReadiness { /// topology, invent conductor counts, or replace missing electrical data with /// source-format defaults. OpenDSS `geometry=`, `spacing=`, `wires=`, /// `cncables=`, and `tscables=` metadata are treated as a hard blocker because -/// the geometry family is not yet lowered into the canonical impedance -/// matrices. A distribution CIM segment whose source states no impedance the -/// reader can use is a hard blocker for the same reason. The audit therefore -/// provides an explicit fail-closed boundary for applications that need to -/// decide whether a parsed network is safe to analyse. +/// those retained references have not been lowered into canonical impedance +/// matrices. Resolved geometry carries explicit matrices instead. A CIM segment +/// whose source states no readable impedance is a hard blocker for the same +/// reason. The audit provides a fail-closed boundary for numerical consumers. #[must_use] pub fn audit_electrical_readiness(net: &MulticonductorNetwork) -> ElectricalReadiness { let mut report = ElectricalReadiness::default(); @@ -272,6 +271,10 @@ fn audit_untyped(net: &MulticonductorNetwork, report: &mut ElectricalReadiness) .is_some_and(|(_, value)| { value.eq_ignore_ascii_case("no") || value.eq_ignore_ascii_case("false") }); + if object.class.eq_ignore_ascii_case("reactor") && !explicitly_disabled { + report.block("READINESS.DSS.REACTOR_UNRESOLVED", &object.name, + "untyped reactor has unresolved electrical behavior; omitting a series reactor can disconnect the feeder"); + } if object.class.eq_ignore_ascii_case("vsource") && !explicitly_disabled { report.block("READINESS.DSS.SOURCE_UNRESOLVED", &object.name, "untyped voltage source must remain explicitly disabled; enabling it requires electrical source conversion"); @@ -481,6 +484,7 @@ fn audit_load_voltage(net: &MulticonductorNetwork, report: &mut ElectricalReadin if matches!( load.voltage_model, crate::DistLoadVoltageModel::BoundedZip { .. } + | crate::DistLoadVoltageModel::BoundedExponential { .. } ) { let n = load.p_nom.len().max(load.q_nom.len()); if n == 0 || load.voltage_model.v_nom().len() != n { @@ -511,6 +515,32 @@ mod tests { use super::*; use crate::{DistBus, DistLine, DistLineCode, Extras, MulticonductorNetwork}; + #[test] + fn unresolved_series_reactor_is_a_blocker_unless_disabled() { + let mut net = MulticonductorNetwork::new(); + net.untyped_objects_mut() + .push(crate::model::UntypedObject::new( + "reactor", + "feed", + vec![ + (Some("bus1".into()), "source".into()), + (Some("bus2".into()), "feeder".into()), + (Some("x".into()), "15".into()), + ], + )); + let report = audit_electrical_readiness(&net); + assert!( + report + .blockers() + .any(|f| f.code == "READINESS.DSS.REACTOR_UNRESOLVED") + ); + assert!(require_electrical_readiness(&net).is_err()); + net.untyped_objects_mut()[0] + .props + .push((Some("enabled".into()), "no".into())); + assert!(audit_electrical_readiness(&net).is_ready()); + } + #[test] fn inactive_source_metadata_cannot_be_reenabled_without_electrical_conversion() { let mut net = MulticonductorNetwork::new(); diff --git a/powerio-dist/tests/dss_direct_spacing.rs b/powerio-dist/tests/dss_direct_spacing.rs new file mode 100644 index 000000000..5e092fc09 --- /dev/null +++ b/powerio-dist/tests/dss_direct_spacing.rs @@ -0,0 +1,23 @@ +use powerio_core::Source; + +#[test] +fn direct_spacing_without_any_geometry_objects_reaches_typed_lines() { + let source = Source::from_memory("direct.dss", "new circuit.c\nnew wiredata.w rac=.0002 radius=.01 radunits=m runits=m\nnew linespacing.s nconds=1 nphases=1 units=m x=[0] h=[10]\nnew line.a bus1=sourcebus.1 bus2=end.1 spacing=s wires=[w] length=100 units=m\n".as_bytes()).unwrap(); + let module = powerio_dist::parse(source).unwrap(); + assert!(module.value().lines().iter().any(|line| line.name == "a")); + assert!(powerio_dist::audit_electrical_readiness(module.value()).is_ready()); +} + +#[test] +fn missing_spacing_and_conductor_bindings_remain_blocked_after_late_definitions() { + for text in [ + "new circuit.c\nnew line.a bus1=sourcebus.1 bus2=end.1 spacing=later\nnew linespacing.later nconds=1 nphases=1 x=[0] h=[10]\n", + "new circuit.c\nnew linespacing.s nconds=1 nphases=1 x=[0] h=[10]\nnew line.a bus1=sourcebus.1 bus2=end.1 spacing=s wires=[later]\nnew wiredata.later rac=.0002 radius=.01\n", + ] { + let module = + powerio_dist::parse(Source::from_memory("missing.dss", text.as_bytes()).unwrap()) + .unwrap(); + assert!(!powerio_dist::audit_electrical_readiness(module.value()).is_ready()); + assert!(module.value().lines().iter().all(|line| line.name != "a")); + } +} diff --git a/powerio-dist/tests/dss_xfmrcode.rs b/powerio-dist/tests/dss_xfmrcode.rs new file mode 100644 index 000000000..faa9aa0ff --- /dev/null +++ b/powerio-dist/tests/dss_xfmrcode.rs @@ -0,0 +1,100 @@ +use powerio_core::Source; +mod helpers; + +fn source(name: &str, text: &str) -> Source { + Source::from_memory(name, text.as_bytes()).unwrap() +} + +#[test] +fn code_binding_keeps_historical_state_and_missing_references_fail() { + let script = "new circuit.c\nnew xfmrcode.c phases=1 kvs=[12 .48] xhl=5\nnew transformer.first xfmrcode=c buses=[sourcebus end]\nedit xfmrcode.c kvs=[12 .24]\nnew transformer.second xfmrcode=c buses=[sourcebus other]\n"; + let module = powerio_dist::parse(source("case.dss", script)).unwrap(); + assert_eq!( + module.value().transformers()[0].windings[1].v_ref.to_bits(), + 480.0_f64.to_bits() + ); + assert_eq!( + module.value().transformers()[1].windings[1].v_ref.to_bits(), + 240.0_f64.to_bits() + ); + assert!( + powerio_dist::parse(source( + "missing.dss", + "new circuit.c\nnew transformer.t xfmrcode=later\nnew xfmrcode.later\n" + )) + .is_err() + ); +} + +#[test] +#[ignore = "requires pinned native transformer-code observations"] +fn pinned_transformer_code_assignments() { + let path = std::env::var("POWERIO_XFMRCODE_ORACLE").expect("native observations"); + let cases: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + for (name, case) in cases.as_object().unwrap() { + let module = powerio_dist::parse(source("case.dss", case["script"].as_str().unwrap())) + .unwrap_or_else(|e| panic!("{name}: {e}")); + for t in module.value().transformers() { + let expected = &case["transformers"][&t.name]; + assert_eq!( + t.phases, + expected["phases"].as_u64().unwrap() as usize, + "{name}" + ); + let windings = expected["windings"].as_array().unwrap(); + assert_eq!(t.windings.len(), windings.len(), "{name}"); + for (i, (w, e)) in t.windings.iter().zip(windings).enumerate() { + for (key, actual) in [ + ("kv", w.v_ref / 1000.0), + ("kva", w.s_rating / 1000.0), + ("tap", w.tap), + ("r", w.r_pct), + ("rneut", w.r_neutral.unwrap_or(-1.0)), + ("xneut", w.x_neutral.unwrap_or(0.0)), + ] { + let expected = e[key].as_f64().unwrap(); + assert!( + (actual - expected).abs() <= 1e-10, + "{name}/{}/{i}/{key}: {actual} != {expected}", + t.name + ); + } + assert_eq!( + w.conn == powerio_dist::DistWindingConn::Delta, + e["delta"].as_bool().unwrap(), + "{name}" + ); + } + let xsc = expected["xsc"].as_array().unwrap(); + assert_eq!(t.xsc_pct.len(), xsc.len(), "{name}"); + for (a, b) in t.xsc_pct.iter().zip(xsc) { + assert!( + (a - b.as_f64().unwrap()).abs() <= 1e-10, + "{name}: {a} != {b}" + ); + } + for (key, e) in expected["extras"].as_object().unwrap() { + let a = t.extras[key].as_str().unwrap().parse::().unwrap(); + assert!( + (a - e.as_f64().unwrap()).abs() <= 1e-10, + "{name}/{key}: {a} != {e}" + ); + } + } + } +} + +#[test] +fn canonical_output_preserves_unequal_and_edited_winding_resistances() { + let module = powerio_dist::parse(source("case.dss", "new circuit.c\nnew xfmrcode.c phases=1 windings=3 kvs=[7.2 .12 .12] kvas=[2000 2000 2000] %rs=[.6 1.2 1.2] xhl=2.04 xht=2.04 xlt=1.36\nnew transformer.t xfmrcode=c buses=[sourcebus house.1.0 house.0.2]\n")).unwrap(); + let mut network = module.value().clone(); + network.transformers_mut()[0].windings[0].r_pct = 0.7; + let output = helpers::emit_dss(&network); + let restored = powerio_dist::parse(source("out.dss", &output.text)).unwrap(); + let resistance: Vec<_> = restored.value().transformers()[0] + .windings + .iter() + .map(|w| w.r_pct) + .collect(); + assert_eq!(resistance, [0.7, 1.2, 1.2]); +} diff --git a/powerio-dist/tests/electrical_readiness.rs b/powerio-dist/tests/electrical_readiness.rs index 9331d1338..4fa49cf8e 100644 --- a/powerio-dist/tests/electrical_readiness.rs +++ b/powerio-dist/tests/electrical_readiness.rs @@ -19,7 +19,7 @@ fn parse_text( } #[test] -fn parsed_geometry_is_blocked_before_analysis() { +fn parsed_overhead_geometry_is_ready_for_analysis() { let module = parse_text( "geometry", r"clear @@ -35,16 +35,12 @@ new line.l bus1=sourcebus bus2=b geometry=g length=1 units=m ); let report = audit_electrical_readiness(module.value()); - assert!(!report.is_ready()); - assert!( - report - .blockers() - .any(|finding| finding.code == "READINESS.DSS.GEOMETRY_DEFERRED") - ); + assert!(report.is_ready(), "{:?}", report.findings); + assert!(report.blockers().next().is_none()); } #[test] -fn parsed_swer_geometry_is_also_blocked() { +fn parsed_single_conductor_geometry_is_ready() { let module = parse_text( "swer", r"clear @@ -57,21 +53,17 @@ new line.l bus1=sourcebus.1 bus2=b.1 geometry=g length=1 units=m ); let report = audit_electrical_readiness(module.value()); - assert!(!report.is_ready()); - assert!( - report - .blockers() - .any(|finding| finding.code == "READINESS.DSS.GEOMETRY_DEFERRED") - ); + assert!(report.is_ready(), "{:?}", report.findings); + assert!(report.blockers().next().is_none()); } -// Unresolved geometry retains its source object and emits a parse diagnostic. +// Resolved geometry retains definitions, without substituting factory matrices. // The Line factory self resistance is (R0 + 2 R1) / 3 in the phase domain. const OPENDSS_FACTORY_R11_PER_M: f64 = 0.098_133_333_333_333_34; #[test] -fn geometry_line_is_reported_at_parse_time_and_not_replaced_by_factory_defaults() { +fn geometry_line_materializes_without_factory_defaults() { let module = parse_text( "geometry-defaults", r"clear @@ -87,16 +79,18 @@ new line.l bus1=sourcebus bus2=b geometry=g length=1 units=m ); assert!( - module + !module .diagnostics() .iter() .any(|finding| finding.code() == "READ.DSS.GEOMETRY_UNRESOLVED"), - "the reader reports unresolved geometry on the parsed module, not only at emission" + "the geometry was electrically resolved" ); let net = module.value(); assert!( - net.lines().iter().all(|line| line.name != "l"), - "a geometry defined line has no typed line" + net.lines() + .iter() + .any(|line| line.name == "l" && line.terminal_map_from.len() == 4), + "all four declared conductors become a typed line" ); assert!( net.line_codes().iter().all(|code| { @@ -110,8 +104,8 @@ new line.l bus1=sourcebus bus2=b geometry=g length=1 units=m assert!( net.untyped_objects() .iter() - .any(|object| object.class.eq_ignore_ascii_case("line") && object.name == "l"), - "the complete source object is retained" + .any(|object| object.class.eq_ignore_ascii_case("linegeometry") && object.name == "g"), + "the source geometry definition is retained" ); } @@ -129,7 +123,7 @@ new line.l bus1=sourcebus.1 bus2=b.1 geometry=g length=1 units=m ); assert!( - module + !module .diagnostics() .iter() .any(|finding| finding.code() == "READ.DSS.GEOMETRY_UNRESOLVED") @@ -146,3 +140,17 @@ new line.l bus1=sourcebus.1 bus2=b.1 geometry=g length=1 units=m "no three conductor linecode was synthesized for a one conductor geometry" ); } + +#[test] +fn missing_geometry_still_blocks_without_a_factory_line() { + let module = parse_text( + "missing-geometry", + "new circuit.c\nnew line.l bus1=sourcebus bus2=end geometry=missing\n", + ); + assert!( + audit_electrical_readiness(module.value()) + .blockers() + .any(|f| f.code == "READINESS.DSS.GEOMETRY_DEFERRED") + ); + assert!(!module.value().lines().iter().any(|line| line.name == "l")); +} diff --git a/powerio-dist/tests/lindist3flow.rs b/powerio-dist/tests/lindist3flow.rs index c678574d3..1ed57e83f 100644 --- a/powerio-dist/tests/lindist3flow.rs +++ b/powerio-dist/tests/lindist3flow.rs @@ -429,8 +429,7 @@ fn permissive_policy_omits_untyped_records_but_lower_retains_them() { ); } -#[test] -fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { +fn assert_bounded_projection(law: &DistLoadVoltageModel) { let mut source = network(); let mut load = DistLoad::new( "demand", @@ -440,19 +439,6 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { vec![100.0], vec![20.0], ); - let law = DistLoadVoltageModel::BoundedZip { - v_nom: vec![230.0], - alpha_z: vec![0.0], - alpha_i: vec![1.0], - alpha_p: vec![0.0], - beta_z: vec![0.0], - beta_i: vec![1.0], - beta_p: vec![0.0], - v_low_pu: 0.5, - v_min_pu: 0.95, - v_max_pu: 1.05, - cutoff_pu: 0.2, - }; load.voltage_model = law.clone(); source.loads_mut().push(load); for policy in [ @@ -460,7 +446,7 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { LinDist3FlowPreparationPolicy::Lower, ] { let prepared = prepare_lindist3flow_network(&source, policy).unwrap(); - assert_eq!(prepared.network().loads()[0].voltage_model, law); + assert_eq!(&prepared.network().loads()[0].voltage_model, law); assert!( !prepared .report() @@ -471,7 +457,7 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { } let prepared = prepare_lindist3flow_network(&source, LinDist3FlowPreparationPolicy::Approximate).unwrap(); - assert_eq!(source.loads()[0].voltage_model, law); + assert_eq!(&source.loads()[0].voltage_model, law); let action = prepared .report() .actions @@ -480,7 +466,7 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { .unwrap(); assert_eq!( action.details["source_voltage_model"], - serde_json::json!(&law) + serde_json::json!(law) ); let projected = &prepared.network().loads()[0].voltage_model; for (actual, expected) in projected @@ -500,15 +486,14 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { (hi[1] - lo[1]) / (2.0 * step), ] }; - for (actual, expected) in slope(projected).into_iter().zip(slope(&law)) { + for (actual, expected) in slope(projected).into_iter().zip(slope(law)) { assert!((actual - expected).abs() < 1e-8); } - let DistLoadVoltageModel::BoundedZip { v_min_pu, .. } = - &mut source.loads_mut()[0].voltage_model - else { - unreachable!() - }; - *v_min_pu = 1.0; + match &mut source.loads_mut()[0].voltage_model { + DistLoadVoltageModel::BoundedZip { v_min_pu, .. } + | DistLoadVoltageModel::BoundedExponential { v_min_pu, .. } => *v_min_pu = 1.0, + _ => unreachable!(), + } let unchanged = prepare_lindist3flow_network(&source, LinDist3FlowPreparationPolicy::Approximate).unwrap(); assert_eq!( @@ -520,3 +505,41 @@ fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { [] as [powerio_dist::LinDist3FlowPreparationAction; 0] ); } + +#[test] +fn bounded_zip_projection_is_explicit_and_preserves_nominal_value_and_slope() { + for (z, i, p) in [ + (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (0.0, 0.0, 1.0), + (0.2, 0.3, 0.5), + ] { + for cutoff_pu in [0.0, 0.2] { + assert_bounded_projection(&DistLoadVoltageModel::BoundedZip { + v_nom: vec![230.0], + alpha_z: vec![z], + alpha_i: vec![i], + alpha_p: vec![p], + beta_z: vec![z], + beta_i: vec![i], + beta_p: vec![p], + v_low_pu: 0.5, + v_min_pu: 0.95, + v_max_pu: 1.05, + cutoff_pu, + }); + } + } +} + +#[test] +fn bounded_exponential_projection_preserves_independent_fractional_slopes() { + assert_bounded_projection(&DistLoadVoltageModel::BoundedExponential { + v_nom: vec![230.0], + gamma_p: vec![-0.5], + gamma_q: vec![1.7], + v_low_pu: 0.5, + v_min_pu: 0.95, + v_max_pu: 1.05, + }); +} diff --git a/powerio-dist/tests/load_voltage.rs b/powerio-dist/tests/load_voltage.rs index f8a3bf155..24c713731 100644 --- a/powerio-dist/tests/load_voltage.rs +++ b/powerio-dist/tests/load_voltage.rs @@ -163,3 +163,154 @@ fn uniform_typed_voltage_edits_override_retained_bank_kv() { } } } + +#[test] +fn exponential_bands_preserve_native_defaults_and_typed_edits() { + for (code, expected_p) in [(3, 0.0), (4, 1.0)] { + let mut module = parse(&format!( + "New Circuit.c phases=1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model={code}\n" + )); + let load = &mut module.value_mut().loads_mut()[0]; + let DistLoadVoltageModel::BoundedExponential { + gamma_p, + gamma_q, + v_min_pu, + v_max_pu, + .. + } = &mut load.voltage_model + else { + panic!("missing typed exponential law") + }; + assert_eq!(gamma_p, &[expected_p]); + assert_eq!(gamma_q, &[2.0]); + *gamma_p = vec![0.7]; + *gamma_q = vec![1.8]; + *v_min_pu = 0.9; + *v_max_pu = 1.1; + load.extras.insert("model".into(), 2.into()); + load.extras.insert("cvrwatts".into(), 9.0.into()); + load.extras.insert("cvrvars".into(), 9.0.into()); + load.extras.insert("vminpu".into(), 0.8.into()); + let expected = load.voltage_model.clone(); + let output = emit_value(module.value(), DistTargetFormat::Dss); + let back = parse(&output.text); + assert_eq!(back.value().loads()[0].voltage_model, expected); + assert_eq!(expected.power_scale(0, 120.).unwrap(), [0.25; 2]); + // Outside the band both powers follow the same fallback, regardless of exponent. + let low = expected.power_scale(0, 168.).unwrap(); + assert!((low[0] - 0.563_888_888_888_888_9).abs() < 1e-14); + assert_eq!(low[0], low[1]); + let high = expected.power_scale(0, 288.).unwrap(); + assert!((high[0] - (1.2_f64 / 1.1).powi(2)).abs() < 1e-14); + assert_eq!(high[0], high[1]); + assert!(expected.power_scale(1, 240.).is_err()); + for target in [DistTargetFormat::BmopfJson, DistTargetFormat::PmdJson] { + let result = emit_value(module.value(), target); + assert!( + result + .warnings + .iter() + .any(|s| s.contains("voltage-band transitions")) + ); + } + } +} + +#[test] +fn per_branch_exponents_survive_dss_decomposition() { + let mut module = parse( + "New Circuit.c phases=3 basekv=.416\nNew Load.l phases=3 bus1=b.1.2.3.0 kv=.416 kw=3 kvar=1.5 model=4\n", + ); + let DistLoadVoltageModel::BoundedExponential { + gamma_p, gamma_q, .. + } = &mut module.value_mut().loads_mut()[0].voltage_model + else { + panic!() + }; + *gamma_p = vec![0.0, 0.7, 1.5]; + *gamma_q = vec![2.0, 1.8, 3.0]; + let expected = module.value().loads()[0].voltage_model.clone(); + let output = emit_value(module.value(), DistTargetFormat::Dss); + let back = parse(&output.text); + assert_eq!(back.value().loads().len(), 3); + for (phase, load) in back.value().loads().iter().enumerate() { + for voltage in [90., 180., 235., 260., 310.] { + assert_eq!( + load.voltage_model.power_scale(0, voltage).unwrap(), + expected.power_scale(phase, voltage).unwrap() + ); + } + } +} + +#[test] +fn exponential_laws_reject_nonfinite_parameters_and_misaligned_arrays() { + let mut module = parse( + "New Circuit.c phases=1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model=4\n", + ); + let DistLoadVoltageModel::BoundedExponential { gamma_p, .. } = + &mut module.value_mut().loads_mut()[0].voltage_model + else { + panic!() + }; + gamma_p[0] = f64::NAN; + assert!( + module.value().loads()[0] + .voltage_model + .power_scale(0, 100.) + .is_err() + ); + assert!( + powerio_dist::audit_electrical_readiness(module.value()) + .findings + .iter() + .any(|f| f.code == "READINESS.LOAD.VOLTAGE_LAW") + ); + let DistLoadVoltageModel::BoundedExponential { gamma_p, .. } = + &mut module.value_mut().loads_mut()[0].voltage_model + else { + panic!() + }; + *gamma_p = vec![1., 2.]; + let canonical = powerio_core::PioModule::new(module.value().clone()); + let error = powerio_dist::emit( + &canonical, + DistTargetFormat::Dss, + powerio_core::Destination::memory("out").unwrap(), + ) + .unwrap_err(); + assert!(error.to_string().contains("voltage-law array"), "{error}"); +} + +#[test] +fn empty_exponential_laws_fail_before_canonical_writing() { + let mut module = parse( + "New Circuit.c phases=1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model=4\n", + ); + let load = &mut module.value_mut().loads_mut()[0]; + load.p_nom.clear(); + load.q_nom.clear(); + let DistLoadVoltageModel::BoundedExponential { + v_nom, + gamma_p, + gamma_q, + .. + } = &mut load.voltage_model + else { + panic!() + }; + v_nom.clear(); + gamma_p.clear(); + gamma_q.clear(); + let canonical = powerio_core::PioModule::new(module.value().clone()); + let error = powerio_dist::emit( + &canonical, + DistTargetFormat::Dss, + powerio_core::Destination::memory("out").unwrap(), + ) + .unwrap_err(); + assert!( + error.to_string().contains("READINESS.LOAD.VOLTAGE_LAW"), + "{error}" + ); +} diff --git a/powerio-dist/tests/matrix.rs b/powerio-dist/tests/matrix.rs index aac952646..62b76073f 100644 --- a/powerio-dist/tests/matrix.rs +++ b/powerio-dist/tests/matrix.rs @@ -250,7 +250,28 @@ fn same_load_voltage_model( a: &DistLoadVoltageModel, b: &DistLoadVoltageModel, allow_derived_v_nom: bool, + allow_exponential_projection: bool, ) -> bool { + if let DistLoadVoltageModel::BoundedExponential { + v_nom, + gamma_p, + gamma_q, + .. + } = a + { + // JSON destinations diagnose the missing voltage band; only BMOPF + // can also retain the nominal exponents. PMD diagnoses their loss. + return same_v_nom(v_nom, b.v_nom(), allow_derived_v_nom) + && match b { + DistLoadVoltageModel::Exponential { + gamma_p: p, + gamma_q: q, + .. + } => gamma_p == p && gamma_q == q, + DistLoadVoltageModel::ConstantPower { .. } => allow_exponential_projection, + _ => false, + }; + } if let DistLoadVoltageModel::BoundedZip { v_nom, alpha_z, @@ -369,7 +390,12 @@ fn assert_loads_eq( &format!("load {} map", x.name), ); assert!( - same_load_voltage_model(&x.voltage_model, &y.voltage_model, allow_derived_v_nom), + same_load_voltage_model( + &x.voltage_model, + &y.voltage_model, + allow_derived_v_nom, + what.contains("→ PMD → back") + ), "{what}: load {} voltage model {:?} vs {:?}", x.name, x.voltage_model, @@ -887,11 +913,13 @@ fn off_diagonal_round_trips() { assert_dss_equivalent(&net, &back, case, "cross-format write"); continue; } - for load in net - .loads() - .iter() - .filter(|l| matches!(l.voltage_model, DistLoadVoltageModel::BoundedZip { .. })) - { + for load in net.loads().iter().filter(|l| { + matches!( + l.voltage_model, + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } + ) + }) { assert!( out.warnings .iter() @@ -899,6 +927,20 @@ fn off_diagonal_round_trips() { && w.contains("voltage-band transitions")), "{what}: lost voltage band without disclosure" ); + if target == Fmt::Pmd + && matches!( + load.voltage_model, + DistLoadVoltageModel::BoundedExponential { .. } + ) + { + assert!( + out.warnings + .iter() + .any(|w| w.contains(&format!("load {}:", load.name)) + && w.contains("exponential load model")), + "{what}: lost exponents without disclosure" + ); + } } let transformers = !(target == Fmt::Bmopf && case.bmopf_restates_transformers); let (expected, actual) = if target == Fmt::Bmopf { diff --git a/powerio-dist/tests/rich.rs b/powerio-dist/tests/rich.rs index 3f7cae701..7f52940e2 100644 --- a/powerio-dist/tests/rich.rs +++ b/powerio-dist/tests/rich.rs @@ -236,11 +236,12 @@ fn rich_opendss_load_models_and_switches_round_trip() { "{}", dss_direct.text ); - assert!( - dss_direct.text.contains("New Load.cp3") && dss_direct.text.contains("model=3"), - "{}", - dss_direct.text - ); + let canonical = parse_dss_str(&dss_direct.text); + assert_eq!(load_model(&canonical, "cp3"), load_model(&net, "cp3")); + assert!(matches!(load_model(&canonical, "cp3"), + DistLoadVoltageModel::BoundedExponential { gamma_p, gamma_q, .. } + if all_close(gamma_p, 0.0) && all_close(gamma_q, 2.0) + )); assert_nominal_json_projection(&net, dss_v_nom, assert_switch_impedance); } @@ -267,7 +268,16 @@ fn assert_nominal_json_projection( load_model(&from_bmopf, "zip"), DistLoadVoltageModel::Zip { .. } )); - for name in ["ci", "zip"] { + assert_eq!(bmopf_doc["load"]["cp3"]["model"], "EXPONENTIAL"); + assert_eq!( + bmopf_doc["load"]["cp3"]["gamma_p"], + serde_json::json!([0., 0., 0.]) + ); + assert_eq!( + bmopf_doc["load"]["cp3"]["gamma_q"], + serde_json::json!([2., 2., 2.]) + ); + for name in ["ci", "zip", "cp3"] { assert!(bmopf.warnings.iter().any( |w| w.contains(&format!("load {name}:")) && w.contains("voltage-band transitions") )); @@ -280,6 +290,12 @@ fn assert_nominal_json_projection( } let dss_back = emit_dss(&from_bmopf); + assert!( + dss_back + .warnings + .iter() + .any(|w| w.contains("load cp3:") && w.contains("exponential voltage model")) + ); let reparsed = parse_dss_str(&dss_back.text); assert_switch_impedance(&reparsed); // JSON retains the nominal law, not the original voltage window. The diff --git a/powerio-matrix/src/mcopf.rs b/powerio-matrix/src/mcopf.rs index 5d55282b9..8375e6073 100644 --- a/powerio-matrix/src/mcopf.rs +++ b/powerio-matrix/src/mcopf.rs @@ -287,7 +287,7 @@ pub struct McAcOpfPreparation { pub struct McOpfLoadLawProjection { /// Source load name. pub load: String, - /// Tag of the source law (`bounded_zip`). + /// Tag of the source law (`bounded_zip` or `bounded_exponential`). pub source_model: String, /// Tag of the nominal law the preparation used. pub projected_model: String, @@ -1106,8 +1106,11 @@ fn prepare_loads( } let projected; let model = if policy == BoundedLoadLawPolicy::ProjectToNominal - && matches!(load.voltage_model, DistLoadVoltageModel::BoundedZip { .. }) - { + && matches!( + load.voltage_model, + DistLoadVoltageModel::BoundedZip { .. } + | DistLoadVoltageModel::BoundedExponential { .. } + ) { projected = load.voltage_model.without_voltage_bounds(); let tag = |model: &DistLoadVoltageModel| { serde_json::to_value(model) @@ -1477,7 +1480,7 @@ fn prepare_load_laws( ], ] } - Law::BoundedZip { .. } => { + Law::BoundedZip { .. } | Law::BoundedExponential { .. } => { return Err(unsupported(&load.name, "voltage-bounded load laws require piecewise IVR equations; a nominal-law approximation is not implicit (opt in with BoundedLoadLawPolicy::ProjectToNominal)")); } _ => return Err(unsupported(&load.name, "unknown load voltage law")), diff --git a/powerio-matrix/tests/mcopf.rs b/powerio-matrix/tests/mcopf.rs index 2cca4e035..46a87c7bb 100644 --- a/powerio-matrix/tests/mcopf.rs +++ b/powerio-matrix/tests/mcopf.rs @@ -955,28 +955,39 @@ fn bounded_load_laws_are_not_silently_projected_by_ivr_preparation() { use powerio_dist::DistLoadVoltageModel as Law; let instance = McAcOpfInstance::from_network(network()).unwrap(); assert!(build_mc_ac_opf_preparation(&instance, &McAcOpfAssemblyOptions::default()).is_ok()); - let law = Law::BoundedZip { - v_nom: vec![230.0], - alpha_z: vec![0.0], - alpha_i: vec![0.0], - alpha_p: vec![1.0], - beta_z: vec![0.0], - beta_i: vec![0.0], - beta_p: vec![1.0], - v_low_pu: 0.5, - v_min_pu: 0.95, - v_max_pu: 1.05, - cutoff_pu: 0.0, - }; - let mut net = network(); - net.loads_mut()[0].voltage_model = law; - let instance = McAcOpfInstance::from_network(net).unwrap(); - let error = - build_mc_ac_opf_preparation(&instance, &McAcOpfAssemblyOptions::default()).unwrap_err(); - assert!( - error.to_string().contains("piecewise IVR equations"), - "{error}" - ); + for law in [ + Law::BoundedZip { + v_nom: vec![230.0], + alpha_z: vec![0.0], + alpha_i: vec![0.0], + alpha_p: vec![1.0], + beta_z: vec![0.0], + beta_i: vec![0.0], + beta_p: vec![1.0], + v_low_pu: 0.5, + v_min_pu: 0.95, + v_max_pu: 1.05, + cutoff_pu: 0.0, + }, + Law::BoundedExponential { + v_nom: vec![230.0], + gamma_p: vec![1.0], + gamma_q: vec![2.0], + v_low_pu: 0.5, + v_min_pu: 0.95, + v_max_pu: 1.05, + }, + ] { + let mut net = network(); + net.loads_mut()[0].voltage_model = law; + let instance = McAcOpfInstance::from_network(net).unwrap(); + let error = + build_mc_ac_opf_preparation(&instance, &McAcOpfAssemblyOptions::default()).unwrap_err(); + assert!( + error.to_string().contains("piecewise IVR equations"), + "{error}" + ); + } } #[test] @@ -1039,6 +1050,28 @@ fn projecting_bounded_load_laws_is_an_explicit_opt_in_with_one_diagnostic_per_lo .unwrap(); assert!(load.coils.iter().all(|coil| coil.load_law.is_some())); + // OpenDSS models 3 and 4 read as a bounded exponential law. + let mut net = network(); + net.loads_mut()[0].voltage_model = Law::BoundedExponential { + v_nom: vec![230.0], + gamma_p: vec![0.0], + gamma_q: vec![2.0], + v_low_pu: 0.5, + v_min_pu: 0.95, + v_max_pu: 1.05, + }; + let instance = McAcOpfInstance::from_network(net).unwrap(); + assert!(build_mc_ac_opf_preparation(&instance, &McAcOpfAssemblyOptions::default()).is_err()); + let prepared = build_mc_ac_opf_preparation(&instance, &opt_in).unwrap(); + assert_eq!( + prepared.load_law_projections[0].source_model, + "bounded_exponential" + ); + assert_eq!( + prepared.load_law_projections[0].projected_model, + "exponential" + ); + // Loads that carry no bounded law are not touched. let instance = McAcOpfInstance::from_network(network()).unwrap(); let prepared = build_mc_ac_opf_preparation(&instance, &opt_in).unwrap(); diff --git a/powerio/examples/dist_network.rs b/powerio/examples/dist_network.rs new file mode 100644 index 000000000..58265acd2 --- /dev/null +++ b/powerio/examples/dist_network.rs @@ -0,0 +1,66 @@ +//! Validation bridge: distribution import, IR and independent canonical targets. +use powerio::{Destination, PioValue, Source}; +use powerio_dist::{DistTargetFormat, audit_electrical_readiness}; + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let input = args + .next() + .ok_or("usage: dist_network INPUT OUTPUT_DIRECTORY [ACQUISITION_ROOT]")?; + let output = std::path::PathBuf::from(args.next().ok_or("missing output directory")?); + let mut source = Source::open(input)?; + if let Some(root) = args.next() { + source = source.with_acquisition_root(root)?; + } + if args.next().is_some() { + return Err("unexpected argument".into()); + } + std::fs::create_dir_all(&output)?; + let module = powerio_dist::parse(source)?; + let ir = output.join("network.pio.json"); + powerio::serialize(&module, ir.as_path())?; + let restored = powerio::deserialize(ir.as_path())?; + let PioValue::MulticonductorNetwork(network) = restored.value() else { + return Err("IR changed structural type".into()); + }; + if serde_json::to_value(network)? != serde_json::to_value(module.value())? { + return Err("IR changed network".into()); + } + let mut targets = serde_json::Map::new(); + for (name, target) in [ + ("dss", DistTargetFormat::Dss), + ("gridlabd", DistTargetFormat::Gridlabd), + ] { + // Fresh module deliberately excludes retained-source replay. + let result = powerio_dist::emit( + &powerio::PioModule::new(network.clone()), + target, + Destination::path(output.join(name)), + ); + let value = match result { + Ok(result) => { + serde_json::json!({"ok": true, "diagnostics": diagnostics(result.diagnostics())}) + } + Err(error) => serde_json::json!({"ok": false, "error": error.to_string()}), + }; + targets.insert(name.into(), value); + } + let readiness = audit_electrical_readiness(network); + println!( + "{}", + serde_json::to_string_pretty(&serde_json::json!({ + "network": network, + "ir_network_equal": true, + "diagnostics": diagnostics(module.diagnostics()), + "readiness": readiness.findings.iter().map(|f| serde_json::json!({"code": f.code, "element": f.element, "message": f.message, "severity": format!("{:?}",f.severity)})).collect::>(), + "targets": targets, + }))? + ); + Ok(()) +} +fn diagnostics(items: &[powerio::Diagnostic]) -> Vec { + items + .iter() + .map(|d| serde_json::json!({"code":d.code(),"message":d.message()})) + .collect() +} diff --git a/powerio/tests/frozen_schemas.rs b/powerio/tests/frozen_schemas.rs index 732f29e0c..69d3b57be 100644 --- a/powerio/tests/frozen_schemas.rs +++ b/powerio/tests/frozen_schemas.rs @@ -470,7 +470,7 @@ fn ir_version_2_schemas_only_add() { ); } } else if name == "DistLoadVoltageModel" { - assert_additive_load_law(earlier, definition, ¤t_defs[name]); + assert_additive_load_laws(earlier, definition, ¤t_defs[name]); } else if name == "MulticonductorNetwork" { assert_located_network_schema_preserved(earlier, definition, ¤t_defs); } else if name == "SourceFormat" { @@ -656,51 +656,89 @@ fn every_powerio_ir_property_is_typed() { assert!(bad.is_empty(), "untyped properties: {bad:?}"); } -fn assert_additive_load_law( +fn assert_additive_load_laws( earlier: &str, published: &serde_json::Value, current: &serde_json::Value, ) { - // A new discriminator is an additive electrical law, not new - // optional fields on a published law that old readers ignore. - // Preserve every old variant exactly and pin the sole addition. + // Explicit discriminators add electrical laws without changing any + // published variant. Pin each addition and its fields, rather than + // accepting an arbitrary increase in the enum's variant count. let old = published["oneOf"].as_array().unwrap(); let new = current["oneOf"].as_array().unwrap(); - assert_eq!(new.len(), old.len() + 1); + let additions: [(&str, &[&str], &[&str]); 2] = [ + ( + "bounded_zip", + &[ + "model", + "v_nom", + "alpha_z", + "alpha_i", + "alpha_p", + "beta_z", + "beta_i", + "beta_p", + "v_low_pu", + "v_min_pu", + "v_max_pu", + "cutoff_pu", + ], + &[], + ), + ( + "bounded_exponential", + &[ + "model", "v_nom", "gamma_p", "gamma_q", "v_low_pu", "v_min_pu", "v_max_pu", + ], + &[], + ), + ]; + assert_eq!(new.len(), old.len() + additions.len()); for variant in old { let tag = &variant["properties"]["model"]["const"]; assert_eq!( new.iter() .find(|candidate| candidate["properties"]["model"]["const"] == *tag), Some(variant), - "{earlier}: load law {tag} changed" + "{earlier}: load law {tag} changed", ); } - let bounded = new + let nominal_voltage = &old .iter() - .find(|variant| variant["properties"]["model"]["const"] == "bounded_zip") - .unwrap(); - assert!( - !old.iter() - .any(|variant| variant["properties"]["model"]["const"] == "bounded_zip") - ); - assert_eq!( - bounded["required"], - serde_json::json!([ - "model", - "v_nom", - "alpha_z", - "alpha_i", - "alpha_p", - "beta_z", - "beta_i", - "beta_p", - "v_low_pu", - "v_min_pu", - "v_max_pu", - "cutoff_pu" - ]) - ); + .find(|variant| variant["properties"]["model"]["const"] == "constant_power") + .unwrap()["properties"]["v_nom"]; + for (tag, required, optional) in additions { + assert!( + !old.iter() + .any(|variant| variant["properties"]["model"]["const"] == tag), + "{earlier}: {tag} was already published", + ); + let added = new + .iter() + .find(|variant| variant["properties"]["model"]["const"] == tag) + .unwrap(); + assert_eq!(added["type"], "object"); + assert_eq!(added["required"], serde_json::json!(required)); + let fields = added["properties"].as_object().unwrap(); + let mut expected_fields: Vec<_> = required.iter().chain(optional).copied().collect(); + expected_fields.sort_unstable(); + assert_eq!( + fields.keys().map(String::as_str).collect::>(), + expected_fields + ); + for (name, schema) in fields { + let expected = match name.as_str() { + "model" => serde_json::json!({"type": "string", "const": tag}), + "v_nom" | "alpha_z" | "alpha_i" | "alpha_p" | "beta_z" | "beta_i" | "beta_p" + | "gamma_p" | "gamma_q" => nominal_voltage.clone(), + "v_low_pu" | "v_min_pu" | "v_max_pu" | "cutoff_pu" => { + nominal_voltage["items"].clone() + } + _ => panic!("unexpected {tag} field {name}"), + }; + assert_eq!(schema, &expected, "{tag}.{name} schema changed"); + } + } } fn tagged_monitor_variant(property: &str, tag: &str) -> serde_json::Value { diff --git a/powerio/tests/load_voltage_ir.rs b/powerio/tests/load_voltage_ir.rs index fc90458ed..bf35053d8 100644 --- a/powerio/tests/load_voltage_ir.rs +++ b/powerio/tests/load_voltage_ir.rs @@ -5,20 +5,26 @@ use powerio_dist::DistLoadVoltageModel; #[test] fn bounded_load_law_survives_ir_in_network_and_calculation() { - let source = Source::from_memory("load.dss", b"New Circuit.c phases=1 bus1=b.1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model=5 vminpu=.9 vmaxpu=1.1 vlowpu=.4\n".to_vec()).unwrap(); - let module = powerio_dist::parse(source).unwrap(); - let net = module.value(); - for value in [ - PioValue::from(net.clone()), - PioValue::from(powerio_prob::McAcPfInstance::from_network(net.clone()).unwrap()), + for (model, tag) in [ + (5, "bounded_zip"), + (3, "bounded_exponential"), + (4, "bounded_exponential"), ] { - let text = serialize_module_text(&PioModule::new(value)).unwrap(); - assert!(text.contains("bounded_zip")); - let back = deserialize_module_text(&text).unwrap(); - let again = serialize_module_text(&back).unwrap(); - let first: serde_json::Value = serde_json::from_str(&text).unwrap(); - let second: serde_json::Value = serde_json::from_str(&again).unwrap(); - assert_eq!(first["value"], second["value"]); + let source = Source::from_memory("load.dss", format!("New Circuit.c phases=1 bus1=b.1 basekv=.24\nNew Load.l phases=1 bus1=b.1.0 kv=.24 kw=1 kvar=.5 model={model} vminpu=.9 vmaxpu=1.1 vlowpu=.4\n").into_bytes()).unwrap(); + let module = powerio_dist::parse(source).unwrap(); + let net = module.value(); + for value in [ + PioValue::from(net.clone()), + PioValue::from(powerio_prob::McAcPfInstance::from_network(net.clone()).unwrap()), + ] { + let text = serialize_module_text(&PioModule::new(value)).unwrap(); + assert!(text.contains(tag)); + let back = deserialize_module_text(&text).unwrap(); + let again = serialize_module_text(&back).unwrap(); + let first: serde_json::Value = serde_json::from_str(&text).unwrap(); + let second: serde_json::Value = serde_json::from_str(&again).unwrap(); + assert_eq!(first["value"], second["value"]); + } } } @@ -38,7 +44,8 @@ fn typed_laws_match_native_load_currents() { let load = &net.loads()[0]; assert!(matches!( load.voltage_model, - DistLoadVoltageModel::BoundedZip { .. } + DistLoadVoltageModel::BoundedExponential { .. } + | DistLoadVoltageModel::BoundedZip { .. } | DistLoadVoltageModel::ConstantImpedance { .. } )); let complex = |v: &serde_json::Value| {