griddiagnose

    Multi-model low-voltage distribution diagnostic engine in MoonBit

    power-systems
    outage-localization
    distribution-grid
    power-quality
    phase-loss
    fault-diagnosis
    edge-computing
    wasm
    Download zip
    Author
    Version
    0.5.0
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    2

    #GridDiagnose

    Current release: 0.5.0

    GridDiagnose is a MoonBit-native diagnostic engine for low-voltage distribution networks. One shared evidence and topology layer supports four different operational problems:

    • fault-section localization and multi-fault decomposition;
    • phase loss, three-phase unbalance, undervoltage, and overvoltage;
    • voltage-sag and voltage-swell event detection;
    • stale, frozen, out-of-order, and topologically inconsistent telemetry.

    The project started as the narrower GridLatch outage locator. Version 0.2.0 retains GridLatch as a compatible diagnostic module while broadening the project into a reusable distribution-grid diagnostic engine.

    GridDiagnose multi-model demo

    #Why GridDiagnose

    Distribution operators do not receive one clean signal when equipment fails. They receive a mixture of last-gasp messages, stale samples, phase voltages, power-quality traces, and inaccurate topology records. Treating each alert as an independent dashboard event creates noise; treating every incident as a single outage model misses phase, quality, and measurement problems.

    GridDiagnose provides a common diagnostic contract:

    1. Normalize observations, timestamps, and confidence.
    2. Represent devices and physical sections as a graph.
    3. Evaluate different scenario models against that graph.
    4. Return typed findings, severity, confidence, affected objects, and evidence.

    The result is useful for utility dispatch, campus and park power systems, industrial auxiliary supplies, building electrical operations, microgrids, and commissioning teams. It is not limited to one fixed fault workflow.

    #Diagnostic models

    #Outage and fault-section diagnosis

    The legacy GridLatch model compares proposed open edges with observed meter states. It handles missing communication evidence, confidence decay, source outage candidates, and restoration checks.

    Version 0.2.0 added greedy multi-fault decomposition: each accepted hypothesis must explain at least one currently unexplained outage, then its affected subtree is masked before the next hypothesis is evaluated.

    #Phase diagnosis

    phase_readings provide A/B/C voltages at one or more nodes. The engine detects:

    • loss of one or two phase voltages;
    • voltage unbalance above warning and critical thresholds;
    • sustained undervoltage;
    • sustained overvoltage.

    #Power-quality diagnosis

    voltage_series provide timestamped voltages. The engine uses interval-aware grouping to identify voltage-sag and voltage-swell events, duration, extreme voltage, and relative deviation from nominal.

    #Telemetry integrity diagnosis

    telemetry_series and topology_links expose operational data problems that a pure fault locator cannot explain:

    • stale latest samples;
    • frozen values over a configurable window;
    • duplicate or decreasing timestamps;
    • missing series;
    • declared parent differing from an observed parent.

    #Topology coverage

    assess_topology classifies:

    • radial: one connected component and no cycle;
    • weakly meshed: one connected component with independent cycles;
    • partial: unregistered relationships or isolated meter nodes;
    • disconnected: multiple connected components;
    • empty: no nodes.

    Outage fault localization still requires a rooted tree. If the topology is not radial, the combined report keeps the topology and other diagnostic findings and records that outage localization was skipped rather than silently making an unsafe approximation.

    #Quick start

    Install MoonBit, then run:

    moon update moon check --target wasm-gc --deny-warn moon test --target wasm-gc --deny-warn moon test --target js --deny-warn # Portable JavaScript backend: moon run cmd/griddiagnose --target js -- diagnose examples/griddiagnose_multimodel.json # Machine-readable report: moon run cmd/griddiagnose --target js -- diagnose examples/griddiagnose_multimodel.json --json # Legacy outage commands remain available: moon run cmd/griddiagnose --target js -- analyze examples/branch_fault.json moon run cmd/griddiagnose --target js -- verify examples/restore_case.json

    A Native build can be used when a C/MSVC toolchain is available:

    moon run cmd/griddiagnose --target native -- diagnose examples/griddiagnose_multimodel.json

    #Combined input

    The unified input is defined by schema/griddiagnose-input.schema.json. Only analysis_time is mandatory; each diagnostic section may be supplied independently.

    { "analysis_time": 500, "network": { "root": "T1", "nodes": [ {"id": "T1", "kind": "source"}, {"id": "J1", "kind": "junction"}, {"id": "M1", "kind": "meter"} ], "edges": [ {"id": "E0", "from": "T1", "to": "J1", "section": "feeder"}, {"id": "E1", "from": "J1", "to": "M1", "section": "service M1"} ] }, "unknown_topology_edge_ids": ["X-NEW"], "observations": [ {"node_id": "M1", "state": "outage", "confidence": 0.97} ], "phase_readings": [ { "node_id": "M1", "timestamp": 499, "a_voltage": 230, "b_voltage": 230, "c_voltage": 0 } ], "voltage_series": [ { "node_id": "M1", "nominal_voltage": 230, "samples": [ {"timestamp": 490.00, "voltage": 230}, {"timestamp": 490.01, "voltage": 178}, {"timestamp": 490.02, "voltage": 230} ] } ] }

    The older outage-only contract remains available at schema/gridlatch-input.schema.json.

    #Cross-model causal arbitration

    The diagnose command does not stop at concatenating independent reports. It cross-checks object IDs across models and classifies the incident into:

    • supply_fault;
    • measurement_issue;
    • topology_issue;
    • model_inapplicable;
    • mixed;
    • undetermined;
    • no_incident.

    The arbitration uses relationships that single-threshold checks cannot express:

    • supply findings supported by outage, phase, or voltage evidence are grouped into one electrical-supply hypothesis;
    • a supply finding co-located with a frozen, stale, or clock-invalid series is downgraded to a measurement hypothesis when no independent outage confirms it;
    • declared-vs-observed parent mismatch and unregistered topology objects create a topology hypothesis;
    • a structurally unsupported model, such as a weakly meshed graph passed to the radial outage locator, creates model_inapplicable rather than incorrectly claiming a topology-registration error;
    • outage results produced on a partial topology retain an explicit topology caveat;
    • when distinct physical, measurement, and registration problems coexist, the primary class is mixed and each cause remains separately actionable.
    • when real phase loss and a stuck zero reading are observationally equivalent, the engine emits undetermined and names the missing discriminator.

    The report includes cause confidence, subject IDs, supporting models, evidence, conflicts, and a recommended action. This is the project's core independent contribution: it turns multiple detectors into an explainable root-cause decision.

    Scores are sums of signed feature contributions normalized with a stable softmax. The JSON report includes the complete feature-weight trace and the margin between the top two causes, allowing the decision to be audited rather than trusted as an opaque label.

    #Combined report

    The diagnose command returns separate sections rather than combining unrelated failure models into one opaque score:

    GridDiagnose combined diagnostic report Analysis time: 500 s Critical findings: 6 Warnings: 3 Primary diagnosis: supply_fault (89.8%) Decision margin: 81.5% [supply_fault] 89.8% -> J3, M31, M32, M33, M21 [topology_issue] 8.3% -> M22, network, X-NEW-DEVICE [measurement_issue] 1.9% -> M22 conflict: outage candidates rely on a topology with registration uncertainty Topology: partial nodes=9 edges=8 components=1 cycles=0 Outage hypotheses: 2 1. E2 [J1-J3 cable] stage confidence 49.85% affected: M31, M32, M33 2. E3 [M21 service] stage confidence 80.16% affected: M21 Phase findings: 2 [critical] M21 phase_loss [critical] M31 voltage_unbalance Power-quality events: 2 [critical] M33 voltage_sag [warning] M33 voltage_swell Telemetry findings: 3 [warning] M22 clock_anomaly [warning] M22 constant_series [critical] M22 topology_mismatch

    A committed machine-readable result is available in examples/griddiagnose_multimodel_output.json.

    The key confusion case is covered by three contrast inputs:

    • real phase loss with two sensors and zero phase current;
    • stuck-sensor reading with live phase current and frozen telemetry;
    • one zero-voltage report with no independent current or second sensor.

    They produce supply_fault, measurement_issue, and undetermined respectively. See docs/CONTRAST_CASES.md.

    Two further contrast groups cover sustained undervoltage and topology:

    • corroborated sustained undervoltage -> supply_fault;
    • flat undervoltage plus an independent normal reference -> measurement_issue;
    • single flat undervoltage with no independent evidence -> undetermined;
    • radial network with a wrong parent relation -> topology_issue;
    • weakly meshed network with no registration mismatch -> model_inapplicable.

    #Evaluation

    The legacy outage benchmark contains 36 reproducible scenarios:

    MetricResult
    Overall Top-1 accuracy91.7%
    Top-3 recall94.4%
    Mean affected-meter Jaccard92.6%
    Clean-scenario Top-1100%
    Mixed-scenario Top-191.7%
    Severe-scenario Top-183.3%

    The multi-model benchmark contains 72 deterministic cases, 12 per model:

    ModelPassedAccuracy
    Multi-fault outage12/12100%
    Phase diagnosis12/12100%
    Power quality12/12100%
    Telemetry integrity12/12100%
    Causal arbitration12/12100%
    Contrast cases12/12100%

    These are synthetic benchmark suites with controlled ground truth. They demonstrate behavior and regression safety, not field accuracy on a specific utility network.

    Reproduce both:

    moon build cmd/griddiagnose --target js --release python scripts/evaluate.py \ --bin _build/js/release/build/cmd/griddiagnose/griddiagnose.js \ --cases 36 python scripts/evaluate_multimodel.py \ --bin _build/js/release/build/cmd/griddiagnose/griddiagnose.js \ --cases-per-model 12

    #Interactive demo

    moon build cmd/griddiagnose --target js --release python scripts/build_demo_data.py

    Open demo/index.html. The first scenario is a combined diagnosis containing two independent fault sections, a missing phase, three- phase unbalance, voltage sag and swell, a frozen/stale telemetry series, a clock anomaly, partially unknown topology, and a confirmed topology mismatch.

    #Relationship to existing MoonBit projects

    • MoonElec computes electrical formulas.
    • moon-power-flow and GridFlow solve steady-state power flow.
    • MoonSignalKit provides general streaming statistics and CUSUM utilities.
    • moon-stream-quality provides generic stream-quality rules.
    • GridDiagnose applies physical distribution-network context to combine topology, outage, phase, power-quality, and telemetry evidence.

    The project does not duplicate a power-flow solver, a generic statistics library, or a generic data-quality rule engine.

    #Scope and safety

    GridDiagnose is decision support, not a protection relay or SCADA controller. The current release does not perform full unbalanced power flow, protection coordination, switching commands, or automatic dispatch.

    • Outage localization supports a rooted radial topology.
    • Weakly meshed and partial networks are classified, but unknown physical relationships are not guessed.
    • Multi-fault decomposition is greedy and should be treated as ranked guidance.
    • Phase and power-quality thresholds are configurable defaults, not universal standards.
    • Operator review is required before field work or switching.

    #Repository map

    • inference.mbt, multi_fault.mbt: outage and multi-fault diagnosis.
    • topology.mbt, topology_assessment.mbt: radial localization and general topology classification.
    • phase.mbt: phase-loss and three-phase supply diagnosis.
    • power_quality.mbt: sag and swell event detection.
    • telemetry.mbt: telemetry integrity and topology consistency.
    • diagnostic.mbt, diagnostic_io.mbt: unified report and JSON contract.
    • cmd/griddiagnose: CLI.
    • examples/: hand-checkable legacy and combined scenarios.
    • demo/: interactive multi-model dashboard.
    • scripts/: generators, benchmarks, release checks, and demo builder.

    #License

    Apache-2.0. See LICENSE.

    AnalysisError

    pub suberror AnalysisError {
    Parse(String)
    InvalidInput(String)
    Topology(String)
    }

    AnalysisError::describe

    fn AnalysisError::describe(self : AnalysisError) -> String

    Candidate

    pub struct Candidate {
    edge_id : String
    fault_node_id : String
    section : String
    raw_score : Double
    confidence : Double
    affected_meter_ids : Array[String]
    supporting_node_ids : Array[String]
    contradicting_node_ids : Array[String]
    blind_node_ids : Array[String]
    }

    CausalArbitration

    pub struct CausalArbitration {
    primary_class : String
    overall_confidence : Double
    decision_margin : Double
    causes : Array[CauseHypothesis]
    contributions : Array[EvidenceContribution]
    conflicts : Array[String]
    independent_evidence_sources : Array[String]
    undetermined_reasons : Array[String]
    }

    CauseHypothesis

    pub struct CauseHypothesis {
    class : String
    raw_score : Double
    confidence : Double
    subject_ids : Array[String]
    supporting_models : Array[String]
    evidence : Array[String]
    recommended_action : String
    }

    DiagnosticInput

    pub struct DiagnosticInput {
    analysis_time : Double
    network : Network?
    outage_observations : Array[Observation]
    phase_readings : Array[PhaseReading]
    voltage_series : Array[VoltageSeries]
    telemetry_series : Array[TelemetrySeries]
    topology_links : Array[TopologyLinkObservation]
    unknown_topology_edge_ids : Array[String]
    }

    DiagnosticReport

    pub struct DiagnosticReport {
    version : String
    analysis_time : Double
    topology : TopologyAssessment?
    outage : MultiFaultReport?
    phase : PhaseReport
    power_quality : PowerQualityReport
    telemetry : TelemetryReport
    arbitration : CausalArbitration
    warnings : Array[String]
    critical_count : Int
    warning_count : Int
    }

    Edge

    pub struct Edge {
    id : String
    from_id : String
    to_id : String
    section : String
    }

    Edge::new

    fn Edge::new(id : String, from_id : String, to_id : String, section? : String) -> Edge

    EvidenceContribution

    pub struct EvidenceContribution {
    cause_class : String
    feature : String
    weight : Double
    detail : String
    }

    FaultHypothesis

    pub struct FaultHypothesis {
    rank : Int
    candidate : Candidate
    newly_explained_meter_ids : Array[String]
    }

    InferencePolicy

    pub struct InferencePolicy {
    half_life_sec : Double
    structural_prior : Double
    outage_penalty : Double
    powered_penalty : Double
    }

    InferencePolicy::balanced

    fn InferencePolicy::balanced(half_life_sec : Double, structural_prior : Double) -> InferencePolicy

    InferencePolicy::default

    InferenceResult

    pub struct InferenceResult {
    analysis_time : Double
    candidates : Array[Candidate]
    used_observation_count : Int
    warnings : Array[String]
    }

    InferenceResult::top

    InputDocument

    pub struct InputDocument {
    network : Network
    observations : Array[Observation]
    analysis_time : Double
    confirmed_fault_edge_id : String?
    }

    MultiFaultReport

    pub struct MultiFaultReport {
    faults : Array[FaultHypothesis]
    residual_outage_meter_ids : Array[String]
    iterations : Int
    warnings : Array[String]
    }

    Network

    pub struct Network {
    root_id : String
    nodes : Array[Node]
    edges : Array[Edge]
    }

    Network::find_node

    fn Network::find_node(self : Network, id : String) -> Int?

    Network::new

    fn Network::new(root_id : String, nodes : Array[Node], edges : Array[Edge]) -> Network

    Node

    pub struct Node {
    id : String
    label : String
    kind : NodeKind
    }

    Node::new

    fn Node::new(id : String, kind : NodeKind, label? : String) -> Node

    NodeKind

    pub(all) enum NodeKind {
    Source
    Junction
    Meter
    }

    Role of a node in a low-voltage distribution tree.

    NodeKind::to_string

    fn NodeKind::to_string(self : NodeKind) -> String

    Observation

    pub struct Observation {
    node_id : String
    state : PowerState
    confidence : Double
    observed_at : Double
    }

    Observation::new

    fn Observation::new(node_id : String, state : PowerState, confidence : Double, observed_at : Double) -> Observation

    PhaseFinding

    pub struct PhaseFinding {
    node_id : String
    kind : String
    severity : String
    metric : Double
    affected_phases : Array[String]
    summary : String
    }

    PhaseReading

    pub struct PhaseReading {
    node_id : String
    timestamp : Double
    a_voltage : Double
    b_voltage : Double
    c_voltage : Double
    a_current : Double
    b_current : Double
    c_current : Double
    }

    PhaseReading::new

    fn PhaseReading::new(node_id : String, timestamp : Double, a_voltage : Double, b_voltage : Double, c_voltage : Double, a_current? : Double, b_current? : Double, c_current? : Double) -> PhaseReading

    PhaseReport

    pub struct PhaseReport {
    findings : Array[PhaseFinding]
    warnings : Array[String]
    }

    PowerQualityEvent

    pub struct PowerQualityEvent {
    node_id : String
    source_id : String
    phase : String
    kind : String
    severity : String
    start_time : Double
    end_time : Double
    duration_sec : Double
    extreme_voltage : Double
    deviation_percent : Double
    minimum_voltage : Double
    maximum_voltage : Double
    variation_percent : Double
    }

    PowerQualityReport

    pub struct PowerQualityReport {
    events : Array[PowerQualityEvent]
    warnings : Array[String]
    }

    PowerState

    pub(all) enum PowerState {
    Energized
    Outage
    Unknown
    }

    PowerState::to_string

    fn PowerState::to_string(self : PowerState) -> String

    RestoreReport

    pub struct RestoreReport {
    fault_edge_id : String
    status : RestoreState
    expected_affected_meter_ids : Array[String]
    restored_meter_ids : Array[String]
    still_out_meter_ids : Array[String]
    unknown_meter_ids : Array[String]
    unexpected_outage_node_ids : Array[String]
    }

    RestoreState

    pub(all) enum RestoreState {
    Complete
    Partial
    UnexpectedOutage
    Indeterminate
    }

    RestoreState::to_string

    fn RestoreState::to_string(self : RestoreState) -> String

    TelemetryFinding

    pub struct TelemetryFinding {
    node_id : String
    kind : String
    severity : String
    summary : String
    metric : Double
    }

    TelemetryPoint

    pub struct TelemetryPoint {
    timestamp : Double
    value : Double
    }

    TelemetryPoint::new

    fn TelemetryPoint::new(timestamp : Double, value : Double) -> TelemetryPoint

    TelemetryReport

    pub struct TelemetryReport {
    findings : Array[TelemetryFinding]
    warnings : Array[String]
    }

    TelemetrySeries

    pub struct TelemetrySeries {
    node_id : String
    samples : Array[TelemetryPoint]
    }

    TelemetrySeries::new

    fn TelemetrySeries::new(node_id : String, samples : Array[TelemetryPoint]) -> TelemetrySeries

    TopologyAssessment

    pub struct TopologyAssessment {
    status : String
    node_count : Int
    edge_count : Int
    connected_components : Int
    cycle_rank : Int
    unknown_edge_ids : Array[String]
    isolated_node_ids : Array[String]
    warnings : Array[String]
    }

    General topology classification used by the broader diagnostic pipeline.

    TopologyError

    pub enum TopologyError {
    EmptyNetwork
    RootNotFound(String)
    DuplicateNodeId(String)
    DuplicateEdgeId(String)
    UnknownEndpoint(String)
    NotRadial
    Disconnected(String)
    }

    TopologyError::describe

    fn TopologyError::describe(self : TopologyError) -> String

    TopologyLinkObservation

    pub struct TopologyLinkObservation {
    node_id : String
    declared_parent_id : String
    observed_parent_id : String
    }

    TopologyLinkObservation::new

    fn TopologyLinkObservation::new(node_id : String, declared_parent_id : String, observed_parent_id : String) -> TopologyLinkObservation

    Tree

    pub struct Tree {
    root : Int
    order : Array[Int]
    parent : Array[Int]
    parent_edge : Array[Int]
    children : Array[Array[Int]]
    }

    Tree::node_count

    fn Tree::node_count(self : Tree) -> Int

    Tree::parent

    fn Tree::parent(self : Tree, node : Int) -> Int

    Tree::root

    fn Tree::root(self : Tree) -> Int

    VoltagePoint

    pub struct VoltagePoint {
    timestamp : Double
    voltage : Double
    }

    VoltagePoint::new

    fn VoltagePoint::new(timestamp : Double, voltage : Double) -> VoltagePoint

    VoltageSeries

    pub struct VoltageSeries {
    node_id : String
    source_id : String
    phase : String
    nominal_voltage : Double
    samples : Array[VoltagePoint]
    }

    VoltageSeries::new

    fn VoltageSeries::new(node_id : String, nominal_voltage : Double, samples : Array[VoltagePoint], source_id? : String, phase? : String) -> VoltageSeries

    all_meter_ids

    fn all_meter_ids(network : Network) -> Array[String]

    arbitrate_causes

    fn arbitrate_causes(topology : TopologyAssessment?, outage : MultiFaultReport?, phase : PhaseReport, power_quality : PowerQualityReport, telemetry : TelemetryReport, phase_readings : Array[PhaseReading], voltage_series? : Array[VoltageSeries]) -> CausalArbitration

    Reconcile diagnostic findings by scoring three competing physical hypotheses. Evidence compatibility and object overlap determine the score; no single detector can assign the final primary cause by itself.

    assess_topology

    fn assess_topology(network : Network, unknown_edge_ids? : Array[String]) -> TopologyAssessment

    Assess connectedness and cycle rank without requiring a radial tree.

    build_tree

    fn build_tree(network : Network) -> Result[Tree, TopologyError]

    Validate a radial network and orient it away from its source root.

    diagnose_phase

    fn diagnose_phase(readings : Array[PhaseReading], nominal_voltage? : Double) -> PhaseReport

    Diagnose phase loss, unbalance, sustained undervoltage, and overvoltage.

    diagnose_power_quality

    fn diagnose_power_quality(series : Array[VoltageSeries], minimum_duration_sec? : Double) -> PowerQualityReport

    Detect persistent voltage-sag and voltage-swell intervals.

    diagnose_telemetry

    fn diagnose_telemetry(series : Array[TelemetrySeries], links : Array[TopologyLinkObservation], analysis_time : Double, stale_after_sec? : Double, stuck_window_sec? : Double, constant_tolerance? : Double) -> TelemetryReport

    Diagnose stale series, delayed timestamps, duplicate samples, frozen values, and declared-vs-observed topology mismatches.

    diagnostic_json_string

    fn diagnostic_json_string(report : DiagnosticReport) -> String

    diagnostic_to_json

    fn diagnostic_to_json(report : DiagnosticReport) ->
    Json

    downstream_mask

    fn downstream_mask(tree : Tree, node : Int) -> Array[Bool]

    Mark the supplied node and every node below it in the rooted tree.

    downstream_meter_ids

    fn downstream_meter_ids(network : Network, tree : Tree, node : Int) -> Array[String]

    fault_node_for_edge

    fn fault_node_for_edge(network : Network, tree : Tree, edge_id : String) -> Int?

    infer_faults

    fn infer_faults(network : Network, observations : Array[Observation], analysis_time : Double, policy? : InferencePolicy) -> InferenceResult raise AnalysisError

    Rank fault candidates from noisy outage evidence using topology-aware likelihood scoring. The function is deterministic and does not mutate its inputs.

    infer_multiple_faults

    fn infer_multiple_faults(network : Network, observations : Array[Observation], analysis_time : Double, max_faults? : Int, minimum_confidence? : Double) -> MultiFaultReport raise AnalysisError

    Greedy multi-fault decomposition. Each accepted hypothesis must explain at least one currently unexplained outage and exceed the confidence threshold. Explained observations are masked as unknown before the next iteration.

    network_to_json

    fn network_to_json(network : Network) ->
    Json

    observations_to_json

    fn observations_to_json(observations : Array[Observation]) ->
    Json

    parse_diagnostic_input

    fn parse_diagnostic_input(source : String) -> DiagnosticInput raise AnalysisError

    parse_input

    fn parse_input(source : String) -> InputDocument raise AnalysisError

    Parse the public JSON input contract used by the CLI and demo.

    restore_json_string

    fn restore_json_string(report : RestoreReport) -> String

    restore_to_json

    fn restore_to_json(report : RestoreReport) ->
    Json

    result_json_string

    fn result_json_string(result : InferenceResult) -> String

    result_to_json

    fn result_to_json(result : InferenceResult) ->
    Json

    run_diagnostic

    fn run_diagnostic(input : DiagnosticInput) -> DiagnosticReport

    Run every supplied diagnostic model through one report.

    verify_restoration

    fn verify_restoration(network : Network, fault_edge_id : String, observations : Array[Observation], analysis_time : Double) -> RestoreReport raise AnalysisError

    version

    fn version() -> String

    Public package version. Keep this synchronized with moon.mod.