From 04edfe6de9dd6c0234dc5e3013d08bd1a79629da Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 08:13:41 +1000
Subject: [PATCH 01/15] feat(awb): import and export Isograph Availability
Workbench projects
Read and write AWB 5.0 .awb table stores, map RBD blocks, nodes, links, hierarchies and failure/repair laws, and print a summary of the features either side cannot represent. Adds raptor convert (with --strict and Markdown/JSON reports) and File-menu import/export entries, plus docs/AWB_FORMAT.md.
---
README.md | 7 +-
docs/AWB_FORMAT.md | 352 ++++
docs/completions/raptor | 2 +-
docs/completions/raptor.fish | 3 +
docs/man/raptor-convert.1 | 19 +-
docs/man/raptor.1 | 2 +-
pyproject.toml | 3 +-
raptor/api/awb.py | 41 +
raptor/cli/cmd_info.py | 96 +-
raptor/core/fileio/awb.py | 1597 +++++++++++++++++++
raptor/core/fileio/awb_tables.json | 2384 ++++++++++++++++++++++++++++
raptor/gui/command_table.py | 30 +-
raptor/gui/resources/icons.py | 28 +
raptor/gui/ui/export_mixin.py | 35 +
raptor/gui/ui/file_io_mixin.py | 51 +
tests/unit/test_awb.py | 318 ++++
16 files changed, 4948 insertions(+), 20 deletions(-)
create mode 100644 docs/AWB_FORMAT.md
create mode 100644 raptor/api/awb.py
create mode 100644 raptor/core/fileio/awb.py
create mode 100644 raptor/core/fileio/awb_tables.json
create mode 100644 tests/unit/test_awb.py
diff --git a/README.md b/README.md
index de3bce04..4eb69fde 100644
--- a/README.md
+++ b/README.md
@@ -54,6 +54,9 @@ organisations, and nobody may charge a fee for it without Booz Allen Hamilton's
- **A model file you can read and diff.** `.rbds` is one JSON document with friendly field names, and `raptor diff`
(or **File ▸ Differences**) says in words what changed between two versions of a model. `.rbd` files open and save
exactly as before.
+- **Interchange with Availability Workbench.** `raptor convert` reads and writes Isograph AWB 5.0 `.awb` projects and
+ prints a summary of the features either side cannot represent — capacity products, PM tasks, spares, cost models
+ and the rest — so a conversion never loses something silently. See [`docs/AWB_FORMAT.md`](docs/AWB_FORMAT.md).
- **Documentation that ships with it.** _Break It Before It Breaks_, a 26-chapter tutorial book with a model for each
chapter that opens from the page, a field-by-field reference manual, and a formulas page. **F1** opens the right
section.
@@ -211,7 +214,7 @@ built-in documentation, which the **Help** ribbon tab also opens:
- **AI assistant** — the [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md), the
generated [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), and
the book's MCP chapter.
-- **File format** — [`docs/RBDS_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md) describes the `.rbds` JSON format.
+- **File format** — [`docs/RBDS_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md) describes the `.rbds` JSON format, and [`docs/AWB_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md) describes the Availability Workbench `.awb` interchange.
- **Analytical solver** — [`docs/ANALYTICAL.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md) covers the exact static solver: scope, assumptions, CLI and API.
## IEC 61078
@@ -258,7 +261,7 @@ The docs render with Ruby asciidoctor: `new_docs/tools/render_docs.sh` (see `new
| `raptor/` | The application: `core/` engine, `api/`, `cli/`, `gui/`, `mcp/`, `render/` |
| `tests/` | `unit/`, `behaviour/`, `integration/` (incl. `sweeps/`), `golden/` (Raptor 7's captured output; large captures gzipped), `fixtures/` (probe models), `ladder/`, `data/` (shared sample models) |
| `new_docs/` | User Guide (tutorial book), its models and build tools |
-| `docs/` | Reference manual, [engine design](https://github.com/openpowershift/RaptorStudio/blob/main/docs/engine-design/README.adoc), [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md) and [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), [analytical solver](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md), formulas, [keyboard shortcuts](https://github.com/openpowershift/RaptorStudio/blob/main/docs/KEYBOARD_SHORTCUTS.md), [`.rbds` file format](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md), [IEC 61078](https://github.com/openpowershift/RaptorStudio/blob/main/docs/IEC61078.md) |
+| `docs/` | Reference manual, [engine design](https://github.com/openpowershift/RaptorStudio/blob/main/docs/engine-design/README.adoc), [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md) and [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), [analytical solver](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md), formulas, [keyboard shortcuts](https://github.com/openpowershift/RaptorStudio/blob/main/docs/KEYBOARD_SHORTCUTS.md), [`.rbds` file format](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md), [AWB interchange](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md), [IEC 61078](https://github.com/openpowershift/RaptorStudio/blob/main/docs/IEC61078.md) |
| `tools/` | Developer tools the tests and CI run: engine snapshot, coverage, type gate, doc generators |
| `installer/` | Packaging (PyInstaller, Inno Setup, deb/AppImage) |
| `packaging/` | `raptor-studio-mcp`, the small PyPI package the MCP Registry lists |
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
new file mode 100644
index 00000000..45f81c8c
--- /dev/null
+++ b/docs/AWB_FORMAT.md
@@ -0,0 +1,352 @@
+# AWB project interchange (`.awb`)
+
+**Status:** import/export implemented in `raptor/core/fileio/awb.py`; format
+checked against Availability Workbench 5.0 (AWB, Isograph).
+
+RAPTOR Studio can read and write the project file of Isograph's Availability
+Workbench 5.0 (`.awb`). The conversion is designed for RBD/AvSim projects:
+blocks, nodes, links, hierarchies, failure models and corrective tasks. It
+does **not** try to be a universal AWB database converter. Everything the
+destination cannot represent is counted and named in a summary before the
+conversion is accepted (and, with `--strict`, before anything is written).
+
+```sh
+# RAPTOR -> AWB
+raptor convert model.rbds model.awb
+raptor convert model.rbds model.awb --strict # refuse on any loss
+raptor convert model.rbds model.awb -f json # machine-readable report
+raptor convert model.rbds model.awb --report report.md
+
+# AWB -> RAPTOR
+raptor convert project.awb model.rbds
+raptor convert project.awb model.rbd
+```
+
+AWB's own demonstration mode can *open and simulate* a project but blocks
+**Save** and **Export**. RAPTOR writes the `.awb` file directly, so the
+exporter does not need an AWB licence or a running AWB. To save a file from
+AWB itself you need an AWB licence; that is a licensing restriction in AWB,
+not in the converter.
+
+---
+
+## 1. The file at a glance
+
+An AWB 5.0 `.awb` file is a little-endian binary table store. It is not a
+ZIP, SQLite or Access database. The layout is:
+
+```
+uint32 table count
+table repeated `table count` times
+```
+
+A table record is:
+
+```
+string table name
+uint32 column count
+column repeated `column count` times:
+ string column name
+ uint32 column type (0 string, 1 int32, 2 double, 3 bool/byte)
+uint32 row count
+cell each row, values in column order
+```
+
+A `string` is a varint byte length followed by that many UTF-8 bytes. A
+varint is the usual little-endian base-128 integer: seven data bits per byte,
+high bit set on every byte except the last. An `int32` is four bytes,
+two's-complement, little-endian. A `double` is IEEE-754 binary64,
+little-endian. A bool is one byte; AWB writes 0 or 1.
+
+There is no per-table byte length and no end marker: the reader walks the
+tables and cells in order. A truncated file, an unknown column type, or
+trailing bytes are reported as `AwbFormatError` rather than guessed at.
+
+The six tables RAPTOR writes are:
+
+| Table | Purpose |
+|---|---|
+| `Project` | project settings, lifetime, simulation count, module state |
+| `FailureModels` | failure law per block (or shared by identical blocks) |
+| `FailureModelCorrectiveTasks` | repair task per failure model |
+| `RbdBlocks` | RBD blocks and hierarchy superblocks |
+| `RbdNodes` | RBD nodes and K-of-N votes |
+| `RbdConnections` | links between blocks and nodes |
+
+AWB adds the tables its other modules need when it opens the project. A
+minimal six-table project was opened, validated and simulated by AWB 5.0 in
+demonstration mode; the tables below are the ones that matter to AvSim.
+
+---
+
+## 2. Pages and hierarchies
+
+AWB's page number is the **row index of the superblock that owns the page**.
+This is the key to the whole RBD mapping:
+
+* `RbdBlocks` row 0 is the project root. Its `Page` is `-1`, its `Super` is
+ `1`, and it owns page `0` (the top-level diagram).
+* A superblock row at index `i` owns page `i`. Its own `Page` is the page it
+ is drawn on (the parent page); its contents are the rows whose `Page` is
+ `i`.
+* An ordinary block's `Page` is the page it is drawn on.
+* An `RbdNode`'s `Page` is the page it is drawn on.
+* An `RbdConnection`'s `Page` is the page its two endpoints are drawn on.
+
+So a top-level block has `Page = 0`; a block inside the hierarchy whose
+superblock is row 3 has `Page = 3`; and a nested hierarchy's superblock has
+`Page = 3` while its own contents have `Page = `.
+
+RAPTOR's hierarchy model maps one-to-one:
+
+| RAPTOR | AWB |
+|---|---|
+| `HIERARCHY_DATA` row | `RbdBlocks` row with `Super = 1` |
+| hierarchy id | superblock row index (its page) |
+| hierarchy's parent | the `Page` of the superblock row |
+| `in` / `out` marker nodes | ordinary `RbdNodes` on the hierarchy page |
+| links inside a hierarchy | `RbdConnections` whose `Page` is the hierarchy page |
+| links to a hierarchy | `RbdConnections` whose endpoint is the superblock row |
+
+When an AWB page has no explicit input/output nodes, the importer synthesises
+AWB's `in`/`out` (or RAPTOR's Start/End) and wires the page's first and last
+items to them. If a page has several open ends, an ordinary junction node is
+added so RAPTOR's one-link-per-block rule is kept.
+
+---
+
+## 3. `RbdBlocks` columns RAPTOR uses
+
+The full table has 101 columns in AWB 5.0. The important ones are:
+
+| Column | Type | Meaning |
+|---|---|---|
+| `Id` | string | label, unique in the project (40 characters) |
+| `Description` | string | block description |
+| `Super` | bool | 1 = hierarchy superblock |
+| `Page` | int | page the block is drawn on; `-1` on the root |
+| `FailureModel` | int | row index in `FailureModels`, `-1` for none |
+| `Consequence` | int | row index in `Consequences`, `-1` for none |
+| `Bom` / `Bitmap` | int | row index, `-1` for none |
+| `XPosition`, `YPosition` | double | diagram position |
+| `Width`, `Height` | double | symbol size (RAPTOR writes 100 x 60) |
+| `LogicMode`, `StandbyMode` | int | 0 = normal, no standby |
+| `NonMaintainable` | bool | 1 = a failure is never repaired |
+| `NonOperational` | bool | 1 = block starts out of service |
+| `MaxCapacity` | double | capacity product 1 (not exported) |
+| `MaxCapacity2..4` | double | further capacity products |
+| `Guid` | string | stable object id (AWB accepts a fresh UUID) |
+
+`RbdNodes` has `Id`, `Page`, `Vote`, `XPosition`, `YPosition`,
+`OperationalCapacityTarget` (and the `2..4` variants), `LocalStandby`,
+`NotLogic`, `BackgroundColor` and `Guid`. `Vote` is the K of a K-of-N node.
+
+`RbdConnections` has `Id`, `Page`, `Type`, `Color`,
+`InputObjectType`, `InputObjectIndex`, `OutputObjectType`,
+`OutputObjectIndex` and `Guid`. The object types are:
+
+| Code | Object |
+|---:|---|
+| 20 | ordinary block (`RbdBlocks` row) |
+| 21 | repeat block (`RbdRepeatBlocks` row) |
+| 22 | node (`RbdNodes` row) |
+
+The index is the **zero-based row index** of the object in its own table, not
+the `Id` label.
+
+---
+
+## 4. Failure and repair laws
+
+### AWB failure-model codes
+
+`FailureModels.FmDistribution` is an enum, not a RAPTOR code:
+
+| Code | AWB law | Parameters RAPTOR writes |
+|---:|---|---|
+| 0 | Exponential | `FmMttf` = mean time to failure |
+| 1 | Weibull | `FmEta1` = scale, `FmBeta1` = shape, `FmGamma1` = location |
+| 2 | Bi-Weibull | three modes; RAPTOR keeps the first |
+| 3 | Tri-Weibull | three modes; RAPTOR keeps the first |
+| 4 | Fixed | `FmMttf` = fixed time |
+| 5 | Lognormal | `FmMttf` = mean, `FmStd` = standard deviation |
+| 6 | Normal | `FmMttf` = mean, `FmStd` = standard deviation |
+| 7 | Buffer | stored capacity; no RAPTOR equivalent |
+| 8 | Phased Bi-Weibull | phased; RAPTOR keeps the first mode |
+| 9 | Phased Tri-Weibull | phased; RAPTOR keeps the first mode |
+
+All times in AWB are **hours**. RAPTOR converts from its model unit with
+`raptor/core/units_conv.py` (`days` = 24, `years` = 8760, etc.) and records
+the conversion in the summary.
+
+RAPTOR reads the same enum in reverse. A multi-mode or buffer law becomes
+its first Weibull mode and is listed under "multi-mode or buffer failure
+distribution". A dormant AWB failure (`FmDormant = 1`) becomes a RAPTOR
+block with no repair. A non-zero start-up failure probability is reported
+but cannot be modelled by RAPTOR.
+
+### Repair tasks
+
+`FailureModelCorrectiveTasks` is one row per failure model. RAPTOR writes:
+
+* `FailureModel` = the failure-model row index,
+* `TaskDuration` = mean repair time (RAPTOR's repair law mean, or the fixed
+ duration) in hours,
+* `RampTime` = 0,
+* `Distribution` = 2 with `Std` = 0 (AWB's deterministic/fixed task form),
+* `TaskId` = `CM1`, `CM2`, ... and a fresh `Guid`.
+
+RAPTOR's exponential (4), Weibull (15), lognormal (7), normal (8) and fixed
+(19) failure laws map exactly to AWB 0, 1, 5, 6 and 4. RAPTOR's "None" (18)
+becomes a fixed time of 9e8 hours (never fails). Anything else (gamma,
+triangular, Pearson, ...) becomes an exponential with the same mean and is
+named in the summary.
+
+RAPTOR's repair law is a distribution more often than not. AWB's task
+duration in the generated file is therefore the distribution's **mean**; the
+summary names this as "repair distribution simplified to a fixed duration".
+On import, AWB task codes are read as:
+
+| Code | RAPTOR repair law |
+|---:|---|
+| 0 | Exponential (`TaskDuration` as mean) |
+| 1 | Lognormal (`TaskDuration`, `Std`) |
+| 2 | Normal when `Std > 0`, otherwise Fixed |
+| 3 | Weibull (`Beta`, `TaskDuration`, `Gamma`) |
+| other | Fixed (`TaskDuration`) |
+
+A block with `NonMaintainable = 1`, or a dormant failure, gets RAPTOR's
+`repair_dist = 18` (no repair).
+
+---
+
+## 5. What the summary reports
+
+Every conversion returns a report. The CLI prints it in text, JSON or
+Markdown; `--report FILE` also writes the Markdown. The report has:
+
+* `direction`, `source`, `target`;
+* `counts` — blocks, nodes, hierarchies, links, failure models;
+* `not_in_target` — features the **destination** has no equivalent for,
+ with a count and a short explanation;
+* `not_in_source` — the few features the source had that are also absent
+ from the destination (used for information, not to block);
+* `notes` and `warnings`.
+
+### Features reported when exporting to AWB
+
+| Feature | Why |
+|---|---|
+| failure events | AWB RBDs use blocks; events are not exported |
+| diagram annotations | text boxes, rectangles and arrows are draw-only |
+| rate definitions and formula-linked fields | values are written as plain numbers |
+| triggers | AWB has no equivalent trigger logic |
+| spare pools | AWB spare holdings are not populated by this export |
+| resource pools | AWB labour/equipment are not populated |
+| mission phases and per-element phase schedules | AWB phase rules are not populated |
+| out-of-service elements | AWB `OutOfService` rules are not populated |
+| capacity analysis and flow links | AWB capacity targets are not populated |
+| block dependencies | AWB dependency rules are not populated |
+| preventive maintenance | AWB scheduled tasks are not populated |
+| age, restoration and growth settings | AWB initial age is 0 |
+| block cost data | AWB cost fields are not populated |
+| node standby/priority settings | AWB nodes carry only a vote |
+| link switching and priority | AWB connections carry no switching data |
+| link routing grips and view settings | AWB owns the diagram view |
+| advisor state and print title block | RAPTOR-only metadata |
+| other failure laws (gamma, triangular, ...) | simplified to an exponential with the same mean |
+| non-fixed repair laws | simplified to a fixed task duration with the same mean |
+| no-repair blocks | written as `NonMaintainable = 1` |
+| no-failure blocks | written with a fixed time of 9e8 hours |
+
+### Features reported when importing from AWB
+
+| Feature | Why |
+|---|---|
+| consequences and cost models | RAPTOR has no financial/safety/environmental consequence model |
+| mission phases and phase rules | AWB phase schedules are not imported |
+| planned maintenance and inspection tasks | RAPTOR PM is not populated |
+| spares and sparing rules | RAPTOR spare pools are not populated |
+| labour and equipment resources | RAPTOR resource pools are not populated |
+| RCM location hierarchy | the RCMCost module is not imported |
+| fault trees | only RBDs are imported |
+| Weibull sets | linked historical data is flattened |
+| diagram bitmaps | AWB images are not imported |
+| capacity flow and capacity targets | not imported |
+| standby and NOT logic | RAPTOR nodes have no equivalent |
+| block consequence links | not imported |
+| dormant failures | modelled as never repaired |
+| multi-mode/buffer failure laws | only the first Weibull mode is kept |
+| non-maintainable blocks | RAPTOR repair is off |
+| start-up failure probability | not modelled by RAPTOR |
+
+Labels (`RbdLabels`) and repeat blocks (`RbdRepeatBlocks`) are **converted**,
+not lost: labels become RAPTOR annotations, and a repeat block becomes a
+never-failing block that is idle whenever the original block is down.
+
+---
+
+## 6. Column defaults and the six-table file
+
+RAPTOR ships the six table schemas in
+`raptor/core/fileio/awb_tables.json` (column names and types plus the neutral
+project row). The file is data, not a template project: rows are generated
+from the RAPTOR model, so a generated `.awb` contains no Isograph sample
+data.
+
+The project row sets:
+
+* `Id = ""`, `Description` = RAPTOR file name,
+* `ProductVersion = "5.0"`, `ProjectVersionLong = "5.0.0.0"`,
+* `LifeTime` = the RAPTOR run length in hours,
+* `AvsimNoSimulationsRequested` = the RAPTOR trial count,
+* `AvsimCurrentRbdPage = 0`, `WeibullCurrentWeibullSet = -1`,
+* the capacity/importance/result-cache fields at neutral values.
+
+AWB 5.0 accepts a fresh UUID in every `Guid` column and creates any missing
+module table when the project is opened.
+
+---
+
+## 7. Verification
+
+The format and mapping were checked against AWB 5.0.0.0 under Wine:
+
+1. A six-table file with two series blocks, two nodes and three connections
+ was opened by AWB without validation errors.
+2. **Simulation → Start** completed 1000 replications on that file.
+3. A RAPTOR model with two hierarchies (three blocks, eight nodes, ten
+ links) exported by this converter was opened by AWB and showed the same
+ hierarchy tree.
+4. AWB's own `OilAndGasExample.awb` and `Example1.awb` were parsed, imported
+ to `.rbds` and validated by `raptor validate` (0 errors; Example1's
+ multi-link hierarchy items produce RAPTOR layout warnings).
+5. The imported Example1 model was exported again and re-imported with the
+ same element and link counts.
+
+AWB demonstration mode was used for opening and simulation. It does not
+allow Save or Export, which is why the writer constructs the file directly
+rather than driving AWB's own export dialog.
+
+---
+
+## 8. Limits and compatibility
+
+* The reader accepts the AWB 5.0 table-store layout. Older AWB projects with
+ fewer columns are accepted; missing columns take the type default.
+* The writer emits the six tables above. AWB upgrades the project to its
+ full module schema when it opens it; it may show validation warnings for
+ fields that are not meaningful in a pure AvSim project, but the RBD data is
+ complete.
+* AWB IDs are limited to 40 characters and RAPTOR names to 20. RAPTOR
+ sanitises names and reports any rename; it never changes the source model.
+* AWB uses the source model's x/y positions as-is and does not auto-layout.
+ RAPTOR's canvas is often more compact than AWB's 100-unit block symbols;
+ use AWB's own **Auto Layout** after opening a model whose blocks overlap.
+* The conversion is one-way per invocation. Round trips are not guaranteed
+ to be byte-identical: AWB renumbers pages and rows, and RAPTOR renumbers
+ element ids. The **logic**, failure data, repair data and hierarchy
+ structure are preserved.
+* The `.awb` layout was reverse-engineered for interoperability; Isograph may
+ change it in a future release. A file that does not parse is reported as
+ `AwbFormatError` with the table and byte offset where possible.
diff --git a/docs/completions/raptor b/docs/completions/raptor
index a59cdc97..cd034808 100644
--- a/docs/completions/raptor
+++ b/docs/completions/raptor
@@ -12,7 +12,7 @@ _raptor() {
compare) opts="--analysis --format --help --importance --jobs --length --max-trials --metric --min-trials --precision --precision-batch --precision-confidence --precision-metric --runs --save-model --seed --set --set-file --stats-start --stop --timeout --weak-type" ;;
completion) opts="--help" ;;
config) opts="--help" ;;
- convert) opts="--allow-lossy --help --to" ;;
+ convert) opts="--allow-lossy --format --help --report --strict --to" ;;
describe) opts="--element --format --help" ;;
diff) opts="--all --exit-code --format --help --ignore --match --only" ;;
doctor) opts="--format --help" ;;
diff --git a/docs/completions/raptor.fish b/docs/completions/raptor.fish
index 1e44e2a3..b05ef664 100644
--- a/docs/completions/raptor.fish
+++ b/docs/completions/raptor.fish
@@ -66,7 +66,10 @@ complete -c raptor -n '__fish_use_subcommand' -a config
complete -c raptor -n '__fish_seen_subcommand_from config' -l help
complete -c raptor -n '__fish_use_subcommand' -a convert
complete -c raptor -n '__fish_seen_subcommand_from convert' -l allow-lossy
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l format
complete -c raptor -n '__fish_seen_subcommand_from convert' -l help
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l report
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l strict
complete -c raptor -n '__fish_seen_subcommand_from convert' -l to
complete -c raptor -n '__fish_use_subcommand' -a describe
complete -c raptor -n '__fish_seen_subcommand_from describe' -l element
diff --git a/docs/man/raptor-convert.1 b/docs/man/raptor-convert.1
index fb9afb7c..ed2e20ae 100644
--- a/docs/man/raptor-convert.1
+++ b/docs/man/raptor-convert.1
@@ -1,17 +1,26 @@
.TH "RAPTOR-CONVERT" 1 "2026-10" "RAPTOR Studio" "RAPTOR Studio Manual"
.SH NAME
-raptor\-convert \- convert between .rbd and .rbds
+raptor\-convert \- convert between .rbd, .rbds and AWB .awb
.SH SYNOPSIS
-\fBraptor convert\fR [\-h] [\-\-to {rbd,rbds}] [\-\-allow\-lossy] IN OUT
+\fBraptor convert\fR [\-h] [\-\-to {rbd,rbds,awb}] [\-\-allow\-lossy] [\-\-strict] [\-f {text,json,markdown}] [\-\-report FILE] IN OUT
.SH DESCRIPTION
-Write IN as OUT in the format OUT's extension names (or \-\-to). Refuses a lossy conversion unless \-\-allow\-lossy.
+Write IN as OUT in the format OUT's extension names (or \-\-to). AWB conversions print a summary of the features the destination cannot represent. Refuses a lossy .rbd conversion unless \-\-allow\-lossy.
.SH OPTIONS
.SS Options
.TP
-\fB\-\-to\fR \fI{rbd|rbds}\fR
+\fB\-\-to\fR \fI{rbd|rbds|awb}\fR
format to write (default: OUT's extension)
.TP
\fB\-\-allow\-lossy\fR
-\&.rbds\-only content (annotations, experiment settings, rate definitions) is dropped in .rbd
+\&.rbds\-only content (annotations, experiment settings, rate definitions) is dropped in .rbd; AWB conversions report their losses instead and do not need this switch
+.TP
+\fB\-\-strict\fR
+AWB only: write nothing and exit 4 if the summary reports any feature the destination cannot use
+.TP
+\fB\-f\fR, \fB\-\-format\fR \fI{text|json|markdown}\fR
+AWB summary format (default text)
+.TP
+\fB\-\-report\fR \fIFILE\fR
+AWB only: also write the summary as Markdown to FILE
.SH SEE ALSO
\fBraptor\fR(1)
diff --git a/docs/man/raptor.1 b/docs/man/raptor.1
index 9261439d..f88aa9f7 100644
--- a/docs/man/raptor.1
+++ b/docs/man/raptor.1
@@ -61,7 +61,7 @@ print model fields
change model fields and save the model
.TP
\fBconvert\fR
-convert between .rbd and .rbds
+convert between .rbd, .rbds and AWB .awb
.TP
\fBadvise\fR
say what looks wrong or unwise in a model
diff --git a/pyproject.toml b/pyproject.toml
index 3629903f..10aaeb96 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -306,6 +306,7 @@ include = ["raptor*"]
[tool.setuptools.package-data]
"raptor.gui.resources" = ["*.png", "examples/*.png"]
"raptor.mcp" = ["output_schemas.json"]
+"raptor.core.fileio" = ["awb_tables.json"]
# The rendered help docs, the book chapters and the tutorial models are part
# of the app (in-app Help viewer, opsmodel:// buttons, the MCP server's
@@ -315,7 +316,7 @@ include = ["raptor*"]
# installers bundle the same trees from the repo checkout.
[tool.setuptools.data-files]
"docs" = ["docs/manual.html", "docs/formulas.html", "docs/ops_asciidoctor.css", "docs/RBDS_FORMAT.md",
- "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
+ "docs/AWB_FORMAT.md", "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
"docs/MCP-reference.md",
"docs/ANALYTICAL.md", "docs/rbds.schema.json"]
# MathJax (Apache-2.0, see its LICENSE) typesets the formulas page offline: the page loads it from js/.
diff --git a/raptor/api/awb.py b/raptor/api/awb.py
new file mode 100644
index 00000000..b30dbc60
--- /dev/null
+++ b/raptor/api/awb.py
@@ -0,0 +1,41 @@
+"""Availability Workbench interchange (headless API).
+
+Thin public surface over :mod:`raptor.core.fileio.awb` so the CLI and GUI
+never import the core file layer directly.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from raptor.core.fileio.awb import (
+ AwbFormatError, AwbReport, export_awb, import_awb, read_awb,
+ write_awb,
+)
+
+__all__ = [
+ "AwbFormatError", "AwbReport", "export", "import_project", "read",
+ "write",
+]
+
+
+def export(rbd: Any, path: str | Path, *, source: str = "",
+ write: bool = True) -> AwbReport:
+ """Write a RAPTOR model as an AWB 5.0 project."""
+ return export_awb(rbd, path, source=source, write=write)
+
+
+def import_project(path: str | Path, *,
+ source: str = "") -> tuple[Any, AwbReport]:
+ """Read an AWB 5.0 project; return a RAPTOR model and its report."""
+ return import_awb(path, source=source)
+
+
+def read(path: str | Path) -> dict:
+ """Read the raw AWB tables (diagnostics and tests)."""
+ return read_awb(path)
+
+
+def write(path: str | Path, tables: dict) -> None:
+ """Write raw AWB tables (diagnostics and tests)."""
+ write_awb(path, tables)
diff --git a/raptor/cli/cmd_info.py b/raptor/cli/cmd_info.py
index eb06cbaa..17bbd33b 100644
--- a/raptor/cli/cmd_info.py
+++ b/raptor/cli/cmd_info.py
@@ -77,17 +77,27 @@ def add_parser(sub: Any) -> None:
s.set_defaults(func=set_command)
c = sub.add_parser(
- "convert", help="convert between .rbd and .rbds",
+ "convert", help="convert between .rbd, .rbds and AWB .awb",
description="Write IN as OUT in the format OUT's extension names "
- "(or --to). Refuses a lossy conversion unless "
- "--allow-lossy.")
+ "(or --to). AWB conversions print a summary of the "
+ "features the destination cannot represent. Refuses a "
+ "lossy .rbd conversion unless --allow-lossy.")
c.add_argument("input", metavar="IN")
c.add_argument("output", metavar="OUT")
- c.add_argument("--to", choices=("rbd", "rbds"),
+ c.add_argument("--to", choices=("rbd", "rbds", "awb"),
help="format to write (default: OUT's extension)")
c.add_argument("--allow-lossy", action="store_true",
help=".rbds-only content (annotations, experiment "
- "settings, rate definitions) is dropped in .rbd")
+ "settings, rate definitions) is dropped in .rbd; "
+ "AWB conversions report their losses instead and do "
+ "not need this switch")
+ c.add_argument("--strict", action="store_true",
+ help="AWB only: write nothing and exit 4 if the summary "
+ "reports any feature the destination cannot use")
+ c.add_argument("-f", "--format", choices=("text", "json", "markdown"),
+ default="text", help="AWB summary format (default text)")
+ c.add_argument("--report", metavar="FILE",
+ help="AWB only: also write the summary as Markdown to FILE")
c.set_defaults(func=convert_command)
@@ -277,7 +287,13 @@ def set_command(args: Any) -> int:
def convert_command(args: Any) -> int:
src, dest = Path(args.input), Path(args.output)
- fmt = args.to or ("rbd" if dest.suffix.lower() == ".rbd" else "rbds")
+ if src.suffix.lower() == ".awb":
+ fmt = args.to if args.to in ("rbd", "rbds") else (
+ "rbd" if dest.suffix.lower() == ".rbd" else "rbds")
+ return _convert_from_awb(args, src, dest, fmt)
+ fmt = args.to or _convert_format(src, dest)
+ if fmt == "awb":
+ return _convert_to_awb(args, src, dest)
if fmt == "rbd" and src.suffix.lower() == ".rbds" and not args.allow_lossy:
with workspace_for() as ws:
mid = open_model(ws, args.input)
@@ -298,3 +314,71 @@ def convert_command(args: Any) -> int:
if res.get("layout_warning"):
eprint(f"warning: layout: {res['layout_warning']}")
return X.OK
+
+
+def _convert_format(src: Path, dest: Path) -> str:
+ """The output format named by ``--to`` or the two extensions."""
+ if dest.suffix.lower() == ".awb" or src.suffix.lower() == ".awb":
+ return "awb"
+ return "rbd" if dest.suffix.lower() == ".rbd" else "rbds"
+
+
+def _convert_to_awb(args: Any, src: Path, dest: Path) -> int:
+ from raptor.api import awb as awb_api
+ if dest.suffix.lower() != ".awb":
+ dest = dest.with_suffix(".awb")
+ with workspace_for() as ws:
+ mid = open_model(ws, args.input)
+ rbd = ws.get(mid).rbd
+ report = awb_api.export(rbd, dest, source=args.input, write=False)
+ if args.strict and report.has_losses:
+ _print_awb_report(report, args)
+ raise CliError(
+ "AWB cannot represent every feature in this model; nothing was "
+ "written (drop --strict to proceed and keep the summary)", X.REFUSED)
+ try:
+ awb_api.export(rbd, dest, source=args.input)
+ except Exception as exc:
+ raise CliError(f"cannot write {dest}: {exc}", X.OUTPUT) from exc
+ _print_awb_report(report, args)
+ eprint(f"wrote {dest}")
+ return X.OK
+
+
+def _convert_from_awb(args: Any, src: Path, dest: Path, fmt: str) -> int:
+ from raptor.api import awb as awb_api
+ if dest.suffix.lower() not in (".rbds", ".rbd"):
+ fmt = "rbds"
+ dest = dest.with_suffix(".rbds")
+ try:
+ rbd, report = awb_api.import_project(src, source=args.input)
+ except Exception as exc:
+ raise CliError(f"cannot read {src}: {exc}", X.USAGE) from exc
+ report.target = str(dest)
+ if args.strict and report.has_losses:
+ _print_awb_report(report, args)
+ raise CliError(
+ "RAPTOR cannot represent every feature in this AWB project; "
+ "nothing was written (drop --strict to proceed)", X.REFUSED)
+ try:
+ with workspace_for() as ws:
+ mid = ws.register_model(rbd, name=dest.stem,
+ source=str(src))["model_id"]
+ ws.save_model_as(mid, str(dest), fmt=fmt)
+ except Exception as exc:
+ raise CliError(f"cannot write {dest}: {exc}", X.OUTPUT) from exc
+ _print_awb_report(report, args)
+ eprint(f"wrote {dest}")
+ return X.OK
+
+
+def _print_awb_report(report: Any, args: Any) -> None:
+ if getattr(args, "report", None):
+ Path(args.report).parent.mkdir(parents=True, exist_ok=True)
+ Path(args.report).write_text(report.summary_markdown(), encoding="utf-8")
+ if getattr(args, "format", "text") == "json":
+ emit_json(report.as_dict(), None)
+ elif getattr(args, "format", "text") == "markdown":
+ sys.stdout.write(report.summary_markdown())
+ else:
+ print(report.summary_text())
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
new file mode 100644
index 00000000..e1b9d759
--- /dev/null
+++ b/raptor/core/fileio/awb.py
@@ -0,0 +1,1597 @@
+"""Availability Workbench (AWB) project interchange.
+
+AWB 5.0 saves a project as one ``.awb`` file: a small, uncompressed binary
+table store. This module reads that store and writes the subset AWB needs
+for a Reliability Block Diagram (RBD) project, so RAPTOR models can move to
+AWB and AWB projects can move back to RAPTOR without either program being
+installed.
+
+The format and the mapping are documented in ``docs/AWB_FORMAT.md``. The
+conversion is deliberately honest about what it cannot carry: every
+conversion returns an :class:`AwbReport` whose ``not_in_target`` list names
+the features the destination program has no equivalent for, with a count.
+The CLI prints the report as a summary before it writes anything.
+"""
+from __future__ import annotations
+
+import json
+import math
+import struct
+import uuid
+from dataclasses import dataclass, field
+from importlib import resources
+from pathlib import Path
+from collections.abc import Iterable
+from typing import Any
+
+from raptor.core.fileio.rbd import RbdFile, RbdSection
+from raptor.core.units_conv import HOURS_PER_UNIT
+
+# ---------------------------------------------------------------------------
+# Errors and report
+# ---------------------------------------------------------------------------
+
+
+class AwbFormatError(ValueError):
+ """The file is not an AWB 5.0 table store we understand."""
+
+
+@dataclass
+class AwbLoss:
+ """One kind of feature the destination cannot represent."""
+
+ feature: str
+ count: int
+ detail: str = ""
+ where: str = "" # "AWB" or "RAPTOR"
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"feature": self.feature, "count": self.count,
+ "detail": self.detail, "where": self.where}
+
+
+@dataclass
+class AwbReport:
+ """What a conversion did, and what it could not carry."""
+
+ direction: str # "rbds-to-awb" or "awb-to-rbds"
+ source: str
+ target: str
+ counts: dict[str, int] = field(default_factory=dict)
+ not_in_target: list[AwbLoss] = field(default_factory=list)
+ not_in_source: list[AwbLoss] = field(default_factory=list)
+ notes: list[str] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+
+ @property
+ def has_losses(self) -> bool:
+ return bool(self.not_in_target or self.not_in_source)
+
+ def add(self, feature: str, count: int, detail: str = "",
+ where: str | None = None) -> None:
+ if count <= 0:
+ return
+ where = where or ("AWB" if self.direction == "rbds-to-awb"
+ else "RAPTOR")
+ self.not_in_target.append(AwbLoss(feature, count, detail, where))
+
+ def add_source(self, feature: str, count: int, detail: str = "") -> None:
+ """A feature the source had that the destination also lacks, but
+ which is not the direction's main ``not_in_target`` list."""
+ if count <= 0:
+ return
+ self.not_in_source.append(
+ AwbLoss(feature, count, detail,
+ "AWB" if self.direction == "rbds-to-awb" else "RAPTOR"))
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "schema": "raptor-awb-report/1",
+ "direction": self.direction,
+ "source": self.source,
+ "target": self.target,
+ "counts": dict(self.counts),
+ "not_in_target": [x.as_dict() for x in self.not_in_target],
+ "not_in_source": [x.as_dict() for x in self.not_in_source],
+ "notes": list(self.notes),
+ "warnings": list(self.warnings),
+ }
+
+ def summary_text(self) -> str:
+ target = "AWB" if self.direction == "rbds-to-awb" else "RAPTOR"
+ source = "RAPTOR" if target == "AWB" else "AWB"
+ lines = [
+ f"{source} -> {target} interchange summary",
+ f" source: {self.source}",
+ f" target: {self.target}",
+ " converted: " + _counts_text(self.counts),
+ ]
+ if self.not_in_target:
+ lines.append(f" not represented in {target}:")
+ for loss in self.not_in_target:
+ lines.append(f" - {loss.feature}: {loss.count}"
+ + (f" ({loss.detail})" if loss.detail else ""))
+ else:
+ lines.append(f" not represented in {target}: none")
+ if self.not_in_source:
+ other = "AWB" if target == "RAPTOR" else "RAPTOR"
+ lines.append(f" not represented in {other}:")
+ for loss in self.not_in_source:
+ lines.append(f" - {loss.feature}: {loss.count}"
+ + (f" ({loss.detail})" if loss.detail else ""))
+ for note in self.notes:
+ lines.append(f" note: {note}")
+ for warning in self.warnings:
+ lines.append(f" warning: {warning}")
+ return "\n".join(lines)
+
+ def summary_markdown(self) -> str:
+ target = "AWB" if self.direction == "rbds-to-awb" else "RAPTOR"
+ source = "RAPTOR" if target == "AWB" else "AWB"
+ lines = [
+ f"# {source} -> {target} interchange summary",
+ "",
+ f"- **Source:** `{self.source}`",
+ f"- **Target:** `{self.target}`",
+ f"- **Converted:** {_counts_text(self.counts) or 'nothing'}",
+ "",
+ f"## Not represented in {target}",
+ "",
+ ]
+ if self.not_in_target:
+ lines += ["| Feature | Count | Detail |", "|---|---:|---|"]
+ for loss in self.not_in_target:
+ lines.append(f"| {loss.feature} | {loss.count} | "
+ f"{loss.detail or ''} |")
+ else:
+ lines.append("None.")
+ if self.not_in_source:
+ other = "AWB" if target == "RAPTOR" else "RAPTOR"
+ lines += ["", f"## Not represented in {other}", "",
+ "| Feature | Count | Detail |", "|---|---:|---|"]
+ for loss in self.not_in_source:
+ lines.append(f"| {loss.feature} | {loss.count} | "
+ f"{loss.detail or ''} |")
+ if self.notes:
+ lines += ["", "## Notes", ""]
+ lines += [f"- {n}" for n in self.notes]
+ if self.warnings:
+ lines += ["", "## Warnings", ""]
+ lines += [f"- {w}" for w in self.warnings]
+ return "\n".join(lines) + "\n"
+
+
+def _counts_text(counts: dict[str, int]) -> str:
+ parts = [f"{n} {name.replace('_', ' ')}"
+ for name, n in counts.items() if n]
+ return ", ".join(parts) if parts else "0 elements"
+
+
+# ---------------------------------------------------------------------------
+# The AWB table store
+# ---------------------------------------------------------------------------
+
+#: Column types in an AWB table record.
+_T_STR, _T_INT, _T_DOUBLE, _T_BOOL = 0, 1, 2, 3
+
+_SCHEMA_FILE = "awb_tables.json"
+
+
+def _load_schema() -> tuple[dict[str, list[tuple[str, int]]], dict[str, dict]]:
+ text = resources.files("raptor.core.fileio").joinpath(_SCHEMA_FILE).read_text()
+ doc = json.loads(text)
+ tables = {name: [(str(c), int(t)) for c, t in cols]
+ for name, cols in doc["tables"].items()}
+ defaults = {name: dict(row) for name, row in doc.get("defaults", {}).items()}
+ return tables, defaults
+
+
+_SCHEMA, _DEFAULTS = _load_schema()
+
+#: The six tables a minimal AWB RBD project needs. AWB adds the other
+#: tables its modules use when it opens the project (verified with AWB 5.0).
+AWB_TABLES = ("Project", "FailureModels", "FailureModelCorrectiveTasks",
+ "RbdBlocks", "RbdNodes", "RbdConnections")
+
+
+def _default_for_type(kind: int) -> Any:
+ return {_T_STR: "", _T_INT: 0, _T_DOUBLE: 0.0, _T_BOOL: 0}[kind]
+
+
+def _row(name: str, **overrides: Any) -> dict[str, Any]:
+ """One row with every column at its type default, then *overrides*."""
+ defaults = _DEFAULTS.get(name, {})
+ row = {col: _default_for_type(kind) for col, kind in _SCHEMA[name]}
+ row.update({k: v for k, v in defaults.items()
+ if k in row and not isinstance(v, (dict, list))})
+ row.update(overrides)
+ return row
+
+
+def _read_varint(data: bytes, pos: int) -> tuple[int, int]:
+ value = 0
+ shift = 0
+ while True:
+ if pos >= len(data):
+ raise AwbFormatError("truncated integer in AWB table store")
+ b = data[pos]
+ pos += 1
+ value |= (b & 0x7F) << shift
+ shift += 7
+ if not b & 0x80:
+ return value, pos
+
+
+def _write_varint(value: int) -> bytes:
+ out = bytearray()
+ while True:
+ b = value & 0x7F
+ value >>= 7
+ if value:
+ out.append(b | 0x80)
+ else:
+ out.append(b)
+ return bytes(out)
+
+
+def _read_string(data: bytes, pos: int) -> tuple[str, int]:
+ size, pos = _read_varint(data, pos)
+ end = pos + size
+ if end > len(data):
+ raise AwbFormatError("truncated string in AWB table store")
+ return data[pos:end].decode("utf-8", "replace"), end
+
+
+def _write_string(out: bytearray, text: str) -> None:
+ raw = str(text).encode("utf-8")
+ out += _write_varint(len(raw))
+ out += raw
+
+
+@dataclass
+class AwbTable:
+ name: str
+ columns: list[tuple[str, int]]
+ rows: list[dict[str, Any]] = field(default_factory=list)
+
+
+def read_awb(path: str | Path) -> dict[str, AwbTable]: # noqa: C901, PLR0912
+ """Read an AWB 5.0 ``.awb`` project into its tables.
+
+ The file starts with a little-endian ``uint32`` table count, then each
+ table is: name, uint32 column count, (column name, uint32 type) pairs,
+ uint32 row count, and the values in column order. Strings are a
+ varint length followed by UTF-8; ints are int32, doubles are IEEE-754
+ little-endian, bools are one byte.
+ """
+ try:
+ data = Path(path).read_bytes()
+ except OSError as exc:
+ raise AwbFormatError(f"cannot read {path}: {exc}") from exc
+ if len(data) < 4:
+ raise AwbFormatError("not an AWB project (file is too short)")
+ count, pos = struct.unpack_from(" 100_000:
+ raise AwbFormatError(f"bad column count in table {name!r}")
+ columns: list[tuple[str, int]] = []
+ for _ in range(ncols):
+ col, pos = _read_string(data, pos)
+ kind, pos = _read_int32(data, pos)
+ if kind not in (_T_STR, _T_INT, _T_DOUBLE, _T_BOOL):
+ raise AwbFormatError(
+ f"unknown column type {kind} in {name}.{col}")
+ columns.append((col, kind))
+ nrows, pos = _read_int32(data, pos)
+ if nrows < 0 or nrows > 10_000_000:
+ raise AwbFormatError(f"bad row count in table {name!r}")
+ rows: list[dict[str, Any]] = []
+ for _ in range(nrows):
+ row: dict[str, Any] = {}
+ for col, kind in columns:
+ if kind == _T_STR:
+ row[col], pos = _read_string(data, pos)
+ elif kind == _T_INT:
+ row[col], pos = _read_int32(data, pos)
+ elif kind == _T_DOUBLE:
+ row[col], pos = _read_double(data, pos)
+ else:
+ if pos >= len(data):
+ raise AwbFormatError("truncated bool in AWB table")
+ row[col] = data[pos]
+ pos += 1
+ rows.append(row)
+ tables[name] = AwbTable(name, columns, rows)
+ except (struct.error, IndexError) as exc:
+ raise AwbFormatError("truncated AWB table store") from exc
+ if pos != len(data):
+ # Trailing bytes are harmless in some writers, but a mismatch is
+ # useful evidence that we read the file wrongly.
+ raise AwbFormatError(
+ f"unexpected {len(data) - pos} trailing byte(s) in AWB project")
+ if "Project" not in tables:
+ raise AwbFormatError("AWB project has no Project table")
+ return tables
+
+
+def _read_int32(data: bytes, pos: int) -> tuple[int, int]:
+ if pos + 4 > len(data):
+ raise AwbFormatError("truncated int32 in AWB table store")
+ return struct.unpack_from(" tuple[float, int]:
+ if pos + 8 > len(data):
+ raise AwbFormatError("truncated double in AWB table store")
+ return struct.unpack_from(" None:
+ """Write tables in the AWB 5.0 table-store format."""
+ out = bytearray(struct.pack(" float:
+ try:
+ out = float(value)
+ except (TypeError, ValueError):
+ return default
+ return default if math.isnan(out) or math.isinf(out) else out
+
+
+def _int(value: Any, default: int = 0) -> int:
+ try:
+ return int(float(value))
+ except (TypeError, ValueError):
+ return default
+
+
+def _text(value: Any, default: str = "") -> str:
+ return default if value is None else str(value)
+
+
+def _hours_factor(units: str | None) -> float:
+ return HOURS_PER_UNIT.get((units or "hours").strip().lower(), 1.0)
+
+
+def _safe_id(text: str, limit: int = 40) -> str:
+ """AWB IDs are short alphanumeric labels; make one without changing the
+ readable part where possible."""
+ cleaned = "".join(ch if ch.isalnum() or ch in "_-." else "_"
+ for ch in (text or "item")).strip("_") or "item"
+ return cleaned[:limit]
+
+
+def _unique(base: str, used: set[str], limit: int = 40) -> str:
+ candidate = _safe_id(base, limit)
+ if candidate not in used:
+ used.add(candidate)
+ return candidate
+ stem = candidate[: max(1, limit - 4)]
+ n = 2
+ while f"{stem}_{n}" in used:
+ n += 1
+ candidate = f"{stem}_{n}"[:limit]
+ used.add(candidate)
+ return candidate
+
+
+def _guid() -> str:
+ return str(uuid.uuid4())
+
+
+def _dist_mean(code: int, params: Iterable[Any]) -> float | None:
+ from raptor.api.distributions import describe_dist
+ try:
+ info = describe_dist(code, [float(x) for x in list(params)[:3]])
+ except Exception: # noqa: BLE001 - a report must never hide the model
+ return None
+ mean = info.get("mean")
+ return None if mean is None else float(mean)
+
+
+def _rows(tables: dict[str, AwbTable], name: str) -> list[dict[str, Any]]:
+ table = tables.get(name)
+ return [] if table is None else table.rows
+
+
+def _has_rows(tables: dict[str, AwbTable], name: str) -> int:
+ return len(_rows(tables, name))
+
+
+# ---------------------------------------------------------------------------
+# RAPTOR -> AWB
+# ---------------------------------------------------------------------------
+
+
+def _system_row(rbd: RbdFile) -> dict[str, Any]:
+ sec = rbd.sections.get("SYSTEM_DATA")
+ return sec.rows[0] if sec and sec.rows else {}
+
+
+def _model_units(rbd: RbdFile) -> str:
+ return _text(_system_row(rbd).get("units"), "hours")
+
+
+def _model_trials(rbd: RbdFile) -> int:
+ exp = getattr(rbd, "experiment", None) or {}
+ if exp.get("trials") is not None:
+ return max(1, _int(exp["trials"], 1))
+ return max(1, _int(_system_row(rbd).get("NumRuns"), 1))
+
+
+def _model_lifetime_hours(rbd: RbdFile) -> tuple[float, bool]:
+ """(lifetime in hours, was a time-terminated model)."""
+ exp = getattr(rbd, "experiment", None) or {}
+ units = _model_units(rbd)
+ factor = _hours_factor(units)
+ if exp.get("term_condition") is not None:
+ return max(1.0, _num(exp["term_condition"]) * factor), \
+ str(exp.get("termination_type", "TimeSim")) == "TimeSim"
+ row = _system_row(rbd)
+ return max(1.0, _num(row.get("TermCondition"), 8760.0) * factor), \
+ _text(row.get("TerminationType"), "TimeSim") == "TimeSim"
+
+
+@dataclass
+class _Page:
+ """One AWB page: where its superblock is drawn and what it owns."""
+
+ page: int
+ parent: int
+ name: str
+ raptor_id: str = ""
+ parent_id: str = ""
+
+
+def _hierarchy_depth(rbd: RbdFile) -> dict[str, int]:
+ rows = rbd.sections.get("HIERARCHY_DATA")
+ if not rows:
+ return {}
+ by_id = {_text(r.get("ID")): r for r in rows.rows}
+ depth: dict[str, int] = {}
+
+ def walk(hid: str, stack: tuple[str, ...] = ()) -> int:
+ if hid in depth:
+ return depth[hid]
+ if hid in stack:
+ depth[hid] = 0
+ return 0
+ parent = _text(by_id.get(hid, {}).get("Parent"), "0")
+ d = 0 if parent in ("", "0") or parent not in by_id else walk(parent, (*stack, hid)) + 1
+ depth[hid] = d
+ return d
+
+ for hid in by_id:
+ walk(hid)
+ return depth
+
+
+def export_awb(rbd: RbdFile, path: str | Path, *, # noqa: C901, PLR0912, PLR0915
+ source: str = "", write: bool = True) -> AwbReport:
+ """Write *rbd* as an AWB 5.0 project and return the loss report.
+
+ ``write=False`` builds the same report and tables without touching the
+ destination, so a strict conversion can refuse before anything exists
+ on disk.
+ """
+ src = source or getattr(rbd, "file_name", "") or "model"
+ dest = str(path)
+ report = AwbReport("rbds-to-awb", src, dest)
+
+ units = _model_units(rbd)
+ factor = _hours_factor(units)
+ if units.lower() != "hours":
+ report.notes.append(
+ f"times converted from {units} to hours for AWB "
+ f"(factor {factor:g})")
+
+ blocks = [r for r in _section_list(rbd, "BLOCK_DATA")
+ if _text(r.get("ID")) not in ("", "0")]
+ nodes = [r for r in _section_list(rbd, "NODE_DATA")
+ if _text(r.get("ID")) not in ("", "0")]
+ hierarchies = [r for r in _section_list(rbd, "HIERARCHY_DATA")
+ if _text(r.get("ID")) not in ("", "0")]
+ links = _section_list(rbd, "LINK_DATA")
+ events = [r for r in _section_list(rbd, "EVENT_DATA")
+ if _text(r.get("ID")) not in ("", "0")]
+
+ report.counts.update(blocks=len(blocks), nodes=len(nodes),
+ hierarchies=len(hierarchies), links=len(links),
+ events=len(events))
+ if not blocks:
+ raise ValueError("an AWB project needs at least one RBD block")
+
+ # ---- pages and row indices -------------------------------------------
+ # AWB's page index is the RbdBlocks row index of the superblock that owns
+ # it: row 0 is the project root and owns page 0; a hierarchy's row owns
+ # the page its contents are drawn on.
+ used_ids: set[str] = {"1"} # the root superblock's own Id
+ hrows: dict[str, dict[str, Any]] = {}
+ hpages: dict[str, _Page] = {}
+ ordered_h = sorted(hierarchies, key=lambda r: (_hierarchy_depth(rbd).get(
+ _text(r.get("ID")), _int(r.get("level"), 1)), _text(r.get("ID"))))
+ next_row = 1
+ for h in ordered_h:
+ hid = _text(h.get("ID"))
+ parent_id = _text(h.get("Parent"), "0")
+ hpage = _Page(next_row, 0, _text(h.get("hierarchyName"), hid), hid,
+ parent_id)
+ hpages[hid] = hpage
+ hrows[hid] = _row(
+ "RbdBlocks", Id=_unique(_text(h.get("hierarchyName"), hid), used_ids),
+ Description=_text(h.get("hierarchyName"), hid), Super=1,
+ FailureModel=-1, Consequence=-1, Bom=-1, Bitmap=-1,
+ Page=0, XPosition=_num(h.get("xPos")),
+ YPosition=_num(h.get("yPos")), Width=100.0, Height=60.0,
+ PageScale=1.0, Guid=_guid(), NonMaintainable=0, NonOperational=0,
+ IncludeInSystemPlot=1, MaxCapacity=0.0, MaxCapacity2=0.0, MaxCapacity3=0.0,
+ MaxCapacity4=0.0, LoadFactor=1.0)
+ next_row += 1
+
+ def page_for_parent(parent_id: str) -> int:
+ return 0 if parent_id in ("", "0") else hpages.get(parent_id, _Page(0, 0, "")).page
+
+ # ---- failure models ---------------------------------------------------
+ fm_by_key: dict[tuple, int] = {}
+ fm_rows: list[dict[str, Any]] = []
+ task_rows: list[dict[str, Any]] = []
+ dist_simplified: dict[str, int] = {}
+ repair_simplified: dict[str, int] = {}
+ no_repair = 0
+ no_failure = 0
+
+ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
+ nonlocal no_repair, no_failure
+ awb_std = 0.0
+ fdist = _int(block.get("FDist"), _R_EXPO)
+ fparams = [_num(block.get("FParam1")), _num(block.get("FParam2")),
+ _num(block.get("FParam3"))]
+ rdist = _int(block.get("RDist"), _R_FIXED)
+ rparams = [_num(block.get("RParam1")), _num(block.get("RParam2")),
+ _num(block.get("RParam3"))]
+ key = (fdist, tuple(round(x, 9) for x in fparams), rdist,
+ tuple(round(x, 9) for x in rparams))
+ if key in fm_by_key:
+ return fm_by_key[key]
+ fm_i = len(fm_rows)
+ fm_by_key[key] = fm_i
+ name = _text(block.get("blockName"), "block")
+ fm_id = _unique(f"{name}_FM", used_ids)
+ awb_dist = _AWB_EXPONENTIAL
+ mttf = 8760.0
+ eta, beta, gamma = 8760.0, 1.0, 0.0
+ if fdist == _R_EXPO:
+ mttf = max(1e-9, fparams[0])
+ if fparams[1] not in (0.0,):
+ dist_simplified["exponential location ignored"] = \
+ dist_simplified.get("exponential location ignored", 0) + 1
+ elif fdist == _R_WEIBULL:
+ awb_dist = _AWB_WEIBULL
+ beta, eta, gamma = fparams[0], fparams[1], fparams[2]
+ mttf = eta
+ elif fdist == _R_LOGNORM:
+ awb_dist = _AWB_LOGNORMAL
+ mttf, awb_std = max(1e-9, fparams[0]), max(0.0, fparams[1])
+ elif fdist == _R_NORM:
+ awb_dist = _AWB_NORMAL
+ mttf, awb_std = max(1e-9, fparams[0]), max(0.0, fparams[1])
+ elif fdist == _R_FIXED:
+ awb_dist = _AWB_FIXED
+ mttf = max(1e-9, fparams[0])
+ elif fdist == _R_NONE:
+ awb_dist = _AWB_FIXED
+ mttf = _NEVER
+ no_failure += 1
+ else:
+ mean = _dist_mean(fdist, fparams)
+ if mean is not None and mean > 0:
+ mttf = mean
+ label = _raptor_dist_name(fdist)
+ dist_simplified[label] = dist_simplified.get(label, 0) + 1
+ # AWB holds all times in hours.
+ mttf *= factor
+ eta *= factor
+ gamma *= factor
+ row = _row(
+ "FailureModels", Id=fm_id,
+ Description=f"Shared failure model for {name}" if not fm_rows else name,
+ Type=-1, DataLinkCause=-1, FmMttf=mttf,
+ FmDistribution=awb_dist, FmWeibullSet=-1,
+ FmStd=awb_std, FmEta1=eta, FmBeta1=beta, FmGamma1=gamma,
+ FmEta2=8760.0 * factor, FmBeta2=1.0, FmGamma2=0.0,
+ FmEta3=8760.0 * factor, FmBeta3=1.0, FmGamma3=0.0,
+ StandbyFailurePercent=50.0, StandbyAgeingPercent=50.0,
+ StartUpFailureProb=0.0, FmDormant=0, Guid=_guid())
+ fm_rows.append(row)
+
+ # Corrective task: AWB's task duration is a fixed duration in the
+ # sample projects (Distribution=2, Std=0). RAPTOR's mean is the
+ # honest equivalent when its repair is a distribution.
+ if rdist == _R_NONE:
+ task_duration = 0.0
+ no_repair += 1
+ elif rdist == _R_FIXED:
+ task_duration = max(0.0, rparams[0])
+ else:
+ mean = _dist_mean(rdist, rparams)
+ task_duration = max(0.0, mean if mean is not None else rparams[0])
+ label = _raptor_dist_name(rdist)
+ repair_simplified[label] = repair_simplified.get(label, 0) + 1
+ task_rows.append(_row(
+ "FailureModelCorrectiveTasks", FailureModel=fm_i,
+ Description=f"Corrective repair for {fm_id}",
+ TaskId=_unique(f"CM{fm_i + 1}", used_ids),
+ TaskDuration=task_duration * factor, RampTime=0.0,
+ Std=0.0, Eta=24.0, Beta=2.0, Gamma=0.0,
+ WeibullSet=-1, Distribution=2, OperationalCost=0.0))
+ return fm_i
+
+ # ---- blocks and nodes -------------------------------------------------
+ # AWB block rows: root first, then hierarchy superblocks, then ordinary
+ # blocks. AWB finds a page's contents by the row index of its superblock,
+ # so the hierarchy rows must come before the ordinary blocks they own.
+ block_rows: list[dict[str, Any]] = []
+ block_index: dict[str, int] = {}
+ block_page: dict[str, int] = {}
+ root = _row("RbdBlocks", Id="1", Description=_text(rbd.file_name, "RAPTOR model"),
+ Super=1, Page=-1, FailureModel=-1, Consequence=-1, Bom=-1,
+ Bitmap=-1, XPosition=0.0, YPosition=0.0, Width=100.0,
+ Height=60.0, PageScale=1.0, Guid=_guid(), NonMaintainable=0,
+ NonOperational=0, IncludeInSystemPlot=1,
+ MaxCapacity=0.0, MaxCapacity2=0.0, MaxCapacity3=0.0,
+ MaxCapacity4=0.0, LoadFactor=1.0)
+ block_rows.append(root)
+ block_rows.extend(hrows[hid] for hid in hpages)
+ # hrows keys are in insertion order of hpages; keep them aligned.
+
+ # The row index of each hierarchy is its page; recompute from block_rows
+ # so a later change cannot silently desynchronise the two.
+ row_of_hier: dict[str, int] = {}
+ for i, row in enumerate(block_rows):
+ for hid, hrow in hrows.items():
+ if row is hrow:
+ row_of_hier[hid] = i
+ for hid, hpage in hpages.items():
+ hpage.page = row_of_hier[hid]
+ hpage.parent = (0 if hpage.parent_id in ("", "0")
+ else hpages[hpage.parent_id].page)
+ hpages[hid] = hpage
+ hrows[hid]["Page"] = hpage.parent
+
+ for b in blocks:
+ bid = _text(b.get("ID"))
+ parent = _text(b.get("ParentId"), "0")
+ page = page_for_parent(parent)
+ fm_i = failure_model(b)
+ idx = len(block_rows)
+ block_index[bid] = idx
+ block_page[bid] = page
+ nonmaint = 1 if _int(b.get("RDist"), _R_FIXED) == _R_NONE else 0
+ block_rows.append(_row(
+ "RbdBlocks", Id=_unique(_text(b.get("blockName"), f"B{bid}"), used_ids),
+ Description=_text(b.get("blockName"), f"Block {bid}"),
+ Super=0, FailureModel=fm_i, Consequence=-1, Bom=-1, Bitmap=-1,
+ Page=page, XPosition=_num(b.get("xPos")), YPosition=_num(b.get("yPos")),
+ Width=100.0, Height=60.0, PageScale=1.0, Guid=_guid(),
+ NonMaintainable=nonmaint, NonOperational=0,
+ IncludeInSystemPlot=1, MaxCapacity=0.0, MaxCapacity2=0.0, MaxCapacity3=0.0,
+ MaxCapacity4=0.0, LoadFactor=1.0,
+ LogicMode=0, StandbyMode=0))
+
+ # AWB nodes: vote count carries RAPTOR's k-of-n requirement. AWB has
+ # no separate marker types, so start/end/in/out all become ordinary nodes.
+ node_rows: list[dict[str, Any]] = []
+ node_index: dict[str, int] = {}
+ node_page: dict[str, int] = {}
+ for n in nodes:
+ nid = _text(n.get("ID"))
+ parent = _text(n.get("parent"), "0")
+ page = page_for_parent(parent)
+ idx = len(node_rows)
+ node_index[nid] = idx
+ node_page[nid] = page
+ vote = _int(n.get("k"), 1)
+ node_rows.append(_row(
+ "RbdNodes", Id=_unique(_text(n.get("Name"), f"N{nid}"), used_ids),
+ Page=page, Vote=max(1, vote), XPosition=_num(n.get("xPos")),
+ YPosition=_num(n.get("yPos")), OperationalCapacityTarget=0.0,
+ LocalStandby=0, NotLogic=0, BackgroundColor=-1, Guid=_guid()))
+
+ # ---- connections ------------------------------------------------------
+ conn_rows: list[dict[str, Any]] = []
+ conn_id: set[str] = set()
+ skipped_links = 0
+ for link in links:
+ ftype = _text(link.get("FromType"))
+ ttype = _text(link.get("ToType"))
+ fid = _text(link.get("FromID"))
+ tid = _text(link.get("ToID"))
+ if ftype == "Event" or ttype == "Event":
+ skipped_links += 1
+ continue
+ if ftype == "Block":
+ if fid not in block_index:
+ skipped_links += 1
+ continue
+ fobj, findex, fpage = _AWB_BLOCK, block_index[fid], block_page[fid]
+ elif ftype == "Hier":
+ if fid not in row_of_hier:
+ skipped_links += 1
+ continue
+ fobj, findex = _AWB_BLOCK, row_of_hier[fid]
+ fpage = hpages[fid].parent
+ elif ftype == "Node":
+ if fid not in node_index:
+ skipped_links += 1
+ continue
+ fobj, findex, fpage = _AWB_NODE, node_index[fid], node_page[fid]
+ else:
+ skipped_links += 1
+ continue
+ if ttype == "Block":
+ if tid not in block_index:
+ skipped_links += 1
+ continue
+ tobj, tindex, tpage = _AWB_BLOCK, block_index[tid], block_page[tid]
+ elif ttype == "Hier":
+ if tid not in row_of_hier:
+ skipped_links += 1
+ continue
+ tobj, tindex = _AWB_BLOCK, row_of_hier[tid]
+ tpage = hpages[tid].parent
+ elif ttype == "Node":
+ if tid not in node_index:
+ skipped_links += 1
+ continue
+ tobj, tindex, tpage = _AWB_NODE, node_index[tid], node_page[tid]
+ else:
+ skipped_links += 1
+ continue
+ page = fpage if fpage == tpage else (fpage if ttype in ("Block", "Hier") else tpage)
+ conn_rows.append(_row(
+ "RbdConnections", Id=_unique(f"C{len(conn_rows) + 1}", conn_id),
+ Page=page, Type=0, Color=-1, InputObjectType=fobj,
+ InputObjectIndex=findex, OutputObjectType=tobj,
+ OutputObjectIndex=tindex, Guid=_guid()))
+
+ # ---- project ----------------------------------------------------------
+ lifetime, time_terminated = _model_lifetime_hours(rbd)
+ trials = _model_trials(rbd)
+ project = _row(
+ "Project", Id="", Description=_text(rbd.file_name, "RAPTOR model"),
+ FileName=dest, Notes=f"Created by RAPTOR Studio from {src}",
+ ProductVersion="5.0", ProjectVersionLong="5.0.0.0",
+ LifeTime=lifetime, LastModule=1, AvsimCurrentRbdPage=0,
+ AvsimNoSimulationsRequested=trials, AvsimNoSimulationsCompleted=0,
+ AvsimCapacityCalcsPerformed=0, AvsimShowCapacity=0,
+ AvsimEquateCapacity=0, AvsimEquateCapacityUnit="",
+ AvsimEquateCapacityValue=1.0, AvsimEquateCapacityUnit2="",
+ AvsimEquateCapacityValue2=1.0, AvsimEquateCapacityUnit3="",
+ AvsimEquateCapacityValue3=1.0, AvsimEquateCapacityUnit4="",
+ AvsimEquateCapacityValue4=1.0,
+ WeibullCurrentWeibullSet=-1, ProcessCurrentProcessSet=-1,
+ ALTCurrentALTSet=-1, Guid=_guid())
+
+ tables: dict[str, AwbTable] = {
+ "Project": AwbTable("Project", _SCHEMA["Project"], [project]),
+ "FailureModels": AwbTable("FailureModels", _SCHEMA["FailureModels"], fm_rows),
+ "FailureModelCorrectiveTasks": AwbTable(
+ "FailureModelCorrectiveTasks", _SCHEMA["FailureModelCorrectiveTasks"],
+ task_rows),
+ "RbdBlocks": AwbTable("RbdBlocks", _SCHEMA["RbdBlocks"], block_rows),
+ "RbdNodes": AwbTable("RbdNodes", _SCHEMA["RbdNodes"], node_rows),
+ "RbdConnections": AwbTable("RbdConnections", _SCHEMA["RbdConnections"],
+ conn_rows),
+ }
+ if write:
+ write_awb(dest, tables)
+
+ report.counts.update(blocks=len(blocks), nodes=len(nodes),
+ hierarchies=len(hierarchies), links=len(conn_rows),
+ failure_models=len(fm_rows))
+ if skipped_links:
+ report.warnings.append(
+ f"{skipped_links} link(s) could not be exported (an endpoint was "
+ "missing or was an event)")
+ if not time_terminated:
+ report.notes.append(
+ "AWB runs for a fixed lifetime, so a run stopped by failures or "
+ f"cycles was written with a {lifetime / 8760:g}-year lifetime")
+ if dist_simplified:
+ for label, count in sorted(dist_simplified.items()):
+ report.add("failure distribution simplified to exponential",
+ count, f"{label} -> exponential with its mean MTTF")
+ if repair_simplified:
+ for label, count in sorted(repair_simplified.items()):
+ report.add("repair distribution simplified to a fixed duration",
+ count, f"{label} -> AWB task duration = its mean")
+ if no_repair:
+ report.add("no-repair blocks", no_repair,
+ "exported with NonMaintainable=1 and a zero-duration task")
+ if no_failure:
+ report.add("no-failure blocks", no_failure,
+ "exported with a fixed time of 9e8 hours (never fails)")
+ _report_raptor_features(rbd, report, blocks, nodes, links, events,
+ hierarchies, units, factor)
+ return report
+
+
+def _report_raptor_features(rbd: RbdFile, report: AwbReport, # noqa: C901, PLR0912, PLR0915
+ blocks: list[dict[str, Any]],
+ nodes: list[dict[str, Any]],
+ links: list[dict[str, Any]],
+ events: list[dict[str, Any]],
+ hierarchies: list[dict[str, Any]],
+ units: str, factor: float) -> None:
+ """Add the RAPTOR features AWB has no equivalent for."""
+ if events:
+ report.add("failure events", len(events),
+ "AWB RBDs use blocks; events are not exported")
+ if getattr(rbd, "annotations", None):
+ report.add("diagram annotations", len(rbd.annotations),
+ "text boxes, rectangles and arrows are not exported")
+ if getattr(rbd, "rates", None):
+ report.add("rate definitions", len(rbd.rates),
+ "values are exported as plain numbers")
+ if getattr(rbd, "formulas", None):
+ report.add("formula-linked fields", len(rbd.formulas),
+ "values are exported as plain numbers")
+ if getattr(rbd, "triggers", None) or _section_rows(rbd.sections, "TRIGGERS"):
+ report.add("triggers", max(len(getattr(rbd, "triggers", []) or []),
+ _section_rows(rbd.sections, "TRIGGERS")),
+ "AWB has no equivalent of RAPTOR's trigger logic")
+ if getattr(rbd, "spare_pools", None) or _section_rows(rbd.sections, "SPARE_POOL_DATA"):
+ report.add("spare pools", max(len(getattr(rbd, "spare_pools", []) or []),
+ _section_rows(rbd.sections, "SPARE_POOL_DATA")),
+ "AWB spares are not linked to blocks by this export")
+ if getattr(rbd, "resources", None) or _section_rows(rbd.sections, "RESOURCE_DATA"):
+ report.add("resource pools", max(len(getattr(rbd, "resources", []) or []),
+ _section_rows(rbd.sections, "RESOURCE_DATA")),
+ "AWB labour and equipment resources are not populated")
+ phases = _section_rows(rbd.sections, "PHASES")
+ if phases:
+ report.add("mission phases", phases,
+ "AWB phase rules are not populated")
+ if getattr(rbd, "out_of_service", None):
+ report.add("out-of-service elements", len(rbd.out_of_service),
+ "AWB's OutOfService rules are not populated")
+ analyses = [str(a).lower() for a in
+ ((getattr(rbd, "experiment", None) or {}).get("analyses") or [])]
+ capacity = _text(_system_row(rbd).get("capacityAnalysis"))
+ flow_links = sum(1 for link in links
+ if _int(link.get("nomFlow"), -2) not in (-2, -1)
+ or _int(link.get("MaxFlow"), -1) not in (-1, 0))
+ if "capacity" in analyses or capacity not in ("", "0", "None") or flow_links:
+ report.add("capacity analysis", flow_links or 1,
+ "AWB capacity flow and capacity targets are not populated")
+ dep = sum(1 for b in blocks if _text(b.get("DepType"), "None") not in ("None", ""))
+ if dep:
+ report.add("block dependencies", dep,
+ "AWB dependency rules are not populated")
+ pm = sum(1 for b in blocks if _int(b.get("usesPM"), 0))
+ if pm:
+ report.add("preventive maintenance", pm,
+ "AWB scheduled tasks are not populated")
+ phasing = sum(1 for b in blocks if _int(b.get("Phasing"), 0))
+ phasing += sum(1 for n in nodes if _int(n.get("Phases"), 0))
+ phasing += sum(1 for h in hierarchies if _int(h.get("Phs"), 0))
+ if phasing:
+ report.add("phased element schedules", phasing,
+ "per-element phase status is not exported")
+ aged = sum(1 for b in blocks
+ if _num(b.get("_DutyCycle"), 1.0) != 1.0
+ or _num(b.get("_StartAge"), 0.0) != 0.0
+ or _num(b.get("_RestoreFactor"), 0.0) != 0.0
+ or _int(b.get("_RestoreType"), 0) != 0
+ or _int(b.get("GDType"), 0) != 0
+ or _num(b.get("SBStress"), 0.0) != 0.0)
+ if aged:
+ report.add("age, restoration and growth settings", aged,
+ "AWB initial age is 0 and restoration/growth are not set")
+ # RAPTOR's own default is 1.0 in every cost column; only a value that
+ # differs from both "unset" and that default is real data.
+ costs = sum(1 for b in blocks
+ if any(_num(b.get(col), 0.0) not in (0.0, 1.0) for col in
+ ("initial", "Running", "standby", "idle", "repHold",
+ "repPerTime", "repFixed", "donePerTime", "doneFixed",
+ "pmHoldCost", "pmCost", "pmFixedCost", "perSpare",
+ "emerShipping")))
+ if costs:
+ report.add("block cost data", costs,
+ "AWB cost fields are not populated")
+ standby = sum(1 for n in nodes if _int(n.get("Cold"), 0) or _int(n.get("PR"), 0))
+ if standby:
+ report.add("node standby/priority settings", standby,
+ "AWB nodes have only a vote count")
+ link_priority = sum(1 for link in links
+ if _int(link.get("ColdPri"), 50) != 50
+ or _num(link.get("AProb"), 1.0) != 1.0
+ or _num(link.get("AutoTime"), 0.0) != 0.0
+ or _num(link.get("ManTime"), 0.0) != 0.0
+ or _int(link.get("CapPri"), 50) != 50)
+ if link_priority:
+ report.add("link switching and priority", link_priority,
+ "AWB connections carry no switching data")
+ if getattr(rbd, "link_grips", None):
+ report.add("link routing grips", len(rbd.link_grips),
+ "AWB lays connections out itself")
+ if getattr(rbd, "view", None) or getattr(rbd, "view_transform", None):
+ report.add("view settings", 1, "AWB uses its own diagram view")
+ if getattr(rbd, "advisor", None):
+ report.add("advisor state", len(getattr(rbd, "advisor", {}).get("ignored", [])),
+ "ignored findings are RAPTOR-only")
+ if getattr(rbd, "project_meta", None):
+ report.add("print title block", 1, "AWB stores its own project notes")
+ if getattr(rbd, "display_unit", None):
+ report.add("display unit override", 1,
+ "AWB always shows the model in hours")
+ if units.lower() != "hours":
+ report.notes.append(
+ f"AWB stores times in hours; RAPTOR's {units} were converted "
+ f"with factor {factor:g}")
+
+
+def _raptor_dist_name(code: int) -> str:
+ try:
+ from raptor.api.distributions import dist_name
+ return dist_name(code)
+ except Exception: # noqa: BLE001
+ return f"distribution {code}"
+
+
+def _section_rows(sections: dict[str, RbdSection], name: str) -> int:
+ sec = sections.get(name)
+ return 0 if sec is None else len(sec.rows)
+
+
+def _section_list(rbd: RbdFile, name: str) -> list[dict[str, Any]]:
+ sec = rbd.sections.get(name)
+ return [] if sec is None else sec.rows
+
+
+# ---------------------------------------------------------------------------
+# AWB -> RAPTOR
+# ---------------------------------------------------------------------------
+
+
+def import_awb(path: str | Path, *, # noqa: C901, PLR0912, PLR0915
+ source: str = "") -> tuple[RbdFile, AwbReport]:
+ """Read an AWB project and return a RAPTOR model plus the loss report."""
+ src = source or str(path)
+ tables = read_awb(path)
+ report = AwbReport("awb-to-rbds", src, "RAPTOR model")
+ _check_import_features(tables, report)
+
+ blocks = _rows(tables, "RbdBlocks")
+ nodes = _rows(tables, "RbdNodes")
+ conns = _rows(tables, "RbdConnections")
+ fms = _rows(tables, "FailureModels")
+ tasks = _rows(tables, "FailureModelCorrectiveTasks")
+ repeats = _rows(tables, "RbdRepeatBlocks")
+ labels = _rows(tables, "RbdLabels")
+
+ # AWB page index: 0 is the top level; a superblock's row index owns the
+ # page its contents are drawn on. Row 0 is the project root (Page -1).
+ root_i = next((i for i, b in enumerate(blocks)
+ if _int(b.get("Page"), 0) == -1 and _int(b.get("Super"), 0) == 1),
+ None)
+ page_owner: dict[int, str] = {0: "0"}
+ hierarchy_page: dict[str, int] = {}
+ super_rows: dict[int, dict[str, Any]] = {}
+ for i, b in enumerate(blocks):
+ if i == root_i:
+ continue
+ if _int(b.get("Super"), 0) == 1:
+ super_rows[i] = b
+ hierarchy_page[_text(b.get("Id"), f"H{i}")] = i
+ page_owner[i] = _text(b.get("Id"), f"H{i}")
+ # A non-superblock page owner (AWB permits nodes/blocks as page roots in
+ # some versions); keep the top-level owner for it.
+ for b in blocks:
+ page_owner.setdefault(_int(b.get("Page"), 0), "0")
+
+ # ---- names and ids ----------------------------------------------------
+ used_block_names: set[str] = set()
+ used_hier_names: set[str] = set()
+ used_node_names: set[str] = set()
+ block_id: dict[int, int] = {}
+ repeat_id: dict[int, int] = {}
+ node_id: dict[int, int] = {}
+ hier_id: dict[int, int] = {}
+ elements: dict[str, list[dict[str, Any]]] = {
+ "blocks": [], "nodes": [], "hierarchies": []}
+ comments: list[dict[str, Any]] = []
+ next_block = next_node = next_hier = 1
+ x_by_page: dict[int, list[float]] = {}
+
+ def block_name(text: str) -> str:
+ base = _safe_id(text, 20)
+ return _unique(base, used_block_names, 20)
+
+ def node_name(text: str) -> str:
+ base = _safe_id(text, 20)
+ return _unique(base, used_node_names, 20)
+
+ # ---- hierarchies first (parents before children) ----------------------
+ # AWB's page owner is the superblock's row index; the hierarchy tree is
+ # implicit in the Page column. Emit a hierarchy per superblock row, then
+ # set each hierarchy's RAPTOR parent from the page it is drawn on.
+ ordered_super = sorted(super_rows.items(),
+ key=lambda kv: _super_depth(kv[0], blocks))
+ for i, b in ordered_super:
+ hid = next_hier
+ next_hier += 1
+ hier_id[i] = hid
+ name = _unique(_safe_id(_text(b.get("Id"), f"H{i}")), used_hier_names, 20)
+ elements["hierarchies"].append({
+ "id": hid, "name": name, "parent": 0,
+ "x": _num(b.get("XPosition")), "y": _num(b.get("YPosition")),
+ "in_id": 0, "out_id": 0,
+ })
+ comments.append({"type": "Hierarchy", "id": hid, "name": name,
+ "text": _comment_text(b)})
+ for i, b in ordered_super:
+ parent_page = _int(b.get("Page"), 0)
+ owner_row = _page_owner_row(parent_page, page_owner, hierarchy_page)
+ parent = 0 if owner_row == 0 else hier_id.get(owner_row, 0)
+ target = next(h for h in elements["hierarchies"] if h["id"] == hier_id[i])
+ target["parent"] = parent
+
+ # ---- ordinary blocks --------------------------------------------------
+ block_losses: dict[str, int] = {}
+ for i, b in enumerate(blocks):
+ if i == root_i or i in super_rows:
+ continue
+ if _text(b.get("Id")) == "" and _int(b.get("FailureModel"), -1) == -1:
+ continue
+ bid = next_block
+ next_block += 1
+ block_id[i] = bid
+ page = _int(b.get("Page"), 0)
+ owner_row = _page_owner_row(page, page_owner, hierarchy_page)
+ parent = 0 if owner_row == 0 else hier_id.get(owner_row, 0)
+ name = block_name(_text(b.get("Id"), f"B{i}"))
+ fdist, fparams, rdist, rparams = _block_data(
+ b, fms, tasks, block_losses)
+ x, y = _num(b.get("XPosition")), _num(b.get("YPosition"))
+ x_by_page.setdefault(page, []).append(x)
+ elements["blocks"].append({
+ "id": bid, "name": name, "parent": parent, "x": x, "y": y,
+ "fail_dist": fdist, "fail_params": fparams,
+ "repair_dist": rdist, "repair_params": rparams,
+ })
+ comments.append({"type": "Block", "id": bid, "name": name,
+ "text": _comment_text(b)})
+ for feature, count in sorted(block_losses.items()):
+ detail = {
+ "multi-mode or buffer failure distribution":
+ "AWB multi-mode/buffer laws kept their first Weibull mode only",
+ "dormant failures":
+ "a dormant AWB failure is modelled as never repaired",
+ "start-up failure probability":
+ "AWB start-up failures are not modelled by RAPTOR",
+ "non-maintainable blocks":
+ "AWB marks the block non-maintainable; RAPTOR repair is off",
+ }.get(feature, "")
+ report.add(feature, count, detail)
+
+ # ---- repeat blocks ----------------------------------------------------
+ for i, r in enumerate(repeats):
+ ref = _int(r.get("ReferenceBlock"), -1)
+ if ref not in block_id:
+ report.warnings.append(
+ f"repeat block {i} refers to block {ref}, which is not an "
+ "ordinary block; it was skipped")
+ continue
+ bid = next_block
+ next_block += 1
+ repeat_id[i] = bid
+ page = _int(r.get("Page"), 0)
+ owner_row = _page_owner_row(page, page_owner, hierarchy_page)
+ parent = 0 if owner_row == 0 else hier_id.get(owner_row, 0)
+ name = block_name(_text(r.get("Id"), f"R{i}"))
+ elements["blocks"].append({
+ "id": bid, "name": name, "parent": parent,
+ "x": _num(r.get("XPosition")), "y": _num(r.get("YPosition")),
+ "fail_dist": _R_FIXED, "fail_params": [_NEVER, 0.0, 0.0],
+ "repair_dist": _R_FIXED,
+ "repair_params": [_num(_system_row_from_tables(tables)
+ .get("LifeTime"), 87600.0), 0.0, 0.0],
+ "dep_type": "RBDBlock", "dep_num": block_id[ref],
+ "dep_nothing": 0.0, "dep_idle": 100.0, "dep_pm": 0.0,
+ "dep_fail": 0.0,
+ })
+ comments.append({"type": "Block", "id": bid, "name": name,
+ "text": "AWB repeat block: same physical item as "
+ f"block {block_id[ref]}; never fails and is "
+ "idle whenever that block is down."})
+
+ # ---- nodes ------------------------------------------------------------
+ # AWB's nodes carry only a vote count. Start/end/in/out are inferred from
+ # the connections: no incoming = start/in, no outgoing = end/out.
+ incoming: dict[int, int] = {}
+ outgoing: dict[int, int] = {}
+ for c in conns:
+ if _int(c.get("InputObjectType"), _AWB_BLOCK) == _AWB_NODE:
+ outgoing[_int(c.get("InputObjectIndex"), 0)] = \
+ outgoing.get(_int(c.get("InputObjectIndex"), 0), 0) + 1
+ if _int(c.get("OutputObjectType"), _AWB_NODE) == _AWB_NODE:
+ incoming[_int(c.get("OutputObjectIndex"), 0)] = \
+ incoming.get(_int(c.get("OutputObjectIndex"), 0), 0) + 1
+ for i, n in enumerate(nodes):
+ nid = next_node
+ next_node += 1
+ node_id[i] = nid
+ page = _int(n.get("Page"), 0)
+ owner_row = _page_owner_row(page, page_owner, hierarchy_page)
+ parent = 0 if owner_row == 0 else hier_id.get(owner_row, 0)
+ vote = _int(n.get("Vote"), 1)
+ if vote > 1:
+ ntype, k = 2, vote
+ elif page == 0:
+ ntype = 1 if incoming.get(i, 0) == 0 else (
+ 3 if outgoing.get(i, 0) == 0 else 2)
+ k = -1 if ntype in (1, 3) else 1
+ else:
+ ntype = 4 if incoming.get(i, 0) == 0 else (
+ 5 if outgoing.get(i, 0) == 0 else 2)
+ k = -1 if ntype in (4, 5) else 1
+ name = node_name(_text(n.get("Id"), f"N{i}"))
+ elements["nodes"].append({
+ "id": nid, "name": name, "type": ntype, "parent": parent,
+ "x": _num(n.get("XPosition")), "y": _num(n.get("YPosition")),
+ "k": k,
+ })
+ # Bind each hierarchy to its input and output nodes and create them when
+ # the AWB page has none (common: AWB superblocks have no explicit nodes).
+ for i, _b in ordered_super:
+ hid = hier_id[i]
+ content_page = i
+ page_nodes = [n for n in elements["nodes"]
+ if _node_page(n, nodes, node_id) == content_page]
+ ins = [n["id"] for n in page_nodes if n["type"] == 4]
+ outs = [n["id"] for n in page_nodes if n["type"] == 5]
+ if not ins:
+ nid = next_node; next_node += 1
+ x = min(x_by_page.get(content_page, [-100.0])) - 120.0
+ elements["nodes"].append({"id": nid, "name": node_name("in"),
+ "type": 4, "parent": hid, "x": x,
+ "y": 0.0, "k": -1})
+ ins = [nid]
+ if not outs:
+ nid = next_node; next_node += 1
+ x = max(x_by_page.get(content_page, [400.0])) + 120.0
+ elements["nodes"].append({"id": nid, "name": node_name("out"),
+ "type": 5, "parent": hid, "x": x,
+ "y": 0.0, "k": -1})
+ outs = [nid]
+ h = next(h for h in elements["hierarchies"] if h["id"] == hid)
+ h["in_id"], h["out_id"] = ins[0], outs[0]
+
+ # Top level needs a start and an end too.
+ top_nodes = [n for n in elements["nodes"] if n["parent"] == 0]
+ if not any(n["type"] == 1 for n in top_nodes):
+ nid = next_node; next_node += 1
+ elements["nodes"].append({"id": nid, "name": node_name("start"),
+ "type": 1, "parent": 0,
+ "x": min(x_by_page.get(0, [-100.0])) - 120.0,
+ "y": 0.0, "k": -1})
+ if not any(n["type"] == 3 for n in top_nodes):
+ nid = next_node; next_node += 1
+ elements["nodes"].append({"id": nid, "name": node_name("end"),
+ "type": 3, "parent": 0,
+ "x": max(x_by_page.get(0, [400.0])) + 120.0,
+ "y": 0.0, "k": -1})
+
+ # ---- links ------------------------------------------------------------
+ links: list[dict[str, Any]] = []
+ next_link = 1
+ for c in conns:
+ ftype = _int(c.get("InputObjectType"), _AWB_BLOCK)
+ ttype = _int(c.get("OutputObjectType"), _AWB_BLOCK)
+ findex = _int(c.get("InputObjectIndex"), 0)
+ tindex = _int(c.get("OutputObjectIndex"), 0)
+ fend = _endpoint(ftype, findex, block_id, repeat_id, node_id, hier_id,
+ blocks, page_owner, hierarchy_page)
+ tend = _endpoint(ttype, tindex, block_id, repeat_id, node_id, hier_id,
+ blocks, page_owner, hierarchy_page)
+ if fend is None or tend is None:
+ report.warnings.append(
+ f"connection {_text(c.get('Id'), str(next_link))} refers to an "
+ "object this reader does not recognise; skipped")
+ continue
+ page = _int(c.get("Page"), 0)
+ owner_row = _page_owner_row(page, page_owner, hierarchy_page)
+ links.append({
+ "id": next_link,
+ "from": list(fend), "to": list(tend),
+ "parent": 0 if owner_row == 0 else hier_id.get(owner_row, 0),
+ })
+ next_link += 1
+
+ # ---- close open ends on each page ------------------------------------
+ # AWB pages may have no explicit input/output nodes at all (Example1 is
+ # built that way): the page's first and last items are the ends. RAPTOR
+ # needs a Start/End (or a hierarchy In/Out) on every level, so add the
+ # missing links, with an ordinary node as a split/join when a page has
+ # several open ends.
+ def add_link(src: tuple[str, int], dst: tuple[str, int], parent: int) -> None:
+ nonlocal next_link
+ links.append({"id": next_link, "from": list(src), "to": list(dst),
+ "parent": parent})
+ next_link += 1
+
+ def add_junction(owner: int, name: str, x: float, y: float) -> int:
+ nonlocal next_node
+ nid = next_node
+ next_node += 1
+ elements["nodes"].append({"id": nid, "name": node_name(name),
+ "type": 2, "parent": owner, "x": x,
+ "y": y, "k": 1})
+ return nid
+
+ page_owner_ids: list[tuple[int, int]] = [(0, 0)]
+ for i, _b in ordered_super:
+ page_owner_ids.append((i, hier_id[i]))
+ for _page, owner in page_owner_ids:
+ if owner == 0:
+ ins = [n["id"] for n in elements["nodes"]
+ if n["parent"] == 0 and n["type"] == 1]
+ outs = [n["id"] for n in elements["nodes"]
+ if n["parent"] == 0 and n["type"] == 3]
+ else:
+ hier: dict[str, Any] | None = None
+ for candidate in elements["hierarchies"]:
+ if candidate["id"] == owner:
+ hier = candidate
+ break
+ if hier is None:
+ continue
+ ins, outs = [hier["in_id"]], [hier["out_id"]]
+ if not ins or not outs:
+ continue
+ items: list[tuple[str, int]] = [
+ ("Block", b["id"]) for b in elements["blocks"] if b["parent"] == owner]
+ items += [("Hier", h["id"]) for h in elements["hierarchies"]
+ if h["parent"] == owner]
+ # Do not use the page's own in/out nodes as flow items.
+ items = [it for it in items if it[1] not in ins + outs]
+ if not items:
+ continue
+ indeg = {it: 0 for it in items}
+ outdeg = {it: 0 for it in items}
+ for link in links:
+ link_src = tuple(link["from"])
+ link_dst = tuple(link["to"])
+ if link_src in outdeg:
+ outdeg[link_src] += 1
+ if link_dst in indeg:
+ indeg[link_dst] += 1
+ open_in = [it for it in items if indeg[it] == 0]
+ open_out = [it for it in items if outdeg[it] == 0]
+ if not open_in and not open_out:
+ continue
+ if len(open_in) == 1:
+ add_link(("Node", ins[0]), open_in[0], owner)
+ elif open_in:
+ j = add_junction(owner, "page_in", 0.0, 0.0)
+ add_link(("Node", ins[0]), ("Node", j), owner)
+ for it in open_in:
+ add_link(("Node", j), it, owner)
+ if len(open_out) == 1:
+ add_link(open_out[0], ("Node", outs[0]), owner)
+ elif open_out:
+ j = add_junction(owner, "page_out", 0.0, 0.0)
+ for it in open_out:
+ add_link(it, ("Node", j), owner)
+ add_link(("Node", j), ("Node", outs[0]), owner)
+
+ # ---- annotations from AWB labels -------------------------------------
+ annotations: list[dict[str, Any]] = []
+ for lab in labels:
+ if _int(lab.get("Type"), 0) != 0:
+ continue
+ annotations.append({
+ "kind": "text", "id": len(annotations) + 1,
+ "parent": 0 if _int(lab.get("Page"), 0) == 0 else hier_id.get(
+ _page_owner_row(_int(lab.get("Page"), 0), page_owner,
+ hierarchy_page), 0),
+ "x": _num(lab.get("XPosition")), "y": _num(lab.get("YPosition")),
+ "w": max(20.0, _num(lab.get("Width"), 100.0)),
+ "h": max(10.0, _num(lab.get("Height"), 20.0)),
+ "text": _text(lab.get("LabelText")),
+ "z": 20, "border_colour": None, "border_width": 0,
+ "line_style": "solid", "fill_colour": None,
+ "text_colour": "#132238", "font_family": "sans-serif",
+ "font_size": max(6.0, _num(lab.get("FontSize"), 10.0)),
+ "font_bold": False, "font_italic": False,
+ })
+
+ # ---- project settings -------------------------------------------------
+ project = _rows(tables, "Project")[0] if _rows(tables, "Project") else {}
+ lifetime = max(1.0, _num(project.get("LifeTime"), 87600.0))
+ trials = max(1, _int(project.get("AvsimNoSimulationsRequested"), 1000))
+ report.counts.update(blocks=len(elements["blocks"]),
+ nodes=len(elements["nodes"]),
+ hierarchies=len(elements["hierarchies"]),
+ links=len(links), failure_models=len(fms),
+ repeats=len(repeats), labels=len(annotations))
+ if annotations:
+ report.notes.append(
+ f"{len(annotations)} AWB label(s) imported as RAPTOR annotations")
+ if repeats:
+ report.notes.append(
+ f"{len(repeats)} AWB repeat block(s) imported as never-failing "
+ "blocks that depend on the original block")
+ if _text(project.get("Description")):
+ report.notes.append(
+ f"AWB project description: {_text(project.get('Description'))}")
+
+ doc = {
+ "format": "raptor-studio",
+ "version": 4,
+ "meta": {"generator": "RAPTOR Studio AWB importer"},
+ "system": {"units": "hours"},
+ "experiment": {
+ "trials": trials,
+ "termination_type": "TimeSim",
+ "term_condition": lifetime,
+ },
+ "elements": elements,
+ "links": links,
+ "annotations": annotations,
+ "comments": comments,
+ }
+ from raptor.core.fileio.rbds import parse_rbds
+ rbd = parse_rbds(json.dumps(doc), default_name=Path(src).stem)
+ return rbd, report
+
+
+def _super_depth(row: int, blocks: list[dict[str, Any]]) -> int:
+ """Depth of a superblock row by following its Page back to page 0."""
+ depth = 0
+ seen: set[int] = set()
+ while row not in seen:
+ seen.add(row)
+ page = _int(blocks[row].get("Page"), 0) if 0 <= row < len(blocks) else 0
+ if page == 0:
+ return depth
+ # The page's owner is the superblock row whose index equals `page`.
+ row = page
+ depth += 1
+ if row < 0 or row >= len(blocks):
+ return depth
+ return depth
+
+
+def _page_owner_row(page: int, page_owner: dict[int, str],
+ hierarchy_page: dict[str, int]) -> int:
+ """The AWB superblock row that owns *page* (0 when it is top level)."""
+ owner = page_owner.get(page, "0")
+ return 0 if owner == "0" else hierarchy_page.get(owner, 0)
+
+
+def _node_page(node: dict[str, Any], nodes: list[dict[str, Any]],
+ node_id: dict[int, int]) -> int:
+ for i, n in enumerate(nodes):
+ if node_id.get(i) == node["id"]:
+ return _int(n.get("Page"), 0)
+ return -1
+
+
+def _endpoint(kind: int, index: int, block_id: dict[int, int],
+ repeat_id: dict[int, int], node_id: dict[int, int],
+ hier_id: dict[int, int], blocks: list[dict[str, Any]],
+ page_owner: dict[int, str],
+ hierarchy_page: dict[str, int]) -> tuple[str, int] | None:
+ if kind == _AWB_BLOCK:
+ if index in block_id:
+ return ("Block", block_id[index])
+ # A superblock is an ordinary row in RbdBlocks too; links to it are
+ # links to the RAPTOR hierarchy element.
+ if index in hier_id:
+ return ("Hier", hier_id[index])
+ return None
+ if kind == _AWB_REPEAT:
+ return ("Block", repeat_id[index]) if index in repeat_id else None
+ if kind == _AWB_NODE:
+ return ("Node", node_id[index]) if index in node_id else None
+ return None
+
+
+def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901, PLR0912
+ tasks: list[dict[str, Any]],
+ losses: dict[str, int]) -> tuple[int, list[float], int, list[float]]:
+ """RAPTOR failure and repair laws for one AWB block.
+
+ *losses* accumulates the things AWB can do and RAPTOR cannot, so the
+ report can give one count per kind rather than one line per block.
+ """
+ fm_i = _int(block.get("FailureModel"), -1)
+ if fm_i < 0 or fm_i >= len(fms):
+ return _R_FIXED, [_NEVER, 0.0, 0.0], _R_FIXED, [1.0, 0.0, 0.0]
+ fm = fms[fm_i]
+ dist = _int(fm.get("FmDistribution"), _AWB_EXPONENTIAL)
+ mttf = max(1e-9, _num(fm.get("FmMttf"), 8760.0))
+ eta = max(1e-9, _num(fm.get("FmEta1"), mttf))
+ beta = max(1e-9, _num(fm.get("FmBeta1"), 1.0))
+ gamma = max(0.0, _num(fm.get("FmGamma1"), 0.0))
+ if dist == _AWB_EXPONENTIAL:
+ fdist, fparams = _R_EXPO, [mttf, 0.0, 0.0]
+ elif dist == _AWB_WEIBULL:
+ fdist, fparams = _R_WEIBULL, [beta, eta, gamma]
+ elif dist == _AWB_FIXED:
+ fdist, fparams = _R_FIXED, [mttf, 0.0, 0.0]
+ elif dist == _AWB_LOGNORMAL:
+ fdist, fparams = _R_LOGNORM, [mttf, max(0.0, _num(fm.get("FmStd"))), 0.0]
+ elif dist == _AWB_NORMAL:
+ fdist, fparams = _R_NORM, [mttf, max(0.0, _num(fm.get("FmStd"))), 0.0]
+ else:
+ # Bi-/tri-Weibull, buffer and phased laws have no exact RAPTOR
+ # equivalent in the friendly model. Keep the first mode and say so.
+ fdist, fparams = _R_WEIBULL, [beta, eta, gamma]
+ losses["multi-mode or buffer failure distribution"] = (
+ losses.get("multi-mode or buffer failure distribution", 0) + 1)
+ if _int(fm.get("FmDormant"), 0):
+ losses["dormant failures"] = losses.get("dormant failures", 0) + 1
+ return fdist, fparams, _R_NONE, [1.0, 0.0, 0.0]
+ if _num(fm.get("StartUpFailureProb"), 0.0) > 0.0:
+ losses["start-up failure probability"] = (
+ losses.get("start-up failure probability", 0) + 1)
+ task = next((t for t in tasks if _int(t.get("FailureModel"), -1) == fm_i), None)
+ if task is None:
+ return fdist, fparams, _R_FIXED, [0.0, 0.0, 0.0]
+ duration = max(0.0, _num(task.get("TaskDuration")) + _num(task.get("RampTime")))
+ tdist = _int(task.get("Distribution"), 2)
+ std = max(0.0, _num(task.get("Std")))
+ if _int(block.get("NonMaintainable"), 0):
+ losses["non-maintainable blocks"] = (
+ losses.get("non-maintainable blocks", 0) + 1)
+ return fdist, fparams, _R_NONE, [1.0, 0.0, 0.0]
+ if tdist == 0:
+ return fdist, fparams, _R_EXPO, [max(1e-9, duration), 0.0, 0.0]
+ if tdist == 1:
+ return fdist, fparams, _R_LOGNORM, [max(1e-9, duration), std, 0.0]
+ if tdist == 3:
+ return fdist, fparams, _R_WEIBULL, [
+ max(1e-9, _num(task.get("Beta"), 2.0)), max(1e-9, duration),
+ max(0.0, _num(task.get("Gamma")))]
+ if std > 0:
+ return fdist, fparams, _R_NORM, [max(1e-9, duration), std, 0.0]
+ return fdist, fparams, _R_FIXED, [max(0.0, duration), 0.0, 0.0]
+
+
+def _comment_text(row: dict[str, Any]) -> str:
+ parts = [_text(row.get("Description"))]
+ for key in ("Notes1", "Notes2", "Notes3", "Notes4"):
+ text = _text(row.get(key))
+ if text:
+ parts.append(text)
+ return " | ".join(p for p in parts if p)
+
+
+def _system_row_from_tables(tables: dict[str, AwbTable]) -> dict[str, Any]:
+ rows = _rows(tables, "Project")
+ return rows[0] if rows else {}
+
+
+def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> None: # noqa: C901, PLR0912
+ """Name the AWB features RAPTOR has no equivalent for."""
+ if _rows(tables, "Consequences"):
+ report.add("consequence and cost models", len(_rows(tables, "Consequences")),
+ "AWB financial/safety/environmental consequences are not "
+ "modelled by RAPTOR")
+ if _rows(tables, "Phases") or _rows(tables, "RbdBlockRuleAssignments"):
+ report.add("mission phases and phase rules",
+ max(len(_rows(tables, "Phases")),
+ len(_rows(tables, "RbdBlockRuleAssignments"))),
+ "AWB phase schedules and rules are not imported")
+ if _rows(tables, "FailureModelScheduledTasks"):
+ report.add("planned maintenance tasks",
+ len(_rows(tables, "FailureModelScheduledTasks")),
+ "AWB scheduled/inspection tasks are not imported")
+ if _rows(tables, "Spares") or _rows(tables, "FailureModelCorrTaskSpares"):
+ report.add("spares and sparing rules",
+ max(len(_rows(tables, "Spares")),
+ len(_rows(tables, "FailureModelCorrTaskSpares"))),
+ "AWB spare holdings and logistics are not imported")
+ if _rows(tables, "Labor") or _rows(tables, "Equipment"):
+ report.add("labour and equipment resources",
+ max(len(_rows(tables, "Labor")), len(_rows(tables, "Equipment"))),
+ "AWB resource pools are not imported")
+ if _rows(tables, "RcmLocations") or _rows(tables, "RcmCauses"):
+ report.add("RCM location hierarchy", max(
+ len(_rows(tables, "RcmLocations")), len(_rows(tables, "RcmCauses"))),
+ "the RCMCost module is not imported")
+ if _rows(tables, "Gates") or _rows(tables, "PrimaryEvents"):
+ report.add("fault trees", max(len(_rows(tables, "Gates")),
+ len(_rows(tables, "PrimaryEvents"))),
+ "fault trees are not imported")
+ if _rows(tables, "WeibullSets") or _rows(tables, "WeibullSetItems"):
+ report.add("Weibull sets", max(len(_rows(tables, "WeibullSets")),
+ len(_rows(tables, "WeibullSetItems"))),
+ "linked historical data is flattened to its first mode")
+ if _rows(tables, "LibraryBitmaps") or _rows(tables, "LibraryBitmapBytes"):
+ report.add("bitmaps", max(len(_rows(tables, "LibraryBitmaps")),
+ len(_rows(tables, "LibraryBitmapBytes"))),
+ "AWB diagram bitmaps are not imported")
+ if _rows(tables, "RbdLabels"):
+ # Labels are imported as annotations (a win, not a loss); note it in
+ # the report rather than in not_in_target.
+ pass
+ capacity = any(_num(b.get("MaxCapacity"), 100000.0) not in (100000.0, 0.0)
+ for b in _rows(tables, "RbdBlocks"))
+ if capacity or _int(_system_row_from_tables(tables)
+ .get("AvsimCapacityCalcsPerformed"), 0):
+ report.add("capacity flow and capacity targets", 1,
+ "AWB capacity products are not imported")
+ nonop = sum(1 for b in _rows(tables, "RbdBlocks")
+ if _int(b.get("NonOperational"), 0))
+ if nonop:
+ report.add("non-operational blocks", nonop,
+ "AWB non-operational state is not imported")
+ standby = sum(1 for b in _rows(tables, "RbdBlocks")
+ if _int(b.get("StandbyMode"), 0) or _int(b.get("LogicMode"), 0))
+ standby += sum(1 for n in _rows(tables, "RbdNodes")
+ if _int(n.get("LocalStandby"), 0) or _int(n.get("NotLogic"), 0))
+ if standby:
+ report.add("standby and NOT logic", standby,
+ "AWB standby/NOT arrangements are not imported")
+ curtailed = sum(1 for b in _rows(tables, "RbdBlocks")
+ if _int(b.get("Consequence"), -1) >= 0)
+ if curtailed:
+ report.add("block consequence links", curtailed,
+ "AWB consequence assignments are not imported")
diff --git a/raptor/core/fileio/awb_tables.json b/raptor/core/fileio/awb_tables.json
new file mode 100644
index 00000000..2de3c156
--- /dev/null
+++ b/raptor/core/fileio/awb_tables.json
@@ -0,0 +1,2384 @@
+{
+ "format": "raptor-awb-tables/1",
+ "source": "AWB 5.0.0.0",
+ "tables": {
+ "Project": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "FileName",
+ 0
+ ],
+ [
+ "ProductVersion",
+ 0
+ ],
+ [
+ "ProjectVersionLong",
+ 0
+ ],
+ [
+ "Notes",
+ 0
+ ],
+ [
+ "CompiledBy",
+ 0
+ ],
+ [
+ "ApprovedBy",
+ 0
+ ],
+ [
+ "DoublePrecision",
+ 1
+ ],
+ [
+ "DoubleFormat",
+ 1
+ ],
+ [
+ "LifeTime",
+ 2
+ ],
+ [
+ "LastModule",
+ 1
+ ],
+ [
+ "LastRcmRightWindowMode",
+ 1
+ ],
+ [
+ "LastAvsimRightWindowMode",
+ 1
+ ],
+ [
+ "LastWeibullRightWindowMode",
+ 1
+ ],
+ [
+ "LastLccRightWindowMode",
+ 1
+ ],
+ [
+ "LastProcessRightWindowMode",
+ 1
+ ],
+ [
+ "LastSapRightWindowMode",
+ 1
+ ],
+ [
+ "LastMaximoRightWindowMode",
+ 1
+ ],
+ [
+ "LastALTRightWindowMode",
+ 1
+ ],
+ [
+ "LastRcmTableType",
+ 1
+ ],
+ [
+ "LastAvsimTableType",
+ 1
+ ],
+ [
+ "LastWeibullTableType",
+ 1
+ ],
+ [
+ "LastLccTableType",
+ 1
+ ],
+ [
+ "LastProcessTableType",
+ 1
+ ],
+ [
+ "LastSapTableType",
+ 1
+ ],
+ [
+ "LastMaximoTableType",
+ 1
+ ],
+ [
+ "LastALTTableType",
+ 1
+ ],
+ [
+ "NpvOn",
+ 3
+ ],
+ [
+ "NpvYieldPercent",
+ 2
+ ],
+ [
+ "NpvLaborPercent",
+ 2
+ ],
+ [
+ "NpvEquipmentPercent",
+ 2
+ ],
+ [
+ "NpvSparesUsagePercent",
+ 2
+ ],
+ [
+ "NpvSparesStoragePercent",
+ 2
+ ],
+ [
+ "NpvOperationalPercent",
+ 2
+ ],
+ [
+ "NpvCommissionPercent",
+ 2
+ ],
+ [
+ "NpvRedesignPercent",
+ 2
+ ],
+ [
+ "NpvAlarmPercent",
+ 2
+ ],
+ [
+ "NpvOutagePercent",
+ 2
+ ],
+ [
+ "RcmCriticalityUseCost",
+ 3
+ ],
+ [
+ "RcmCriticalityUseSafety",
+ 3
+ ],
+ [
+ "RcmCriticalityUseOperational",
+ 3
+ ],
+ [
+ "RcmCriticalityUseEnvironmental",
+ 3
+ ],
+ [
+ "ErpCriticalityUseCost",
+ 3
+ ],
+ [
+ "ErpCriticalityUseEffect",
+ 3
+ ],
+ [
+ "ErpCriticalityUseNoCM",
+ 3
+ ],
+ [
+ "ErpCriticalityUseNoPM",
+ 3
+ ],
+ [
+ "ErpCriticalityUseNoIN",
+ 3
+ ],
+ [
+ "RcmNoSimulations",
+ 1
+ ],
+ [
+ "RcmRandomNoSeed",
+ 1
+ ],
+ [
+ "RcmSafetyCriticalityTarget",
+ 2
+ ],
+ [
+ "RcmOperationalCritTarget",
+ 2
+ ],
+ [
+ "RcmEnvironmentalCritTarget",
+ 2
+ ],
+ [
+ "RcmSpareOptQTarget",
+ 2
+ ],
+ [
+ "RcmSpareOptNSites",
+ 1
+ ],
+ [
+ "RcmAutoCriticality",
+ 3
+ ],
+ [
+ "RcmShowId",
+ 3
+ ],
+ [
+ "RcmShowDescription",
+ 3
+ ],
+ [
+ "RcmShowQuantity",
+ 3
+ ],
+ [
+ "RcmShowUnavailability",
+ 3
+ ],
+ [
+ "RcmShowFrequency",
+ 3
+ ],
+ [
+ "RcmShowEffect",
+ 3
+ ],
+ [
+ "RcmShowTaskGroup",
+ 3
+ ],
+ [
+ "RcmShowCost",
+ 3
+ ],
+ [
+ "RcmShowSafetyCrit",
+ 3
+ ],
+ [
+ "RcmShowOperationalCrit",
+ 3
+ ],
+ [
+ "RcmShowEnvironmentalCrit",
+ 3
+ ],
+ [
+ "RcmShowStrategy",
+ 3
+ ],
+ [
+ "NoProfileIntervalS",
+ 1
+ ],
+ [
+ "ProfileStart",
+ 2
+ ],
+ [
+ "ProfileInterval",
+ 2
+ ],
+ [
+ "MapProfileToLifetime",
+ 3
+ ],
+ [
+ "ApplyInsPrdDataAtZero",
+ 3
+ ],
+ [
+ "RcmLocationTreeNodeExp",
+ 3
+ ],
+ [
+ "RcmLocationTypeTreeNodeExp",
+ 3
+ ],
+ [
+ "SpareTreeNodeExp",
+ 3
+ ],
+ [
+ "LaborTreeNodeExp",
+ 3
+ ],
+ [
+ "EquipmentTreeNodeExp",
+ 3
+ ],
+ [
+ "TaskGroupTreeNodeExp",
+ 3
+ ],
+ [
+ "RcmEffectTreeNodeExp",
+ 3
+ ],
+ [
+ "WeibullSetTreeNodeExp",
+ 3
+ ],
+ [
+ "ProcessSetTreeNodeExp",
+ 3
+ ],
+ [
+ "ALTSetTreeNodeExp",
+ 3
+ ],
+ [
+ "BomTreeNodeExp",
+ 3
+ ],
+ [
+ "RbdBlockTreeNodeExp",
+ 3
+ ],
+ [
+ "ConsequenceTreeNodeExp",
+ 3
+ ],
+ [
+ "PhaseTreeNodeExp",
+ 3
+ ],
+ [
+ "LibraryBitmapTreeNodeExp",
+ 3
+ ],
+ [
+ "GateTreeNodeExp",
+ 3
+ ],
+ [
+ "FailureModelTreeNodeExp",
+ 3
+ ],
+ [
+ "SapLocationTreeNodeExp",
+ 3
+ ],
+ [
+ "SapCatalogTreeNodeExp",
+ 3
+ ],
+ [
+ "SapCatProfTreeNodeExp",
+ 3
+ ],
+ [
+ "SapEffectTreeNodeExp",
+ 3
+ ],
+ [
+ "SapABCIndTreeNodeExp",
+ 3
+ ],
+ [
+ "SapTecOTTreeNodeExp",
+ 3
+ ],
+ [
+ "SapClassTreeNodeExp",
+ 3
+ ],
+ [
+ "SapEqClTreeNodeExp",
+ 3
+ ],
+ [
+ "SapLoClTreeNodeExp",
+ 3
+ ],
+ [
+ "SapMaClTreeNodeExp",
+ 3
+ ],
+ [
+ "SapDoClTreeNodeExp",
+ 3
+ ],
+ [
+ "SapLaborTreeNodeExp",
+ 3
+ ],
+ [
+ "SapBomTreeNodeExp",
+ 3
+ ],
+ [
+ "SapEqBomTreeNodeExp",
+ 3
+ ],
+ [
+ "SapLoBomTreeNodeExp",
+ 3
+ ],
+ [
+ "SapMtBomTreeNodeExp",
+ 3
+ ],
+ [
+ "SapMaterialTreeNodeExp",
+ 3
+ ],
+ [
+ "SapMPlanTreeNodeExp",
+ 3
+ ],
+ [
+ "MaximoLocationTreeNodeExp",
+ 3
+ ],
+ [
+ "MaximoPMTreeNodeExp",
+ 3
+ ],
+ [
+ "MaximoFailureListTreeNodeExp",
+ 3
+ ],
+ [
+ "MaximoCraftTreeNodeExp",
+ 3
+ ],
+ [
+ "MaximoCommodityTreeNodeExp",
+ 3
+ ],
+ [
+ "AvsimCurrentRbdPage",
+ 1
+ ],
+ [
+ "AvsimCurrentFtPage",
+ 1
+ ],
+ [
+ "AvsimNoSimulationsRequested",
+ 1
+ ],
+ [
+ "AvsimNoSimulationsCompleted",
+ 1
+ ],
+ [
+ "AvsimCapacityCalcsPerformed",
+ 3
+ ],
+ [
+ "AvsimTreeControlShowId",
+ 3
+ ],
+ [
+ "AvsimTreeControlShowDesc",
+ 3
+ ],
+ [
+ "AvsimShowFailureData",
+ 3
+ ],
+ [
+ "AvsimShowRepairData",
+ 3
+ ],
+ [
+ "AvsimShowCapacity",
+ 3
+ ],
+ [
+ "AvsimShowFailureModelId",
+ 3
+ ],
+ [
+ "AvsimAvailabilityPreference",
+ 3
+ ],
+ [
+ "AvsimShowQm",
+ 3
+ ],
+ [
+ "AvsimShowF",
+ 3
+ ],
+ [
+ "AvsimShowW",
+ 3
+ ],
+ [
+ "AvsimShowRbdArrows",
+ 3
+ ],
+ [
+ "AvsimShowGrid",
+ 3
+ ],
+ [
+ "AvsimShowRbdDescWithBitmaps",
+ 3
+ ],
+ [
+ "AvsimShowSymbol",
+ 1
+ ],
+ [
+ "AvsimShowFtIecSymbols",
+ 3
+ ],
+ [
+ "AvsimShowFtNameBorder",
+ 3
+ ],
+ [
+ "AvsimShowFtRepeatBars",
+ 3
+ ],
+ [
+ "AvsimDisableFtPaging",
+ 3
+ ],
+ [
+ "AvsimDisableTransferTabs",
+ 3
+ ],
+ [
+ "IncludeInitialSpares",
+ 3
+ ],
+ [
+ "ResultsEffectIndex",
+ 1
+ ],
+ [
+ "ResultsConsequenceIndex",
+ 1
+ ],
+ [
+ "ResultsCauseIndex",
+ 1
+ ],
+ [
+ "ResultsSpareIndex",
+ 1
+ ],
+ [
+ "ResultsLaborIndex",
+ 1
+ ],
+ [
+ "ResultsEquipmentIndex",
+ 1
+ ],
+ [
+ "ResultsSystemBlockIndex",
+ 1
+ ],
+ [
+ "ResultsSystemGateIndex",
+ 1
+ ],
+ [
+ "ResultsComponentBlockIndex",
+ 1
+ ],
+ [
+ "ResultsComponentEventIndex",
+ 1
+ ],
+ [
+ "ResultsPhaseIndex",
+ 1
+ ],
+ [
+ "ResultsDetailedLifeCosts",
+ 3
+ ],
+ [
+ "WeibullCurrentWeibullSet",
+ 1
+ ],
+ [
+ "ProcessCurrentProcessSet",
+ 1
+ ],
+ [
+ "ALTCurrentALTSet",
+ 1
+ ],
+ [
+ "AvsimDiagramMode",
+ 1
+ ],
+ [
+ "AvsimFtPageScale",
+ 2
+ ],
+ [
+ "AvsimFtPagePositionX",
+ 2
+ ],
+ [
+ "AvsimFtPagePositionY",
+ 2
+ ],
+ [
+ "AvsimReplenishSpares",
+ 3
+ ],
+ [
+ "AvsimReplenishInterval",
+ 2
+ ],
+ [
+ "AvsimRandomNumberSeed",
+ 1
+ ],
+ [
+ "AvsimMultipleSites",
+ 3
+ ],
+ [
+ "AvsimImportanceConsequence",
+ 1
+ ],
+ [
+ "AvsimImportanceCutoff",
+ 2
+ ],
+ [
+ "AvsimImportanceInitCap",
+ 3
+ ],
+ [
+ "ImportanceShowCost",
+ 3
+ ],
+ [
+ "ImportanceShowTdt",
+ 3
+ ],
+ [
+ "ImportanceShowTdtC",
+ 3
+ ],
+ [
+ "ImportanceShowTdtP",
+ 3
+ ],
+ [
+ "ImportanceShowTdtI",
+ 3
+ ],
+ [
+ "ImportanceShowW",
+ 3
+ ],
+ [
+ "ImportanceShowTdtSpare",
+ 3
+ ],
+ [
+ "ImportanceShowTdtCrew",
+ 3
+ ],
+ [
+ "ImportanceShowCapacity",
+ 3
+ ],
+ [
+ "ImportanceShowCapacityC",
+ 3
+ ],
+ [
+ "ImportanceShowCapacityP",
+ 3
+ ],
+ [
+ "ImportanceShowCapacityI",
+ 3
+ ],
+ [
+ "ImportanceShowCapacitySpare",
+ 3
+ ],
+ [
+ "ImportanceShowCapacityCrew",
+ 3
+ ],
+ [
+ "ImportanceShowSafety",
+ 3
+ ],
+ [
+ "ImportanceShowOperational",
+ 3
+ ],
+ [
+ "ImportanceShowEnvironmental",
+ 3
+ ],
+ [
+ "AvsimCapAvailSystemType",
+ 1
+ ],
+ [
+ "AvsimCapAvailSystemIndex",
+ 1
+ ],
+ [
+ "AvsimCapAvailNoIntervals",
+ 1
+ ],
+ [
+ "AvsimCapAvailNoPoints",
+ 1
+ ],
+ [
+ "AvsimCapAvailStartTime",
+ 2
+ ],
+ [
+ "AvsimCapAvailIntervalLength",
+ 2
+ ],
+ [
+ "AvsimCapAvailIntervalIndex",
+ 1
+ ],
+ [
+ "AvsimCapAvailMap",
+ 3
+ ],
+ [
+ "AvsimEquateCapacity",
+ 3
+ ],
+ [
+ "AvsimEquateCapacityUnit",
+ 0
+ ],
+ [
+ "AvsimEquateCapacityValue",
+ 2
+ ],
+ [
+ "StorageCostMethod",
+ 1
+ ],
+ [
+ "SpareCostPUnitWeightLevel1",
+ 2
+ ],
+ [
+ "SpareCostPUnitWeightLevel2",
+ 2
+ ],
+ [
+ "SpareCostPUnitVolumeLevel1",
+ 2
+ ],
+ [
+ "SpareCostPUnitVolumeLevel2",
+ 2
+ ],
+ [
+ "GlobalLogDelayOnLevel1",
+ 3
+ ],
+ [
+ "GlobalLogDelayOnLevel2",
+ 3
+ ],
+ [
+ "GlobalLogDelayOnLevel3",
+ 3
+ ],
+ [
+ "GlobalLogDelayLevel1",
+ 2
+ ],
+ [
+ "GlobalLogDelayLevel2",
+ 2
+ ],
+ [
+ "GlobalLogDelayLevel3",
+ 2
+ ],
+ [
+ "AvsimBufferDepletionOnCapacity",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatFailureModels",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatConsequences",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatWeibullSets",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatSpares",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatEquipments",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatLabors",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatTaskGroups",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatPhases",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatBitmaps",
+ 3
+ ],
+ [
+ "AvsimPasteRenMatBoms",
+ 3
+ ],
+ [
+ "WeibullTreeControlShowId",
+ 3
+ ],
+ [
+ "WeibullTreeControlShowDesc",
+ 3
+ ],
+ [
+ "ProcessTreeControlShowId",
+ 3
+ ],
+ [
+ "ProcessTreeControlShowDesc",
+ 3
+ ],
+ [
+ "SapTreeControlShowId",
+ 3
+ ],
+ [
+ "SapTreeControlShowDesc",
+ 3
+ ],
+ [
+ "MaximoTreeControlShowId",
+ 3
+ ],
+ [
+ "MaximoTreeControlShowDesc",
+ 3
+ ],
+ [
+ "ALTTreeControlShowId",
+ 3
+ ],
+ [
+ "ALTTreeControlShowDesc",
+ 3
+ ],
+ [
+ "OptimizationVariable",
+ 1
+ ],
+ [
+ "RbdReportRankingMethod",
+ 1
+ ],
+ [
+ "FtReportRankingMethod",
+ 1
+ ],
+ [
+ "LccShowId",
+ 3
+ ],
+ [
+ "LccShowDescription",
+ 3
+ ],
+ [
+ "LccShowLocalVariables",
+ 3
+ ],
+ [
+ "ProcessCapacityUnit",
+ 0
+ ],
+ [
+ "ProTranStartDate",
+ 2
+ ],
+ [
+ "SetNamesToUpperCase",
+ 3
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "NoProducts",
+ 1
+ ],
+ [
+ "ProdDesc1",
+ 0
+ ],
+ [
+ "ProdDesc2",
+ 0
+ ],
+ [
+ "ProdDesc3",
+ 0
+ ],
+ [
+ "ProdDesc4",
+ 0
+ ],
+ [
+ "AvsimImportanceProduct",
+ 1
+ ],
+ [
+ "AvsimCapAvailProductIndex",
+ 1
+ ],
+ [
+ "AvsimEquateCapacityUnit2",
+ 0
+ ],
+ [
+ "AvsimEquateCapacityValue2",
+ 2
+ ],
+ [
+ "AvsimEquateCapacityUnit3",
+ 0
+ ],
+ [
+ "AvsimEquateCapacityValue3",
+ 2
+ ],
+ [
+ "AvsimEquateCapacityUnit4",
+ 0
+ ],
+ [
+ "AvsimEquateCapacityValue4",
+ 2
+ ]
+ ],
+ "FailureModels": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "DataLinkCause",
+ 1
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "DetectionMethod",
+ 0
+ ],
+ [
+ "CompensatingProvisions",
+ 0
+ ],
+ [
+ "Remarks",
+ 0
+ ],
+ [
+ "FmMttf",
+ 2
+ ],
+ [
+ "FmStd",
+ 2
+ ],
+ [
+ "FmEta1",
+ 2
+ ],
+ [
+ "FmBeta1",
+ 2
+ ],
+ [
+ "FmGamma1",
+ 2
+ ],
+ [
+ "FmEta2",
+ 2
+ ],
+ [
+ "FmBeta2",
+ 2
+ ],
+ [
+ "FmGamma2",
+ 2
+ ],
+ [
+ "FmEta3",
+ 2
+ ],
+ [
+ "FmBeta3",
+ 2
+ ],
+ [
+ "FmGamma3",
+ 2
+ ],
+ [
+ "FmWeibullSet",
+ 1
+ ],
+ [
+ "FmDistribution",
+ 1
+ ],
+ [
+ "StandbyFailurePercent",
+ 2
+ ],
+ [
+ "StandbyAgeingPercent",
+ 2
+ ],
+ [
+ "StartUpFailureProb",
+ 2
+ ],
+ [
+ "AlDescription",
+ 0
+ ],
+ [
+ "AlScadaTagId",
+ 0
+ ],
+ [
+ "AlEnabled",
+ 3
+ ],
+ [
+ "FmDormant",
+ 3
+ ],
+ [
+ "AlCapitalCost",
+ 2
+ ],
+ [
+ "AlCostRate",
+ 2
+ ],
+ [
+ "AlPfInterval",
+ 2
+ ],
+ [
+ "AlDetectionP",
+ 2
+ ],
+ [
+ "AlPfDistribution",
+ 1
+ ],
+ [
+ "CoDescription",
+ 0
+ ],
+ [
+ "CoEnabled",
+ 3
+ ],
+ [
+ "CoCapitalCost",
+ 2
+ ],
+ [
+ "CoCostRate",
+ 2
+ ],
+ [
+ "CoPeriod",
+ 2
+ ],
+ [
+ "RdDescription",
+ 0
+ ],
+ [
+ "RdEnabled",
+ 3
+ ],
+ [
+ "RdCapitalCost",
+ 2
+ ],
+ [
+ "RdCostRate",
+ 2
+ ],
+ [
+ "FmWizardRandomOn",
+ 3
+ ],
+ [
+ "FmWizardWearoutOn",
+ 3
+ ],
+ [
+ "FmWizardInfantOn",
+ 3
+ ],
+ [
+ "FmWizardRandomRate",
+ 2
+ ],
+ [
+ "FmWizardWearoutStartAge",
+ 2
+ ],
+ [
+ "FmWizardWearoutDuration",
+ 2
+ ],
+ [
+ "FmWizardInfantPeriod",
+ 2
+ ],
+ [
+ "FmWizardInfantRate",
+ 2
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "FmInhibitBufferFill",
+ 3
+ ],
+ [
+ "FmInhibitBufferFillByCapacity",
+ 3
+ ],
+ [
+ "FmInhibitBufferFillByRevCap",
+ 3
+ ],
+ [
+ "Guid",
+ 0
+ ],
+ [
+ "AlPfStd",
+ 2
+ ],
+ [
+ "FmProductIndex",
+ 1
+ ]
+ ],
+ "FailureModelCorrectiveTasks": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "TaskId",
+ 0
+ ],
+ [
+ "OperationNumber",
+ 0
+ ],
+ [
+ "AgeReductionFactor",
+ 2
+ ],
+ [
+ "AgeReductionMode",
+ 1
+ ],
+ [
+ "TaskDuration",
+ 2
+ ],
+ [
+ "RampTime",
+ 2
+ ],
+ [
+ "Std",
+ 2
+ ],
+ [
+ "Eta",
+ 2
+ ],
+ [
+ "Beta",
+ 2
+ ],
+ [
+ "Gamma",
+ 2
+ ],
+ [
+ "WeibullSet",
+ 1
+ ],
+ [
+ "Distribution",
+ 1
+ ],
+ [
+ "OperationalCost",
+ 2
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Notes5",
+ 0
+ ],
+ [
+ "Notes6",
+ 0
+ ],
+ [
+ "Notes7",
+ 0
+ ],
+ [
+ "Notes8",
+ 0
+ ],
+ [
+ "Notes9",
+ 0
+ ],
+ [
+ "Notes10",
+ 0
+ ],
+ [
+ "Notes11",
+ 0
+ ],
+ [
+ "Notes12",
+ 0
+ ],
+ [
+ "Notes13",
+ 0
+ ],
+ [
+ "Notes14",
+ 0
+ ],
+ [
+ "Notes15",
+ 0
+ ],
+ [
+ "Notes16",
+ 0
+ ],
+ [
+ "Notes17",
+ 0
+ ],
+ [
+ "Notes18",
+ 0
+ ],
+ [
+ "Notes19",
+ 0
+ ],
+ [
+ "Notes20",
+ 0
+ ],
+ [
+ "Notes21",
+ 0
+ ],
+ [
+ "Notes22",
+ 0
+ ],
+ [
+ "Notes23",
+ 0
+ ],
+ [
+ "Notes24",
+ 0
+ ]
+ ],
+ "RbdBlocks": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Super",
+ 3
+ ],
+ [
+ "LogicMode",
+ 1
+ ],
+ [
+ "StandbyMode",
+ 1
+ ],
+ [
+ "Consequence",
+ 1
+ ],
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "Bom",
+ 1
+ ],
+ [
+ "Bitmap",
+ 1
+ ],
+ [
+ "XPosition",
+ 2
+ ],
+ [
+ "YPosition",
+ 2
+ ],
+ [
+ "Width",
+ 2
+ ],
+ [
+ "Height",
+ 2
+ ],
+ [
+ "Page",
+ 1
+ ],
+ [
+ "PageScale",
+ 2
+ ],
+ [
+ "XPagePosition",
+ 2
+ ],
+ [
+ "YPagePosition",
+ 2
+ ],
+ [
+ "DescriptionFontName",
+ 0
+ ],
+ [
+ "DescriptionFontSize",
+ 2
+ ],
+ [
+ "DescriptionFontStyle",
+ 1
+ ],
+ [
+ "DescriptionFontColor",
+ 1
+ ],
+ [
+ "BackgroundColor",
+ 1
+ ],
+ [
+ "MaxCapacity",
+ 2
+ ],
+ [
+ "InitialAge",
+ 2
+ ],
+ [
+ "SwitchingDelay",
+ 2
+ ],
+ [
+ "LoadFactor",
+ 2
+ ],
+ [
+ "NonMaintainable",
+ 3
+ ],
+ [
+ "NonOperational",
+ 3
+ ],
+ [
+ "DiagramReportRanking",
+ 1
+ ],
+ [
+ "Tdt",
+ 2
+ ],
+ [
+ "TdtStd",
+ 2
+ ],
+ [
+ "TdtErr",
+ 2
+ ],
+ [
+ "W",
+ 2
+ ],
+ [
+ "WStd",
+ 2
+ ],
+ [
+ "WErr",
+ 2
+ ],
+ [
+ "MeanCapacity",
+ 2
+ ],
+ [
+ "MeanCapacityStd",
+ 2
+ ],
+ [
+ "MeanCapacityErr",
+ 2
+ ],
+ [
+ "F",
+ 2
+ ],
+ [
+ "R",
+ 2
+ ],
+ [
+ "Q",
+ 2
+ ],
+ [
+ "Qm",
+ 2
+ ],
+ [
+ "A",
+ 2
+ ],
+ [
+ "Am",
+ 2
+ ],
+ [
+ "Wm",
+ 2
+ ],
+ [
+ "Mtto",
+ 2
+ ],
+ [
+ "Mtbo",
+ 2
+ ],
+ [
+ "Mttr",
+ 2
+ ],
+ [
+ "SpareTdt",
+ 2
+ ],
+ [
+ "CrewTdt",
+ 2
+ ],
+ [
+ "CTdt",
+ 2
+ ],
+ [
+ "PTdt",
+ 2
+ ],
+ [
+ "ITdt",
+ 2
+ ],
+ [
+ "CW",
+ 2
+ ],
+ [
+ "PW",
+ 2
+ ],
+ [
+ "IW",
+ 2
+ ],
+ [
+ "ImpCost",
+ 2
+ ],
+ [
+ "ImpTdt",
+ 2
+ ],
+ [
+ "ImpTdtC",
+ 2
+ ],
+ [
+ "ImpTdtP",
+ 2
+ ],
+ [
+ "ImpTdtI",
+ 2
+ ],
+ [
+ "ImpW",
+ 2
+ ],
+ [
+ "ImpTdtSpare",
+ 2
+ ],
+ [
+ "ImpTdtCrew",
+ 2
+ ],
+ [
+ "ImpCapacity",
+ 2
+ ],
+ [
+ "ImpCapacityC",
+ 2
+ ],
+ [
+ "ImpCapacityP",
+ 2
+ ],
+ [
+ "ImpCapacityI",
+ 2
+ ],
+ [
+ "ImpCapacitySpare",
+ 2
+ ],
+ [
+ "ImpCapacityCrew",
+ 2
+ ],
+ [
+ "ImpSafety",
+ 2
+ ],
+ [
+ "ImpOperational",
+ 2
+ ],
+ [
+ "ImpEnvironmental",
+ 2
+ ],
+ [
+ "SparePurchaseCost",
+ 2
+ ],
+ [
+ "LaborCost",
+ 2
+ ],
+ [
+ "EquipmentCost",
+ 2
+ ],
+ [
+ "OperationalCost",
+ 2
+ ],
+ [
+ "AlarmCost",
+ 2
+ ],
+ [
+ "CommissionCost",
+ 2
+ ],
+ [
+ "RedesignCost",
+ 2
+ ],
+ [
+ "IncludeInSystemPlot",
+ 3
+ ],
+ [
+ "ProcessTransferP",
+ 3
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "Guid",
+ 0
+ ],
+ [
+ "TimeInStandby",
+ 2
+ ],
+ [
+ "MaxCapacity2",
+ 2
+ ],
+ [
+ "MaxCapacity3",
+ 2
+ ],
+ [
+ "MaxCapacity4",
+ 2
+ ],
+ [
+ "MeanCapacity2",
+ 2
+ ],
+ [
+ "MeanCapacity3",
+ 2
+ ],
+ [
+ "MeanCapacity4",
+ 2
+ ],
+ [
+ "MeanCapacityStd2",
+ 2
+ ],
+ [
+ "MeanCapacityStd3",
+ 2
+ ],
+ [
+ "MeanCapacityStd4",
+ 2
+ ],
+ [
+ "MeanCapacityErr2",
+ 2
+ ],
+ [
+ "MeanCapacityErr3",
+ 2
+ ],
+ [
+ "MeanCapacityErr4",
+ 2
+ ]
+ ],
+ "RbdNodes": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Page",
+ 1
+ ],
+ [
+ "Vote",
+ 1
+ ],
+ [
+ "XPosition",
+ 2
+ ],
+ [
+ "YPosition",
+ 2
+ ],
+ [
+ "OperationalCapacityTarget",
+ 2
+ ],
+ [
+ "LocalStandby",
+ 3
+ ],
+ [
+ "NotLogic",
+ 3
+ ],
+ [
+ "BackgroundColor",
+ 1
+ ],
+ [
+ "Guid",
+ 0
+ ],
+ [
+ "OperationalCapacityTarget2",
+ 2
+ ],
+ [
+ "OperationalCapacityTarget3",
+ 2
+ ],
+ [
+ "OperationalCapacityTarget4",
+ 2
+ ]
+ ],
+ "RbdConnections": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Page",
+ 1
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "Color",
+ 1
+ ],
+ [
+ "InputObjectType",
+ 1
+ ],
+ [
+ "InputObjectIndex",
+ 1
+ ],
+ [
+ "OutputObjectType",
+ 1
+ ],
+ [
+ "OutputObjectIndex",
+ 1
+ ],
+ [
+ "Guid",
+ 0
+ ]
+ ]
+ },
+ "defaults": {
+ "Project": {
+ "Id": "",
+ "Description": "",
+ "FileName": "",
+ "ProductVersion": "5.0",
+ "ProjectVersionLong": "5.0.0.0",
+ "Notes": "Created by RAPTOR Studio",
+ "CompiledBy": "",
+ "ApprovedBy": "",
+ "DoublePrecision": 2,
+ "DoubleFormat": 0,
+ "LifeTime": 87600.0,
+ "LastModule": 1,
+ "LastRcmRightWindowMode": 1,
+ "LastAvsimRightWindowMode": 0,
+ "LastWeibullRightWindowMode": 5,
+ "LastLccRightWindowMode": 1,
+ "LastProcessRightWindowMode": 5,
+ "LastSapRightWindowMode": 1,
+ "LastMaximoRightWindowMode": 1,
+ "LastALTRightWindowMode": 5,
+ "LastRcmTableType": 23,
+ "LastAvsimTableType": 38,
+ "LastWeibullTableType": 46,
+ "LastLccTableType": 94,
+ "LastProcessTableType": 99,
+ "LastSapTableType": 103,
+ "LastMaximoTableType": 145,
+ "LastALTTableType": 165,
+ "NpvOn": 0,
+ "NpvYieldPercent": 0.0,
+ "NpvLaborPercent": 0.0,
+ "NpvEquipmentPercent": 0.0,
+ "NpvSparesUsagePercent": 0.0,
+ "NpvSparesStoragePercent": 0.0,
+ "NpvOperationalPercent": 0.0,
+ "NpvCommissionPercent": 0.0,
+ "NpvRedesignPercent": 0.0,
+ "NpvAlarmPercent": 0.0,
+ "NpvOutagePercent": 0.0,
+ "RcmCriticalityUseCost": 1,
+ "RcmCriticalityUseSafety": 0,
+ "RcmCriticalityUseOperational": 0,
+ "RcmCriticalityUseEnvironmental": 0,
+ "ErpCriticalityUseCost": 1,
+ "ErpCriticalityUseEffect": 0,
+ "ErpCriticalityUseNoCM": 0,
+ "ErpCriticalityUseNoPM": 0,
+ "ErpCriticalityUseNoIN": 0,
+ "RcmNoSimulations": 100,
+ "RcmRandomNoSeed": 1,
+ "RcmSafetyCriticalityTarget": 0.0,
+ "RcmOperationalCritTarget": 0.0,
+ "RcmEnvironmentalCritTarget": 0.0,
+ "RcmSpareOptQTarget": 0.0,
+ "RcmSpareOptNSites": 1,
+ "RcmAutoCriticality": 0,
+ "RcmShowId": 1,
+ "RcmShowDescription": 1,
+ "RcmShowQuantity": 0,
+ "RcmShowUnavailability": 0,
+ "RcmShowFrequency": 0,
+ "RcmShowEffect": 0,
+ "RcmShowTaskGroup": 0,
+ "RcmShowCost": 0,
+ "RcmShowSafetyCrit": 0,
+ "RcmShowOperationalCrit": 0,
+ "RcmShowEnvironmentalCrit": 0,
+ "RcmShowStrategy": 0,
+ "NoProfileIntervalS": 100,
+ "ProfileStart": 0.0,
+ "ProfileInterval": 876.0,
+ "MapProfileToLifetime": 1,
+ "ApplyInsPrdDataAtZero": 0,
+ "RcmLocationTreeNodeExp": 0,
+ "RcmLocationTypeTreeNodeExp": 0,
+ "SpareTreeNodeExp": 0,
+ "LaborTreeNodeExp": 0,
+ "EquipmentTreeNodeExp": 0,
+ "TaskGroupTreeNodeExp": 0,
+ "RcmEffectTreeNodeExp": 0,
+ "WeibullSetTreeNodeExp": 0,
+ "ProcessSetTreeNodeExp": 0,
+ "ALTSetTreeNodeExp": 0,
+ "BomTreeNodeExp": 0,
+ "RbdBlockTreeNodeExp": 1,
+ "ConsequenceTreeNodeExp": 1,
+ "PhaseTreeNodeExp": 1,
+ "LibraryBitmapTreeNodeExp": 1,
+ "GateTreeNodeExp": 0,
+ "FailureModelTreeNodeExp": 1,
+ "SapLocationTreeNodeExp": 0,
+ "SapCatalogTreeNodeExp": 0,
+ "SapCatProfTreeNodeExp": 0,
+ "SapEffectTreeNodeExp": 0,
+ "SapABCIndTreeNodeExp": 0,
+ "SapTecOTTreeNodeExp": 0,
+ "SapClassTreeNodeExp": 0,
+ "SapEqClTreeNodeExp": 0,
+ "SapLoClTreeNodeExp": 0,
+ "SapMaClTreeNodeExp": 0,
+ "SapDoClTreeNodeExp": 0,
+ "SapLaborTreeNodeExp": 0,
+ "SapBomTreeNodeExp": 0,
+ "SapEqBomTreeNodeExp": 0,
+ "SapLoBomTreeNodeExp": 0,
+ "SapMtBomTreeNodeExp": 0,
+ "SapMaterialTreeNodeExp": 0,
+ "SapMPlanTreeNodeExp": 0,
+ "MaximoLocationTreeNodeExp": 0,
+ "MaximoPMTreeNodeExp": 0,
+ "MaximoFailureListTreeNodeExp": 0,
+ "MaximoCraftTreeNodeExp": 0,
+ "MaximoCommodityTreeNodeExp": 0,
+ "AvsimCurrentRbdPage": 0,
+ "AvsimCurrentFtPage": -1,
+ "AvsimNoSimulationsRequested": 1000,
+ "AvsimNoSimulationsCompleted": 0,
+ "AvsimCapacityCalcsPerformed": 0,
+ "AvsimTreeControlShowId": 1,
+ "AvsimTreeControlShowDesc": 1,
+ "AvsimShowFailureData": 0,
+ "AvsimShowRepairData": 0,
+ "AvsimShowCapacity": 0,
+ "AvsimShowFailureModelId": 0,
+ "AvsimAvailabilityPreference": 0,
+ "AvsimShowQm": 0,
+ "AvsimShowF": 0,
+ "AvsimShowW": 0,
+ "AvsimShowRbdArrows": 1,
+ "AvsimShowGrid": 1,
+ "AvsimShowRbdDescWithBitmaps": 0,
+ "AvsimShowSymbol": 0,
+ "AvsimShowFtIecSymbols": 0,
+ "AvsimShowFtNameBorder": 1,
+ "AvsimShowFtRepeatBars": 1,
+ "AvsimDisableFtPaging": 0,
+ "AvsimDisableTransferTabs": 0,
+ "IncludeInitialSpares": 1,
+ "ResultsEffectIndex": -1,
+ "ResultsConsequenceIndex": -1,
+ "ResultsCauseIndex": -1,
+ "ResultsSpareIndex": -1,
+ "ResultsLaborIndex": -1,
+ "ResultsEquipmentIndex": -1,
+ "ResultsSystemBlockIndex": 0,
+ "ResultsSystemGateIndex": -1,
+ "ResultsComponentBlockIndex": -1,
+ "ResultsComponentEventIndex": -1,
+ "ResultsPhaseIndex": -1,
+ "ResultsDetailedLifeCosts": 0,
+ "WeibullCurrentWeibullSet": -1,
+ "ProcessCurrentProcessSet": -1,
+ "ALTCurrentALTSet": -1,
+ "AvsimDiagramMode": 0,
+ "AvsimFtPageScale": 1.0,
+ "AvsimFtPagePositionX": 0.0,
+ "AvsimFtPagePositionY": 0.0,
+ "AvsimReplenishSpares": 0,
+ "AvsimReplenishInterval": 8760.0,
+ "AvsimRandomNumberSeed": 1,
+ "AvsimMultipleSites": 0,
+ "AvsimImportanceConsequence": -1,
+ "AvsimImportanceCutoff": 0.0,
+ "AvsimImportanceInitCap": 0,
+ "ImportanceShowCost": 1,
+ "ImportanceShowTdt": 1,
+ "ImportanceShowTdtC": 0,
+ "ImportanceShowTdtP": 0,
+ "ImportanceShowTdtI": 0,
+ "ImportanceShowW": 1,
+ "ImportanceShowTdtSpare": 0,
+ "ImportanceShowTdtCrew": 0,
+ "ImportanceShowCapacity": 1,
+ "ImportanceShowCapacityC": 0,
+ "ImportanceShowCapacityP": 0,
+ "ImportanceShowCapacityI": 0,
+ "ImportanceShowCapacitySpare": 0,
+ "ImportanceShowCapacityCrew": 0,
+ "ImportanceShowSafety": 1,
+ "ImportanceShowOperational": 1,
+ "ImportanceShowEnvironmental": 1,
+ "AvsimCapAvailSystemType": 0,
+ "AvsimCapAvailSystemIndex": -1,
+ "AvsimCapAvailNoIntervals": 1,
+ "AvsimCapAvailNoPoints": 1001,
+ "AvsimCapAvailStartTime": 0.0,
+ "AvsimCapAvailIntervalLength": 87600.0,
+ "AvsimCapAvailIntervalIndex": 0,
+ "AvsimCapAvailMap": 0,
+ "AvsimEquateCapacity": 1,
+ "AvsimEquateCapacityUnit": "",
+ "AvsimEquateCapacityValue": 0.0,
+ "StorageCostMethod": 0,
+ "SpareCostPUnitWeightLevel1": 0.0,
+ "SpareCostPUnitWeightLevel2": 0.0,
+ "SpareCostPUnitVolumeLevel1": 0.0,
+ "SpareCostPUnitVolumeLevel2": 0.0,
+ "GlobalLogDelayOnLevel1": 0,
+ "GlobalLogDelayOnLevel2": 0,
+ "GlobalLogDelayOnLevel3": 0,
+ "GlobalLogDelayLevel1": 0.0,
+ "GlobalLogDelayLevel2": 0.0,
+ "GlobalLogDelayLevel3": 0.0,
+ "AvsimBufferDepletionOnCapacity": 1,
+ "AvsimPasteRenMatFailureModels": 0,
+ "AvsimPasteRenMatConsequences": 0,
+ "AvsimPasteRenMatWeibullSets": 0,
+ "AvsimPasteRenMatSpares": 0,
+ "AvsimPasteRenMatEquipments": 0,
+ "AvsimPasteRenMatLabors": 0,
+ "AvsimPasteRenMatTaskGroups": 0,
+ "AvsimPasteRenMatPhases": 0,
+ "AvsimPasteRenMatBitmaps": 0,
+ "AvsimPasteRenMatBoms": 0,
+ "WeibullTreeControlShowId": 1,
+ "WeibullTreeControlShowDesc": 1,
+ "ProcessTreeControlShowId": 1,
+ "ProcessTreeControlShowDesc": 1,
+ "SapTreeControlShowId": 1,
+ "SapTreeControlShowDesc": 1,
+ "MaximoTreeControlShowId": 1,
+ "MaximoTreeControlShowDesc": 1,
+ "ALTTreeControlShowId": 1,
+ "ALTTreeControlShowDesc": 1,
+ "OptimizationVariable": 0,
+ "RbdReportRankingMethod": 0,
+ "FtReportRankingMethod": 0,
+ "LccShowId": 1,
+ "LccShowDescription": 1,
+ "LccShowLocalVariables": 1,
+ "ProcessCapacityUnit": "",
+ "ProTranStartDate": 6.33979008e+17,
+ "SetNamesToUpperCase": 1,
+ "ExternalReference": "",
+ "NoProducts": 3,
+ "ProdDesc1": "",
+ "ProdDesc2": "",
+ "ProdDesc3": "",
+ "ProdDesc4": "",
+ "AvsimImportanceProduct": -1,
+ "AvsimCapAvailProductIndex": 0,
+ "AvsimEquateCapacityUnit2": "",
+ "AvsimEquateCapacityValue2": 0.0,
+ "AvsimEquateCapacityUnit3": "",
+ "AvsimEquateCapacityValue3": 0.0,
+ "AvsimEquateCapacityUnit4": "",
+ "AvsimEquateCapacityValue4": 0.0,
+ "AvsimEquateCapacityUnit1": "",
+ "AvsimEquateCapacityValue1": 0.0
+ },
+ "FailureModels": {
+ "Id": "",
+ "Description": "",
+ "Type": -1,
+ "DataLinkCause": -1,
+ "Notes1": "",
+ "Notes2": "",
+ "Notes3": "",
+ "Notes4": "",
+ "DetectionMethod": "",
+ "CompensatingProvisions": "",
+ "Remarks": "",
+ "FmMttf": 8760.0,
+ "FmStd": 0.0,
+ "FmEta1": 8760.0,
+ "FmBeta1": 1.0,
+ "FmGamma1": 0.0,
+ "FmEta2": 8760.0,
+ "FmBeta2": 1.0,
+ "FmGamma2": 0.0,
+ "FmEta3": 8760.0,
+ "FmBeta3": 1.0,
+ "FmGamma3": 0.0,
+ "FmWeibullSet": -1,
+ "FmDistribution": 0,
+ "StandbyFailurePercent": 50.0,
+ "StandbyAgeingPercent": 50.0,
+ "StartUpFailureProb": 0.0,
+ "AlDescription": "",
+ "AlScadaTagId": "",
+ "AlEnabled": 0,
+ "FmDormant": 0,
+ "AlCapitalCost": 0.0,
+ "AlCostRate": 0.0,
+ "AlPfInterval": 0.0,
+ "AlDetectionP": 1.0,
+ "AlPfDistribution": 0,
+ "CoDescription": "",
+ "CoEnabled": 0,
+ "CoCapitalCost": 0.0,
+ "CoCostRate": 0.0,
+ "CoPeriod": 0.0,
+ "RdDescription": "",
+ "RdEnabled": 0,
+ "RdCapitalCost": 0.0,
+ "RdCostRate": 0.0,
+ "FmWizardRandomOn": 1,
+ "FmWizardWearoutOn": 0,
+ "FmWizardInfantOn": 0,
+ "FmWizardRandomRate": 0.0,
+ "FmWizardWearoutStartAge": 0.0,
+ "FmWizardWearoutDuration": 87600.0,
+ "FmWizardInfantPeriod": 0.0,
+ "FmWizardInfantRate": 0.0,
+ "ExternalReference": "",
+ "FmInhibitBufferFill": 0,
+ "FmInhibitBufferFillByCapacity": 0,
+ "FmInhibitBufferFillByRevCap": 0,
+ "Guid": "dee1ceed-e7ae-43a6-81f3-78a2eadb1131",
+ "AlPfStd": 0.0,
+ "FmProductIndex": 0
+ },
+ "FailureModelCorrectiveTasks": {
+ "FailureModel": 0,
+ "Description": "Corrective repair",
+ "TaskId": "CM1",
+ "OperationNumber": "",
+ "AgeReductionFactor": 0.0,
+ "AgeReductionMode": 0,
+ "TaskDuration": 24.0,
+ "RampTime": 0.0,
+ "Std": 0.0,
+ "Eta": 24.0,
+ "Beta": 2.0,
+ "Gamma": 0.0,
+ "WeibullSet": -1,
+ "Distribution": 2,
+ "OperationalCost": 0.0,
+ "ExternalReference": "",
+ "Notes1": "",
+ "Notes2": "",
+ "Notes3": "",
+ "Notes4": "",
+ "Notes5": "",
+ "Notes6": "",
+ "Notes7": "",
+ "Notes8": "",
+ "Notes9": "",
+ "Notes10": "",
+ "Notes11": "",
+ "Notes12": "",
+ "Notes13": "",
+ "Notes14": "",
+ "Notes15": "",
+ "Notes16": "",
+ "Notes17": "",
+ "Notes18": "",
+ "Notes19": "",
+ "Notes20": "",
+ "Notes21": "",
+ "Notes22": "",
+ "Notes23": "",
+ "Notes24": ""
+ },
+ "RbdBlocks": {
+ "Id": "",
+ "Description": "",
+ "Notes1": "",
+ "Notes2": "",
+ "Notes3": "",
+ "Notes4": "",
+ "Super": 0,
+ "LogicMode": 0,
+ "StandbyMode": 0,
+ "Consequence": -1,
+ "FailureModel": -1,
+ "Bom": -1,
+ "Bitmap": -1,
+ "XPosition": 0.0,
+ "YPosition": 0.0,
+ "Width": 100.0,
+ "Height": 60.0,
+ "Page": 0,
+ "PageScale": 1.0,
+ "XPagePosition": 0.0,
+ "YPagePosition": 0.0,
+ "DescriptionFontName": "",
+ "DescriptionFontSize": 0.0,
+ "DescriptionFontStyle": 0,
+ "DescriptionFontColor": 0,
+ "BackgroundColor": -1,
+ "MaxCapacity": 100000.0,
+ "InitialAge": 0.0,
+ "SwitchingDelay": 0.0,
+ "LoadFactor": 1.0,
+ "NonMaintainable": 0,
+ "NonOperational": 0,
+ "DiagramReportRanking": -1,
+ "Tdt": 2346.1697784812877,
+ "TdtStd": 687.8770087785166,
+ "TdtErr": 2.931914881385055,
+ "W": 9.8,
+ "WStd": 2.856571371417137,
+ "WErr": 2.914868746344017,
+ "MeanCapacity": 45.76142883397376,
+ "MeanCapacityStd": 0.7111563364848121,
+ "MeanCapacityErr": 0.15540518611535187,
+ "F": 1.0000000000000004,
+ "R": -4.440892098500626e-16,
+ "Q": 0.009999999999999998,
+ "Qm": 0.026782760028325203,
+ "A": 0.99,
+ "Am": 0.9732172399716748,
+ "Wm": 0.00011187214611872147,
+ "Mtto": 8561.597083703056,
+ "Mtbo": 8938.775510204081,
+ "Mttr": 239.4050794368661,
+ "SpareTdt": 0.0,
+ "CrewTdt": 0.0,
+ "CTdt": 0.0,
+ "PTdt": 0.0,
+ "ITdt": 0.0,
+ "CW": 0.0,
+ "PW": 0.0,
+ "IW": 0.0,
+ "ImpCost": 0.0,
+ "ImpTdt": 0.0,
+ "ImpTdtC": 0.0,
+ "ImpTdtP": 0.0,
+ "ImpTdtI": 0.0,
+ "ImpW": 0.0,
+ "ImpTdtSpare": 0.0,
+ "ImpTdtCrew": 0.0,
+ "ImpCapacity": 0.0,
+ "ImpCapacityC": 0.0,
+ "ImpCapacityP": 0.0,
+ "ImpCapacityI": 0.0,
+ "ImpCapacitySpare": 0.0,
+ "ImpCapacityCrew": 0.0,
+ "ImpSafety": 0.0,
+ "ImpOperational": 0.0,
+ "ImpEnvironmental": 0.0,
+ "SparePurchaseCost": 0.0,
+ "LaborCost": 0.0,
+ "EquipmentCost": 0.0,
+ "OperationalCost": 0.0,
+ "AlarmCost": 0.0,
+ "CommissionCost": 0.0,
+ "RedesignCost": 0.0,
+ "IncludeInSystemPlot": 1,
+ "ProcessTransferP": 0,
+ "ExternalReference": "",
+ "Guid": "96271e98-068b-4e2d-b610-e935f7ef39cf",
+ "TimeInStandby": 0.0,
+ "MaxCapacity2": 100000.0,
+ "MaxCapacity3": 100000.0,
+ "MaxCapacity4": 100000.0,
+ "MeanCapacity2": 3757.139421638092,
+ "MeanCapacity3": 4.9301667674933185,
+ "MeanCapacity4": 0.0,
+ "MeanCapacityStd2": 40.64182661599955,
+ "MeanCapacityStd3": 0.04801477677460852,
+ "MeanCapacityStd4": 0.0,
+ "MeanCapacityErr2": 0.10817226100776409,
+ "MeanCapacityErr3": 0.09738976192689934,
+ "MeanCapacityErr4": 0.0
+ },
+ "RbdNodes": {
+ "Id": "",
+ "Page": 0,
+ "Vote": 1,
+ "XPosition": 0.0,
+ "YPosition": 0.0,
+ "OperationalCapacityTarget": 0.0,
+ "LocalStandby": 0,
+ "NotLogic": 0,
+ "BackgroundColor": -1,
+ "Guid": "8c8ee3c3-5ffe-4358-b686-474df8eca05e",
+ "OperationalCapacityTarget2": 0.0,
+ "OperationalCapacityTarget3": 0.0,
+ "OperationalCapacityTarget4": 0.0
+ },
+ "RbdConnections": {
+ "Id": "",
+ "Page": 0,
+ "Type": 0,
+ "Color": -1,
+ "InputObjectType": 20,
+ "InputObjectIndex": 0,
+ "OutputObjectType": 20,
+ "OutputObjectIndex": 0,
+ "Guid": "66666666-6666-6666-6666-666666666661"
+ }
+ }
+}
diff --git a/raptor/gui/command_table.py b/raptor/gui/command_table.py
index b7c1726a..084a8dbb 100644
--- a/raptor/gui/command_table.py
+++ b/raptor/gui/command_table.py
@@ -57,6 +57,17 @@
handler="_save_file_as",
shortcut="Ctrl+Shift+S",
enabled_when="model_open"),
+ CommandSpec(
+ id="file.import_awb",
+ attr="_import_awb_action",
+ text="Import Availability Workbench…",
+ icon="awb_import_icon:text",
+ tooltip=(
+ "Open an Isograph Availability Workbench 5.0 .awb project as a "
+ "RAPTOR model; the summary lists what AWB features RAPTOR cannot "
+ "represent"),
+ handler="_import_awb",
+ enabled_when="not_running"),
CommandSpec(
id="file.new",
attr="_new_action",
@@ -115,6 +126,17 @@
"file"),
handler="_export_pdf",
enabled_when="model_open"),
+ CommandSpec(
+ id="file.export_awb",
+ attr="_export_awb_action",
+ text="Export to Availability Workbench…",
+ icon="awb_export_icon:text",
+ tooltip=(
+ "Save this model as an Isograph Availability Workbench 5.0 .awb "
+ "project; the summary lists what RAPTOR features AWB cannot "
+ "represent"),
+ handler="_export_awb",
+ enabled_when="model_open"),
CommandSpec(
id="file.export_tables",
attr="_export_tables_action",
@@ -1416,13 +1438,13 @@ def _p(title: str, index_attr: str, *groups: Group) -> Page:
#: left of the tabs, as in Office: (section title, command ids). Commands
#: here are placed as surely as those on a ribbon page.
BACKSTAGE: tuple[tuple[str, tuple[str, ...]], ...] = (
- ("File", ("file.new", "file.open", "file.save", "file.save_as",
- "file.close_file", "file.quit", "home.diff")),
+ ("File", ("file.new", "file.open", "file.import_awb", "file.save",
+ "file.save_as", "file.close_file", "file.quit", "home.diff")),
# U22: one Export (the file type picks what is written), then Export
# Tables for choosing tables; the single-type commands stay in the
# command palette and on their shortcuts.
- ("Print and Export", ("file.print", "file.export", "file.export_tables",
- "file.copy_view")),
+ ("Print and Export", ("file.print", "file.export", "file.export_awb",
+ "file.export_tables", "file.copy_view")),
)
#: Commands with a top level entry in the File view's nav column, after
diff --git a/raptor/gui/resources/icons.py b/raptor/gui/resources/icons.py
index e7005d5a..a4b76363 100644
--- a/raptor/gui/resources/icons.py
+++ b/raptor/gui/resources/icons.py
@@ -1383,6 +1383,34 @@ def draw(p: QPainter, c: QColor):
return _icon("exportlib", colour, draw)
+def awb_import_icon(colour: str) -> QIcon:
+ """Import AWB: a document with an arrow entering it."""
+ def draw(p: QPainter, c: QColor):
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.setPen(QPen(c, 3))
+ p.drawRect(10, 4, 26, 38)
+ p.drawLine(16, 12, 30, 12)
+ p.drawLine(16, 19, 30, 19)
+ p.drawLine(16, 26, 24, 26)
+ p.setBrush(c)
+ p.drawPolygon([QPointF(6, 32), QPointF(16, 32), QPointF(11, 38)])
+ return _icon("awbimport", colour, draw)
+
+
+def awb_export_icon(colour: str) -> QIcon:
+ """Export AWB: a document with an arrow leaving it."""
+ def draw(p: QPainter, c: QColor):
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.setPen(QPen(c, 3))
+ p.drawRect(6, 4, 26, 38)
+ p.drawLine(12, 12, 26, 12)
+ p.drawLine(12, 19, 26, 19)
+ p.drawLine(12, 26, 20, 26)
+ p.setBrush(c)
+ p.drawPolygon([QPointF(44, 32), QPointF(34, 32), QPointF(39, 38)])
+ return _icon("awbexport", colour, draw)
+
+
def clear_results_icon(colour: str) -> QIcon:
"""Clear Results: table swept by a diagonal wipe."""
def draw(p: QPainter, c: QColor):
diff --git a/raptor/gui/ui/export_mixin.py b/raptor/gui/ui/export_mixin.py
index 84dd1abe..ebecd573 100644
--- a/raptor/gui/ui/export_mixin.py
+++ b/raptor/gui/ui/export_mixin.py
@@ -5,6 +5,7 @@
from raptor.gui.ui import msgbox
+from raptor.gui.ui.qtcompat import req
import os
from typing import TYPE_CHECKING, Any
from pathlib import Path
@@ -115,6 +116,40 @@ def _export_tables(self):
from raptor.gui.ui.tables_dialog import open_export_tables_dialog
open_export_tables_dialog(self)
+ def _export_awb(self, path: str | None = None):
+ """File ▸ Export to Availability Workbench…: write one .awb project."""
+ if self._rbd is None:
+ return
+ stem = Path(self._current_file).stem if self._current_file else "model"
+ if path is None:
+ path, _ = fdg.getSaveFileName(
+ self, "Export Availability Workbench Project",
+ stem + ".awb", "Availability Workbench projects (*.awb)")
+ if not path:
+ return
+ if not str(path).lower().endswith(".awb"):
+ path += ".awb"
+ from raptor.core.fileio.awb import export_awb
+ QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
+ self._export_in_progress = True
+ try:
+ self._diagram_dock.view.write_back_to_rbd(self._rbd)
+ report = export_awb(
+ req(self._rbd), path, source=self._current_file or "")
+ except Exception as exc: # noqa: BLE001 - report the file, not a crash
+ msgbox.critical(
+ self, "Export Failed",
+ f"Could not write the Availability Workbench project:\n\n{exc}")
+ self._statusbar.showMessage("AWB export failed", 8000)
+ return
+ finally:
+ self._export_in_progress = False
+ QApplication.restoreOverrideCursor()
+ show = getattr(self, "_show_awb_report", None)
+ if show is not None:
+ show("Availability Workbench export", report, path, wrote=True)
+ self._statusbar.showMessage(f"AWB project saved: {Path(path).name}", 8000)
+
def _export_workbook_xlsx(self, path: str | None = None):
"""File > Export Excel Workbook...: one .xlsx of the default tables."""
self._export_workbook(".xlsx", path)
diff --git a/raptor/gui/ui/file_io_mixin.py b/raptor/gui/ui/file_io_mixin.py
index 397b77f0..c46759b6 100644
--- a/raptor/gui/ui/file_io_mixin.py
+++ b/raptor/gui/ui/file_io_mixin.py
@@ -490,6 +490,57 @@ def _open_file(self):
return
self._open_path(path)
+ def _import_awb(self):
+ """File ▸ Import Availability Workbench…: read an AWB project."""
+ if self._refuse_during_run("import an Availability Workbench project"):
+ return
+ path, _ = fdg.getOpenFileName(
+ self, "Import Availability Workbench Project", "",
+ "Availability Workbench projects (*.awb);;All files (*)")
+ if not path:
+ return
+ self._inspector.flush_pending_comment()
+ if not self._confirm_discard_unsaved(closing=True):
+ return
+ from raptor.core.fileio.awb import import_awb
+ try:
+ rbd, report = import_awb(path, source=path)
+ except Exception as exc: # noqa: BLE001 - show the file, don't crash
+ msgbox.critical(
+ self, "Import Failed",
+ f"Could not read {Path(path).name}:\n\n{exc}")
+ return
+ self._load_into_app(rbd, None)
+ self._show_awb_report("Availability Workbench import",
+ report, path, wrote=False)
+ self._statusbar.showMessage(
+ f"Imported {Path(path).name}; save it as .rbds to keep it", 10000)
+
+ def _show_awb_report(self, title: str, report: Any, path: str,
+ *, wrote: bool) -> None:
+ """The conversion summary, with the full Markdown report behind
+ 'Show Details' so a long list does not fill the dialog."""
+ from PySide6.QtWidgets import QMessageBox
+ box = QMessageBox(self)
+ box.setWindowTitle(title)
+ if wrote:
+ box.setText(f"Wrote {path}.")
+ else:
+ box.setText(f"Imported {path}.")
+ losses = len(report.not_in_target)
+ if losses:
+ box.setInformativeText(
+ f"{losses} kind(s) of feature have no equivalent in the "
+ "destination. Nothing in the source file was changed; "
+ "the details say what was left out.")
+ else:
+ box.setInformativeText(
+ "Every feature in the source was represented in the "
+ "destination.")
+ box.setDetailedText(report.summary_text())
+ box.setIcon(QMessageBox.Icon.Information)
+ box.exec()
+
def _write_model(self, path: str) -> bool:
"""Write the model in the format its EXTENSION asks for
(.rbds JSON vs legacy .rbd). One place so every save path
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
new file mode 100644
index 00000000..9b325ce2
--- /dev/null
+++ b/tests/unit/test_awb.py
@@ -0,0 +1,318 @@
+"""AWB project interchange: table store, RBD mapping and loss summary."""
+from __future__ import annotations
+
+import json
+import struct
+
+import pytest
+
+from raptor.core.fileio.awb import (
+ AwbFormatError, AwbTable, _SCHEMA, export_awb, import_awb, read_awb,
+ write_awb,
+)
+from raptor.core.fileio.rbds import parse_rbds, save_rbds
+
+
+def _model(**overrides):
+ doc = {
+ "format": "raptor-studio",
+ "version": 4,
+ "meta": {"generator": "test"},
+ "system": {"units": "hours"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 1000.0},
+ "elements": {
+ "blocks": [
+ {"id": 1, "name": "Pump", "x": 0.0, "y": 0.0,
+ "fail_dist": 4, "fail_params": [1000.0, 0.0, 0.0],
+ "repair_dist": 19, "repair_params": [10.0, 0.0, 0.0]},
+ {"id": 2, "name": "Valve", "x": 100.0, "y": 0.0,
+ "fail_dist": 15,
+ "fail_params": [2.0, 2000.0, 0.0],
+ "repair_dist": 19, "repair_params": [4.0, 0.0, 0.0]},
+ ],
+ "nodes": [
+ {"id": 3, "name": "start", "type": 1, "x": -50.0, "y": 0.0},
+ {"id": 4, "name": "end", "type": 3, "x": 150.0, "y": 0.0},
+ ],
+ "hierarchies": [],
+ },
+ "links": [
+ {"id": 5, "from": ["Node", 3], "to": ["Block", 1]},
+ {"id": 6, "from": ["Block", 1], "to": ["Block", 2]},
+ {"id": 7, "from": ["Block", 2], "to": ["Node", 4]},
+ ],
+ }
+ doc.update(overrides)
+ return parse_rbds(json.dumps(doc), default_name="test")
+
+
+def _rows(rbd, name):
+ return [r for r in rbd.sections[name].rows
+ if str(r.get("ID", "")) not in ("", "0")]
+
+
+def test_table_store_round_trip(tmp_path):
+ tables = {
+ "Project": AwbTable("Project", _SCHEMA["Project"], [
+ {c: ("" if t == 0 else (0 if t in (1, 3) else 0.0))
+ for c, t in _SCHEMA["Project"]} | {"Id": ""}]),
+ "RbdBlocks": AwbTable("RbdBlocks", _SCHEMA["RbdBlocks"], [
+ {"Id": "B1", "Super": 0, "Page": 0, "XPosition": 1.5,
+ "YPosition": 2.5}]),
+ }
+ path = tmp_path / "small.awb"
+ write_awb(path, tables)
+ back = read_awb(path)
+ assert set(back) == {"Project", "RbdBlocks"}
+ assert back["Project"].rows[0]["Id"] == ""
+ assert back["RbdBlocks"].rows[0]["XPosition"] == 1.5
+ assert back["RbdBlocks"].rows[0]["YPosition"] == 2.5
+ # Every column is present, even ones the row did not name.
+ assert set(back["RbdBlocks"].rows[0]) == {c for c, _t in _SCHEMA["RbdBlocks"]}
+
+
+def test_export_writes_the_six_tables_and_the_model(tmp_path):
+ rbd = _model()
+ path = tmp_path / "model.awb"
+ report = export_awb(rbd, path, source="model.rbds")
+ assert path.exists()
+ tables = read_awb(path)
+ assert set(tables) == {
+ "Project", "FailureModels", "FailureModelCorrectiveTasks",
+ "RbdBlocks", "RbdNodes", "RbdConnections"}
+ assert len(tables["RbdBlocks"].rows) == 3 # root + two blocks
+ assert len(tables["RbdNodes"].rows) == 2
+ assert len(tables["RbdConnections"].rows) == 3
+ assert len(tables["FailureModels"].rows) == 2
+ assert report.counts["blocks"] == 2
+ assert report.counts["links"] == 3
+ assert report.direction == "rbds-to-awb"
+
+
+def test_round_trip_keeps_the_series_logic(tmp_path):
+ path = tmp_path / "model.awb"
+ export_awb(_model(), path)
+ rbd, report = import_awb(path)
+ blocks = _rows(rbd, "BLOCK_DATA")
+ links = rbd.sections["LINK_DATA"].rows
+ assert [b["blockName"] for b in blocks] == ["Pump", "Valve"]
+ assert {b["FDist"] for b in blocks} == {"4", "15"}
+ assert len(links) == 3
+ assert report.counts["blocks"] == 2
+ assert report.counts["links"] == 3
+
+
+def test_exact_failure_laws_survive_the_round_trip(tmp_path):
+ laws = [
+ (4, [1000.0, 0.0, 0.0]), # exponential
+ (15, [2.0, 2000.0, 0.0]), # Weibull
+ (7, [300.0, 30.0, 0.0]), # lognormal
+ (8, [400.0, 40.0, 0.0]), # normal
+ (19, [500.0, 0.0, 0.0]), # fixed
+ ]
+ blocks = [{"id": i + 1, "name": f"B{i + 1}", "x": i * 100.0, "y": 0.0,
+ "fail_dist": d, "fail_params": p,
+ "repair_dist": 19, "repair_params": [10.0, 0.0, 0.0]}
+ for i, (d, p) in enumerate(laws)]
+ links = [{"id": 100, "from": ["Node", 90], "to": ["Block", 1]}]
+ for i in range(1, len(blocks)):
+ links.append({"id": 100 + i, "from": ["Block", i],
+ "to": ["Block", i + 1]})
+ links.append({"id": 200, "from": ["Block", len(blocks)],
+ "to": ["Node", 91]})
+ doc = {
+ "format": "raptor-studio", "version": 4,
+ "system": {"units": "hours"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 1000.0},
+ "elements": {
+ "blocks": blocks,
+ "nodes": [{"id": 90, "name": "start", "type": 1, "x": -50.0,
+ "y": 0.0},
+ {"id": 91, "name": "end", "type": 3,
+ "x": len(blocks) * 100.0 + 50.0, "y": 0.0}],
+ "hierarchies": [],
+ },
+ "links": links,
+ }
+ rbd = parse_rbds(json.dumps(doc))
+ path = tmp_path / "laws.awb"
+ export_awb(rbd, path)
+ back, _report = import_awb(path)
+ got = {int(r["FDist"]) for r in _rows(back, "BLOCK_DATA")}
+ assert got == {4, 15, 7, 8, 19}
+
+
+def test_export_report_names_raptor_features_awb_cannot_use(tmp_path):
+ # Add an event, PM, dependency and a non-exponential repair law.
+ rbd = parse_rbds(json.dumps({
+ "format": "raptor-studio", "version": 4,
+ "system": {"units": "days"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 10.0, "analyses": ["capacity"]},
+ "elements": {
+ "blocks": [{"id": 1, "name": "Pump", "x": 0, "y": 0,
+ "fail_dist": 14, "fail_params": [0, 50, 100],
+ "repair_dist": 15, "repair_params": [2, 10, 0],
+ "uses_pm": True, "uses_phasing": True,
+ "dep_type": "RBDBlock", "dep_num": 2}],
+ "nodes": [{"id": 2, "name": "start", "type": 1},
+ {"id": 3, "name": "end", "type": 3}],
+ "events": [{"id": 4, "name": "quake", "prob": 1.0}],
+ "hierarchies": [],
+ },
+ "links": [{"id": 5, "from": ["Node", 2], "to": ["Block", 1]},
+ {"id": 6, "from": ["Block", 1], "to": ["Node", 3]}],
+ "annotations": [{"kind": "text", "id": 1, "parent": 0,
+ "x": 0, "y": 0, "w": 10, "h": 10, "text": "note"}],
+ "rates": [{"name": "base", "expr": "1/1000", "value": 0.001}],
+ "formulas": {"block:1:FParam1": {"rate": "base", "value": 0.001}},
+ "triggers": [{"name": "T1"}],
+ "spare_pools": [{"name": "pool", "stock": 2}],
+ "resources": [{"name": "crew", "num": 1}],
+ "phases": [{"name": "phase 1"}],
+ "out_of_service": {"block:1": "cut"},
+ }), default_name="lossy")
+ path = tmp_path / "lossy.awb"
+ report = export_awb(rbd, path, source="lossy.rbds")
+ features = {loss.feature for loss in report.not_in_target}
+ for expected in (
+ "failure events", "diagram annotations", "rate definitions",
+ "formula-linked fields", "triggers", "spare pools",
+ "resource pools", "mission phases", "out-of-service elements",
+ "capacity analysis", "block dependencies",
+ "preventive maintenance", "phased element schedules",
+ "failure distribution simplified to exponential",
+ "repair distribution simplified to a fixed duration"):
+ assert expected in features, (expected, sorted(features))
+ assert "times converted from days to hours" in " ".join(report.notes)
+
+
+def test_import_report_names_awb_features_raptor_cannot_use(tmp_path):
+ path = tmp_path / "extra.awb"
+ export_awb(_model(), path)
+ tables = read_awb(path)
+ # Add the non-RBD tables an AvSim project often carries.
+ extra = {
+ "Consequences": {"Id": "C", "Description": "cost"},
+ "Phases": {"Id": "P1", "Duration": 100.0},
+ "FailureModelScheduledTasks": {"FailureModel": 0, "TaskId": "PM1"},
+ "Spares": {"Id": "S", "CapacityLevel1": 2},
+ "Labor": {"Id": "L", "NoAvailable": 1},
+ "RcmLocations": {"Id": "LOC"},
+ "WeibullSets": {"Id": "W", "Description": "history"},
+ "LibraryBitmaps": {"Id": "B"},
+ "RbdBlockRuleAssignments": {"Block": 1},
+ }
+ for name, row in extra.items():
+ tables[name] = AwbTable(name, list(row.keys()) and [
+ (k, 0) for k in row], [row])
+ tables["Project"].rows[0]["AvsimCapacityCalcsPerformed"] = 1
+ write_awb(path, tables)
+ rbd, report = import_awb(path)
+ features = {loss.feature for loss in report.not_in_target}
+ for expected in (
+ "consequence and cost models", "mission phases and phase rules",
+ "planned maintenance tasks", "spares and sparing rules",
+ "labour and equipment resources", "RCM location hierarchy",
+ "Weibull sets", "bitmaps", "capacity flow and capacity targets"):
+ assert expected in features, (expected, sorted(features))
+ assert rbd is not None
+
+
+def test_import_synthesises_in_out_nodes_for_a_node_less_hierarchy(tmp_path):
+ path = tmp_path / "hier.awb"
+ export_awb(_model(), path)
+ tables = read_awb(path)
+ blocks = tables["RbdBlocks"].rows
+ # Turn block 2 into a superblock with its own page, and put a new block
+ # inside it. This is the shape Example1 uses (no explicit nodes).
+ blocks[2].update(Id="Sub", Super=1, FailureModel=-1, Page=0)
+ blocks.append(dict(blocks[1], Id="Inner", Super=0, Page=2,
+ FailureModel=0))
+ tables["RbdBlocks"].rows = blocks
+ # The old series link now connects to the superblock; add the inner
+ # page's own two-block chain.
+ tables["RbdConnections"].rows = [
+ dict(tables["RbdConnections"].rows[0], InputObjectIndex=0,
+ OutputObjectIndex=1),
+ dict(tables["RbdConnections"].rows[1], InputObjectIndex=1,
+ OutputObjectIndex=2),
+ dict(tables["RbdConnections"].rows[2], InputObjectIndex=2,
+ OutputObjectIndex=1),
+ ]
+ write_awb(path, tables)
+ rbd, report = import_awb(path)
+ hiers = rbd.sections["HIERARCHY_DATA"].rows
+ assert len(hiers) == 1
+ assert int(hiers[0]["in"]) > 0 and int(hiers[0]["out"]) > 0
+ assert report.counts["hierarchies"] == 1
+ # The importer added an In and an Out node to the hierarchy page.
+ assert any(n["Type"] == "4" for n in rbd.sections["NODE_DATA"].rows)
+ assert any(n["Type"] == "5" for n in rbd.sections["NODE_DATA"].rows)
+
+
+def test_truncated_file_is_a_clear_error(tmp_path):
+ path = tmp_path / "bad.awb"
+ path.write_bytes(struct.pack(" AWB interchange summary" in text
+ assert "Converted" in text
+
+
+def test_cli_convert_awb_round_trip(tmp_path, capsys):
+ from raptor.cli.main import main
+ src = tmp_path / "model.rbds"
+ save_rbds(_model(), str(src))
+ awb = tmp_path / "model.awb"
+ back = tmp_path / "back.rbds"
+ assert main(["convert", str(src), str(awb), "-f", "json"]) == 0
+ out = capsys.readouterr().out
+ payload = json.loads(out)
+ assert payload["schema"] == "raptor-awb-report/1"
+ assert payload["direction"] == "rbds-to-awb"
+ assert main(["convert", str(awb), str(back), "-f", "json"]) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["direction"] == "awb-to-rbds"
+ assert back.exists()
+ from raptor.core.fileio.model_file import load_model_file
+ loaded = load_model_file(back)
+ assert len(_rows(loaded, "BLOCK_DATA")) == 2
From 50379cb49c9c13ffab819d3b3da045eb9a35306a Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 18:32:59 +1000
Subject: [PATCH 02/15] docs(awb): describe Availability Workbench capability
and limits in manual
Adds the .awb file entry, the interchange capability table and the File view commands to the reference manual. The format guide remains docs/AWB_FORMAT.md.
---
docs/manual-reference.adoc | 2 +
docs/manual.adoc | 42 ++++++++++++
docs/manual.html | 124 +++++++++++++++++++++++++++++++++++-
raptor/gui/command_table.py | 4 +-
4 files changed, 169 insertions(+), 3 deletions(-)
diff --git a/docs/manual-reference.adoc b/docs/manual-reference.adoc
index d55c11ff..3f5374d9 100644
--- a/docs/manual-reference.adoc
+++ b/docs/manual-reference.adoc
@@ -368,6 +368,7 @@ documentation.
|Control |What it does |Shortcut / value
|New |Create a new blank model (Ctrl+N) |Ctrl+N
|Open |Open an .rbd or .rbds file (Ctrl+O) |Ctrl+O
+|Import Availability Workbench… |Open an Isograph Availability Workbench 5.0 .awb project as a new RAPTOR model; the summary lists what AWB features RAPTOR cannot represent |
|Save |Save (Ctrl+S) |Ctrl+S
|Save As |Save to a new .rbds or .rbd file (Ctrl+Shift+S) |Ctrl+Shift+S
|Close |Close the current model (with save prompt) (Ctrl+W) |Ctrl+W
@@ -382,6 +383,7 @@ documentation.
|Control |What it does |Shortcut / value
|Print… |Print diagrams, simulation results and the Weak Link analysis with a project title block (Ctrl+P) |Ctrl+P
|Export… |Save the report, the tables or the diagram: one window, pick the file type (PDF, Excel, OpenDocument, SVG or PNG) (Ctrl+E) |Ctrl+E
+|Export to Availability Workbench… |Save this model as an Isograph Availability Workbench 5.0 .awb project; the summary lists what RAPTOR features AWB cannot represent |
|Export Tables… |Choose which tables to write, the model's and a run's results, as CSV files, text or one spreadsheet with a tab per table |
|Copy View |Copy the current view to the clipboard as a high-resolution PNG |
|===
diff --git a/docs/manual.adoc b/docs/manual.adoc
index 6962bcfd..3e973747 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1634,6 +1634,14 @@ the Help window stays usable, and can be closed, while a dialog is open.
sectioned). Opens and round-trips; saving data the classic format cannot hold
(annotations, for example) as `.rbd` drops it, with a warning
first. Import RBD merges a `.rbd` or `.rbds` file in as one hierarchy.
+* `.awb` — an Isograph **Availability Workbench 5.0** project (RBD/AvSim).
+ *File ▸ Import Availability Workbench…* reads one into a new model and
+ *File ▸ Export to Availability Workbench…* writes one; `raptor convert`
+ does the same headless. The conversion always prints a summary of the
+ features the destination cannot represent, with a count; `--strict`
+ writes nothing when that list is not empty. AWB's demonstration mode can
+ open and simulate a project but not save or export it; RAPTOR writes the
+ `.awb` file directly, so no AWB licence is needed to create one.
* Export Library / Import Library — reuse blocks across models.
* Open / New / the examples — each opens in a new window when the current
one holds a model worth keeping (see <>). File ▸ New
@@ -1661,6 +1669,40 @@ the Help window stays usable, and can be closed, while a dialog is open.
* Diagram as SVG — the current hierarchy level as a scalable vector file.
* Diagram as PNG / Copy View — PNG of the diagram, file or clipboard.
+[[awb-interchange]]
+=== Availability Workbench interchange
+
+The complete file layout and feature matrix are in
+link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md[the AWB format guide].
+In short:
+
+[cols="2,3,3",options="header"]
+|===
+|Feature |RAPTOR → AWB |AWB → RAPTOR
+
+|RBD blocks, nodes, links, K-of-N votes, nested hierarchies |yes |yes
+|Exponential, Weibull, lognormal, normal and fixed failure laws |yes |yes
+|Corrective repair duration, project lifetime and trial count |yes |yes
+|Failure events |not exported (AWB RBDs use blocks) |n/a
+|RAPTOR annotations, rates, formulas, triggers |not exported |n/a
+|Mission phases, out-of-service rules, dependencies |not exported |not imported
+|PM/inspection tasks, spare holdings, labour/equipment |not exported |not imported
+|Capacity products and capacity targets |not exported |not imported
+|Consequence and cost models |not exported |not imported
+|RCM location hierarchy, fault trees, Weibull sets, bitmaps |n/a |not imported
+|AWB labels, repeat blocks |n/a |labels become annotations; repeats become dependent blocks
+|Unsupported failure laws |mean-matched exponential |n/a
+|Unsupported repair laws |mean-matched fixed task |n/a
+|===
+
+AWB projects can carry more than an RBD. The converter reads and writes
+the AvSim RBD part; it does not transfer an AWB RCMCost study, fault tree,
+capacity network or life-cycle-cost model. The summary names each of these
+with a count, so nothing is lost silently. AWB may renumber pages and
+element ids on a round trip, and it uses the source x/y positions rather
+than auto-layout; use AWB's Auto Layout after opening a model whose blocks
+overlap.
+
[[standards]]
== IEC 61078 and standards alignment
diff --git a/docs/manual.html b/docs/manual.html
index 17639676..2dcbf415 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -68,7 +68,11 @@ RAPTOR Studio Reference Manual
Keyboard: Alt key tips
Preferences
-Files and formats
+Files and formats
+
+
IEC 61078 and standards alignment
Fidelity and known limits
UI Reference
@@ -2390,6 +2394,16 @@ Files and formats
first. Import RBD merges a .rbd or .rbds file in as one hierarchy.
+.awb — an Isograph Availability Workbench 5.0 project (RBD/AvSim).
+File ▸ Import Availability Workbench… reads one into a new model and
+File ▸ Export to Availability Workbench… writes one; raptor convert
+does the same headless. The conversion always prints a summary of the
+features the destination cannot represent, with a count; --strict
+writes nothing when that list is not empty. AWB’s demonstration mode can
+open and simulate a project but not save or export it; RAPTOR writes the
+.awb file directly, so no AWB licence is needed to create one.
+
+
Export Library / Import Library — reuse blocks across models.
@@ -2431,6 +2445,104 @@ Files and formats
+
+
Availability Workbench interchange
+
+
+
+
+
+
+
+
+
+| Feature |
+RAPTOR → AWB |
+AWB → RAPTOR |
+
+
+
+
+RBD blocks, nodes, links, K-of-N votes, nested hierarchies |
+yes |
+yes |
+
+
+Exponential, Weibull, lognormal, normal and fixed failure laws |
+yes |
+yes |
+
+
+Corrective repair duration, project lifetime and trial count |
+yes |
+yes |
+
+
+Failure events |
+not exported (AWB RBDs use blocks) |
+n/a |
+
+
+RAPTOR annotations, rates, formulas, triggers |
+not exported |
+n/a |
+
+
+Mission phases, out-of-service rules, dependencies |
+not exported |
+not imported |
+
+
+PM/inspection tasks, spare holdings, labour/equipment |
+not exported |
+not imported |
+
+
+Capacity products and capacity targets |
+not exported |
+not imported |
+
+
+Consequence and cost models |
+not exported |
+not imported |
+
+
+RCM location hierarchy, fault trees, Weibull sets, bitmaps |
+n/a |
+not imported |
+
+
+AWB labels, repeat blocks |
+n/a |
+labels become annotations; repeats become dependent blocks |
+
+
+Unsupported failure laws |
+mean-matched exponential |
+n/a |
+
+
+Unsupported repair laws |
+mean-matched fixed task |
+n/a |
+
+
+
+
+
AWB projects can carry more than an RBD. The converter reads and writes
+the AvSim RBD part; it does not transfer an AWB RCMCost study, fault tree,
+capacity network or life-cycle-cost model. The summary names each of these
+with a count, so nothing is lost silently. AWB may renumber pages and
+element ids on a round trip, and it uses the source x/y positions rather
+than auto-layout; use AWB’s Auto Layout after opening a model whose blocks
+overlap.
+
+
@@ -3827,6 +3939,11 @@
File
Ctrl+O |
+Import Availability Workbench… |
+Open an Isograph Availability Workbench 5.0 .awb project as a new RAPTOR model; the summary lists what AWB features RAPTOR cannot represent |
+ |
+
+
Save |
Save (Ctrl+S) |
Ctrl+S |
@@ -3881,6 +3998,11 @@ Print and Export
Ctrl+E |
+Export to Availability Workbench… |
+Save this model as an Isograph Availability Workbench 5.0 .awb project; the summary lists what RAPTOR features AWB cannot represent |
+ |
+
+
Export Tables… |
Choose which tables to write, the model’s and a run’s results, as CSV files, text or one spreadsheet with a tab per table |
|
diff --git a/raptor/gui/command_table.py b/raptor/gui/command_table.py
index 084a8dbb..5248cf7d 100644
--- a/raptor/gui/command_table.py
+++ b/raptor/gui/command_table.py
@@ -64,8 +64,8 @@
icon="awb_import_icon:text",
tooltip=(
"Open an Isograph Availability Workbench 5.0 .awb project as a "
- "RAPTOR model; the summary lists what AWB features RAPTOR cannot "
- "represent"),
+ "new RAPTOR model; the summary lists what AWB features RAPTOR "
+ "cannot represent"),
handler="_import_awb",
enabled_when="not_running"),
CommandSpec(
From 29adfb7733252aa6416439066bce1e260c0c4ca9 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 19:47:10 +1000
Subject: [PATCH 03/15] docs(awb): compare all tutorial examples with
Availability Workbench
Screens all 27 example models, compares the six exactly representable ones at 10,000 trials, and records the compatibility gaps for the rest. Adds AWB_VALIDATION.md and links it from the manual and format guide.
---
README.md | 4 +-
docs/AWB_FORMAT.md | 5 ++
docs/AWB_VALIDATION.md | 132 +++++++++++++++++++++++++++++++++++++++++
docs/manual.adoc | 4 +-
docs/manual.html | 4 +-
pyproject.toml | 2 +-
6 files changed, 146 insertions(+), 5 deletions(-)
create mode 100644 docs/AWB_VALIDATION.md
diff --git a/README.md b/README.md
index 4eb69fde..8caf394a 100644
--- a/README.md
+++ b/README.md
@@ -214,7 +214,7 @@ built-in documentation, which the **Help** ribbon tab also opens:
- **AI assistant** — the [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md), the
generated [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), and
the book's MCP chapter.
-- **File format** — [`docs/RBDS_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md) describes the `.rbds` JSON format, and [`docs/AWB_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md) describes the Availability Workbench `.awb` interchange.
+- **File format** — [`docs/RBDS_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md) describes the `.rbds` JSON format, [`docs/AWB_FORMAT.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md) describes the Availability Workbench `.awb` interchange, and [`docs/AWB_VALIDATION.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_VALIDATION.md) gives the example-by-example AWB comparison.
- **Analytical solver** — [`docs/ANALYTICAL.md`](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md) covers the exact static solver: scope, assumptions, CLI and API.
## IEC 61078
@@ -261,7 +261,7 @@ The docs render with Ruby asciidoctor: `new_docs/tools/render_docs.sh` (see `new
| `raptor/` | The application: `core/` engine, `api/`, `cli/`, `gui/`, `mcp/`, `render/` |
| `tests/` | `unit/`, `behaviour/`, `integration/` (incl. `sweeps/`), `golden/` (Raptor 7's captured output; large captures gzipped), `fixtures/` (probe models), `ladder/`, `data/` (shared sample models) |
| `new_docs/` | User Guide (tutorial book), its models and build tools |
-| `docs/` | Reference manual, [engine design](https://github.com/openpowershift/RaptorStudio/blob/main/docs/engine-design/README.adoc), [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md) and [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), [analytical solver](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md), formulas, [keyboard shortcuts](https://github.com/openpowershift/RaptorStudio/blob/main/docs/KEYBOARD_SHORTCUTS.md), [`.rbds` file format](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md), [AWB interchange](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md), [IEC 61078](https://github.com/openpowershift/RaptorStudio/blob/main/docs/IEC61078.md) |
+| `docs/` | Reference manual, [engine design](https://github.com/openpowershift/RaptorStudio/blob/main/docs/engine-design/README.adoc), [MCP guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md) and [tool reference](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP-reference.md), [analytical solver](https://github.com/openpowershift/RaptorStudio/blob/main/docs/ANALYTICAL.md), formulas, [keyboard shortcuts](https://github.com/openpowershift/RaptorStudio/blob/main/docs/KEYBOARD_SHORTCUTS.md), [`.rbds` file format](https://github.com/openpowershift/RaptorStudio/blob/main/docs/RBDS_FORMAT.md), [AWB interchange](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md) and [AWB validation](https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_VALIDATION.md), [IEC 61078](https://github.com/openpowershift/RaptorStudio/blob/main/docs/IEC61078.md) |
| `tools/` | Developer tools the tests and CI run: engine snapshot, coverage, type gate, doc generators |
| `installer/` | Packaging (PyInstaller, Inno Setup, deb/AppImage) |
| `packaging/` | `raptor-studio-mcp`, the small PyPI package the MCP Registry lists |
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index 45f81c8c..d1e2951f 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -323,6 +323,11 @@ The format and mapping were checked against AWB 5.0.0.0 under Wine:
multi-link hierarchy items produce RAPTOR layout warnings).
5. The imported Example1 model was exported again and re-imported with the
same element and link counts.
+6. The six tutorial examples that AWB can represent exactly were simulated
+ in both programs at 10,000 replications; every availability difference
+ was within 0.53 percentage points and 1.3 combined standard errors. The
+ full example sweep and the models that are only partly representable are
+ in [`AWB_VALIDATION.md`](AWB_VALIDATION.md).
AWB demonstration mode was used for opening and simulation. It does not
allow Save or Export, which is why the writer constructs the file directly
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
new file mode 100644
index 00000000..30f3cfb2
--- /dev/null
+++ b/docs/AWB_VALIDATION.md
@@ -0,0 +1,132 @@
+# Availability Workbench vs RAPTOR: example validation
+
+**Scope:** the 27 example models in `new_docs/models/`, tested against
+Isograph Availability Workbench 5.0.0.0 under Wine.
+
+The result is in two parts:
+
+1. every example was **screened** for what AWB can represent;
+2. the six examples that AWB can represent **exactly** were simulated in
+ both programs and their availabilities compared.
+
+AWB's demonstration mode was used. It opens and simulates projects but
+blocks Save and Export; the `.awb` files were written by RAPTOR's own
+exporter. No AWB licence or licence bypass was used.
+
+---
+
+## 1. Exact-compatible examples
+
+Six examples use only features the converter carries without loss:
+blocks, nodes, links, exponential/Weibull/fixed failure laws, no repair,
+and no dependency/spares/PM/phase/capacity data.
+
+| Example | RAPTOR mean availability | AWB mean availability | Difference (pp) | Difference / combined σ |
+|---|---:|---:|---:|---:|
+| `Drone1` | 0.85610 | 0.8545 | -0.160 | 0.48 |
+| `Espresso1` | 0.71912 | 0.7138 | -0.532 | 1.28 |
+| `Lantern1` | 0.69339 | 0.6933 | -0.009 | 0.02 |
+| `Toaster_Expo` | 0.75374 | 0.7499 | -0.384 | 0.81 |
+| `Toaster_Fixed` | 1.00000 | 1.0000 | 0.000 | 0.00 |
+| `Toaster_Weibull` | 0.85782 | 0.8546 | -0.322 | 0.89 |
+
+Every difference is within **0.6 percentage points** and within **1.3
+combined standard errors**. There is no systematic AWB bias in this
+sample: the small differences are consistent with Monte Carlo noise.
+
+### Method
+
+For each model:
+
+* 10,000 replications, the example's own lifetime and failure/repair data;
+* RAPTOR: `raptor run MODEL -n 10000 -j 1 -f json`, reading
+ `summary.Availability.mean` and `summary.Availability.sem`;
+* export with `raptor convert MODEL MODEL.awb`, open in AWB, run
+ **Simulation → Start**, then read **Simulation Results → Systems**:
+ `Mean unavailability` and `Std total downtime`;
+* AWB availability is `1 - mean unavailability`;
+* the AWB standard error is estimated from the time-weighted downtime:
+ `std total downtime / (sqrt(10000) * lifetime)`;
+* the combined σ is the root sum of the RAPTOR and AWB standard errors.
+
+AWB shows the mean unavailability to four decimal places, so the AWB
+availability carries about ±0.00005 of display rounding on top of its
+sampling error.
+
+### What this checks
+
+* series and parallel block logic, including start/end nodes;
+* exponential, Weibull and fixed failure laws;
+* no-repair blocks (`NonMaintainable` in AWB);
+* lifetime and trial-count transfer;
+* the direct `.awb` writer and reader.
+
+`Toaster_Fixed` is a useful edge case: its fixed failure time is 1000 h
+and the run is 600 h, so both programs correctly report no failures and
+availability 1.0000.
+
+---
+
+## 2. Compatibility screening of all 27 examples
+
+"Screened" means the model was exported and the conversion report was
+read. Models marked **exact** were also simulated in both programs.
+Models marked with a loss can still be exported, but the AWB run would be
+a *reduced* model, so a difference could not be attributed to the engine.
+
+| Example | AWB compatibility |
+|---|---|
+| AirlinerMission | rate definitions (6); formula-linked fields (12); mission phases (5); phased element schedules (7) |
+| Bakery1 | repair distribution simplified to a fixed duration (1); node standby/priority settings (1); link switching and priority (6) |
+| CarCare0 | repair distribution simplified to a fixed duration (1) |
+| CarCare1 | repair distribution simplified to a fixed duration (1); preventive maintenance (1) |
+| CarWash1 | mission phases (3); phased element schedules (1) |
+| DC1 | repair distribution simplified to a fixed duration (1); spare pools (1); node standby/priority settings (1); link switching and priority (5) |
+| DC2 | repair distribution simplified to a fixed duration (1); spare pools (1); preventive maintenance (1); node standby/priority settings (1); link switching and priority (5) |
+| Drone1 | **exact** |
+| Espresso1 | **exact** |
+| EspressoDep1 | block dependencies (1) |
+| FinaleShow1 | **not exportable**: event-only model, no RBD blocks |
+| Flight1 | failure events (1); mission phases (4); capacity analysis (2); block dependencies (1); phased element schedules (2); node standby/priority settings (1); link switching and priority (3) |
+| HospitalPower | repair distribution simplified to a fixed duration (8); rate definitions (7); formula-linked fields (17); spare pools (1); preventive maintenance (3); block cost data (9) |
+| Lantern1 | **exact** |
+| Laundromat1 | repair distribution simplified to a fixed duration (1) |
+| ProdLine0 | repair distribution simplified to a fixed duration (12); block cost data (2) |
+| ProdLine1 | repair distribution simplified to a fixed duration (12); preventive maintenance (1); block cost data (3) |
+| TacoTruck1 | repair distribution simplified to a fixed duration (1) |
+| Toaster_Expo | **exact** |
+| Toaster_Fixed | **exact** |
+| Toaster_Weibull | **exact** |
+| Van1 | repair distribution simplified to a fixed duration (2) |
+| VanFlat | repair distribution simplified to a fixed duration (2) |
+| Vendo1 | repair distribution simplified to a fixed duration (1) |
+| Water1 | capacity analysis (3); link switching and priority (2) |
+| Water2 | capacity analysis (3); block cost data (3); link switching and priority (2) |
+| WaterTreatment | repair distribution simplified to a fixed duration (6); rate definitions (6); formula-linked fields (15); spare pools (1); preventive maintenance (6); block cost data (10) |
+
+### Reading the table
+
+* **exact** — no reported loss; the comparison above applies.
+* **repair distribution simplified** — RAPTOR has a repair *distribution*,
+ AWB's generated task is a fixed duration with the same mean. The models
+ can be compared if both sides use the fixed mean, but not as shipped.
+* **spare pools / PM / dependencies / phases / capacity / standby /
+ link switching** — AWB has features in these areas, but this converter
+ does not populate them, so the AWB run is a reduced model.
+* **rates/formulas/costs** — metadata or cost data; availability is still
+ driven by the same numbers, but the conversion is lossy.
+* **FinaleShow1** — a fault-tree/event model with no RBD blocks; AWB RBD
+ export needs at least one block.
+
+---
+
+## 3. Conclusion
+
+For the part of the model AWB and RAPTOR both represent, the two engines
+agree on these examples within Monte Carlo error. The larger question for
+the other examples is feature coverage, not engine disagreement: the AWB
+converter deliberately refuses to invent capacity networks, PM schedules,
+spares, dependencies or phase rules it cannot populate faithfully.
+
+The full mapping and feature matrix are in
+[`AWB_FORMAT.md`](AWB_FORMAT.md).
diff --git a/docs/manual.adoc b/docs/manual.adoc
index 3e973747..7f9c7926 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1673,7 +1673,9 @@ the Help window stays usable, and can be closed, while a dialog is open.
=== Availability Workbench interchange
The complete file layout and feature matrix are in
-link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md[the AWB format guide].
+link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md[the AWB format guide];
+link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_VALIDATION.md[the example validation report]
+gives the 10,000-trial AWB comparison for the examples both programs can represent exactly.
In short:
[cols="2,3,3",options="header"]
diff --git a/docs/manual.html b/docs/manual.html
index 2dcbf415..bac77a8f 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2449,7 +2449,9 @@ Files and formats
Availability Workbench interchange
diff --git a/pyproject.toml b/pyproject.toml
index 10aaeb96..8fbd41c5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -316,7 +316,7 @@ include = ["raptor*"]
# installers bundle the same trees from the repo checkout.
[tool.setuptools.data-files]
"docs" = ["docs/manual.html", "docs/formulas.html", "docs/ops_asciidoctor.css", "docs/RBDS_FORMAT.md",
- "docs/AWB_FORMAT.md", "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
+ "docs/AWB_FORMAT.md", "docs/AWB_VALIDATION.md", "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
"docs/MCP-reference.md",
"docs/ANALYTICAL.md", "docs/rbds.schema.json"]
# MathJax (Apache-2.0, see its LICENSE) typesets the formulas page offline: the page loads it from js/.
From 0e35c9360a7fa4d283a504b49c93d8c25b8f62db Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 19:49:34 +1000
Subject: [PATCH 04/15] docs(awb): keep example validation out of the in-app
manual
The comparison stays in the standalone docs/AWB_VALIDATION.md note; the manual keeps only the capability and limitation summary.
---
docs/AWB_FORMAT.md | 6 ------
docs/manual.adoc | 4 +---
docs/manual.html | 4 +---
pyproject.toml | 2 +-
4 files changed, 3 insertions(+), 13 deletions(-)
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index d1e2951f..65d6cd93 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -323,12 +323,6 @@ The format and mapping were checked against AWB 5.0.0.0 under Wine:
multi-link hierarchy items produce RAPTOR layout warnings).
5. The imported Example1 model was exported again and re-imported with the
same element and link counts.
-6. The six tutorial examples that AWB can represent exactly were simulated
- in both programs at 10,000 replications; every availability difference
- was within 0.53 percentage points and 1.3 combined standard errors. The
- full example sweep and the models that are only partly representable are
- in [`AWB_VALIDATION.md`](AWB_VALIDATION.md).
-
AWB demonstration mode was used for opening and simulation. It does not
allow Save or Export, which is why the writer constructs the file directly
rather than driving AWB's own export dialog.
diff --git a/docs/manual.adoc b/docs/manual.adoc
index 7f9c7926..3e973747 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1673,9 +1673,7 @@ the Help window stays usable, and can be closed, while a dialog is open.
=== Availability Workbench interchange
The complete file layout and feature matrix are in
-link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md[the AWB format guide];
-link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_VALIDATION.md[the example validation report]
-gives the 10,000-trial AWB comparison for the examples both programs can represent exactly.
+link:https://github.com/openpowershift/RaptorStudio/blob/main/docs/AWB_FORMAT.md[the AWB format guide].
In short:
[cols="2,3,3",options="header"]
diff --git a/docs/manual.html b/docs/manual.html
index bac77a8f..2dcbf415 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2449,9 +2449,7 @@ Files and formats
Availability Workbench interchange
diff --git a/pyproject.toml b/pyproject.toml
index 8fbd41c5..10aaeb96 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -316,7 +316,7 @@ include = ["raptor*"]
# installers bundle the same trees from the repo checkout.
[tool.setuptools.data-files]
"docs" = ["docs/manual.html", "docs/formulas.html", "docs/ops_asciidoctor.css", "docs/RBDS_FORMAT.md",
- "docs/AWB_FORMAT.md", "docs/AWB_VALIDATION.md", "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
+ "docs/AWB_FORMAT.md", "docs/KEYBOARD_SHORTCUTS.md", "docs/IEC61078.md", "docs/MCP.md",
"docs/MCP-reference.md",
"docs/ANALYTICAL.md", "docs/rbds.schema.json"]
# MathJax (Apache-2.0, see its LICENSE) typesets the formulas page offline: the page loads it from js/.
From 989210c0645b61e49315677addfc631c49c1804b Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 20:36:38 +1000
Subject: [PATCH 05/15] feat(awb): carry PM, spares, resources, phases and
labels both ways
Adds optional AWB tables for scheduled maintenance, spare and resource links, phases, block phase rules and text labels; imports them back into RAPTOR as PM, spare pools, resource pools, phases and cut/linked phase states. Applies out-of-service what-ifs to the AWB copy and keeps AWB Type=-1 for untyped labour/spare rows. Updates the manual and validation notes.
---
docs/AWB_FORMAT.md | 59 +-
docs/AWB_VALIDATION.md | 53 +-
docs/manual.adoc | 11 +-
docs/manual.html | 37 +-
raptor/core/fileio/awb.py | 674 ++++++++++++++++--
raptor/core/fileio/awb_tables.json | 1024 ++++++++++++++++++++++++++++
tests/unit/test_awb.py | 84 ++-
7 files changed, 1828 insertions(+), 114 deletions(-)
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index 65d6cd93..1af74598 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -62,7 +62,7 @@ There is no per-table byte length and no end marker: the reader walks the
tables and cells in order. A truncated file, an unknown column type, or
trailing bytes are reported as `AwbFormatError` rather than guessed at.
-The six tables RAPTOR writes are:
+The six core tables RAPTOR always writes are:
| Table | Purpose |
|---|---|
@@ -73,9 +73,23 @@ The six tables RAPTOR writes are:
| `RbdNodes` | RBD nodes and K-of-N votes |
| `RbdConnections` | links between blocks and nodes |
+When the model uses them, RAPTOR also writes:
+
+| Table | Purpose |
+|---|---|
+| `FailureModelScheduledTasks` | one preventive-maintenance task per failure model |
+| `FailureModelSchedTaskLabor` / `...Spares` | PM resource and spare links |
+| `FailureModelCorrTaskLabor` / `...Spares` | repair resource and spare links |
+| `Spares` | spare holdings |
+| `Labor` | labour/resource pools |
+| `Phases` | mission phase durations |
+| `RbdBlockRuleAssignments` | phase cut/linked rules |
+| `RbdLabels` | text annotations |
+
AWB adds the tables its other modules need when it opens the project. A
minimal six-table project was opened, validated and simulated by AWB 5.0 in
-demonstration mode; the tables below are the ones that matter to AvSim.
+demonstration mode; the extra tables above have also been opened and
+simulated in AWB with PM, spares, labour and phases present.
---
@@ -238,16 +252,12 @@ Markdown; `--report FILE` also writes the Markdown. The report has:
| Feature | Why |
|---|---|
| failure events | AWB RBDs use blocks; events are not exported |
-| diagram annotations | text boxes, rectangles and arrows are draw-only |
+| non-text annotations | text annotations become AWB labels; rectangles, ellipses and arrows are draw-only |
| rate definitions and formula-linked fields | values are written as plain numbers |
| triggers | AWB has no equivalent trigger logic |
-| spare pools | AWB spare holdings are not populated by this export |
-| resource pools | AWB labour/equipment are not populated |
-| mission phases and per-element phase schedules | AWB phase rules are not populated |
-| out-of-service elements | AWB `OutOfService` rules are not populated |
| capacity analysis and flow links | AWB capacity targets are not populated |
| block dependencies | AWB dependency rules are not populated |
-| preventive maintenance | AWB scheduled tasks are not populated |
+| node and hierarchy phase schedules | block phase rules are exported; node/hierarchy phase states are not |
| age, restoration and growth settings | AWB initial age is 0 |
| block cost data | AWB cost fields are not populated |
| node standby/priority settings | AWB nodes carry only a vote |
@@ -256,6 +266,7 @@ Markdown; `--report FILE` also writes the Markdown. The report has:
| advisor state and print title block | RAPTOR-only metadata |
| other failure laws (gamma, triangular, ...) | simplified to an exponential with the same mean |
| non-fixed repair laws | simplified to a fixed task duration with the same mean |
+| additional or non-fixed PM | one fixed-duration PM per failure model is written |
| no-repair blocks | written as `NonMaintainable = 1` |
| no-failure blocks | written with a fixed time of 9e8 hours |
@@ -264,10 +275,12 @@ Markdown; `--report FILE` also writes the Markdown. The report has:
| Feature | Why |
|---|---|
| consequences and cost models | RAPTOR has no financial/safety/environmental consequence model |
-| mission phases and phase rules | AWB phase schedules are not imported |
-| planned maintenance and inspection tasks | RAPTOR PM is not populated |
-| spares and sparing rules | RAPTOR spare pools are not populated |
-| labour and equipment resources | RAPTOR resource pools are not populated |
+| inspection tasks | AWB inspections are not imported as RAPTOR PM |
+| extra planned tasks | RAPTOR has one PM per block; extra AWB tasks are not imported |
+| two-level spare holdings | AWB level-1 and level-2 stock are summed |
+| spare repair shop | AWB spare repair/recycling is not imported |
+| labour call-out delay | AWB labour logistics delay is not imported |
+| phase capacity/load rules | only AWB phase logic/out-of-service rules are imported |
| RCM location hierarchy | the RCMCost module is not imported |
| fault trees | only RBDs are imported |
| Weibull sets | linked historical data is flattened |
@@ -280,15 +293,18 @@ Markdown; `--report FILE` also writes the Markdown. The report has:
| non-maintainable blocks | RAPTOR repair is off |
| start-up failure probability | not modelled by RAPTOR |
-Labels (`RbdLabels`) and repeat blocks (`RbdRepeatBlocks`) are **converted**,
-not lost: labels become RAPTOR annotations, and a repeat block becomes a
-never-failing block that is idle whenever the original block is down.
+**Converted in both directions:** the first enabled planned-maintenance
+task per failure model, spare holdings (AWB level 1 + 2 become one RAPTOR
+pool), labour/equipment rows as RAPTOR resource pools, phase durations,
+block phase cut/linked rules, text annotations and global out-of-service
+states. Repeat blocks (`RbdRepeatBlocks`) become never-failing blocks that
+are idle whenever the original block is down.
---
-## 6. Column defaults and the six-table file
+## 6. Column defaults and the table schema file
-RAPTOR ships the six table schemas in
+RAPTOR ships the table schemas in
`raptor/core/fileio/awb_tables.json` (column names and types plus the neutral
project row). The file is data, not a template project: rows are generated
from the RAPTOR model, so a generated `.awb` contains no Isograph sample
@@ -333,10 +349,11 @@ rather than driving AWB's own export dialog.
* The reader accepts the AWB 5.0 table-store layout. Older AWB projects with
fewer columns are accepted; missing columns take the type default.
-* The writer emits the six tables above. AWB upgrades the project to its
- full module schema when it opens it; it may show validation warnings for
- fields that are not meaningful in a pure AvSim project, but the RBD data is
- complete.
+* The writer emits the six core tables and only adds the PM/spare/resource/
+ phase/label tables the model actually uses. AWB upgrades the project to
+ its full module schema when it opens it; it may show validation warnings
+ for fields that are not meaningful in a pure AvSim project, but the RBD
+ data is complete.
* AWB IDs are limited to 40 characters and RAPTOR names to 20. RAPTOR
sanitises names and reports any rename; it never changes the source model.
* AWB uses the source model's x/y positions as-is and does not auto-layout.
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
index 30f3cfb2..0b9a3249 100644
--- a/docs/AWB_VALIDATION.md
+++ b/docs/AWB_VALIDATION.md
@@ -65,34 +65,46 @@ sampling error.
and the run is 600 h, so both programs correctly report no failures and
availability 1.0000.
+### Feature smoke test (Stage 1/2)
+
+A synthetic two-block model with one PM task, a custom spare, a resource
+pool, two phases, a text label and one cut block was exported and opened in
+AWB. AWB simulated 10 replications and showed the **Phases**, **Spares** and
+**Labor** tabs with non-zero labour/spare costs. The same `.awb` imported
+back to RAPTOR with 0 validation errors and preserved the PM, spare/resource
+links, phase cut/linked token and cut block. This is a mapping smoke test,
+not a 10,000-trial engine comparison.
+
---
## 2. Compatibility screening of all 27 examples
"Screened" means the model was exported and the conversion report was
-read. Models marked **exact** were also simulated in both programs.
-Models marked with a loss can still be exported, but the AWB run would be
-a *reduced* model, so a difference could not be attributed to the engine.
+read. The six models in the comparison above were simulated in both
+programs; `CarWash1` also became exact once phases were mapped, but it is
+not part of the 10,000-trial comparison yet. Models marked with a loss can
+still be exported, but the AWB run would be a *reduced* model, so a
+difference could not be attributed to the engine.
| Example | AWB compatibility |
|---|---|
-| AirlinerMission | rate definitions (6); formula-linked fields (12); mission phases (5); phased element schedules (7) |
+| AirlinerMission | rate definitions (6); formula-linked fields (12); node and hierarchy phase schedules (1) |
| Bakery1 | repair distribution simplified to a fixed duration (1); node standby/priority settings (1); link switching and priority (6) |
| CarCare0 | repair distribution simplified to a fixed duration (1) |
-| CarCare1 | repair distribution simplified to a fixed duration (1); preventive maintenance (1) |
-| CarWash1 | mission phases (3); phased element schedules (1) |
-| DC1 | repair distribution simplified to a fixed duration (1); spare pools (1); node standby/priority settings (1); link switching and priority (5) |
-| DC2 | repair distribution simplified to a fixed duration (1); spare pools (1); preventive maintenance (1); node standby/priority settings (1); link switching and priority (5) |
+| CarCare1 | repair distribution simplified to a fixed duration (1) |
+| CarWash1 | **exact** (phases now exported) |
+| DC1 | repair distribution simplified to a fixed duration (1); node standby/priority settings (1); link switching and priority (5) |
+| DC2 | repair distribution simplified to a fixed duration (1); node standby/priority settings (1); link switching and priority (5) |
| Drone1 | **exact** |
| Espresso1 | **exact** |
| EspressoDep1 | block dependencies (1) |
| FinaleShow1 | **not exportable**: event-only model, no RBD blocks |
-| Flight1 | failure events (1); mission phases (4); capacity analysis (2); block dependencies (1); phased element schedules (2); node standby/priority settings (1); link switching and priority (3) |
-| HospitalPower | repair distribution simplified to a fixed duration (8); rate definitions (7); formula-linked fields (17); spare pools (1); preventive maintenance (3); block cost data (9) |
+| Flight1 | failure events (1); capacity analysis (2); block dependencies (1); node standby/priority settings (1); link switching and priority (3) |
+| HospitalPower | repair distribution simplified to a fixed duration (8); rate definitions (7); formula-linked fields (17); block cost data (9); additional or non-fixed PM (2) |
| Lantern1 | **exact** |
| Laundromat1 | repair distribution simplified to a fixed duration (1) |
| ProdLine0 | repair distribution simplified to a fixed duration (12); block cost data (2) |
-| ProdLine1 | repair distribution simplified to a fixed duration (12); preventive maintenance (1); block cost data (3) |
+| ProdLine1 | repair distribution simplified to a fixed duration (12); block cost data (3) |
| TacoTruck1 | repair distribution simplified to a fixed duration (1) |
| Toaster_Expo | **exact** |
| Toaster_Fixed | **exact** |
@@ -102,7 +114,7 @@ a *reduced* model, so a difference could not be attributed to the engine.
| Vendo1 | repair distribution simplified to a fixed duration (1) |
| Water1 | capacity analysis (3); link switching and priority (2) |
| Water2 | capacity analysis (3); block cost data (3); link switching and priority (2) |
-| WaterTreatment | repair distribution simplified to a fixed duration (6); rate definitions (6); formula-linked fields (15); spare pools (1); preventive maintenance (6); block cost data (10) |
+| WaterTreatment | repair distribution simplified to a fixed duration (6); rate definitions (6); formula-linked fields (15); block cost data (10); additional or non-fixed PM (5) |
### Reading the table
@@ -110,9 +122,13 @@ a *reduced* model, so a difference could not be attributed to the engine.
* **repair distribution simplified** — RAPTOR has a repair *distribution*,
AWB's generated task is a fixed duration with the same mean. The models
can be compared if both sides use the fixed mean, but not as shipped.
-* **spare pools / PM / dependencies / phases / capacity / standby /
- link switching** — AWB has features in these areas, but this converter
- does not populate them, so the AWB run is a reduced model.
+* **PM / spares / labour / phases** — now partially mapped:
+ one planned task per failure model, one spare pool and one resource pool
+ per block, phase durations and block cut/linked rules. Inspections, extra
+ costs, repair-shop recycling and capacity/load rules remain lossy.
+* **capacity / dependencies / standby / link switching** — AWB has features
+ in these areas, but this converter does not populate them, so the AWB run
+ is a reduced model.
* **rates/formulas/costs** — metadata or cost data; availability is still
driven by the same numbers, but the conversion is lossy.
* **FinaleShow1** — a fault-tree/event model with no RBD blocks; AWB RBD
@@ -124,9 +140,10 @@ a *reduced* model, so a difference could not be attributed to the engine.
For the part of the model AWB and RAPTOR both represent, the two engines
agree on these examples within Monte Carlo error. The larger question for
-the other examples is feature coverage, not engine disagreement: the AWB
-converter deliberately refuses to invent capacity networks, PM schedules,
-spares, dependencies or phase rules it cannot populate faithfully.
+the other examples is feature coverage, not engine disagreement. The
+Stage 1 mappings now carry PM, spares, labour and phase rules; capacity,
+consequences, RCM/fault trees and exact cost models remain outside the
+converter.
The full mapping and feature matrix are in
[`AWB_FORMAT.md`](AWB_FORMAT.md).
diff --git a/docs/manual.adoc b/docs/manual.adoc
index 3e973747..fd4b88cd 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1684,9 +1684,14 @@ In short:
|Exponential, Weibull, lognormal, normal and fixed failure laws |yes |yes
|Corrective repair duration, project lifetime and trial count |yes |yes
|Failure events |not exported (AWB RBDs use blocks) |n/a
-|RAPTOR annotations, rates, formulas, triggers |not exported |n/a
-|Mission phases, out-of-service rules, dependencies |not exported |not imported
-|PM/inspection tasks, spare holdings, labour/equipment |not exported |not imported
+|Text annotations |yes (AWB labels) |yes (RAPTOR annotations)
+|Shape annotations, rates, formulas, triggers |not exported |n/a
+|Mission phases |partial: durations and block cut/linked rules |partial: durations and cut/linked rules; node/hierarchy and capacity/load rules are not imported
+|Out-of-service states |yes: applied to the AWB copy |yes: AWB global logic state becomes a RAPTOR cut/linked state
+|Block dependencies |not exported |partial: AWB state dependencies become 100% idle dependencies
+|Preventive maintenance |partial: one planned task per failure model |partial: first enabled planned task; inspections and extra tasks are not imported
+|Spare holdings |partial: level-1 stock and lead time |partial: level 1 + 2 become one pool; repair shop is not imported
+|Labour/equipment resources |partial: resource pools and task links |partial: labour/equipment become RAPTOR resources; call-out delay is not imported
|Capacity products and capacity targets |not exported |not imported
|Consequence and cost models |not exported |not imported
|RCM location hierarchy, fault trees, Weibull sets, bitmaps |n/a |not imported
diff --git a/docs/manual.html b/docs/manual.html
index 2dcbf415..25c0be5f 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2487,19 +2487,44 @@ Availability Workbench interchange
n/a |
-RAPTOR annotations, rates, formulas, triggers |
+Text annotations |
+yes (AWB labels) |
+yes (RAPTOR annotations) |
+
+
+Shape annotations, rates, formulas, triggers |
not exported |
n/a |
-Mission phases, out-of-service rules, dependencies |
-not exported |
-not imported |
+Mission phases |
+partial: durations and block cut/linked rules |
+partial: durations and cut/linked rules; node/hierarchy and capacity/load rules are not imported |
-PM/inspection tasks, spare holdings, labour/equipment |
+Out-of-service states |
+yes: applied to the AWB copy |
+yes: AWB global logic state becomes a RAPTOR cut/linked state |
+
+
+Block dependencies |
not exported |
-not imported |
+partial: AWB state dependencies become 100% idle dependencies |
+
+
+Preventive maintenance |
+partial: one planned task per failure model |
+partial: first enabled planned task; inspections and extra tasks are not imported |
+
+
+Spare holdings |
+partial: level-1 stock and lead time |
+partial: level 1 + 2 become one pool; repair shop is not imported |
+
+
+Labour/equipment resources |
+partial: resource pools and task links |
+partial: labour/equipment become RAPTOR resources; call-out delay is not imported |
Capacity products and capacity targets |
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index e1b9d759..57bb93ef 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -191,7 +191,11 @@ def _load_schema() -> tuple[dict[str, list[tuple[str, int]]], dict[str, dict]]:
#: The six tables a minimal AWB RBD project needs. AWB adds the other
#: tables its modules use when it opens the project (verified with AWB 5.0).
AWB_TABLES = ("Project", "FailureModels", "FailureModelCorrectiveTasks",
- "RbdBlocks", "RbdNodes", "RbdConnections")
+ "RbdBlocks", "RbdNodes", "RbdConnections",
+ "FailureModelScheduledTasks", "FailureModelSchedTaskLabor",
+ "FailureModelSchedTaskSpares", "FailureModelCorrTaskLabor",
+ "FailureModelCorrTaskSpares", "Spares", "Labor", "Phases",
+ "RbdBlockRuleAssignments", "RbdLabels")
def _default_for_type(kind: int) -> Any:
@@ -531,6 +535,21 @@ def export_awb(rbd: RbdFile, path: str | Path, *, # noqa: C901, PLR0912, PLR091
dest = str(path)
report = AwbReport("rbds-to-awb", src, dest)
+ # RAPTOR's out-of-service what-if is ordinary effective model data: a cut
+ # block starts failed with no repair, a linked block never fails. Apply
+ # it to a copy so the AWB run sees the same view as a RAPTOR run.
+ from raptor.core.fileio.out_of_service import apply as oos_apply
+ from raptor.core.fileio.out_of_service import effective as oos_effective
+ from raptor.core.fileio.out_of_service import states as oos_states
+ oos_block_states: dict[int, str] = {}
+ if oos_states(rbd):
+ oos_block_states, _events = oos_effective(rbd)
+ rbd = oos_apply(rbd)
+ rbd.out_of_service = {}
+ report.notes.append(
+ "out-of-service what-if applied to the AWB copy: cut elements "
+ "start failed, linked elements never fail")
+
units = _model_units(rbd)
factor = _hours_factor(units)
if units.lower() != "hours":
@@ -686,6 +705,7 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
block_rows: list[dict[str, Any]] = []
block_index: dict[str, int] = {}
block_page: dict[str, int] = {}
+ fm_index_for_block: dict[str, int] = {}
root = _row("RbdBlocks", Id="1", Description=_text(rbd.file_name, "RAPTOR model"),
Super=1, Page=-1, FailureModel=-1, Consequence=-1, Bom=-1,
Bitmap=-1, XPosition=0.0, YPosition=0.0, Width=100.0,
@@ -716,6 +736,7 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
parent = _text(b.get("ParentId"), "0")
page = page_for_parent(parent)
fm_i = failure_model(b)
+ fm_index_for_block[bid] = fm_i
idx = len(block_rows)
block_index[bid] = idx
block_page[bid] = page
@@ -729,7 +750,9 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
NonMaintainable=nonmaint, NonOperational=0,
IncludeInSystemPlot=1, MaxCapacity=0.0, MaxCapacity2=0.0, MaxCapacity3=0.0,
MaxCapacity4=0.0, LoadFactor=1.0,
- LogicMode=0, StandbyMode=0))
+ LogicMode=(1 if oos_block_states.get(_int(b.get("ID"))) == "cut"
+ else 2 if oos_block_states.get(_int(b.get("ID"))) == "linked"
+ else 0), StandbyMode=0))
# AWB nodes: vote count carries RAPTOR's k-of-n requirement. AWB has
# no separate marker types, so start/end/in/out all become ordinary nodes.
@@ -807,6 +830,252 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
InputObjectIndex=findex, OutputObjectType=tobj,
OutputObjectIndex=tindex, Guid=_guid()))
+ # ---- preventive maintenance, spares, resources, phases and labels ----
+ # Each block's PM is one AWB scheduled task on its failure model. RAPTOR
+ # has one PM per block; AWB allows several tasks per failure model, but
+ # this first mapping keeps the common case exact and names the rest.
+ scheduled_rows: list[dict[str, Any]] = []
+ sched_labor_rows: list[dict[str, Any]] = []
+ sched_spare_rows: list[dict[str, Any]] = []
+ pm_task_by_fm: dict[int, int] = {}
+ pm_duration_by_fm: dict[int, float] = {}
+ pm_sub_by_fm: dict[int, int] = {}
+ pm_lossy = 0
+ for b in blocks:
+ if not _int(b.get("usesPM"), 0):
+ continue
+ bid = _text(b.get("ID"))
+ fm_idx = fm_index_for_block.get(bid)
+ if fm_idx is None:
+ continue
+ if fm_idx in pm_task_by_fm:
+ pm_lossy += 1
+ continue
+ pm_freq = _num(b.get("PMFreq"), 100.0)
+ if pm_freq <= 0:
+ pm_lossy += 1
+ continue
+ pm_dist = _int(b.get("Dist"), _R_FIXED)
+ pm_params = [_num(b.get("Param1#3"), 0.0),
+ _num(b.get("Param2#3"), 0.0),
+ _num(b.get("Param3#3"), 0.0)]
+ if pm_dist == _R_FIXED:
+ pm_duration = pm_params[0]
+ else:
+ mean = _dist_mean(pm_dist, pm_params)
+ pm_duration = mean if mean is not None else pm_params[0]
+ pm_lossy += 1
+ sub = len([r for r in scheduled_rows if _int(r.get("FailureModel")) == fm_idx])
+ pm_sub_by_fm[fm_idx] = sub
+ pm_task_by_fm[fm_idx] = sub
+ pm_duration_by_fm[fm_idx] = max(0.0, pm_duration) * factor
+ task_id = _unique(f"PM{fm_idx + 1}", used_ids)
+ scheduled_rows.append(_row(
+ "FailureModelScheduledTasks", FailureModel=fm_idx, SubIndex=sub,
+ Type=0, Description=_text(b.get("blockName"), f"PM for {bid}"),
+ TaskId=task_id, Enabled=1, OperationNumber="", Baseline="",
+ TaskTrigger="", Mandatory=0,
+ AgeReductionFactor=1.0 if _int(b.get("PMRefresh"), 0) else 0.0,
+ AgeReductionMode=0, Std=0.0, Eta=24.0, Beta=2.0, Gamma=0.0,
+ WeibullSet=-1, Distribution=2, OperationalCost=0.0,
+ TaskGroup=-1, SecondaryActionTask=1,
+ TaskDuration=pm_duration_by_fm[fm_idx], RampTime=0.0,
+ TaskInterval=pm_freq * factor, FixedInterval=0, Offset=0.0,
+ MinimumAge=0.0, OutedDuringMaintenance=1, PfInterval=0.0,
+ PfStd=0.0, DetectionP=1.0, PfDistribution=0,
+ OptimizationInitialInterval=730.0,
+ OptimizationIntervalIncrement=730.0,
+ OptimizationNumberIntervals=30,
+ OptimizationCostPointIndex=-1, OptimizationQPointIndex=0.0,
+ OptimizationCostBenefit=0.0, OptimizationCbr=1.0,
+ OptimizationQBenefit=0.0, OptimizationQbr=1.0))
+
+ # Spares: RAPTOR's spare pool is AWB's level-1 stock. Level-2 is not
+ # populated; a stock-out waits the RAPTOR emergency time as AWB's
+ # level-3 lead time.
+ spare_rows: list[dict[str, Any]] = []
+ spare_index: dict[str, int] = {}
+ corr_spare_rows: list[dict[str, Any]] = []
+ custom_spare_count = 0
+
+ def add_spare(name: str, description: str, stock: int, new_spares: int,
+ arrive: float, emer: float, cost: float) -> int:
+ key = name
+ if key in spare_index:
+ return spare_index[key]
+ idx = len(spare_rows)
+ spare_index[key] = idx
+ spare_rows.append(_row(
+ "Spares", Id=_unique(name, used_ids), Description=description,
+ Type=-1, UnitCost=max(0.0, cost), CapacityLevel1=max(0, stock),
+ CapacityLevel2=0, LogisticDelayLevel1=0.0,
+ LogisticDelayLevel2=max(0.0, arrive),
+ LogisticDelayLevel3=max(0.0, emer),
+ MinimumReorderQuantity=max(1, new_spares), Guid=_guid()))
+ return idx
+
+ for pool in _section_list(rbd, "SPARE_POOL_DATA"):
+ add_spare(_text(pool.get("PoolName"), "Spare"),
+ _text(pool.get("PoolName"), "Spare"),
+ _int(pool.get("Stock"), 0), _int(pool.get("NewSp"), 1),
+ _num(pool.get("ArriveEvery"), 720.0) * factor,
+ _num(pool.get("EmerTime"), 24.0) * factor,
+ _num(pool.get("SpCost"), 1.0))
+
+ for b in blocks:
+ bid = _text(b.get("ID"))
+ fm_idx = fm_index_for_block.get(bid)
+ if fm_idx is None:
+ continue
+ sp_type = _text(b.get("SpType"), "Infinite")
+ if sp_type in ("", "None", "Infinite"):
+ continue
+ if sp_type == "Pooled":
+ pool_name = _text(b.get("SparePoolName"))
+ if pool_name not in spare_index:
+ report.warnings.append(
+ f"block {bid} draws on spare pool {pool_name!r}, which "
+ "is not in the model; no AWB spare was written")
+ continue
+ spare_i = spare_index[pool_name]
+ else:
+ # Custom: one AWB spare per block, named after the block.
+ custom_spare_count += 1
+ spare_i = add_spare(
+ f"{bid}_Spare", f"Spares held for {bid}",
+ _int(b.get("Stock"), 0), _int(b.get("NewSp"), 1),
+ _num(b.get("ArriveEvery"), 720.0) * factor,
+ _num(b.get("EmerTime"), 24.0) * factor,
+ _num(b.get("SpCost"), 1.0))
+ qty = max(1, _int(b.get("Quan"), 1))
+ corr_spare_rows.append(_row(
+ "FailureModelCorrTaskSpares", FailureModel=fm_idx, SubIndex=0,
+ Spare=spare_i, Quantity=qty, ExternalReference=""))
+ if _int(b.get("PMSpare"), 0) and fm_idx in pm_sub_by_fm:
+ sched_spare_rows.append(_row(
+ "FailureModelSchedTaskSpares", FailureModel=fm_idx,
+ SubIndex=pm_sub_by_fm[fm_idx], SecondarySubIndex=0,
+ Spare=spare_i, Quantity=1, ExternalReference=""))
+
+ # Resources: RAPTOR has one generic resource pool per block repair/PM.
+ # AWB's nearest equivalent is a labour category; it is created for every
+ # RAPTOR resource and linked to the corrective and scheduled tasks.
+ labor_rows: list[dict[str, Any]] = []
+ labor_index: dict[str, int] = {}
+ corr_labor_rows: list[dict[str, Any]] = []
+ for res in _section_list(rbd, "RESOURCE_DATA"):
+ name = _text(res.get("PoolName"), "Resource")
+ idx = len(labor_rows)
+ labor_index[name] = idx
+ labor_rows.append(_row(
+ "Labor", Id=_unique(name, used_ids), Description=name, Type=-1,
+ CostRate=max(0.0, _num(res.get("PerTimeUnit"), 1.0)),
+ CorrectiveCalloutCost=max(0.0, _num(res.get("FixedPerUse"), 1.0)),
+ ScheduledCalloutCost=max(0.0, _num(res.get("FixedPerUse"), 1.0)),
+ CorrectiveLogisticDelay=0.0,
+ NoAvailable=max(1, _int(res.get("NumIn"), 1)), Guid=_guid()))
+ for b in blocks:
+ bid = _text(b.get("ID"))
+ fm_idx = fm_index_for_block.get(bid)
+ if fm_idx is None or _int(b.get("NumRes"), 0) <= 0:
+ continue
+ name = _text(b.get("Resource1Name"), "None")
+ if name not in labor_index:
+ report.warnings.append(
+ f"block {bid} uses resource {name!r}, which is not in the "
+ "model; no AWB labour row was written")
+ continue
+ task_duration = float(task_rows[fm_idx].get("TaskDuration", 0.0))
+ qty = max(1, _int(b.get("#Res1Rep"), 1))
+ corr_labor_rows.append(_row(
+ "FailureModelCorrTaskLabor", FailureModel=fm_idx, SubIndex=0,
+ Labor=labor_index[name], ActiveTime=task_duration,
+ SetToTaskDuration=0, Quantity=qty, ExternalReference=""))
+ if _int(b.get("usesPM"), 0) and fm_idx in pm_sub_by_fm:
+ sched_labor_rows.append(_row(
+ "FailureModelSchedTaskLabor", FailureModel=fm_idx,
+ SubIndex=pm_sub_by_fm[fm_idx], SecondarySubIndex=0,
+ Labor=labor_index[name],
+ ActiveTime=pm_duration_by_fm.get(fm_idx, 0.0),
+ SetToTaskDuration=0,
+ Quantity=max(1, _int(b.get("#Res1pmRep"), 1)),
+ ExternalReference=""))
+
+ # Phases: durations transfer; per-block AWB rules are reproduced for the
+ # Active/Cut/Linked status RAPTOR stores in its phase columns.
+ phase_rows: list[dict[str, Any]] = []
+ phase_index_by_num: dict[int, int] = {}
+ for p in _section_list(rbd, "PHASES"):
+ num = _int(p.get("Num"), len(phase_rows) + 1)
+ dist = _int(p.get("Dist"), _R_FIXED)
+ params = [_num(p.get("Param1")), _num(p.get("Param2")),
+ _num(p.get("Param3"))]
+ if dist == _R_FIXED:
+ duration = params[0]
+ else:
+ mean = _dist_mean(dist, params)
+ duration = mean if mean is not None else params[0]
+ report.notes.append(
+ f"phase {_text(p.get('PhaseName'), str(num))} had a "
+ f"{_raptor_dist_name(dist)} duration; AWB uses its mean")
+ phase_index_by_num[num] = len(phase_rows)
+ phase_rows.append(_row(
+ "Phases", Id=_unique(_text(p.get("PhaseName"), f"Phase {num}"),
+ used_ids),
+ Description=_text(p.get("PhaseName"), f"Phase {num}"),
+ PhaseGroup=-1, Duration=max(0.0, duration) * factor,
+ Guid=_guid()))
+
+ rule_rows: list[dict[str, Any]] = []
+ rule_count_by_block: dict[int, int] = {}
+ for b in blocks:
+ if not _int(b.get("Phasing"), 0):
+ continue
+ bid = _text(b.get("ID"))
+ block_i = block_index.get(bid)
+ if block_i is None:
+ continue
+ for num, phase_i in phase_index_by_num.items():
+ token = _text(b.get(f"P {num:03d}"))
+ if not token or ":" not in token:
+ continue
+ kind = token.split(":", 1)[0].strip().upper()
+ if kind not in ("C", "L"):
+ continue
+ sub = rule_count_by_block.get(block_i, 0)
+ rule_count_by_block[block_i] = sub + 1
+ rule_rows.append(_row(
+ "RbdBlockRuleAssignments", Block=block_i, SubIndex=sub,
+ Type=1,
+ Description=(f"Phase {phase_rows[phase_i]['Id']}: "
+ + ("Cut" if kind == "C" else "Linked")),
+ Phase=phase_i,
+ LogicMode=1 if kind == "C" else 2, StandbyMode=0,
+ LoadFactor=1.0, MaxCapacity=0.0, DependentBlock=-1,
+ OutOfService=1 if kind == "C" else 0))
+
+ # Text annotations become AWB labels. Rectangles, ellipses and arrows
+ # have no RbdLabels equivalent and stay in the report.
+ label_rows: list[dict[str, Any]] = []
+ labels_skipped = 0
+ for ann in (getattr(rbd, "annotations", None) or []):
+ if _text(ann.get("kind"), "text") != "text":
+ labels_skipped += 1
+ continue
+ parent_num = _int(ann.get("parent"), 0)
+ page = page_for_parent(str(parent_num))
+ label_rows.append(_row(
+ "RbdLabels", Id=_unique(f"Label{len(label_rows) + 1}", used_ids),
+ Type=0, Page=page,
+ XPosition=_num(ann.get("x")), YPosition=_num(ann.get("y")),
+ Width=max(10.0, _num(ann.get("w"), 100.0)),
+ Height=max(10.0, _num(ann.get("h"), 20.0)),
+ LabelText=_text(ann.get("text")), Alignment=1,
+ FontName=_text(ann.get("font_family"), "Arial"),
+ FontSize=max(6.0, _num(ann.get("font_size"), 10.0)),
+ FontStyle=0, FontColor=-16777216, Border=0, BitmapOn=0,
+ Bitmap=-1, BackgroundColor=-1, Guid=_guid()))
+
# ---- project ----------------------------------------------------------
lifetime, time_terminated = _model_lifetime_hours(rbd)
trials = _model_trials(rbd)
@@ -823,7 +1092,7 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
AvsimEquateCapacityValue3=1.0, AvsimEquateCapacityUnit4="",
AvsimEquateCapacityValue4=1.0,
WeibullCurrentWeibullSet=-1, ProcessCurrentProcessSet=-1,
- ALTCurrentALTSet=-1, Guid=_guid())
+ ALTCurrentALTSet=-1, IncludeInitialSpares=1, Guid=_guid())
tables: dict[str, AwbTable] = {
"Project": AwbTable("Project", _SCHEMA["Project"], [project]),
@@ -836,6 +1105,21 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
"RbdConnections": AwbTable("RbdConnections", _SCHEMA["RbdConnections"],
conn_rows),
}
+ # Optional tables are written only when they carry data, so a plain RBD
+ # project stays the same small six-table file AWB already accepts.
+ for name, rows in (
+ ("FailureModelScheduledTasks", scheduled_rows),
+ ("FailureModelSchedTaskLabor", sched_labor_rows),
+ ("FailureModelSchedTaskSpares", sched_spare_rows),
+ ("FailureModelCorrTaskLabor", corr_labor_rows),
+ ("FailureModelCorrTaskSpares", corr_spare_rows),
+ ("Spares", spare_rows),
+ ("Labor", labor_rows),
+ ("Phases", phase_rows),
+ ("RbdBlockRuleAssignments", rule_rows),
+ ("RbdLabels", label_rows)):
+ if rows:
+ tables[name] = AwbTable(name, _SCHEMA[name], rows)
if write:
write_awb(dest, tables)
@@ -866,6 +1150,29 @@ def failure_model(block: dict[str, Any]) -> int: # noqa: C901, PLR0912, PLR0915
"exported with a fixed time of 9e8 hours (never fails)")
_report_raptor_features(rbd, report, blocks, nodes, links, events,
hierarchies, units, factor)
+ if pm_lossy:
+ report.add("additional or non-fixed PM", pm_lossy,
+ "one fixed-duration PM per failure model is written; "
+ "extra tasks and random PM durations are simplified")
+ if custom_spare_count:
+ report.notes.append(
+ f"{custom_spare_count} block-owned spare stock(s) became "
+ "per-block AWB spare rows")
+ if spare_rows:
+ report.notes.append(
+ f"{len(spare_rows)} spare row(s), {len(corr_spare_rows)} "
+ "corrective spare link(s) exported")
+ if labor_rows:
+ report.notes.append(
+ f"{len(labor_rows)} labour row(s), {len(corr_labor_rows)} "
+ "corrective resource link(s) exported")
+ if phase_rows:
+ report.notes.append(
+ f"{len(phase_rows)} phase(s) and {len(rule_rows)} block phase "
+ "rule(s) exported")
+ if labels_skipped:
+ report.add("non-text annotations", labels_skipped,
+ "only text annotations become AWB labels")
return report
@@ -881,8 +1188,12 @@ def _report_raptor_features(rbd: RbdFile, report: AwbReport, # noqa: C901, PLR0
report.add("failure events", len(events),
"AWB RBDs use blocks; events are not exported")
if getattr(rbd, "annotations", None):
- report.add("diagram annotations", len(rbd.annotations),
- "text boxes, rectangles and arrows are not exported")
+ shapes = sum(1 for a in rbd.annotations
+ if _text(a.get("kind"), "text") != "text")
+ if shapes:
+ report.add("non-text annotations", shapes,
+ "text annotations become AWB labels; rectangles, "
+ "ellipses and arrows have no AWB equivalent")
if getattr(rbd, "rates", None):
report.add("rate definitions", len(rbd.rates),
"values are exported as plain numbers")
@@ -893,21 +1204,6 @@ def _report_raptor_features(rbd: RbdFile, report: AwbReport, # noqa: C901, PLR0
report.add("triggers", max(len(getattr(rbd, "triggers", []) or []),
_section_rows(rbd.sections, "TRIGGERS")),
"AWB has no equivalent of RAPTOR's trigger logic")
- if getattr(rbd, "spare_pools", None) or _section_rows(rbd.sections, "SPARE_POOL_DATA"):
- report.add("spare pools", max(len(getattr(rbd, "spare_pools", []) or []),
- _section_rows(rbd.sections, "SPARE_POOL_DATA")),
- "AWB spares are not linked to blocks by this export")
- if getattr(rbd, "resources", None) or _section_rows(rbd.sections, "RESOURCE_DATA"):
- report.add("resource pools", max(len(getattr(rbd, "resources", []) or []),
- _section_rows(rbd.sections, "RESOURCE_DATA")),
- "AWB labour and equipment resources are not populated")
- phases = _section_rows(rbd.sections, "PHASES")
- if phases:
- report.add("mission phases", phases,
- "AWB phase rules are not populated")
- if getattr(rbd, "out_of_service", None):
- report.add("out-of-service elements", len(rbd.out_of_service),
- "AWB's OutOfService rules are not populated")
analyses = [str(a).lower() for a in
((getattr(rbd, "experiment", None) or {}).get("analyses") or [])]
capacity = _text(_system_row(rbd).get("capacityAnalysis"))
@@ -921,16 +1217,12 @@ def _report_raptor_features(rbd: RbdFile, report: AwbReport, # noqa: C901, PLR0
if dep:
report.add("block dependencies", dep,
"AWB dependency rules are not populated")
- pm = sum(1 for b in blocks if _int(b.get("usesPM"), 0))
- if pm:
- report.add("preventive maintenance", pm,
- "AWB scheduled tasks are not populated")
- phasing = sum(1 for b in blocks if _int(b.get("Phasing"), 0))
- phasing += sum(1 for n in nodes if _int(n.get("Phases"), 0))
+ phasing = sum(1 for n in nodes if _int(n.get("Phases"), 0))
phasing += sum(1 for h in hierarchies if _int(h.get("Phs"), 0))
if phasing:
- report.add("phased element schedules", phasing,
- "per-element phase status is not exported")
+ report.add("node and hierarchy phase schedules", phasing,
+ "block phase rules are exported; node and hierarchy "
+ "phase schedules are not")
aged = sum(1 for b in blocks
if _num(b.get("_DutyCycle"), 1.0) != 1.0
or _num(b.get("_StartAge"), 0.0) != 0.0
@@ -1022,6 +1314,16 @@ def import_awb(path: str | Path, *, # noqa: C901, PLR0912, PLR0915
tasks = _rows(tables, "FailureModelCorrectiveTasks")
repeats = _rows(tables, "RbdRepeatBlocks")
labels = _rows(tables, "RbdLabels")
+ sched_tasks = _rows(tables, "FailureModelScheduledTasks")
+ corr_labor = _rows(tables, "FailureModelCorrTaskLabor")
+ sched_labor = _rows(tables, "FailureModelSchedTaskLabor")
+ corr_spares = _rows(tables, "FailureModelCorrTaskSpares")
+ sched_spares = _rows(tables, "FailureModelSchedTaskSpares")
+ spare_rows = _rows(tables, "Spares")
+ labor_rows = _rows(tables, "Labor")
+ equipment_rows = _rows(tables, "Equipment")
+ phase_rows = _rows(tables, "Phases")
+ rule_rows = _rows(tables, "RbdBlockRuleAssignments")
# AWB page index: 0 is the top level; a superblock's row index owns the
# page its contents are drawn on. Row 0 is the project root (Page -1).
@@ -1065,6 +1367,138 @@ def node_name(text: str) -> str:
base = _safe_id(text, 20)
return _unique(base, used_node_names, 20)
+ # ---- phase, spare, PM and resource side tables ------------------------
+ # RAPTOR has one PM per block, one resource pool per block repair and one
+ # spare pool per block. AWB may have several tasks/resources per failure
+ # model; this maps the first and names the rest in the report.
+ def task_law(task: dict[str, Any]) -> tuple[int, list[float]]:
+ dist = _int(task.get("Distribution"), 2)
+ duration = max(0.0, _num(task.get("TaskDuration"))
+ + _num(task.get("RampTime")))
+ std = max(0.0, _num(task.get("Std")))
+ if dist == 0:
+ return _R_EXPO, [max(1e-9, duration), 0.0, 0.0]
+ if dist == 1:
+ return _R_LOGNORM, [max(1e-9, duration), std, 0.0]
+ if dist == 3:
+ return _R_WEIBULL, [max(1e-9, _num(task.get("Beta"), 2.0)),
+ max(1e-9, duration),
+ max(0.0, _num(task.get("Gamma")))]
+ if std > 0:
+ return _R_NORM, [max(1e-9, duration), std, 0.0]
+ return _R_FIXED, [max(0.0, duration), 0.0, 0.0]
+
+ phase_doc: list[dict[str, Any]] = []
+ phase_number: dict[int, int] = {}
+ for i, p in enumerate(phase_rows):
+ phase_doc.append({
+ "name": _safe_id(_text(p.get("Id"), f"Phase{i + 1}"), 20),
+ "num": i + 1, "mission": 1,
+ "duration_dist": _R_FIXED,
+ "params": [max(0.0, _num(p.get("Duration"), 1.0)), 0.0, 0.0],
+ })
+ phase_number[i] = i + 1
+ group_ids = {_int(p.get("PhaseGroup"), -1) for p in phase_rows}
+ if len(group_ids) > 1:
+ report.notes.append(
+ f"{len(group_ids)} AWB phase groups flattened into one RAPTOR "
+ "phase sequence")
+
+ spare_doc: list[dict[str, Any]] = []
+ spare_name: dict[int, str] = {}
+ used_spares: set[str] = set()
+ for i, sp in enumerate(spare_rows):
+ name = _unique(_safe_id(_text(sp.get("Id"), f"Spare{i + 1}"), 20),
+ used_spares, 20)
+ stock = max(0, _int(sp.get("CapacityLevel1"), 0)
+ + _int(sp.get("CapacityLevel2"), 0))
+ arrive = max(1.0, _num(sp.get("LogisticDelayLevel2"), 0.0)
+ or _num(sp.get("LogisticDelayLevel3"), 24.0))
+ emer = max(1.0, _num(sp.get("LogisticDelayLevel3"), arrive))
+ spare_doc.append({
+ "name": name, "stock": stock,
+ "new_spares": max(1, _int(sp.get("MinimumReorderQuantity"), 1)),
+ "arrive_every": arrive, "eso": 1 if stock else 0,
+ "emer_time": emer, "slo": 0, "level": 0, "quantity": 1,
+ "slo_time": 24.0, "rso": 0,
+ "spare_cost": max(0.0, _num(sp.get("UnitCost"), 1.0)),
+ "emer_ship_cost": max(0.0, _num(sp.get("TransportationCostLevel2"), 1.0)),
+ })
+ spare_name[i] = name
+ if any(_int(sp.get("CapacityLevel2"), 0) for sp in spare_rows):
+ report.add("two-level spare holdings", 1,
+ "AWB level-1 and level-2 stock are summed into one "
+ "RAPTOR pool")
+
+ resource_doc: list[dict[str, Any]] = []
+ resource_name: dict[tuple[str, int], str] = {}
+ used_resources: set[str] = set()
+
+ def add_resource(kind: str, i: int, row: dict[str, Any],
+ quantity: int) -> str:
+ name = _unique(_safe_id(_text(row.get("Id"), f"{kind}{i + 1}"), 20),
+ used_resources, 20)
+ resource_doc.append({
+ "name": name, "num_in": max(1, quantity),
+ "spare_cost": max(0.0, _num(row.get("CostRate"), 1.0)),
+ "fixed_per_use": max(0.0, _num(row.get("CorrectiveCalloutCost"), 1.0)),
+ "per_time_unit": max(0.0, _num(row.get("CostRate"), 1.0)),
+ "phases": 0,
+ })
+ resource_name[(kind, i)] = name
+ return name
+
+ for i, row in enumerate(labor_rows):
+ add_resource("labor", i, row, _int(row.get("NoAvailable"), 1))
+ for i, row in enumerate(equipment_rows):
+ add_resource("equipment", i, row,
+ _int(row.get("NoAvailable"), 1))
+ if equipment_rows:
+ report.notes.append(
+ f"{len(equipment_rows)} AWB equipment row(s) imported as RAPTOR "
+ "resource pools, like labour")
+
+ pm_by_fm: dict[int, dict[str, Any]] = {}
+ pm_sub_by_fm: dict[int, int] = {}
+ for t in sched_tasks:
+ if _int(t.get("Type"), 0) != 0 or not _int(t.get("Enabled"), 0):
+ continue
+ fm_i = _int(t.get("FailureModel"), -1)
+ if fm_i < 0 or fm_i in pm_by_fm:
+ continue
+ pm_by_fm[fm_i] = t
+ pm_sub_by_fm[fm_i] = _int(t.get("SubIndex"), 0)
+ if len(pm_by_fm) < len({_int(t.get("FailureModel"), -1)
+ for t in sched_tasks if _int(t.get("Type"), 0) == 0}):
+ report.notes.append(
+ "one RAPTOR PM per block: extra AWB planned tasks, and "
+ "inspection tasks, are not imported")
+
+ corr_spare_by_fm: dict[int, dict[str, Any]] = {}
+ for row in corr_spares:
+ fm_i = _int(row.get("FailureModel"), -1)
+ corr_spare_by_fm.setdefault(fm_i, row)
+ corr_labor_by_fm: dict[int, dict[str, Any]] = {}
+ for row in corr_labor:
+ fm_i = _int(row.get("FailureModel"), -1)
+ corr_labor_by_fm.setdefault(fm_i, row)
+ sched_spare_by_fm: dict[int, dict[str, Any]] = {}
+ for row in sched_spares:
+ fm_i = _int(row.get("FailureModel"), -1)
+ sched_spare_by_fm.setdefault(fm_i, row)
+ sched_labor_by_fm: dict[int, dict[str, Any]] = {}
+ for row in sched_labor:
+ fm_i = _int(row.get("FailureModel"), -1)
+ sched_labor_by_fm.setdefault(fm_i, row)
+
+ rules_by_block: dict[int, list[dict[str, Any]]] = {}
+ for row in rule_rows:
+ if _int(row.get("Type"), 0) != 1:
+ continue
+ rules_by_block.setdefault(_int(row.get("Block"), -1), []).append(row)
+
+ out_of_service_doc: dict[str, str] = {}
+
# ---- hierarchies first (parents before children) ----------------------
# AWB's page owner is the superblock's row index; the hierarchy tree is
# implicit in the Page column. Emit a hierarchy per superblock row, then
@@ -1092,6 +1526,7 @@ def node_name(text: str) -> str:
# ---- ordinary blocks --------------------------------------------------
block_losses: dict[str, int] = {}
+ block_by_row: dict[int, dict[str, Any]] = {}
for i, b in enumerate(blocks):
if i == root_i or i in super_rows:
continue
@@ -1108,11 +1543,79 @@ def node_name(text: str) -> str:
b, fms, tasks, block_losses)
x, y = _num(b.get("XPosition")), _num(b.get("YPosition"))
x_by_page.setdefault(page, []).append(x)
- elements["blocks"].append({
+ block = {
"id": bid, "name": name, "parent": parent, "x": x, "y": y,
"fail_dist": fdist, "fail_params": fparams,
"repair_dist": rdist, "repair_params": rparams,
- })
+ }
+ fm_i = _int(b.get("FailureModel"), -1)
+ pm = pm_by_fm.get(fm_i)
+ if pm is not None:
+ pm_dist, pm_params = task_law(pm)
+ pm_freq = max(1.0, _num(pm.get("TaskInterval"), 100.0))
+ if pm_freq > 1e9:
+ report.add("very long PM intervals", 1,
+ "an AWB PM interval above 1e9 hours was capped")
+ pm_freq = 1e9
+ block.update({
+ "uses_pm": True, "pm_freq": pm_freq,
+ "pm_duration_dist": pm_dist, "pm_params": pm_params,
+ "pm_refresh": _num(pm.get("AgeReductionFactor"), 0.0) >= 0.999,
+ "pm_spare": fm_i in sched_spare_by_fm,
+ })
+ pm_res = sched_labor_by_fm.get(fm_i)
+ if pm_res is not None:
+ kind_i = _int(pm_res.get("Labor"), -1)
+ if ("labor", kind_i) in resource_name:
+ block["pm_resources_needed"] = max(
+ 1, _int(pm_res.get("Quantity"), 1))
+ spare_link = corr_spare_by_fm.get(fm_i)
+ if spare_link is not None:
+ spare_i = _int(spare_link.get("Spare"), -1)
+ if spare_i in spare_name:
+ block.update({
+ "sparing_type": "Pooled",
+ "spare_pool": spare_name[spare_i],
+ "quantity": max(1, _int(spare_link.get("Quantity"), 1)),
+ })
+ res_link = corr_labor_by_fm.get(fm_i)
+ if res_link is not None:
+ kind_i = _int(res_link.get("Labor"), -1)
+ name2 = resource_name.get(("labor", kind_i))
+ if name2:
+ block.update({
+ "num_resources": 1, "resource_name": name2,
+ "repair_resources_needed": max(
+ 1, _int(res_link.get("Quantity"), 1)),
+ })
+ rules = rules_by_block.get(i)
+ if rules and phase_doc:
+ legacy_obj = block.get("legacy")
+ if not isinstance(legacy_obj, dict):
+ legacy_obj = {}
+ block["legacy"] = legacy_obj
+ block["uses_phasing"] = True
+ for phase_seq in range(1, len(phase_doc) + 1):
+ legacy_obj[f"P {phase_seq:03d}"] = "A: 1.000"
+ for rule in rules:
+ pidx = _int(rule.get("Phase"), 0)
+ phase_no = phase_number.get(pidx)
+ if phase_no is None:
+ continue
+ logic = _int(rule.get("LogicMode"), 0)
+ if logic == 1 or _int(rule.get("OutOfService"), 0):
+ legacy_obj[f"P {phase_no:03d}"] = "C: 1.000"
+ elif logic == 2:
+ legacy_obj[f"P {phase_no:03d}"] = "L: 0.000"
+ logic = _int(b.get("LogicMode"), 0)
+ if logic == 1:
+ out_of_service_doc[f"block:{bid}"] = "cut"
+ elif logic == 2:
+ out_of_service_doc[f"block:{bid}"] = "linked"
+ elif _int(b.get("NonOperational"), 0):
+ out_of_service_doc[f"block:{bid}"] = "cut"
+ elements["blocks"].append(block)
+ block_by_row[i] = block
comments.append({"type": "Block", "id": bid, "name": name,
"text": _comment_text(b)})
for feature, count in sorted(block_losses.items()):
@@ -1127,6 +1630,23 @@ def node_name(text: str) -> str:
"AWB marks the block non-maintainable; RAPTOR repair is off",
}.get(feature, "")
report.add(feature, count, detail)
+ dep_count = 0
+ for row in rule_rows:
+ dep_row = _int(row.get("DependentBlock"), -1)
+ block_row = _int(row.get("Block"), -1)
+ dep_target: dict[str, Any] | None = block_by_row.get(block_row)
+ dep_id = block_id.get(dep_row)
+ if dep_target is not None and dep_id is not None:
+ dep_target.update({
+ "dep_type": "RBDBlock", "dep_num": dep_id,
+ "dep_nothing": 0.0, "dep_idle": 100.0,
+ "dep_pm": 0.0, "dep_fail": 0.0,
+ })
+ dep_count += 1
+ if dep_count:
+ report.notes.append(
+ f"{dep_count} AWB state dependency rule(s) imported as "
+ "100% idle dependencies")
# ---- repeat blocks ----------------------------------------------------
for i, r in enumerate(repeats):
@@ -1368,7 +1888,29 @@ def add_junction(owner: int, name: str, x: float, y: float) -> int:
nodes=len(elements["nodes"]),
hierarchies=len(elements["hierarchies"]),
links=len(links), failure_models=len(fms),
- repeats=len(repeats), labels=len(annotations))
+ repeats=len(repeats), labels=len(annotations),
+ pm_tasks=len(pm_by_fm), spares=len(spare_doc),
+ resources=len(resource_doc), phases=len(phase_doc),
+ out_of_service=len(out_of_service_doc))
+ if pm_by_fm:
+ report.notes.append(
+ f"{len(pm_by_fm)} AWB planned task(s) imported as RAPTOR PM")
+ if spare_doc:
+ report.notes.append(
+ f"{len(spare_doc)} AWB spare(s) imported as RAPTOR spare pools")
+ if resource_doc:
+ report.notes.append(
+ f"{len(resource_doc)} AWB labour/equipment row(s) imported as "
+ "RAPTOR resource pools")
+ if phase_doc:
+ rule_uses = sum(1 for b in elements["blocks"] if b.get("uses_phasing"))
+ report.notes.append(
+ f"{len(phase_doc)} AWB phase(s) imported; {rule_uses} block(s) "
+ "carry phase cut/linked rules")
+ if out_of_service_doc:
+ report.notes.append(
+ f"{len(out_of_service_doc)} AWB global logic/out-of-service "
+ "state(s) imported as RAPTOR out-of-service")
if annotations:
report.notes.append(
f"{len(annotations)} AWB label(s) imported as RAPTOR annotations")
@@ -1394,6 +1936,10 @@ def add_junction(owner: int, name: str, x: float, y: float) -> int:
"links": links,
"annotations": annotations,
"comments": comments,
+ "spare_pools": spare_doc,
+ "resources": resource_doc,
+ "phases": phase_doc,
+ "out_of_service": out_of_service_doc,
}
from raptor.core.fileio.rbds import parse_rbds
rbd = parse_rbds(json.dumps(doc), default_name=Path(src).stem)
@@ -1497,7 +2043,7 @@ def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901,
duration = max(0.0, _num(task.get("TaskDuration")) + _num(task.get("RampTime")))
tdist = _int(task.get("Distribution"), 2)
std = max(0.0, _num(task.get("Std")))
- if _int(block.get("NonMaintainable"), 0):
+ if _int(block.get("NonMaintainable"), 0) and _int(block.get("LogicMode"), 0) != 1:
losses["non-maintainable blocks"] = (
losses.get("non-maintainable blocks", 0) + 1)
return fdist, fparams, _R_NONE, [1.0, 0.0, 0.0]
@@ -1534,24 +2080,45 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
report.add("consequence and cost models", len(_rows(tables, "Consequences")),
"AWB financial/safety/environmental consequences are not "
"modelled by RAPTOR")
- if _rows(tables, "Phases") or _rows(tables, "RbdBlockRuleAssignments"):
- report.add("mission phases and phase rules",
- max(len(_rows(tables, "Phases")),
- len(_rows(tables, "RbdBlockRuleAssignments"))),
- "AWB phase schedules and rules are not imported")
- if _rows(tables, "FailureModelScheduledTasks"):
- report.add("planned maintenance tasks",
- len(_rows(tables, "FailureModelScheduledTasks")),
- "AWB scheduled/inspection tasks are not imported")
- if _rows(tables, "Spares") or _rows(tables, "FailureModelCorrTaskSpares"):
- report.add("spares and sparing rules",
- max(len(_rows(tables, "Spares")),
- len(_rows(tables, "FailureModelCorrTaskSpares"))),
- "AWB spare holdings and logistics are not imported")
- if _rows(tables, "Labor") or _rows(tables, "Equipment"):
- report.add("labour and equipment resources",
- max(len(_rows(tables, "Labor")), len(_rows(tables, "Equipment"))),
- "AWB resource pools are not imported")
+ sched = _rows(tables, "FailureModelScheduledTasks")
+ planned = [t for t in sched
+ if _int(t.get("Type"), 0) == 0 and _int(t.get("Enabled"), 0)]
+ fms_with_planned = {_int(t.get("FailureModel"), -1) for t in planned}
+ if len(planned) > len(fms_with_planned):
+ report.add("extra planned-maintenance tasks",
+ len(planned) - len(fms_with_planned),
+ "RAPTOR has one PM per block; only the first planned "
+ "task per failure model is imported")
+ inspections = [t for t in sched
+ if _int(t.get("Type"), 0) == 1 and _int(t.get("Enabled"), 0)]
+ if inspections:
+ report.add("inspection tasks", len(inspections),
+ "AWB inspection tasks are not imported as RAPTOR PM")
+ calendar_pm = [t for t in planned if _int(t.get("FixedInterval"), 0)]
+ if calendar_pm:
+ report.add("calendar-interval PM", len(calendar_pm),
+ "RAPTOR PM is driven by operating time")
+ two_level = sum(1 for sp in _rows(tables, "Spares")
+ if _int(sp.get("CapacityLevel2"), 0))
+ if two_level:
+ report.add("two-level spare holdings", two_level,
+ "AWB level-1 and level-2 stock are summed into one "
+ "RAPTOR pool")
+ repair_shop = sum(1 for sp in _rows(tables, "Spares")
+ if _int(sp.get("RepairLevel"), 0))
+ if repair_shop:
+ report.add("spare repair shop", repair_shop,
+ "AWB spare repair/recycling is not imported")
+ delay = sum(1 for lab in _rows(tables, "Labor")
+ if _num(lab.get("CorrectiveLogisticDelay"), 0.0) > 0)
+ if delay:
+ report.add("labour call-out delay", delay,
+ "AWB labour logistics delay is not imported")
+ capacity_rules = [r for r in _rows(tables, "RbdBlockRuleAssignments")
+ if _int(r.get("Type"), 0) != 1]
+ if capacity_rules:
+ report.add("phase capacity/load rules", len(capacity_rules),
+ "only AWB phase logic/out-of-service rules are imported")
if _rows(tables, "RcmLocations") or _rows(tables, "RcmCauses"):
report.add("RCM location hierarchy", max(
len(_rows(tables, "RcmLocations")), len(_rows(tables, "RcmCauses"))),
@@ -1578,13 +2145,8 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
.get("AvsimCapacityCalcsPerformed"), 0):
report.add("capacity flow and capacity targets", 1,
"AWB capacity products are not imported")
- nonop = sum(1 for b in _rows(tables, "RbdBlocks")
- if _int(b.get("NonOperational"), 0))
- if nonop:
- report.add("non-operational blocks", nonop,
- "AWB non-operational state is not imported")
standby = sum(1 for b in _rows(tables, "RbdBlocks")
- if _int(b.get("StandbyMode"), 0) or _int(b.get("LogicMode"), 0))
+ if _int(b.get("StandbyMode"), 0))
standby += sum(1 for n in _rows(tables, "RbdNodes")
if _int(n.get("LocalStandby"), 0) or _int(n.get("NotLogic"), 0))
if standby:
diff --git a/raptor/core/fileio/awb_tables.json b/raptor/core/fileio/awb_tables.json
index 2de3c156..e085c8c0 100644
--- a/raptor/core/fileio/awb_tables.json
+++ b/raptor/core/fileio/awb_tables.json
@@ -1893,6 +1893,1030 @@
"Guid",
0
]
+ ],
+ "Spares": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "UnitCost",
+ 2
+ ],
+ [
+ "LogisticDelayLevel1",
+ 2
+ ],
+ [
+ "LogisticDelayLevel2",
+ 2
+ ],
+ [
+ "LogisticDelayLevel3",
+ 2
+ ],
+ [
+ "CostRateLevel1",
+ 2
+ ],
+ [
+ "CostRateLevel2",
+ 2
+ ],
+ [
+ "CapacityLevel1",
+ 1
+ ],
+ [
+ "CapacityLevel2",
+ 1
+ ],
+ [
+ "RepairLevel",
+ 1
+ ],
+ [
+ "CostOfRepair",
+ 2
+ ],
+ [
+ "RepairMttr",
+ 2
+ ],
+ [
+ "RepairDiscard",
+ 2
+ ],
+ [
+ "BatchDiscount",
+ 2
+ ],
+ [
+ "MinimumReorderQuantity",
+ 1
+ ],
+ [
+ "Volume",
+ 2
+ ],
+ [
+ "Weight",
+ 2
+ ],
+ [
+ "SourceDistribution",
+ 1
+ ],
+ [
+ "SourceStd",
+ 2
+ ],
+ [
+ "LimitedManufacturingCapacity",
+ 3
+ ],
+ [
+ "ManufacturingCapacity",
+ 1
+ ],
+ [
+ "TransportationCostLevel2",
+ 2
+ ],
+ [
+ "OptimizationLevel1Min",
+ 1
+ ],
+ [
+ "OptimizationLevel1Max",
+ 1
+ ],
+ [
+ "OptimizationLevel1Opt",
+ 1
+ ],
+ [
+ "OptimizationLevel2Min",
+ 1
+ ],
+ [
+ "OptimizationLevel2Max",
+ 1
+ ],
+ [
+ "OptimizationLevel2Opt",
+ 1
+ ],
+ [
+ "OptimizationSensitivity",
+ 2
+ ],
+ [
+ "OptimizationUptodate",
+ 3
+ ],
+ [
+ "RcmTotalW",
+ 2
+ ],
+ [
+ "RcmCW",
+ 2
+ ],
+ [
+ "RcmPW",
+ 2
+ ],
+ [
+ "RcmTotalCost",
+ 2
+ ],
+ [
+ "RcmTotalPurchaseCost",
+ 2
+ ],
+ [
+ "RcmLevel1DemandQ",
+ 2
+ ],
+ [
+ "RcmCPurchaseCost",
+ 2
+ ],
+ [
+ "RcmPPurchaseCost",
+ 2
+ ],
+ [
+ "RcmStorageCost",
+ 2
+ ],
+ [
+ "RcmRepairCost",
+ 2
+ ],
+ [
+ "RcmNoRecycled",
+ 2
+ ],
+ [
+ "AvsimTotalW",
+ 2
+ ],
+ [
+ "AvsimCW",
+ 2
+ ],
+ [
+ "AvsimPW",
+ 2
+ ],
+ [
+ "AvsimTotalCost",
+ 2
+ ],
+ [
+ "AvsimTotalPurchaseCost",
+ 2
+ ],
+ [
+ "AvsimLevel1DemandQ",
+ 2
+ ],
+ [
+ "AvsimCPurchaseCost",
+ 2
+ ],
+ [
+ "AvsimPPurchaseCost",
+ 2
+ ],
+ [
+ "AvsimStorageCost",
+ 2
+ ],
+ [
+ "AvsimRepairCost",
+ 2
+ ],
+ [
+ "AvsimNoRecycled",
+ 2
+ ],
+ [
+ "AvsimImportanceCost",
+ 2
+ ],
+ [
+ "AvsimImportanceTdt",
+ 2
+ ],
+ [
+ "AvsimImportanceW",
+ 2
+ ],
+ [
+ "AvsimImportanceCapacity",
+ 2
+ ],
+ [
+ "AvsimImportanceSafety",
+ 2
+ ],
+ [
+ "AvsimImportanceOperational",
+ 2
+ ],
+ [
+ "AvsimImportanceEnvironmental",
+ 2
+ ],
+ [
+ "AvsimImportanceUptodate",
+ 3
+ ],
+ [
+ "RcmOptOk",
+ 3
+ ],
+ [
+ "RcmOptCbr",
+ 2
+ ],
+ [
+ "RcmOptCostBenefit",
+ 2
+ ],
+ [
+ "RcmOptPointIndex",
+ 1
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "Guid",
+ 0
+ ]
+ ],
+ "Labor": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "CostRate",
+ 2
+ ],
+ [
+ "CorrectiveCalloutCost",
+ 2
+ ],
+ [
+ "ScheduledCalloutCost",
+ 2
+ ],
+ [
+ "CorrectiveLogisticDelay",
+ 2
+ ],
+ [
+ "NoAvailable",
+ 1
+ ],
+ [
+ "RcmTotalTdt",
+ 2
+ ],
+ [
+ "RcmCTdt",
+ 2
+ ],
+ [
+ "RcmPTdt",
+ 2
+ ],
+ [
+ "RcmITdt",
+ 2
+ ],
+ [
+ "RcmTotalW",
+ 2
+ ],
+ [
+ "RcmCW",
+ 2
+ ],
+ [
+ "RcmPW",
+ 2
+ ],
+ [
+ "RcmIW",
+ 2
+ ],
+ [
+ "RcmTotalCost",
+ 2
+ ],
+ [
+ "RcmCCost",
+ 2
+ ],
+ [
+ "RcmPCost",
+ 2
+ ],
+ [
+ "RcmICost",
+ 2
+ ],
+ [
+ "AvsimTotalTdt",
+ 2
+ ],
+ [
+ "AvsimCTdt",
+ 2
+ ],
+ [
+ "AvsimPTdt",
+ 2
+ ],
+ [
+ "AvsimITdt",
+ 2
+ ],
+ [
+ "AvsimTotalW",
+ 2
+ ],
+ [
+ "AvsimCW",
+ 2
+ ],
+ [
+ "AvsimPW",
+ 2
+ ],
+ [
+ "AvsimIW",
+ 2
+ ],
+ [
+ "AvsimTotalCost",
+ 2
+ ],
+ [
+ "AvsimCCost",
+ 2
+ ],
+ [
+ "AvsimPCost",
+ 2
+ ],
+ [
+ "AvsimICost",
+ 2
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "Guid",
+ 0
+ ]
+ ],
+ "FailureModelScheduledTasks": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "TaskId",
+ 0
+ ],
+ [
+ "Enabled",
+ 3
+ ],
+ [
+ "OperationNumber",
+ 0
+ ],
+ [
+ "Baseline",
+ 0
+ ],
+ [
+ "TaskTrigger",
+ 0
+ ],
+ [
+ "Mandatory",
+ 3
+ ],
+ [
+ "AgeReductionFactor",
+ 2
+ ],
+ [
+ "AgeReductionMode",
+ 1
+ ],
+ [
+ "Std",
+ 2
+ ],
+ [
+ "Eta",
+ 2
+ ],
+ [
+ "Beta",
+ 2
+ ],
+ [
+ "Gamma",
+ 2
+ ],
+ [
+ "WeibullSet",
+ 1
+ ],
+ [
+ "Distribution",
+ 1
+ ],
+ [
+ "OperationalCost",
+ 2
+ ],
+ [
+ "TaskGroup",
+ 1
+ ],
+ [
+ "SecondaryActionTask",
+ 3
+ ],
+ [
+ "TaskDuration",
+ 2
+ ],
+ [
+ "RampTime",
+ 2
+ ],
+ [
+ "TaskInterval",
+ 2
+ ],
+ [
+ "FixedInterval",
+ 3
+ ],
+ [
+ "Offset",
+ 2
+ ],
+ [
+ "MinimumAge",
+ 2
+ ],
+ [
+ "OutedDuringMaintenance",
+ 3
+ ],
+ [
+ "PfInterval",
+ 2
+ ],
+ [
+ "PfStd",
+ 2
+ ],
+ [
+ "DetectionP",
+ 2
+ ],
+ [
+ "PfDistribution",
+ 1
+ ],
+ [
+ "OptimizationInitialInterval",
+ 2
+ ],
+ [
+ "OptimizationIntervalIncrement",
+ 2
+ ],
+ [
+ "OptimizationNumberIntervals",
+ 1
+ ],
+ [
+ "OptimizationCostPointIndex",
+ 1
+ ],
+ [
+ "OptimizationQPointIndex",
+ 2
+ ],
+ [
+ "OptimizationCostBenefit",
+ 2
+ ],
+ [
+ "OptimizationCbr",
+ 2
+ ],
+ [
+ "OptimizationQBenefit",
+ 2
+ ],
+ [
+ "OptimizationQbr",
+ 2
+ ],
+ [
+ "OptimizationOk",
+ 3
+ ],
+ [
+ "ExternalReference",
+ 0
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Notes5",
+ 0
+ ],
+ [
+ "Notes6",
+ 0
+ ],
+ [
+ "Notes7",
+ 0
+ ],
+ [
+ "Notes8",
+ 0
+ ],
+ [
+ "Notes9",
+ 0
+ ],
+ [
+ "Notes10",
+ 0
+ ],
+ [
+ "Notes11",
+ 0
+ ],
+ [
+ "Notes12",
+ 0
+ ],
+ [
+ "Notes13",
+ 0
+ ],
+ [
+ "Notes14",
+ 0
+ ],
+ [
+ "Notes15",
+ 0
+ ],
+ [
+ "Notes16",
+ 0
+ ],
+ [
+ "Notes17",
+ 0
+ ],
+ [
+ "Notes18",
+ 0
+ ],
+ [
+ "Notes19",
+ 0
+ ],
+ [
+ "Notes20",
+ 0
+ ],
+ [
+ "Notes21",
+ 0
+ ],
+ [
+ "Notes22",
+ 0
+ ],
+ [
+ "Notes23",
+ 0
+ ],
+ [
+ "Notes24",
+ 0
+ ]
+ ],
+ "FailureModelSchedTaskLabor": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "SecondarySubIndex",
+ 1
+ ],
+ [
+ "Labor",
+ 1
+ ],
+ [
+ "ActiveTime",
+ 2
+ ],
+ [
+ "SetToTaskDuration",
+ 3
+ ],
+ [
+ "Quantity",
+ 1
+ ],
+ [
+ "ExternalReference",
+ 0
+ ]
+ ],
+ "FailureModelSchedTaskSpares": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "SecondarySubIndex",
+ 1
+ ],
+ [
+ "Spare",
+ 1
+ ],
+ [
+ "Quantity",
+ 1
+ ],
+ [
+ "ExternalReference",
+ 0
+ ]
+ ],
+ "FailureModelCorrTaskLabor": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "Labor",
+ 1
+ ],
+ [
+ "ActiveTime",
+ 2
+ ],
+ [
+ "SetToTaskDuration",
+ 3
+ ],
+ [
+ "Quantity",
+ 1
+ ],
+ [
+ "ExternalReference",
+ 0
+ ]
+ ],
+ "FailureModelCorrTaskSpares": [
+ [
+ "FailureModel",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "Spare",
+ 1
+ ],
+ [
+ "Quantity",
+ 1
+ ],
+ [
+ "ExternalReference",
+ 0
+ ]
+ ],
+ "Phases": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "PhaseGroup",
+ 1
+ ],
+ [
+ "Notes1",
+ 0
+ ],
+ [
+ "Notes2",
+ 0
+ ],
+ [
+ "Notes3",
+ 0
+ ],
+ [
+ "Notes4",
+ 0
+ ],
+ [
+ "Duration",
+ 2
+ ],
+ [
+ "TotalCost",
+ 2
+ ],
+ [
+ "LaborCost",
+ 2
+ ],
+ [
+ "EquipmentCost",
+ 2
+ ],
+ [
+ "SparePurchaseCost",
+ 2
+ ],
+ [
+ "SpareStorageCost",
+ 2
+ ],
+ [
+ "OperationalCost",
+ 2
+ ],
+ [
+ "AlarmCost",
+ 2
+ ],
+ [
+ "CommissionCost",
+ 2
+ ],
+ [
+ "RedesignCost",
+ 2
+ ],
+ [
+ "ConsequenceCost",
+ 2
+ ],
+ [
+ "Guid",
+ 0
+ ]
+ ],
+ "RbdBlockRuleAssignments": [
+ [
+ "Block",
+ 1
+ ],
+ [
+ "SubIndex",
+ 1
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "Description",
+ 0
+ ],
+ [
+ "Phase",
+ 1
+ ],
+ [
+ "LogicMode",
+ 1
+ ],
+ [
+ "StandbyMode",
+ 1
+ ],
+ [
+ "LoadFactor",
+ 2
+ ],
+ [
+ "MaxCapacity",
+ 2
+ ],
+ [
+ "DependentBlock",
+ 1
+ ],
+ [
+ "OutOfService",
+ 3
+ ]
+ ],
+ "RbdLabels": [
+ [
+ "Id",
+ 0
+ ],
+ [
+ "Type",
+ 1
+ ],
+ [
+ "Page",
+ 1
+ ],
+ [
+ "XPosition",
+ 2
+ ],
+ [
+ "YPosition",
+ 2
+ ],
+ [
+ "Width",
+ 2
+ ],
+ [
+ "Height",
+ 2
+ ],
+ [
+ "LabelText",
+ 0
+ ],
+ [
+ "Alignment",
+ 1
+ ],
+ [
+ "FontName",
+ 0
+ ],
+ [
+ "FontSize",
+ 2
+ ],
+ [
+ "FontStyle",
+ 1
+ ],
+ [
+ "FontColor",
+ 1
+ ],
+ [
+ "Border",
+ 3
+ ],
+ [
+ "BitmapOn",
+ 3
+ ],
+ [
+ "Bitmap",
+ 1
+ ],
+ [
+ "BackgroundColor",
+ 1
+ ],
+ [
+ "Guid",
+ 0
+ ]
]
},
"defaults": {
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
index 9b325ce2..240736b3 100644
--- a/tests/unit/test_awb.py
+++ b/tests/unit/test_awb.py
@@ -178,13 +178,10 @@ def test_export_report_names_raptor_features_awb_cannot_use(tmp_path):
report = export_awb(rbd, path, source="lossy.rbds")
features = {loss.feature for loss in report.not_in_target}
for expected in (
- "failure events", "diagram annotations", "rate definitions",
- "formula-linked fields", "triggers", "spare pools",
- "resource pools", "mission phases", "out-of-service elements",
- "capacity analysis", "block dependencies",
- "preventive maintenance", "phased element schedules",
- "failure distribution simplified to exponential",
- "repair distribution simplified to a fixed duration"):
+ "failure events", "rate definitions",
+ "formula-linked fields", "triggers",
+ "capacity analysis",
+ "failure distribution simplified to exponential"):
assert expected in features, (expected, sorted(features))
assert "times converted from days to hours" in " ".join(report.notes)
@@ -213,9 +210,7 @@ def test_import_report_names_awb_features_raptor_cannot_use(tmp_path):
rbd, report = import_awb(path)
features = {loss.feature for loss in report.not_in_target}
for expected in (
- "consequence and cost models", "mission phases and phase rules",
- "planned maintenance tasks", "spares and sparing rules",
- "labour and equipment resources", "RCM location hierarchy",
+ "consequence and cost models", "RCM location hierarchy",
"Weibull sets", "bitmaps", "capacity flow and capacity targets"):
assert expected in features, (expected, sorted(features))
assert rbd is not None
@@ -316,3 +311,72 @@ def test_cli_convert_awb_round_trip(tmp_path, capsys):
from raptor.core.fileio.model_file import load_model_file
loaded = load_model_file(back)
assert len(_rows(loaded, "BLOCK_DATA")) == 2
+
+
+def test_pm_spares_resources_phases_and_out_of_service_round_trip(tmp_path):
+ doc = {
+ "format": "raptor-studio", "version": 4,
+ "system": {"units": "hours"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 1000.0},
+ "elements": {
+ "blocks": [
+ {"id": 1, "name": "Pump", "x": 0, "y": 0,
+ "fail_dist": 4, "fail_params": [1000, 0, 0],
+ "repair_dist": 19, "repair_params": [10, 0, 0],
+ "uses_pm": True, "pm_freq": 100.0,
+ "pm_duration_dist": 19, "pm_params": [5, 0, 0],
+ "pm_refresh": True, "pm_spare": True,
+ "num_resources": 1, "resource_name": "Crew",
+ "repair_resources_needed": 2, "pm_resources_needed": 1,
+ "sparing_type": "Custom", "stock": 3, "new_spares": 1,
+ "quantity": 2, "arrive_every": 720.0, "emer_time": 48.0,
+ "uses_phasing": True,
+ "legacy": {"P 001": "C: 1.000", "P 002": "A: 1.000"}},
+ {"id": 2, "name": "Valve", "x": 200, "y": 0,
+ "fail_dist": 4, "fail_params": [2000, 0, 0],
+ "repair_dist": 19, "repair_params": [20, 0, 0]},
+ ],
+ "nodes": [{"id": 3, "name": "start", "type": 1, "x": -100, "y": 0},
+ {"id": 4, "name": "end", "type": 3, "x": 300, "y": 0}],
+ "hierarchies": [],
+ },
+ "links": [{"id": 5, "from": ["Node", 3], "to": ["Block", 1]},
+ {"id": 6, "from": ["Block", 1], "to": ["Block", 2]},
+ {"id": 7, "from": ["Block", 2], "to": ["Node", 4]}],
+ "spare_pools": [{"name": "CrewSpares", "stock": 2, "new_spares": 1,
+ "arrive_every": 720, "eso": 1, "emer_time": 48,
+ "quantity": 1}],
+ "resources": [{"name": "Crew", "num_in": 2, "spare_cost": 1,
+ "fixed_per_use": 10, "per_time_unit": 20, "phases": 0}],
+ "phases": [{"name": "PhaseA", "num": 1, "mission": 1,
+ "duration_dist": 19, "params": [100, 0, 0]},
+ {"name": "PhaseB", "num": 2, "mission": 1,
+ "duration_dist": 19, "params": [200, 0, 0]}],
+ "annotations": [{"kind": "text", "id": 1, "parent": 0, "x": 10,
+ "y": 10, "w": 100, "h": 20, "text": "note"}],
+ "out_of_service": {"block:2": "cut"},
+ }
+ rbd = parse_rbds(json.dumps(doc))
+ path = tmp_path / "stage12.awb"
+ export_awb(rbd, path, source="stage12.rbds")
+ tables = read_awb(path)
+ for name in ("FailureModelScheduledTasks", "FailureModelSchedTaskLabor",
+ "FailureModelSchedTaskSpares", "FailureModelCorrTaskLabor",
+ "FailureModelCorrTaskSpares", "Spares", "Labor", "Phases",
+ "RbdBlockRuleAssignments", "RbdLabels"):
+ assert tables[name].rows, name
+ back, report = import_awb(path)
+ assert len(back.sections["PHASES"].rows) == 2
+ assert back.sections["RESOURCE_DATA"].rows
+ assert back.sections["SPARE_POOL_DATA"].rows
+ pump = next(r for r in _rows(back, "BLOCK_DATA")
+ if r["blockName"] == "Pump")
+ assert pump["usesPM"] == "1"
+ assert pump["SpType"] == "Pooled"
+ assert pump["NumRes"] == "1"
+ assert pump["Resource1Name"]
+ assert pump["P 001"].startswith("C:")
+ assert back.out_of_service.get("block:2") == "cut"
+ assert "non-maintainable blocks" not in {
+ loss.feature for loss in report.not_in_target}
From a3ee53f74244b5b3ef00e472fd921ca69306d993 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 21:16:19 +1000
Subject: [PATCH 06/15] feat(awb): sidecar, normalization, dry-run and MCP
parity
Adds report categories, a hashed RAPTOR sidecar, a reduced-model normalizer, CLI/API/MCP dry-run and normalize options, a GUI preview command, and MCP export/import tools. Documents large-model risks and the CarWash1 phase and CarCare0 normalized checks.
---
README.md | 4 +-
docs/AWB_FORMAT.md | 66 ++++-
docs/AWB_VALIDATION.md | 39 +++
docs/MCP-reference.md | 101 +++++++-
docs/MCP.md | 2 +-
docs/completions/raptor | 2 +-
docs/completions/raptor.fish | 3 +
docs/man/raptor-convert.1 | 11 +-
docs/manual-reference.adoc | 1 +
docs/manual.adoc | 6 +-
docs/manual.html | 11 +-
new_docs/book.html | 18 +-
new_docs/chapters/ch16-mcp.adoc | 16 +-
raptor/api/awb.py | 28 ++-
raptor/cli/cmd_info.py | 32 ++-
raptor/core/fileio/awb.py | 386 +++++++++++++++++++++++++++--
raptor/gui/command_table.py | 13 +-
raptor/gui/resources/icons.py | 14 ++
raptor/gui/ui/export_mixin.py | 27 +-
raptor/gui/ui/file_io_mixin.py | 5 +-
raptor/mcp/output_schemas.json | 78 ++++++
raptor/mcp/tools_model.py | 66 +++++
tests/unit/test_awb.py | 121 +++++++++
tests/unit/test_mcp_tools_model.py | 23 ++
tools/gen_mcp_output_schemas.py | 5 +-
tools/gen_mcp_reference.py | 10 +-
26 files changed, 1029 insertions(+), 59 deletions(-)
diff --git a/README.md b/README.md
index 8caf394a..92decb06 100644
--- a/README.md
+++ b/README.md
@@ -41,7 +41,7 @@ organisations, and nobody may charge a fee for it without Booz Allen Hamilton's
- **Scriptable.** Everything the application does is also a command (`raptor run`, `advise`, `explain`, `whatif`,
`recommend`, `sensitivity`, `optimise`, `sweep`, `compare`, `diff`, `render` and more) with machine-readable
results. It fits in a continuous-integration job, a Jupyter notebook or a shell loop.
-- **Usable from an AI assistant.** An MCP server with **94 tools** (93 when `--no-render` hides the PNG diagram tool)
+- **Usable from an AI assistant.** An MCP server with **96 tools** (95 when `--no-render` hides the PNG diagram tool)
lets an assistant build, edit, validate, simulate, explain and improve models, run long batches in the background,
and draw the diagram. The [MCP server guide](https://github.com/openpowershift/RaptorStudio/blob/main/docs/MCP.md)
covers install, client setup, concepts and task recipes; the generated
@@ -107,7 +107,7 @@ Everything above runs on a copy of the model and changes nothing until you apply
| **Parallel batches** | Runs spread over your cores (`-j N` on the command line); results are reproducible for a given core count, and one core reproduces Raptor 7's own random sequence exactly. |
| **Check part of a model** | Run one hierarchy on its own, with its input assumed available, or save it as a standalone model (`raptor extract`). The results are labelled as isolated. |
| **Sweeps and comparisons** | Vary any field over a list of values, or run two or more models side by side. **Differences** shows what is different between two models, and runs nothing. |
-| **AI assistant (MCP)** | 94 tools (93 with `--no-render`) to build, edit, run, explain and improve models, over stdio or authenticated HTTP. |
+| **AI assistant (MCP)** | 96 tools (95 with `--no-render`) to build, edit, run, explain and improve models, over stdio or authenticated HTTP. |
| **Stepping debugger** | Step a run event by event, pause on a condition, jump to the next run, and see what each step changed. Failure Effects View and the Single Point Failure file are also available headless. |
| **Faster editing** | Command search finds any command by name; Quick Add places an element by typing its kind; Duplicate in Parallel adds a redundant copy with the nodes it needs; several models open at once, each with its own undo history. |
| **Charts and reports** | One Charts view (availability through the run, run-to-run system state you can zoom into, downtime, cost, capacity); presentation-ready export; reports as PDF, HTML, AsciiDoc, spreadsheet, CSV or JSON (a versioned schema). |
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index 1af74598..41329e83 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -20,6 +20,13 @@ raptor convert model.rbds model.awb --report report.md
# AWB -> RAPTOR
raptor convert project.awb model.rbds
raptor convert project.awb model.rbd
+
+# report only, write nothing
+raptor convert model.rbds preview.awb --dry-run
+# preserve RAPTOR-only metadata in a companion sidecar (default)
+raptor convert model.rbds model.awb
+# write a matched reduced RAPTOR model as well
+raptor convert model.rbds model.awb --normalize-out model.awb.rbds
```
AWB's own demonstration mode can *open and simulate* a project but blocks
@@ -247,6 +254,10 @@ Markdown; `--report FILE` also writes the Markdown. The report has:
from the destination (used for information, not to block);
* `notes` and `warnings`.
+Each loss is classed **substituted** (a defensible equivalent was written),
+**partially mapped** (only part of the feature travelled) or **dropped** (no
+AWB field was written; the `.raptor.json` sidecar keeps the RAPTOR copy).
+
### Features reported when exporting to AWB
| Feature | Why |
@@ -302,7 +313,30 @@ are idle whenever the original block is down.
---
-## 6. Column defaults and the table schema file
+## 6. Sidecar and normalization
+
+The `.awb` file is the interchange; it is not a lossless container for
+RAPTOR. When a conversion has RAPTOR-only data, the exporter also writes
+`.awb.raptor.json` beside it. It holds things AWB has no field for:
+triggers, rate/formula metadata, failure events, shape annotations,
+dependencies, costs, capacity flags and link/node extras. It is hashed
+against the `.awb`; changing the AWB file makes the importer ignore a stale
+sidecar rather than apply old values. `--no-sidecar` disables it.
+
+`--normalize-out FILE` writes a reduced RAPTOR model that carries only what
+the AWB file represents: unsupported failure laws become mean-matched
+exponentials, random repairs become fixed means, dependencies/capacity/
+events/triggers/rates are removed, and node/link switching settings return
+to defaults. Running RAPTOR and AWB on that reduced pair measures engine
+agreement, not missing-feature effects.
+
+The report separates **substituted**, **partially mapped** and **dropped**
+features. `--strict` still refuses to write if any of those three lists is
+non-empty.
+
+---
+
+## 7. Column defaults and the table schema file
RAPTOR ships the table schemas in
`raptor/core/fileio/awb_tables.json` (column names and types plus the neutral
@@ -324,7 +358,7 @@ module table when the project is opened.
---
-## 7. Verification
+## 8. Verification
The format and mapping were checked against AWB 5.0.0.0 under Wine:
@@ -345,7 +379,7 @@ rather than driving AWB's own export dialog.
---
-## 8. Limits and compatibility
+## 9. Limits and compatibility
* The reader accepts the AWB 5.0 table-store layout. Older AWB projects with
fewer columns are accepted; missing columns take the type default.
@@ -366,3 +400,29 @@ rather than driving AWB's own export dialog.
* The `.awb` layout was reverse-engineered for interoperability; Isograph may
change it in a future release. A file that does not parse is reported as
`AwbFormatError` with the table and byte offset where possible.
+
+### Risk on large and complex models
+
+The format is a table store, but correctness depends on **index and foreign
+key agreement**, not just field names. The known risks are:
+
+* **Index references**: `RbdConnections`, failure models, spare/labour links
+ and phase rules are row-index based. A missing or extra row shifts them.
+ The converter writes them from the same in-memory row lists, and tests
+ open, simulate and round-trip the resulting files.
+* **Optional tables**: AWB does not require the PM/spare/resource/phase
+ tables to exist. When written, each row needs its type and parent tables
+ (`Labor.Type = -1`, `Spares.Type = -1`, PM optimization intervals); an
+ omitted type or a zero interval produced AWB validation errors or an
+ index crash during development.
+* **Demo limits**: AWB demonstration mode may open a large project but
+ refuse to analyse it because of its object limit. This is an AWB licence
+ restriction, not a file-format failure.
+* **Large project test**: `ProjectX_BESS_RAM.rbds` — 3,470 blocks, 900
+ nodes, 217 hierarchies, 5,184 links — exported to a 3.0 MB `.awb` plus a
+ 3.4 MB sidecar. AWB 5.0 opened it without validation errors, and the
+ `.awb` + sidecar imported back to RAPTOR with 0 validation errors.
+* **Version drift**: AWB 5.0 files vary in column count between samples.
+ Missing columns take type defaults; a future AWB may add required columns
+ or change a rule type. Re-run the AWB smoke tests before relying on a new
+ AWB release.
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
index 0b9a3249..8ff6153e 100644
--- a/docs/AWB_VALIDATION.md
+++ b/docs/AWB_VALIDATION.md
@@ -65,6 +65,34 @@ sampling error.
and the run is 600 h, so both programs correctly report no failures and
availability 1.0000.
+### Phase check: CarWash1
+
+`CarWash1` became format-exact once phase rules were mapped, but its
+1000-trial result is not yet counted as validated:
+
+| | RAPTOR | AWB |
+|---|---:|---:|
+| Availability | 0.6970 | 0.6914 |
+| System failures | 69.06 | 69.01 |
+
+The failure count matches; the 0.56 percentage-point availability
+difference points at phase/mission semantics (the first phase is
+non-mission in RAPTOR, and AWB has no equivalent mission flag). It is
+listed as **format exact, result under investigation**, not as a clean
+comparison.
+
+### Normalized comparison: CarCare0
+
+`raptor convert ... --normalize-out` reduced CarCare0's lognormal repair
+to its fixed mean and wrote both files. At 1000 trials:
+
+| | RAPTOR | AWB |
+|---|---:|---:|
+| Availability | 0.990345 | 0.9904 |
+
+Difference **0.0055 percentage points**, excellent agreement. This
+validates the normalization pathway for repair-law-only differences.
+
### Feature smoke test (Stage 1/2)
A synthetic two-block model with one PM task, a custom spare, a resource
@@ -75,6 +103,17 @@ back to RAPTOR with 0 validation errors and preserved the PM, spare/resource
links, phase cut/linked token and cut block. This is a mapping smoke test,
not a 10,000-trial engine comparison.
+### Large-model check
+
+`ProjectX_BESS_RAM.rbds` (8.4 MB) has 3,470 blocks, 900 nodes, 217
+hierarchies, 5,184 links and capacity analysis. It exported in 3.6 s to a
+3.0 MB `.awb` plus a 3.4 MB sidecar; AWB 5.0 opened the `.awb` without
+validation errors. The `.awb` plus sidecar imported back to RAPTOR with 0
+validation errors. Capacity and random repair laws were the only reported
+losses: capacity is preserved in the sidecar, and the repair law is
+mean-matched for AWB. AWB demonstration mode may still refuse to analyse a
+project of this size; that is its object limit, not a file-format failure.
+
---
## 2. Compatibility screening of all 27 examples
diff --git a/docs/MCP-reference.md b/docs/MCP-reference.md
index a26dcdf0..622d9dbd 100644
--- a/docs/MCP-reference.md
+++ b/docs/MCP-reference.md
@@ -1,16 +1,18 @@
# MCP tool reference
-This is the exhaustive catalogue generated from the live `raptor-studio` server: **94 tools** (93 with `--no-render`), **8 resources** and **3 prompts**. For installation, client setup, concepts and task recipes, start with the [MCP guide](MCP.md).
+This is the exhaustive catalogue generated from the live `raptor-studio` server: **96 tools** (95 with `--no-render`), **8 resources** and **3 prompts**. For installation, client setup, concepts and task recipes, start with the [MCP guide](MCP.md).
Every tool section is generated from the server's `tools/list` payload. It repeats the full description the assistant sees, turns the input schema into a typed parameter table, lists the declared return fields, and gives one argument example. A trailing `?` is not used here: the **Required** column is authoritative.
## Contents
-- [Workspace and lifecycle](#tools-workspace) — 8 tools
+- [Workspace and lifecycle](#tools-workspace) — 10 tools
- [`close_model`](#tool-close_model)
- [`create_model`](#tool-create_model)
- [`delete_file`](#tool-delete_file)
+ - [`export_awb`](#tool-export_awb)
+ - [`import_awb`](#tool-import_awb)
- [`list_models`](#tool-list_models)
- [`open_model`](#tool-open_model)
- [`ping`](#tool-ping)
@@ -247,6 +249,101 @@ allow-write directories, same containment `save_model_as` enforces.
}
```
+
+
+#### `export_awb`
+
+- **Kind:** destructive
+- **Group:** [Workspace and lifecycle](#tools-workspace)
+
+Write the model as an Isograph Availability Workbench .awb project.
+
+The report names substituted, partially mapped and dropped features.
+`dry_run=true` writes nothing. `sidecar=true` also writes a
+`.awb.raptor.json` beside the file with RAPTOR-only metadata.
+`normalize_out` writes a reduced RAPTOR model carrying only what the AWB
+file represents; that reduced copy is what gets exported.
+
+**Parameters**
+
+| Parameter | Type | Required | Schema default | Enum / allowed values |
+| --- | --- | --- | --- | --- |
+| `dry_run` | boolean | no | `false` | — |
+| `model_id` | string | yes | — | — |
+| `normalize_out` | string \| null | no | `null` | — |
+| `path` | string | yes | — | — |
+| `sidecar` | boolean | no | `true` | — |
+
+Parameter notes:
+
+- `model_id` — Id of a loaded model, from open_model, build_model, create_model or list_models.
+- `normalize_out` — `normalize_out` writes a reduced RAPTOR model carrying only what the AWB file represents; that reduced copy is what gets exported.
+
+**Returns**
+
+| Field | Type | Always present |
+| --- | --- | --- |
+| `counts` | object | yes |
+| `direction` | string | yes |
+| `dry_run` | boolean | yes |
+| `normalized_path` | null | yes |
+| `not_in_source` | array | yes |
+| `not_in_target` | array | yes |
+| `notes` | array | yes |
+| `path` | string | yes |
+| `schema` | string | yes |
+| `sidecar` | string | yes |
+| `source` | string | yes |
+| `target` | string | yes |
+| `warnings` | array | yes |
+
+**Example**
+
+```json
+{
+ "model_id": "",
+ "path": "exports/pump-station.awb",
+ "dry_run": true,
+ "sidecar": true
+}
+```
+
+
+
+#### `import_awb`
+
+- **Kind:** writes
+- **Group:** [Workspace and lifecycle](#tools-workspace)
+
+Open an Isograph Availability Workbench .awb project as a model.
+
+The report names the AWB features RAPTOR does not import. A matching
+`.awb.raptor.json` sidecar, when present and unchanged, restores
+RAPTOR-only metadata (rates, formulas, triggers, shape annotations,
+dependencies and costs).
+
+**Parameters**
+
+| Parameter | Type | Required | Schema default | Enum / allowed values |
+| --- | --- | --- | --- | --- |
+| `path` | string | yes | — | — |
+
+**Returns**
+
+| Field | Type | Always present |
+| --- | --- | --- |
+| `model_id` | string | yes |
+| `report` | object | yes |
+| `summary` | string | yes |
+
+**Example**
+
+```json
+{
+ "path": "exports/pump-station.awb"
+}
+```
+
#### `list_models`
diff --git a/docs/MCP.md b/docs/MCP.md
index bd2db248..3db10711 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -21,7 +21,7 @@ The server is named `raptor-studio`. Its entry points are
## At a glance
-- **94 tools** in 8 task groups. With `--no-render`, which hides the PNG diagram tool, the server exposes **93**.
+- **96 tools** in 8 task groups. With `--no-render`, which hides the PNG diagram tool, the server exposes **95**.
- **8 resources** (fixed URIs and templates) and **3 prompts**.
- The tutorial book has **26 chapters**; the MCP chapter is book chapter 23 of 26 (source `new_docs/chapters/ch16-mcp.adoc`).
diff --git a/docs/completions/raptor b/docs/completions/raptor
index cd034808..a0d3c7d0 100644
--- a/docs/completions/raptor
+++ b/docs/completions/raptor
@@ -12,7 +12,7 @@ _raptor() {
compare) opts="--analysis --format --help --importance --jobs --length --max-trials --metric --min-trials --precision --precision-batch --precision-confidence --precision-metric --runs --save-model --seed --set --set-file --stats-start --stop --timeout --weak-type" ;;
completion) opts="--help" ;;
config) opts="--help" ;;
- convert) opts="--allow-lossy --format --help --report --strict --to" ;;
+ convert) opts="--allow-lossy --dry-run --format --help --no-sidecar --normalize-out --report --strict --to" ;;
describe) opts="--element --format --help" ;;
diff) opts="--all --exit-code --format --help --ignore --match --only" ;;
doctor) opts="--format --help" ;;
diff --git a/docs/completions/raptor.fish b/docs/completions/raptor.fish
index b05ef664..d3fda41b 100644
--- a/docs/completions/raptor.fish
+++ b/docs/completions/raptor.fish
@@ -66,8 +66,11 @@ complete -c raptor -n '__fish_use_subcommand' -a config
complete -c raptor -n '__fish_seen_subcommand_from config' -l help
complete -c raptor -n '__fish_use_subcommand' -a convert
complete -c raptor -n '__fish_seen_subcommand_from convert' -l allow-lossy
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l dry-run
complete -c raptor -n '__fish_seen_subcommand_from convert' -l format
complete -c raptor -n '__fish_seen_subcommand_from convert' -l help
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l no-sidecar
+complete -c raptor -n '__fish_seen_subcommand_from convert' -l normalize-out
complete -c raptor -n '__fish_seen_subcommand_from convert' -l report
complete -c raptor -n '__fish_seen_subcommand_from convert' -l strict
complete -c raptor -n '__fish_seen_subcommand_from convert' -l to
diff --git a/docs/man/raptor-convert.1 b/docs/man/raptor-convert.1
index ed2e20ae..6decef70 100644
--- a/docs/man/raptor-convert.1
+++ b/docs/man/raptor-convert.1
@@ -2,7 +2,7 @@
.SH NAME
raptor\-convert \- convert between .rbd, .rbds and AWB .awb
.SH SYNOPSIS
-\fBraptor convert\fR [\-h] [\-\-to {rbd,rbds,awb}] [\-\-allow\-lossy] [\-\-strict] [\-f {text,json,markdown}] [\-\-report FILE] IN OUT
+\fBraptor convert\fR [\-h] [\-\-to {rbd,rbds,awb}] [\-\-allow\-lossy] [\-\-strict] [\-f {text,json,markdown}] [\-\-report FILE] [\-\-dry\-run] [\-\-no\-sidecar] [\-\-normalize\-out FILE] IN OUT
.SH DESCRIPTION
Write IN as OUT in the format OUT's extension names (or \-\-to). AWB conversions print a summary of the features the destination cannot represent. Refuses a lossy .rbd conversion unless \-\-allow\-lossy.
.SH OPTIONS
@@ -22,5 +22,14 @@ AWB summary format (default text)
.TP
\fB\-\-report\fR \fIFILE\fR
AWB only: also write the summary as Markdown to FILE
+.TP
+\fB\-\-dry\-run\fR
+AWB only: print the summary and write nothing
+.TP
+\fB\-\-no\-sidecar\fR
+AWB only: do not write the .raptor.json sidecar of RAPTOR\-only metadata
+.TP
+\fB\-\-normalize\-out\fR \fIFILE\fR
+AWB only: write a reduced RAPTOR model carrying only what the AWB file represents, and export that
.SH SEE ALSO
\fBraptor\fR(1)
diff --git a/docs/manual-reference.adoc b/docs/manual-reference.adoc
index 3f5374d9..07ff4ab1 100644
--- a/docs/manual-reference.adoc
+++ b/docs/manual-reference.adoc
@@ -384,6 +384,7 @@ documentation.
|Print… |Print diagrams, simulation results and the Weak Link analysis with a project title block (Ctrl+P) |Ctrl+P
|Export… |Save the report, the tables or the diagram: one window, pick the file type (PDF, Excel, OpenDocument, SVG or PNG) (Ctrl+E) |Ctrl+E
|Export to Availability Workbench… |Save this model as an Isograph Availability Workbench 5.0 .awb project; the summary lists what RAPTOR features AWB cannot represent |
+|Check Availability Workbench Export… |Report what an Availability Workbench export would substitute, partially map or drop, without writing a file |
|Export Tables… |Choose which tables to write, the model's and a run's results, as CSV files, text or one spreadsheet with a tab per table |
|Copy View |Copy the current view to the clipboard as a high-resolution PNG |
|===
diff --git a/docs/manual.adoc b/docs/manual.adoc
index fd4b88cd..d93b6134 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1703,7 +1703,11 @@ In short:
AWB projects can carry more than an RBD. The converter reads and writes
the AvSim RBD part; it does not transfer an AWB RCMCost study, fault tree,
capacity network or life-cycle-cost model. The summary names each of these
-with a count, so nothing is lost silently. AWB may renumber pages and
+with a count, so nothing is lost silently. **File ▸ Check Availability
+Workbench Export…** is the preview: it reports substitutions, partial
+mappings and drops without writing. The command line adds `--dry-run`,
+`--no-sidecar` and `--normalize-out`; the normalizer writes a matched reduced
+RAPTOR model for a fair engine comparison. AWB may renumber pages and
element ids on a round trip, and it uses the source x/y positions rather
than auto-layout; use AWB's Auto Layout after opening a model whose blocks
overlap.
diff --git a/docs/manual.html b/docs/manual.html
index 25c0be5f..5022d8a7 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2562,7 +2562,11 @@ Availability Workbench interchange
AWB projects can carry more than an RBD. The converter reads and writes
the AvSim RBD part; it does not transfer an AWB RCMCost study, fault tree,
capacity network or life-cycle-cost model. The summary names each of these
-with a count, so nothing is lost silently. AWB may renumber pages and
+with a count, so nothing is lost silently. File ▸ Check Availability
+Workbench Export… is the preview: it reports substitutions, partial
+mappings and drops without writing. The command line adds --dry-run,
+--no-sidecar and --normalize-out; the normalizer writes a matched reduced
+RAPTOR model for a fair engine comparison. AWB may renumber pages and
element ids on a round trip, and it uses the source x/y positions rather
than auto-layout; use AWB’s Auto Layout after opening a model whose blocks
overlap.
@@ -4028,6 +4032,11 @@ Print and Export
|
+Check Availability Workbench Export… |
+Report what an Availability Workbench export would substitute, partially map or drop, without writing a file |
+ |
+
+
Export Tables… |
Choose which tables to write, the model’s and a run’s results, as CSV files, text or one spreadsheet with a tab per table |
|
diff --git a/new_docs/book.html b/new_docs/book.html
index f48c5b0b..7196fa32 100644
--- a/new_docs/book.html
+++ b/new_docs/book.html
@@ -9752,7 +9752,7 @@ 23. RAPTOR from an AI Assistant
full tool catalogue, and worked examples.
-
The server exposes 94 tools (including the ping health check), a set of
+
The server exposes 96 tools (including the ping health check), a set of
resources, and three prompts. A standalone guide to installing, connecting,
concepts and task recipes is docs/MCP.md; the exhaustive, generated
catalogue of every tool, parameter, return field and example is
@@ -10279,8 +10279,8 @@
23.5. Verifying the server works
Check the tool list. Ask your assistant "What RAPTOR tools do you
have?" or, in the MCP Inspector, click Tools. You should see the tools
-listed below: 93 including render_diagram, render_diagram_svg and
-ping, or 92 when --no-render hides the PNG diagram tool.
+listed below: 96 including render_diagram, render_diagram_svg and
+ping, or 95 when --no-render hides the PNG diagram tool.
Ping the server. Ask the assistant to "ping RAPTOR" or call the ping
@@ -10343,6 +10343,18 @@
23.6.1. Workspace and lifecycle
refuses on error.
+export_awb
|
+Write an Isograph Availability Workbench .awb project. dry_run
+ reports substitutions/partial mappings/drops without writing; sidecar
+ preserves RAPTOR-only metadata; normalize_out writes a matched reduced
+ RAPTOR model for a fair comparison. |
+
+
+import_awb
|
+Open an .awb project as a model. A matching .awb.raptor.json sidecar
+ restores RAPTOR-only metadata when the file hash still matches. |
+
+
close_model
|
Close one or more models (a single id or a list), optionally deleting
their files irreversibly. |
diff --git a/new_docs/chapters/ch16-mcp.adoc b/new_docs/chapters/ch16-mcp.adoc
index 63036b6b..7a93b5b5 100644
--- a/new_docs/chapters/ch16-mcp.adoc
+++ b/new_docs/chapters/ch16-mcp.adoc
@@ -14,7 +14,7 @@ diagram.
This chapter covers installation, configuration for popular clients, the
full tool catalogue, and worked examples.
-The server exposes *94 tools* (including the `ping` health check), a set of
+The server exposes *96 tools* (including the `ping` health check), a set of
resources, and three prompts. A standalone guide to installing, connecting,
concepts and task recipes is `docs/MCP.md`; the exhaustive, generated
catalogue of every tool, parameter, return field and example is
@@ -388,8 +388,8 @@ careful about what it exposes:
. *Check the tool list.* Ask your assistant "What RAPTOR tools do you
have?" or, in the MCP Inspector, click *Tools*. You should see the tools
- listed below: 93 including `render_diagram`, `render_diagram_svg` and
- `ping`, or 92 when `--no-render` hides the PNG diagram tool.
+ listed below: 96 including `render_diagram`, `render_diagram_svg` and
+ `ping`, or 95 when `--no-render` hides the PNG diagram tool.
. *Ping the server.* Ask the assistant to "ping RAPTOR" or call the `ping`
tool manually. It should return `"pong"`.
@@ -433,6 +433,16 @@ you need the exact argument shape.
directory). `.rbds` by default; `.rbd` export validates first and
refuses on error.
+| `export_awb`
+| Write an Isograph Availability Workbench `.awb` project. `dry_run`
+ reports substitutions/partial mappings/drops without writing; `sidecar`
+ preserves RAPTOR-only metadata; `normalize_out` writes a matched reduced
+ RAPTOR model for a fair comparison.
+
+| `import_awb`
+| Open an `.awb` project as a model. A matching `.awb.raptor.json` sidecar
+ restores RAPTOR-only metadata when the file hash still matches.
+
| `close_model`
| Close one or more models (a single id or a list), optionally deleting
their files irreversibly.
diff --git a/raptor/api/awb.py b/raptor/api/awb.py
index b30dbc60..c027d198 100644
--- a/raptor/api/awb.py
+++ b/raptor/api/awb.py
@@ -9,20 +9,25 @@
from typing import Any
from raptor.core.fileio.awb import (
- AwbFormatError, AwbReport, export_awb, import_awb, read_awb,
- write_awb,
+ AwbFormatError, AwbReport, export_awb, import_awb, normalize_for_awb,
+ read_awb, write_awb,
)
__all__ = [
- "AwbFormatError", "AwbReport", "export", "import_project", "read",
- "write",
+ "AwbFormatError", "AwbReport", "export", "import_project", "normalize",
+ "read", "write",
]
def export(rbd: Any, path: str | Path, *, source: str = "",
- write: bool = True) -> AwbReport:
+ write: bool = True, sidecar: bool = True) -> AwbReport:
"""Write a RAPTOR model as an AWB 5.0 project."""
- return export_awb(rbd, path, source=source, write=write)
+ return export_awb(rbd, path, source=source, write=write, sidecar=sidecar)
+
+
+def normalize(rbd: Any) -> tuple[Any, list[str]]:
+ """Return a copy reduced to the AWB-representable subset."""
+ return normalize_for_awb(rbd)
def import_project(path: str | Path, *,
@@ -31,6 +36,17 @@ def import_project(path: str | Path, *,
return import_awb(path, source=source)
+def save_normalized(rbd: Any, path: str | Path) -> None:
+ """Write a normalized RAPTOR model, chosen by the path's extension."""
+ suffix = Path(path).suffix.lower()
+ if suffix == ".rbd":
+ from raptor.core.fileio.rbd import save_rbd
+ save_rbd(rbd, str(path))
+ else:
+ from raptor.core.fileio.rbds import save_rbds
+ save_rbds(rbd, str(path))
+
+
def read(path: str | Path) -> dict:
"""Read the raw AWB tables (diagnostics and tests)."""
return read_awb(path)
diff --git a/raptor/cli/cmd_info.py b/raptor/cli/cmd_info.py
index 17bbd33b..8b3bdbc3 100644
--- a/raptor/cli/cmd_info.py
+++ b/raptor/cli/cmd_info.py
@@ -98,6 +98,14 @@ def add_parser(sub: Any) -> None:
default="text", help="AWB summary format (default text)")
c.add_argument("--report", metavar="FILE",
help="AWB only: also write the summary as Markdown to FILE")
+ c.add_argument("--dry-run", action="store_true",
+ help="AWB only: print the summary and write nothing")
+ c.add_argument("--no-sidecar", action="store_true",
+ help="AWB only: do not write the .raptor.json sidecar of "
+ "RAPTOR-only metadata")
+ c.add_argument("--normalize-out", metavar="FILE",
+ help="AWB only: write a reduced RAPTOR model carrying only "
+ "what the AWB file represents, and export that")
c.set_defaults(func=convert_command)
@@ -330,18 +338,38 @@ def _convert_to_awb(args: Any, src: Path, dest: Path) -> int:
with workspace_for() as ws:
mid = open_model(ws, args.input)
rbd = ws.get(mid).rbd
- report = awb_api.export(rbd, dest, source=args.input, write=False)
+ actions: list[str] = []
+ if getattr(args, "normalize_out", None):
+ rbd, actions = awb_api.normalize(rbd)
+ norm = Path(args.normalize_out)
+ if norm.suffix.lower() not in (".rbds", ".rbd"):
+ norm = norm.with_suffix(".rbds")
+ nmid = ws.register_model(rbd, name=norm.stem,
+ source=str(src))["model_id"]
+ ws.save_model_as(nmid, str(norm), fmt=(
+ "rbd" if norm.suffix.lower() == ".rbd" else "rbds"))
+ eprint(f"wrote normalized model {norm}")
+ report = awb_api.export(rbd, dest, source=args.input, write=False,
+ sidecar=not args.no_sidecar)
+ report.notes.extend(f"normalized: {a}" for a in actions)
if args.strict and report.has_losses:
_print_awb_report(report, args)
raise CliError(
"AWB cannot represent every feature in this model; nothing was "
"written (drop --strict to proceed and keep the summary)", X.REFUSED)
+ if args.dry_run:
+ _print_awb_report(report, args)
+ eprint("dry run: nothing written")
+ return X.OK
try:
- awb_api.export(rbd, dest, source=args.input)
+ written_report = awb_api.export(rbd, dest, source=args.input,
+ sidecar=not args.no_sidecar)
except Exception as exc:
raise CliError(f"cannot write {dest}: {exc}", X.OUTPUT) from exc
_print_awb_report(report, args)
eprint(f"wrote {dest}")
+ if written_report.sidecar:
+ eprint(f"wrote sidecar {written_report.sidecar}")
return X.OK
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index 57bb93ef..5569ef24 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -14,6 +14,7 @@
"""
from __future__ import annotations
+import copy
import json
import math
import struct
@@ -44,10 +45,12 @@ class AwbLoss:
count: int
detail: str = ""
where: str = "" # "AWB" or "RAPTOR"
+ kind: str = "dropped" # "substituted", "partial" or "dropped"
def as_dict(self) -> dict[str, Any]:
return {"feature": self.feature, "count": self.count,
- "detail": self.detail, "where": self.where}
+ "detail": self.detail, "where": self.where,
+ "kind": self.kind}
@dataclass
@@ -62,18 +65,21 @@ class AwbReport:
not_in_source: list[AwbLoss] = field(default_factory=list)
notes: list[str] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
+ sidecar: str = ""
@property
def has_losses(self) -> bool:
return bool(self.not_in_target or self.not_in_source)
def add(self, feature: str, count: int, detail: str = "",
- where: str | None = None) -> None:
+ where: str | None = None, kind: str = "dropped") -> None:
if count <= 0:
return
where = where or ("AWB" if self.direction == "rbds-to-awb"
else "RAPTOR")
- self.not_in_target.append(AwbLoss(feature, count, detail, where))
+ if kind not in ("substituted", "partial", "dropped"):
+ kind = "dropped"
+ self.not_in_target.append(AwbLoss(feature, count, detail, where, kind))
def add_source(self, feature: str, count: int, detail: str = "") -> None:
"""A feature the source had that the destination also lacks, but
@@ -95,6 +101,7 @@ def as_dict(self) -> dict[str, Any]:
"not_in_source": [x.as_dict() for x in self.not_in_source],
"notes": list(self.notes),
"warnings": list(self.warnings),
+ "sidecar": self.sidecar,
}
def summary_text(self) -> str:
@@ -108,9 +115,16 @@ def summary_text(self) -> str:
]
if self.not_in_target:
lines.append(f" not represented in {target}:")
- for loss in self.not_in_target:
- lines.append(f" - {loss.feature}: {loss.count}"
- + (f" ({loss.detail})" if loss.detail else ""))
+ for kind, label in (("substituted", "substituted"),
+ ("partial", "partially mapped"),
+ ("dropped", "dropped")):
+ group = [loss for loss in self.not_in_target if loss.kind == kind]
+ if not group:
+ continue
+ lines.append(f" {label}:")
+ for loss in group:
+ lines.append(f" - {loss.feature}: {loss.count}"
+ + (f" ({loss.detail})" if loss.detail else ""))
else:
lines.append(f" not represented in {target}: none")
if self.not_in_source:
@@ -139,10 +153,17 @@ def summary_markdown(self) -> str:
"",
]
if self.not_in_target:
- lines += ["| Feature | Count | Detail |", "|---|---:|---|"]
- for loss in self.not_in_target:
- lines.append(f"| {loss.feature} | {loss.count} | "
- f"{loss.detail or ''} |")
+ for kind, label in (("substituted", "Substituted"),
+ ("partial", "Partially mapped"),
+ ("dropped", "Dropped")):
+ group = [loss for loss in self.not_in_target if loss.kind == kind]
+ if not group:
+ continue
+ lines += ["", f"### {label}", "",
+ "| Feature | Count | Detail |", "|---|---:|---|"]
+ for loss in group:
+ lines.append(f"| {loss.feature} | {loss.count} | "
+ f"{loss.detail or ''} |")
else:
lines.append("None.")
if self.not_in_source:
@@ -455,6 +476,240 @@ def _has_rows(tables: dict[str, AwbTable], name: str) -> int:
return len(_rows(tables, name))
+_SIDECAR_SUFFIX = ".raptor.json"
+
+
+def sidecar_path(path: str | Path) -> Path:
+ p = Path(path)
+ return p.with_name(p.name + _SIDECAR_SUFFIX)
+
+
+def _sidecar_payload(rbd: RbdFile) -> dict[str, Any]: # noqa: C901, PLR0912, PLR0915
+ """The RAPTOR-only data an AWB file cannot carry, in one JSON object.
+
+ The payload is deliberately separate from the .awb: it should never make
+ AWB validate or open a field it does not know. Import reads it only when
+ the .awb beside it still has the hash recorded here.
+ """
+ data: dict[str, Any] = {}
+ annotations = [dict(a) for a in (getattr(rbd, "annotations", None) or [])
+ if _text(a.get("kind"), "text") != "text"]
+ if annotations:
+ data["annotations"] = annotations
+ if getattr(rbd, "rates", None):
+ data["rates"] = list(rbd.rates)
+ if getattr(rbd, "formulas", None):
+ data["formulas"] = dict(rbd.formulas)
+ triggers = _section_list(rbd, "TRIGGERS")
+ if triggers:
+ data["triggers"] = [dict(t) for t in triggers]
+ events = [dict(e) for e in _section_list(rbd, "EVENT_DATA")
+ if _text(e.get("ID")) not in ("", "0")]
+ if events:
+ data["events"] = events
+ if getattr(rbd, "out_of_service", None):
+ data["out_of_service"] = dict(rbd.out_of_service)
+ if getattr(rbd, "comments", None) or _section_list(rbd, "COMMENTS"):
+ data["comments"] = [dict(c) for c in _section_list(rbd, "COMMENTS")]
+ block_extras = {}
+ for b in _section_list(rbd, "BLOCK_DATA"):
+ bid = _text(b.get("ID"))
+ if bid in ("", "0"):
+ continue
+ extra = {k: b.get(k) for k in (
+ "DepType", "DepNum", "DepNothing", "DepIdle", "DepPM",
+ "DepFail", "DepPMThresh", "defDepStateIdle", "Phasing",
+ "SimStart", "AmtExhausted", "SBStress", "GDType", "GDRate",
+ "GDLimit", "_DutyCycle", "_StartAge", "_RestoreFactor",
+ "_RestoreType", "NonOperational", "usesPM", "PMFreq",
+ "Dist", "Param1#3", "Param2#3", "Param3#3",
+ "initial", "Running", "standby", "idle", "repHold",
+ "repPerTime", "repFixed", "donePerTime", "doneFixed",
+ "pmHoldCost", "pmCost", "pmFixedCost", "perSpare",
+ "emerShipping")
+ if b.get(k) not in (None, "", "0", "0.000000")}
+ phases = {k: v for k, v in b.items() if k.startswith("P ")}
+ if phases:
+ extra["phases"] = phases
+ if extra:
+ block_extras[bid] = extra
+ if block_extras:
+ data["block_extras"] = block_extras
+ node_extras = {}
+ for n in _section_list(rbd, "NODE_DATA"):
+ nid = _text(n.get("ID"))
+ if nid in ("", "0"):
+ continue
+ extra = {k: n.get(k) for k in (
+ "Cold", "PR", "Autos", "k*", "Phases", "depNum", "depType",
+ "repCap", "repNA", "fullflow", "divFlow")
+ if n.get(k) not in (None, "", "0", "0.000000")}
+ phases = {k: v for k, v in n.items() if k.startswith("P")}
+ if phases:
+ extra["phases"] = phases
+ if extra:
+ node_extras[nid] = extra
+ if node_extras:
+ data["node_extras"] = node_extras
+ hier_extras = {}
+ for h in _section_list(rbd, "HIERARCHY_DATA"):
+ hid = _text(h.get("ID"))
+ if hid in ("", "0"):
+ continue
+ extra = {k: h.get(k) for k in ("Phs", "In", "Out")
+ if h.get(k) not in (None, "", "0")}
+ if extra:
+ hier_extras[hid] = extra
+ if hier_extras:
+ data["hierarchy_extras"] = hier_extras
+ system = _system_row(rbd)
+ system_extra = {k: system.get(k) for k in (
+ "capacityAnalysis", "costAnalysis", "weakAnalysis", "flowGenerated",
+ "systemRedCost", "sysLostCost", "nodeAnalType", "GYthreshold",
+ "YRthreshold") if system.get(k) not in (None, "", "0")}
+ if system_extra:
+ data["system"] = system_extra
+ link_extras = []
+ for link in _section_list(rbd, "LINK_DATA"):
+ extra = {k: link.get(k) for k in (
+ "ColdPri", "AProb", "AutoTime", "ManTime", "CapPri",
+ "nomFlow", "MaxFlow") if link.get(k) not in (None, "", "0")}
+ if extra:
+ link_extras.append({"id": link.get("ID"), **extra})
+ if link_extras:
+ data["links"] = link_extras
+ for key in ("project_meta", "display_unit", "advisor", "view",
+ "link_grips", "flow_directions"):
+ value = getattr(rbd, key, None)
+ if value:
+ data[key] = value
+ pools = _section_list(rbd, "SPARE_POOL_DATA")
+ if pools:
+ data["spare_pools"] = [dict(p) for p in pools]
+ resources = _section_list(rbd, "RESOURCE_DATA")
+ if resources:
+ data["resources"] = [dict(r) for r in resources]
+ return data
+
+
+def write_sidecar(awb_path: str | Path, payload: dict[str, Any]) -> Path:
+ import hashlib
+ import json
+ target = Path(awb_path)
+ doc = {
+ "schema": "raptor-awb-sidecar/1",
+ "awb": target.name,
+ "awb_sha256": hashlib.sha256(target.read_bytes()).hexdigest(),
+ "data": payload,
+ }
+ path = sidecar_path(target)
+ path.write_text(json.dumps(doc, indent=1, default=str) + "\n")
+ return path
+
+
+def read_sidecar(awb_path: str | Path) -> dict[str, Any] | None:
+ import hashlib
+ import json
+ path = sidecar_path(awb_path)
+ if not path.is_file():
+ return None
+ try:
+ doc = json.loads(path.read_text())
+ except (OSError, ValueError):
+ return None
+ expected = doc.get("awb_sha256")
+ actual = hashlib.sha256(Path(awb_path).read_bytes()).hexdigest()
+ if expected and expected != actual:
+ return None
+ return doc.get("data") if isinstance(doc.get("data"), dict) else None
+
+
+def apply_sidecar(doc: dict[str, Any], data: dict[str, Any], # noqa: C901, PLR0912, PLR0915
+ report: AwbReport) -> None:
+ """Put RAPTOR-only metadata back into the document before parse_rbds."""
+ if not data:
+ return
+ if data.get("annotations"):
+ doc.setdefault("annotations", []).extend(data["annotations"])
+ report.notes.append(
+ f"{len(data['annotations'])} non-text annotation(s) restored "
+ "from the AWB sidecar")
+ for key in ("rates", "formulas", "triggers", "out_of_service",
+ "project_meta", "display_unit", "advisor", "view",
+ "link_grips", "flow_directions"):
+ if data.get(key):
+ doc[key] = data[key]
+ if data.get("system"):
+ system = data["system"]
+ doc.setdefault("system", {}).update(
+ {k: v for k, v in system.items()
+ if k not in ("capacityAnalysis", "costAnalysis", "weakAnalysis")})
+ analyses = doc.setdefault("experiment", {}).setdefault("analyses", [])
+ for flag, name in (("capacityAnalysis", "capacity"),
+ ("costAnalysis", "cost"),
+ ("weakAnalysis", "weak")):
+ value = system.get(flag)
+ if value not in (None, "", "0", 0) and name not in analyses:
+ analyses.append(name)
+ if data.get("comments"):
+ existing = doc.get("comments") or []
+ existing.extend(data["comments"])
+ doc["comments"] = existing
+ blocks = {(b.get("name") or str(b.get("id"))): b
+ for b in doc.get("elements", {}).get("blocks", [])}
+ for bid, extra in (data.get("block_extras") or {}).items():
+ target = blocks.get(bid)
+ if target is None:
+ continue
+ for key, value in extra.items():
+ if key == "phases":
+ target["uses_phasing"] = True
+ target.setdefault("legacy", {}).update(value)
+ elif key not in target:
+ target[key] = value
+ for nid, extra in (data.get("node_extras") or {}).items():
+ for node in doc.get("elements", {}).get("nodes", []):
+ if (node.get("name") or str(node.get("id"))) == nid:
+ for key, value in extra.items():
+ if key == "phases":
+ node["uses_phasing"] = True
+ node.setdefault("legacy", {}).update(value)
+ elif key not in node:
+ node[key] = value
+ break
+ for hid, extra in (data.get("hierarchy_extras") or {}).items():
+ for hier in doc.get("elements", {}).get("hierarchies", []):
+ if (hier.get("name") or str(hier.get("id"))) == hid:
+ for key, value in extra.items():
+ if key == "Phs":
+ hier["uses_phasing"] = True
+ hier.setdefault("legacy", {})["Phs"] = value
+ elif key not in hier:
+ hier[key] = value
+ break
+ if data.get("spare_pools"):
+ by_name = {p.get("name"): p for p in doc.get("spare_pools", [])}
+ for row in data["spare_pools"]:
+ name = row.get("PoolName") or row.get("name")
+ if name and name in by_name:
+ # Keep the imported values; restore only fields RAPTOR has.
+ for key in ("rso", "stock", "new_spares", "arrive_every",
+ "eso", "emer_time", "slo", "level", "quantity",
+ "slo_time", "spare_cost", "emer_ship_cost"):
+ if key in row:
+ by_name[name][key] = row[key]
+ if data.get("resources"):
+ by_name = {r.get("name"): r for r in doc.get("resources", [])}
+ for row in data["resources"]:
+ name = row.get("PoolName") or row.get("name")
+ if name and name in by_name:
+ for key in ("num_in", "spare_cost", "fixed_per_use",
+ "per_time_unit", "phases"):
+ if key in row:
+ by_name[name][key] = row[key]
+ report.notes.append("AWB sidecar merged with the imported model")
+
+
# ---------------------------------------------------------------------------
# RAPTOR -> AWB
# ---------------------------------------------------------------------------
@@ -524,7 +779,8 @@ def walk(hid: str, stack: tuple[str, ...] = ()) -> int:
def export_awb(rbd: RbdFile, path: str | Path, *, # noqa: C901, PLR0912, PLR0915
- source: str = "", write: bool = True) -> AwbReport:
+ source: str = "", write: bool = True,
+ sidecar: bool = True) -> AwbReport:
"""Write *rbd* as an AWB 5.0 project and return the loss report.
``write=False`` builds the same report and tables without touching the
@@ -534,6 +790,7 @@ def export_awb(rbd: RbdFile, path: str | Path, *, # noqa: C901, PLR0912, PLR091
src = source or getattr(rbd, "file_name", "") or "model"
dest = str(path)
report = AwbReport("rbds-to-awb", src, dest)
+ side_payload = _sidecar_payload(rbd)
# RAPTOR's out-of-service what-if is ordinary effective model data: a cut
# block starts failed with no repair, a linked block never fails. Apply
@@ -1122,6 +1379,12 @@ def add_spare(name: str, description: str, stock: int, new_spares: int,
tables[name] = AwbTable(name, _SCHEMA[name], rows)
if write:
write_awb(dest, tables)
+ if sidecar and side_payload:
+ side_path = write_sidecar(dest, side_payload)
+ report.sidecar = str(side_path)
+ report.notes.append(
+ f"RAPTOR-only metadata preserved in {side_path.name}; "
+ "import it beside the .awb to restore it")
report.counts.update(blocks=len(blocks), nodes=len(nodes),
hierarchies=len(hierarchies), links=len(conn_rows),
@@ -1137,23 +1400,28 @@ def add_spare(name: str, description: str, stock: int, new_spares: int,
if dist_simplified:
for label, count in sorted(dist_simplified.items()):
report.add("failure distribution simplified to exponential",
- count, f"{label} -> exponential with its mean MTTF")
+ count, f"{label} -> exponential with its mean MTTF",
+ kind="substituted")
if repair_simplified:
for label, count in sorted(repair_simplified.items()):
report.add("repair distribution simplified to a fixed duration",
- count, f"{label} -> AWB task duration = its mean")
+ count, f"{label} -> AWB task duration = its mean",
+ kind="substituted")
if no_repair:
report.add("no-repair blocks", no_repair,
- "exported with NonMaintainable=1 and a zero-duration task")
+ "exported with NonMaintainable=1 and a zero-duration task",
+ kind="substituted")
if no_failure:
report.add("no-failure blocks", no_failure,
- "exported with a fixed time of 9e8 hours (never fails)")
+ "exported with a fixed time of 9e8 hours (never fails)",
+ kind="substituted")
_report_raptor_features(rbd, report, blocks, nodes, links, events,
hierarchies, units, factor)
if pm_lossy:
report.add("additional or non-fixed PM", pm_lossy,
"one fixed-duration PM per failure model is written; "
- "extra tasks and random PM durations are simplified")
+ "extra tasks and random PM durations are simplified",
+ kind="partial")
if custom_spare_count:
report.notes.append(
f"{custom_spare_count} block-owned spare stock(s) became "
@@ -1176,6 +1444,82 @@ def add_spare(name: str, description: str, stock: int, new_spares: int,
return report
+def normalize_for_awb(rbd: RbdFile) -> tuple[RbdFile, list[str]]: # noqa: C901
+ """Return a copy reduced to what the AWB export actually carries.
+
+ Used by ``--normalize-out`` and by paired engine comparisons: both
+ programs then run the same reduced model, so a difference measures the
+ engines rather than a feature the AWB file does not contain.
+ """
+ out = copy.deepcopy(rbd)
+ actions: list[str] = []
+ for row in _section_list(out, "BLOCK_DATA"):
+ if _text(row.get("ID")) in ("", "0"):
+ continue
+ fdist = _int(row.get("FDist"), _R_EXPO)
+ if fdist not in (_R_EXPO, _R_LOGNORM, _R_NORM, _R_WEIBULL, _R_NONE, _R_FIXED):
+ mean = _dist_mean(fdist, [_num(row.get("FParam1")),
+ _num(row.get("FParam2")),
+ _num(row.get("FParam3"))])
+ row.update({"FDist": str(_R_EXPO), "#FParam": "2",
+ "FParam1": f"{mean if mean and mean > 0 else _num(row.get('FParam1')):.6f}",
+ "FParam2": "0.000000", "FParam3": "0.000000"})
+ actions.append("unsupported failure law -> exponential mean")
+ rdist = _int(row.get("RDist"), _R_FIXED)
+ if rdist not in (_R_NONE, _R_FIXED):
+ mean = _dist_mean(rdist, [_num(row.get("RParam1")),
+ _num(row.get("RParam2")),
+ _num(row.get("RParam3"))])
+ row.update({"RDist": str(_R_FIXED), "#RParam": "1",
+ "RParam1": f"{mean if mean and mean > 0 else _num(row.get('RParam1')):.6f}",
+ "RParam2": "0.000000", "RParam3": "0.000000"})
+ actions.append("repair distribution -> fixed mean")
+ row.update({"DepType": "None", "DepNum": "0", "DepNothing": "0.00",
+ "DepIdle": "100.00", "DepPM": "0.00", "DepFail": "0.00",
+ "DepPMThresh": "75.00", "defDepStateIdle": "0",
+ "SBStress": "0.000", "GDType": "0", "GDRate": "1.000000",
+ "GDLimit": "1.000000", "_DutyCycle": "1.000000",
+ "_StartAge": "0.000000", "_RestoreFactor": "0.000000",
+ "_RestoreType": "0"})
+ # Events are not exported at all; remove them and every link touching one.
+ event_ids = {_text(e.get("ID")) for e in _section_list(out, "EVENT_DATA")
+ if _text(e.get("ID")) not in ("", "0")}
+ if event_ids:
+ ev_sec = out.sections.get("EVENT_DATA")
+ if ev_sec:
+ ev_sec.rows = [r for r in ev_sec.rows
+ if _text(r.get("ID")) in ("", "0")]
+ link_sec = out.sections.get("LINK_DATA")
+ if link_sec:
+ link_sec.rows = [r for r in link_sec.rows
+ if not ((_text(r.get("FromType")) == "Event"
+ and _text(r.get("FromID")) in event_ids)
+ or (_text(r.get("ToType")) == "Event"
+ and _text(r.get("ToID")) in event_ids))]
+ actions.append("failure events and their links removed")
+ for row in _section_list(out, "NODE_DATA"):
+ row.update({"Cold": "0", "PR": "0", "Autos": "1", "k*": "0",
+ "Phases": "0"})
+ for row in _section_list(out, "HIERARCHY_DATA"):
+ row["Phs"] = "0"
+ for row in _section_list(out, "LINK_DATA"):
+ row.update({"ColdPri": "50", "AProb": "1.000000",
+ "AutoTime": "0.000000", "ManTime": "0.000000",
+ "CapPri": "50", "nomFlow": "-2", "MaxFlow": "-1"})
+ system = _system_row(out)
+ system.update({"capacityAnalysis": "0", "costAnalysis": "0",
+ "weakAnalysis": "0"})
+ out.rates = []
+ out.formulas = {}
+ triggers = out.sections.get("TRIGGERS")
+ if triggers is not None:
+ triggers.rows = []
+ out.annotations = []
+ out.link_grips = []
+ out.view = {}
+ return out, actions
+
+
def _report_raptor_features(rbd: RbdFile, report: AwbReport, # noqa: C901, PLR0912, PLR0915
blocks: list[dict[str, Any]],
nodes: list[dict[str, Any]],
@@ -1305,6 +1649,7 @@ def import_awb(path: str | Path, *, # noqa: C901, PLR0912, PLR0915
src = source or str(path)
tables = read_awb(path)
report = AwbReport("awb-to-rbds", src, "RAPTOR model")
+ side_data = read_sidecar(path)
_check_import_features(tables, report)
blocks = _rows(tables, "RbdBlocks")
@@ -1941,6 +2286,8 @@ def add_junction(owner: int, name: str, x: float, y: float) -> int:
"phases": phase_doc,
"out_of_service": out_of_service_doc,
}
+ if side_data:
+ apply_sidecar(doc, side_data, report)
from raptor.core.fileio.rbds import parse_rbds
rbd = parse_rbds(json.dumps(doc), default_name=Path(src).stem)
return rbd, report
@@ -2088,7 +2435,7 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
report.add("extra planned-maintenance tasks",
len(planned) - len(fms_with_planned),
"RAPTOR has one PM per block; only the first planned "
- "task per failure model is imported")
+ "task per failure model is imported", kind="partial")
inspections = [t for t in sched
if _int(t.get("Type"), 0) == 1 and _int(t.get("Enabled"), 0)]
if inspections:
@@ -2103,7 +2450,7 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
if two_level:
report.add("two-level spare holdings", two_level,
"AWB level-1 and level-2 stock are summed into one "
- "RAPTOR pool")
+ "RAPTOR pool", kind="substituted")
repair_shop = sum(1 for sp in _rows(tables, "Spares")
if _int(sp.get("RepairLevel"), 0))
if repair_shop:
@@ -2118,7 +2465,8 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
if _int(r.get("Type"), 0) != 1]
if capacity_rules:
report.add("phase capacity/load rules", len(capacity_rules),
- "only AWB phase logic/out-of-service rules are imported")
+ "only AWB phase logic/out-of-service rules are imported",
+ kind="partial")
if _rows(tables, "RcmLocations") or _rows(tables, "RcmCauses"):
report.add("RCM location hierarchy", max(
len(_rows(tables, "RcmLocations")), len(_rows(tables, "RcmCauses"))),
diff --git a/raptor/gui/command_table.py b/raptor/gui/command_table.py
index 5248cf7d..fc2fbfcf 100644
--- a/raptor/gui/command_table.py
+++ b/raptor/gui/command_table.py
@@ -137,6 +137,16 @@
"represent"),
handler="_export_awb",
enabled_when="model_open"),
+ CommandSpec(
+ id="file.preview_awb",
+ attr="_preview_awb_action",
+ text="Check Availability Workbench Export…",
+ icon="awb_preview_icon:text",
+ tooltip=(
+ "Report what an Availability Workbench export would substitute, "
+ "partially map or drop, without writing a file"),
+ handler="_preview_awb",
+ enabled_when="model_open"),
CommandSpec(
id="file.export_tables",
attr="_export_tables_action",
@@ -1444,7 +1454,8 @@ def _p(title: str, index_attr: str, *groups: Group) -> Page:
# Tables for choosing tables; the single-type commands stay in the
# command palette and on their shortcuts.
("Print and Export", ("file.print", "file.export", "file.export_awb",
- "file.export_tables", "file.copy_view")),
+ "file.preview_awb", "file.export_tables",
+ "file.copy_view")),
)
#: Commands with a top level entry in the File view's nav column, after
diff --git a/raptor/gui/resources/icons.py b/raptor/gui/resources/icons.py
index a4b76363..8341e402 100644
--- a/raptor/gui/resources/icons.py
+++ b/raptor/gui/resources/icons.py
@@ -1411,6 +1411,20 @@ def draw(p: QPainter, c: QColor):
return _icon("awbexport", colour, draw)
+def awb_preview_icon(colour: str) -> QIcon:
+ """Preview an AWB export: a document under a magnifier."""
+ def draw(p: QPainter, c: QColor):
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.setPen(QPen(c, 3))
+ p.drawRect(6, 6, 24, 32)
+ p.drawLine(12, 14, 24, 14)
+ p.drawLine(12, 21, 24, 21)
+ p.drawLine(12, 28, 19, 28)
+ p.drawEllipse(QPointF(31, 31), 8, 8)
+ p.drawLine(37, 37, 44, 44)
+ return _icon("awbpreview", colour, draw)
+
+
def clear_results_icon(colour: str) -> QIcon:
"""Clear Results: table swept by a diagonal wipe."""
def draw(p: QPainter, c: QColor):
diff --git a/raptor/gui/ui/export_mixin.py b/raptor/gui/ui/export_mixin.py
index ebecd573..30f39adf 100644
--- a/raptor/gui/ui/export_mixin.py
+++ b/raptor/gui/ui/export_mixin.py
@@ -116,12 +116,15 @@ def _export_tables(self):
from raptor.gui.ui.tables_dialog import open_export_tables_dialog
open_export_tables_dialog(self)
- def _export_awb(self, path: str | None = None):
- """File ▸ Export to Availability Workbench…: write one .awb project."""
+ def _export_awb(self, path: str | None = None, *, dry_run: bool = False):
+ """File ▸ Export to Availability Workbench…: write/preview .awb."""
if self._rbd is None:
return
stem = Path(self._current_file).stem if self._current_file else "model"
- if path is None:
+ if path is None and dry_run:
+ path = str(Path(self._current_file).with_suffix(".awb")) \
+ if self._current_file else stem + ".awb"
+ elif path is None:
path, _ = fdg.getSaveFileName(
self, "Export Availability Workbench Project",
stem + ".awb", "Availability Workbench projects (*.awb)")
@@ -129,13 +132,14 @@ def _export_awb(self, path: str | None = None):
return
if not str(path).lower().endswith(".awb"):
path += ".awb"
- from raptor.core.fileio.awb import export_awb
+ from raptor.api import awb as awb_api
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
self._export_in_progress = True
try:
self._diagram_dock.view.write_back_to_rbd(self._rbd)
- report = export_awb(
- req(self._rbd), path, source=self._current_file or "")
+ report = awb_api.export(
+ req(self._rbd), path, source=self._current_file or "",
+ write=not dry_run)
except Exception as exc: # noqa: BLE001 - report the file, not a crash
msgbox.critical(
self, "Export Failed",
@@ -147,8 +151,15 @@ def _export_awb(self, path: str | None = None):
QApplication.restoreOverrideCursor()
show = getattr(self, "_show_awb_report", None)
if show is not None:
- show("Availability Workbench export", report, path, wrote=True)
- self._statusbar.showMessage(f"AWB project saved: {Path(path).name}", 8000)
+ show("Availability Workbench export", report, path,
+ wrote=not dry_run)
+ self._statusbar.showMessage(
+ "AWB export preview" if dry_run
+ else f"AWB project saved: {Path(path).name}", 8000)
+
+ def _preview_awb(self):
+ """File ▸ Check Availability Workbench export…: report only."""
+ self._export_awb(dry_run=True)
def _export_workbook_xlsx(self, path: str | None = None):
"""File > Export Excel Workbook...: one .xlsx of the default tables."""
diff --git a/raptor/gui/ui/file_io_mixin.py b/raptor/gui/ui/file_io_mixin.py
index c46759b6..e3849bb3 100644
--- a/raptor/gui/ui/file_io_mixin.py
+++ b/raptor/gui/ui/file_io_mixin.py
@@ -523,8 +523,9 @@ def _show_awb_report(self, title: str, report: Any, path: str,
from PySide6.QtWidgets import QMessageBox
box = QMessageBox(self)
box.setWindowTitle(title)
- if wrote:
- box.setText(f"Wrote {path}.")
+ if report.direction == "rbds-to-awb":
+ box.setText(f"Wrote {path}." if wrote
+ else f"Preview for {path}; nothing was written.")
else:
box.setText(f"Imported {path}.")
losses = len(report.not_in_target)
diff --git a/raptor/mcp/output_schemas.json b/raptor/mcp/output_schemas.json
index 624b306e..f923f922 100644
--- a/raptor/mcp/output_schemas.json
+++ b/raptor/mcp/output_schemas.json
@@ -1183,6 +1183,65 @@
],
"type": "object"
},
+ "export_awb": {
+ "properties": {
+ "counts": {
+ "type": "object"
+ },
+ "direction": {
+ "type": "string"
+ },
+ "dry_run": {
+ "type": "boolean"
+ },
+ "normalized_path": {
+ "type": "null"
+ },
+ "not_in_source": {
+ "type": "array"
+ },
+ "not_in_target": {
+ "type": "array"
+ },
+ "notes": {
+ "type": "array"
+ },
+ "path": {
+ "type": "string"
+ },
+ "schema": {
+ "type": "string"
+ },
+ "sidecar": {
+ "type": "string"
+ },
+ "source": {
+ "type": "string"
+ },
+ "target": {
+ "type": "string"
+ },
+ "warnings": {
+ "type": "array"
+ }
+ },
+ "required": [
+ "counts",
+ "direction",
+ "dry_run",
+ "normalized_path",
+ "not_in_source",
+ "not_in_target",
+ "notes",
+ "path",
+ "schema",
+ "sidecar",
+ "source",
+ "target",
+ "warnings"
+ ],
+ "type": "object"
+ },
"export_report": {
"properties": {
"bytes": {
@@ -1614,6 +1673,25 @@
],
"type": "object"
},
+ "import_awb": {
+ "properties": {
+ "model_id": {
+ "type": "string"
+ },
+ "report": {
+ "type": "object"
+ },
+ "summary": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "model_id",
+ "report",
+ "summary"
+ ],
+ "type": "object"
+ },
"insert_assembly": {
"properties": {
"annotations": {
diff --git a/raptor/mcp/tools_model.py b/raptor/mcp/tools_model.py
index f40c402a..b4db7563 100644
--- a/raptor/mcp/tools_model.py
+++ b/raptor/mcp/tools_model.py
@@ -238,6 +238,72 @@ def save_model_as(model_id: str, path: str,
return ok(result, markdown=md)
+@mcp.tool(annotations=DESTRUCTIVE("Export Availability Workbench project"))
+@guarded
+def export_awb(model_id: str, path: str, dry_run: bool = False,
+ sidecar: bool = True,
+ normalize_out: str | None = None) -> CallToolResult:
+ """Write the model as an Isograph Availability Workbench .awb project.
+
+ The report names substituted, partially mapped and dropped features.
+ `dry_run=true` writes nothing. `sidecar=true` also writes a
+ `.awb.raptor.json` beside the file with RAPTOR-only metadata.
+ `normalize_out` writes a reduced RAPTOR model carrying only what the AWB
+ file represents; that reduced copy is what gets exported.
+ """
+ context.require_write()
+ ws = context.workspace()
+ path = context.require_relative_path(path)
+ dest = ws.resolve_output_path(path, allow_extra=context.allowed_write_dirs())
+ from raptor.api import awb as awb_api
+ rbd = ws.get(model_id).rbd
+ actions: list[str] = []
+ norm_path = None
+ if normalize_out:
+ norm_path = ws.resolve_output_path(
+ normalize_out, allow_extra=context.allowed_write_dirs())
+ rbd, actions = awb_api.normalize(rbd)
+ awb_api.save_normalized(rbd, norm_path)
+ report = awb_api.export(rbd, dest, source=model_id, write=False,
+ sidecar=sidecar)
+ report.notes.extend(f"normalized: {a}" for a in actions)
+ if not dry_run:
+ written = awb_api.export(rbd, dest, source=model_id, sidecar=sidecar)
+ report.sidecar = written.sidecar
+ payload = report.as_dict() | {
+ "path": str(dest), "dry_run": dry_run,
+ "normalized_path": str(norm_path) if norm_path else None,
+ }
+ md = report.summary_text()
+ if dry_run:
+ md += "\n\nDry run: nothing written."
+ return ok(payload, markdown=md)
+
+
+@mcp.tool(annotations=ADDITIVE("Import Availability Workbench project"))
+@guarded
+def import_awb(path: str) -> CallToolResult:
+ """Open an Isograph Availability Workbench .awb project as a model.
+
+ The report names the AWB features RAPTOR does not import. A matching
+ `.awb.raptor.json` sidecar, when present and unchanged, restores
+ RAPTOR-only metadata (rates, formulas, triggers, shape annotations,
+ dependencies and costs).
+ """
+ context.require_write()
+ ws = context.workspace()
+ src = ws.resolve_output_path(context.require_relative_path(path),
+ allow_extra=context.allowed_read_dirs())
+ from raptor.api import awb as awb_api
+ rbd, report = awb_api.import_project(src, source=str(src))
+ result = ws.register_model(rbd, name=src.stem, source=str(src))
+ payload = {"model_id": result["model_id"], "summary": result["summary"],
+ "report": report.as_dict()}
+ return ok(payload, markdown=(
+ f"Imported `{src.name}` as `{result['model_id']}`.\n\n"
+ + report.summary_text()))
+
+
@mcp.tool(annotations=DESTRUCTIVE("Close model"))
@guarded
def close_model(model_id: str | list[str],
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
index 240736b3..c5640c51 100644
--- a/tests/unit/test_awb.py
+++ b/tests/unit/test_awb.py
@@ -380,3 +380,124 @@ def test_pm_spares_resources_phases_and_out_of_service_round_trip(tmp_path):
assert back.out_of_service.get("block:2") == "cut"
assert "non-maintainable blocks" not in {
loss.feature for loss in report.not_in_target}
+
+
+def test_sidecar_preserves_raptor_only_metadata(tmp_path):
+ doc = {
+ "format": "raptor-studio", "version": 4,
+ "system": {"units": "hours", "capacityAnalysis": "1"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 1000.0},
+ "elements": {
+ "blocks": [{"id": 1, "name": "Pump", "x": 0, "y": 0,
+ "fail_dist": 4, "fail_params": [1000, 0, 0],
+ "dep_type": "RBDBlock", "dep_num": 2,
+ "rep_fixed_cost": 25.0}],
+ "nodes": [{"id": 2, "name": "start", "type": 1},
+ {"id": 3, "name": "end", "type": 3}],
+ "hierarchies": [],
+ },
+ "links": [{"id": 4, "from": ["Node", 2], "to": ["Block", 1]},
+ {"id": 5, "from": ["Block", 1], "to": ["Node", 3]}],
+ "rates": [{"name": "base", "expr": "1/1000", "value": 0.001}],
+ "formulas": {"block:1:FParam1": {"rate": "base", "value": 0.001}},
+ "triggers": [{"name": "Storm", "repeats": 1, "init_used": 0.0,
+ "dist": 8, "params": [288, 1, 0]}],
+ "annotations": [{"kind": "rect", "id": 1, "parent": 0,
+ "x": 0, "y": 0, "w": 20, "h": 20,
+ "text": ""}],
+ }
+ rbd = parse_rbds(json.dumps(doc))
+ path = tmp_path / "sidecar.awb"
+ report = export_awb(rbd, path)
+ side = path.with_name(path.name + ".raptor.json")
+ assert side.exists()
+ assert report.sidecar == str(side)
+ back, import_report = import_awb(path)
+ assert back.rates and back.formulas
+ assert len(back.sections["TRIGGERS"].rows) == 1
+ assert any(a.get("kind") == "rect" for a in back.annotations)
+ assert "sidecar" in " ".join(import_report.notes).lower()
+
+
+def test_sidecar_can_be_disabled(tmp_path):
+ rbd = _model()
+ path = tmp_path / "no-sidecar.awb"
+ export_awb(rbd, path, sidecar=False)
+ assert not path.with_name(path.name + ".raptor.json").exists()
+
+
+def test_dry_run_writes_nothing(tmp_path):
+ rbd = _model()
+ path = tmp_path / "dry.awb"
+ report = export_awb(rbd, path, write=False)
+ assert not path.exists()
+ assert not path.with_name(path.name + ".raptor.json").exists()
+ assert report.direction == "rbds-to-awb"
+
+
+def test_normalize_replaces_unsupported_repair_and_clears_extras(tmp_path):
+ doc = {
+ "format": "raptor-studio", "version": 4,
+ "system": {"units": "hours", "capacityAnalysis": "1"},
+ "experiment": {"trials": 10, "termination_type": "TimeSim",
+ "term_condition": 1000.0},
+ "elements": {
+ "blocks": [{"id": 1, "name": "Pump", "x": 0, "y": 0,
+ "fail_dist": 14, "fail_params": [0, 50, 100],
+ "repair_dist": 15, "repair_params": [2, 10, 0],
+ "dep_type": "RBDBlock", "dep_num": 2}],
+ "nodes": [{"id": 2, "name": "start", "type": 1},
+ {"id": 3, "name": "end", "type": 3}],
+ "hierarchies": [],
+ },
+ "links": [{"id": 4, "from": ["Node", 2], "to": ["Block", 1]},
+ {"id": 5, "from": ["Block", 1], "to": ["Node", 3]}],
+ "annotations": [{"kind": "text", "id": 1, "parent": 0,
+ "x": 0, "y": 0, "w": 10, "h": 10, "text": "x"}],
+ "rates": [{"name": "base", "expr": "1/1000", "value": 0.001}],
+ }
+ from raptor.core.fileio.awb import normalize_for_awb
+ rbd = parse_rbds(json.dumps(doc))
+ norm, actions = normalize_for_awb(rbd)
+ block = _rows(norm, "BLOCK_DATA")[0]
+ assert block["FDist"] == "4"
+ assert block["RDist"] == "19"
+ assert block["DepType"] == "None"
+ assert not norm.annotations and not norm.rates
+ assert actions
+
+
+def test_cli_dry_run_writes_nothing(tmp_path, capsys):
+ from raptor.cli.main import main
+ src = tmp_path / "model.rbds"
+ save_rbds(_model(), str(src))
+ dest = tmp_path / "preview.awb"
+ assert main(["convert", str(src), str(dest), "--dry-run",
+ "-f", "json"]) == 0
+ assert not dest.exists()
+ assert not dest.with_name(dest.name + ".raptor.json").exists()
+ assert '"direction": "rbds-to-awb"' in capsys.readouterr().out
+
+
+def test_cli_normalize_out_writes_reduced_model(tmp_path):
+ from raptor.cli.main import main
+ src = tmp_path / "model.rbds"
+ save_rbds(_model(), str(src))
+ dest = tmp_path / "model.awb"
+ norm = tmp_path / "normalized.rbds"
+ assert main(["convert", str(src), str(dest),
+ "--normalize-out", str(norm)]) == 0
+ assert dest.exists() and norm.exists()
+ from raptor.core.fileio.model_file import load_model_file
+ loaded = load_model_file(norm)
+ assert _rows(loaded, "BLOCK_DATA")
+
+
+def test_cli_no_sidecar(tmp_path):
+ from raptor.cli.main import main
+ src = tmp_path / "model.rbds"
+ save_rbds(_model(), str(src))
+ dest = tmp_path / "model.awb"
+ assert main(["convert", str(src), str(dest), "--no-sidecar"]) == 0
+ assert not dest.with_name(dest.name + ".raptor.json").exists()
diff --git a/tests/unit/test_mcp_tools_model.py b/tests/unit/test_mcp_tools_model.py
index 7f1701b6..1c355812 100644
--- a/tests/unit/test_mcp_tools_model.py
+++ b/tests/unit/test_mcp_tools_model.py
@@ -532,3 +532,26 @@ def test_every_file_argument_refuses_an_absolute_path(tmp_path):
delete_file("/tmp/x.rbds")):
assert result.is_error
assert result.structured_content["error"]["code"] == "invalid_argument"
+
+
+class TestAwbInterchange:
+ def test_export_dry_run_then_import(self, tmp_path):
+ from raptor.mcp.server import mcp
+ mcp._raptor_args = type("A", (), {
+ "workspace": str(tmp_path), "allow_write": [],
+ "allow_read": []})()
+ mcp._raptor_ws = None
+ from raptor.mcp.tools_model import (
+ create_model, export_awb, import_awb,
+ )
+ model_id = _sc(create_model("AWBParity", template="blank"))["model_id"]
+ out = tmp_path / "parity.awb"
+ dry = _sc(export_awb(model_id, "parity.awb", dry_run=True))
+ assert dry["dry_run"] is True
+ assert not out.exists()
+ result = _sc(export_awb(model_id, "parity.awb"))
+ assert out.exists()
+ assert result["path"].endswith("parity.awb")
+ imported = _sc(import_awb("parity.awb"))
+ assert imported["model_id"].startswith("m")
+ assert imported["report"]["direction"] == "awb-to-rbds"
diff --git a/tools/gen_mcp_output_schemas.py b/tools/gen_mcp_output_schemas.py
index 7d4b6274..8d25cb22 100644
--- a/tools/gen_mcp_output_schemas.py
+++ b/tools/gen_mcp_output_schemas.py
@@ -183,6 +183,9 @@ def session(rec: Recorder, workspace: Path) -> None: # noqa: PLR0915
rec.call("read_doc", name="rbds", limit=5)
rec.call("read_doc", name="iec61078", limit=5)
rec.call("save_model_as", model_id=m1, path="out.rbds")
+ rec.call("export_awb", model_id=m1, path="out.awb", dry_run=True)
+ rec.call("export_awb", model_id=m1, path="out.awb")
+ rec.call("import_awb", path="out.awb")
rec.call("delete_element", model_id=m3, selector="E1")
rec.call("collapse_selection", model_id=m1, selectors=["B1"], name="Sub") # one link in, one out: a hierarchy takes no more (Raptor 7)
rec.call("close_model", model_id=m3)
@@ -219,7 +222,7 @@ def optimisers(rec: Recorder) -> None:
quantiles=[{"probability": 0.1, "age": 100}, {"probability": 0.5, "age": 300}])
-def more(rec: Recorder, m1: str, run: str | None, attributed_run: str | None) -> None: # noqa: PLR0915
+def more(rec: Recorder, m1: str, run: str | None, attributed_run: str | None) -> None: # noqa: C901, PLR0915
"""The tools the main session does not reach: batch edits, library,
pools, jobs, scenarios and run outputs. On a model of its own, so the
main session's results do not move."""
diff --git a/tools/gen_mcp_reference.py b/tools/gen_mcp_reference.py
index 77cadf46..06e0a823 100644
--- a/tools/gen_mcp_reference.py
+++ b/tools/gen_mcp_reference.py
@@ -77,6 +77,8 @@
"open_model": "workspace",
"create_model": "workspace",
"save_model_as": "workspace",
+ "export_awb": "workspace",
+ "import_awb": "workspace",
"close_model": "workspace",
"delete_file": "workspace",
# Build and edit
@@ -184,6 +186,10 @@
"create_model": {"name": "Pump station", "template": "series", "n": 3},
"save_model_as": {"model_id": "",
"path": "exports/pump-station.rbds"},
+ "export_awb": {"model_id": "",
+ "path": "exports/pump-station.awb",
+ "dry_run": True, "sidecar": True},
+ "import_awb": {"path": "exports/pump-station.awb"},
"close_model": {"model_id": ""},
"delete_file": {"path": "exports/old-model.rbds"},
"build_model": {
@@ -414,7 +420,7 @@ def _dedupe(items: list[str]) -> list[str]:
return out
-def _schema_types(schema: Any) -> tuple[list[str], list[Any]]:
+def _schema_types(schema: Any) -> tuple[list[str], list[Any]]: # noqa: C901
"""Return ``(type labels, enum/const values)`` for a JSON Schema node."""
if not isinstance(schema, dict):
return ["any"], []
@@ -755,7 +761,7 @@ def _validate_metadata(tools: list[Any]) -> None:
problems))
-def render() -> str:
+def render() -> str: # noqa: C901
"""Render ``docs/MCP-reference.md`` from the live server."""
tools, fixed, templates, prompts = _live()
_validate_metadata(tools)
From caf49c2ee47a9a778ce5ab1c82f6b806ce299c41 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Tue, 17 Nov 2026 21:22:53 +1000
Subject: [PATCH 07/15] feat(awb): GUI reduced-model export and final
validation notes
---
docs/AWB_VALIDATION.md | 14 ++++++++------
docs/manual-reference.adoc | 1 +
docs/manual.adoc | 6 +++---
docs/manual.html | 11 ++++++++---
raptor/gui/command_table.py | 14 ++++++++++++--
raptor/gui/resources/icons.py | 15 +++++++++++++++
raptor/gui/ui/export_mixin.py | 36 +++++++++++++++++++++++++++++++++++
7 files changed, 83 insertions(+), 14 deletions(-)
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
index 8ff6153e..de39f979 100644
--- a/docs/AWB_VALIDATION.md
+++ b/docs/AWB_VALIDATION.md
@@ -86,12 +86,14 @@ comparison.
`raptor convert ... --normalize-out` reduced CarCare0's lognormal repair
to its fixed mean and wrote both files. At 1000 trials:
-| | RAPTOR | AWB |
-|---|---:|---:|
-| Availability | 0.990345 | 0.9904 |
-
-Difference **0.0055 percentage points**, excellent agreement. This
-validates the normalization pathway for repair-law-only differences.
+| Example | RAPTOR | AWB | Difference (pp) |
+|---|---:|---:|---:|
+| CarCare0 | 0.990345 | 0.9904 | 0.0055 |
+| Van1 (2 hierarchies) | 0.986632 | 0.9869 | 0.026 |
+
+Both are within display precision. This validates the normalization
+pathway for repair-law-only differences, including a model with nested
+hierarchies.
### Feature smoke test (Stage 1/2)
diff --git a/docs/manual-reference.adoc b/docs/manual-reference.adoc
index 07ff4ab1..fac24f49 100644
--- a/docs/manual-reference.adoc
+++ b/docs/manual-reference.adoc
@@ -385,6 +385,7 @@ documentation.
|Export… |Save the report, the tables or the diagram: one window, pick the file type (PDF, Excel, OpenDocument, SVG or PNG) (Ctrl+E) |Ctrl+E
|Export to Availability Workbench… |Save this model as an Isograph Availability Workbench 5.0 .awb project; the summary lists what RAPTOR features AWB cannot represent |
|Check Availability Workbench Export… |Report what an Availability Workbench export would substitute, partially map or drop, without writing a file |
+|Export Reduced AWB Model… |Save a matched pair: a reduced RAPTOR model and the .awb it represents, for a fair engine-to-engine comparison |
|Export Tables… |Choose which tables to write, the model's and a run's results, as CSV files, text or one spreadsheet with a tab per table |
|Copy View |Copy the current view to the clipboard as a high-resolution PNG |
|===
diff --git a/docs/manual.adoc b/docs/manual.adoc
index d93b6134..57671d5a 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1705,9 +1705,9 @@ the AvSim RBD part; it does not transfer an AWB RCMCost study, fault tree,
capacity network or life-cycle-cost model. The summary names each of these
with a count, so nothing is lost silently. **File ▸ Check Availability
Workbench Export…** is the preview: it reports substitutions, partial
-mappings and drops without writing. The command line adds `--dry-run`,
-`--no-sidecar` and `--normalize-out`; the normalizer writes a matched reduced
-RAPTOR model for a fair engine comparison. AWB may renumber pages and
+mappings and drops without writing. **File ▸ Export Reduced AWB Model…**
+writes a matched reduced RAPTOR model and its `.awb`. The command line adds
+`--dry-run`, `--no-sidecar` and `--normalize-out`. AWB may renumber pages and
element ids on a round trip, and it uses the source x/y positions rather
than auto-layout; use AWB's Auto Layout after opening a model whose blocks
overlap.
diff --git a/docs/manual.html b/docs/manual.html
index 5022d8a7..46cb16a9 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2564,9 +2564,9 @@ Availability Workbench interchange
capacity network or life-cycle-cost model. The summary names each of these
with a count, so nothing is lost silently. File ▸ Check Availability
Workbench Export… is the preview: it reports substitutions, partial
-mappings and drops without writing. The command line adds --dry-run,
---no-sidecar and --normalize-out; the normalizer writes a matched reduced
-RAPTOR model for a fair engine comparison. AWB may renumber pages and
+mappings and drops without writing. File ▸ Export Reduced AWB Model…
+writes a matched reduced RAPTOR model and its .awb. The command line adds
+--dry-run, --no-sidecar and --normalize-out. AWB may renumber pages and
element ids on a round trip, and it uses the source x/y positions rather
than auto-layout; use AWB’s Auto Layout after opening a model whose blocks
overlap.
@@ -4037,6 +4037,11 @@ Print and Export
|
+Export Reduced AWB Model… |
+Save a matched pair: a reduced RAPTOR model and the .awb it represents, for a fair engine-to-engine comparison |
+ |
+
+
Export Tables… |
Choose which tables to write, the model’s and a run’s results, as CSV files, text or one spreadsheet with a tab per table |
|
diff --git a/raptor/gui/command_table.py b/raptor/gui/command_table.py
index fc2fbfcf..85195848 100644
--- a/raptor/gui/command_table.py
+++ b/raptor/gui/command_table.py
@@ -147,6 +147,16 @@
"partially map or drop, without writing a file"),
handler="_preview_awb",
enabled_when="model_open"),
+ CommandSpec(
+ id="file.export_awb_normalized",
+ attr="_export_awb_normalized_action",
+ text="Export Reduced AWB Model…",
+ icon="awb_normalize_icon:text",
+ tooltip=(
+ "Save a matched pair: a reduced RAPTOR model and the .awb it "
+ "represents, for a fair engine-to-engine comparison"),
+ handler="_export_awb_normalized",
+ enabled_when="model_open"),
CommandSpec(
id="file.export_tables",
attr="_export_tables_action",
@@ -1454,8 +1464,8 @@ def _p(title: str, index_attr: str, *groups: Group) -> Page:
# Tables for choosing tables; the single-type commands stay in the
# command palette and on their shortcuts.
("Print and Export", ("file.print", "file.export", "file.export_awb",
- "file.preview_awb", "file.export_tables",
- "file.copy_view")),
+ "file.preview_awb", "file.export_awb_normalized",
+ "file.export_tables", "file.copy_view")),
)
#: Commands with a top level entry in the File view's nav column, after
diff --git a/raptor/gui/resources/icons.py b/raptor/gui/resources/icons.py
index 8341e402..6eb463c0 100644
--- a/raptor/gui/resources/icons.py
+++ b/raptor/gui/resources/icons.py
@@ -1425,6 +1425,21 @@ def draw(p: QPainter, c: QColor):
return _icon("awbpreview", colour, draw)
+def awb_normalize_icon(colour: str) -> QIcon:
+ """Reduced AWB pair: two documents with a balancing arrow."""
+ def draw(p: QPainter, c: QColor):
+ p.setBrush(Qt.BrushStyle.NoBrush)
+ p.setPen(QPen(c, 3))
+ p.drawRect(5, 5, 18, 30)
+ p.drawRect(25, 13, 18, 30)
+ p.setPen(QPen(c, 2))
+ p.drawLine(12, 13, 16, 13)
+ p.drawLine(12, 20, 16, 20)
+ p.drawLine(32, 21, 36, 21)
+ p.drawLine(32, 28, 36, 28)
+ return _icon("awbnormalize", colour, draw)
+
+
def clear_results_icon(colour: str) -> QIcon:
"""Clear Results: table swept by a diagonal wipe."""
def draw(p: QPainter, c: QColor):
diff --git a/raptor/gui/ui/export_mixin.py b/raptor/gui/ui/export_mixin.py
index 30f39adf..5fe766de 100644
--- a/raptor/gui/ui/export_mixin.py
+++ b/raptor/gui/ui/export_mixin.py
@@ -161,6 +161,42 @@ def _preview_awb(self):
"""File ▸ Check Availability Workbench export…: report only."""
self._export_awb(dry_run=True)
+ def _export_awb_normalized(self):
+ """File ▸ Export Reduced AWB Model…: matched RAPTOR + AWB pair."""
+ if self._rbd is None:
+ return
+ stem = Path(self._current_file).stem if self._current_file else "model"
+ path, _ = fdg.getSaveFileName(
+ self, "Save Reduced RAPTOR Model", stem + ".awb.rbds",
+ "RAPTOR Studio models (*.rbds)")
+ if not path:
+ return
+ norm = Path(path if str(path).lower().endswith(".rbds")
+ else path + ".rbds")
+ awb = norm.with_name(norm.name[:-5] + ".awb")
+ from raptor.api import awb as awb_api
+ QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
+ self._export_in_progress = True
+ try:
+ self._diagram_dock.view.write_back_to_rbd(self._rbd)
+ reduced, actions = awb_api.normalize(req(self._rbd))
+ awb_api.save_normalized(reduced, norm)
+ report = awb_api.export(reduced, awb,
+ source=self._current_file or "")
+ except Exception as exc: # noqa: BLE001
+ msgbox.critical(self, "Export Failed",
+ f"Could not write the reduced AWB pair:\n\n{exc}")
+ self._statusbar.showMessage("AWB normalized export failed", 8000)
+ return
+ finally:
+ self._export_in_progress = False
+ QApplication.restoreOverrideCursor()
+ report.notes.extend(f"normalized: {a}" for a in actions)
+ show = getattr(self, "_show_awb_report", None)
+ if show is not None:
+ show("Reduced AWB model export", report, str(awb), wrote=True)
+ self._statusbar.showMessage(f"Reduced AWB pair saved: {awb.name}", 8000)
+
def _export_workbook_xlsx(self, path: str | None = None):
"""File > Export Excel Workbook...: one .xlsx of the default tables."""
self._export_workbook(".xlsx", path)
From 7273d27764d0c488646a274eced809b732402dde Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:16:55 +1000
Subject: [PATCH 08/15] feat(awb): approximate dormant failures with inspection
detection delay
---
raptor/core/fileio/awb.py | 74 ++++++++++++++++++++++++++++++++++++---
tests/unit/test_awb.py | 24 +++++++++++++
2 files changed, 93 insertions(+), 5 deletions(-)
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index 5569ef24..5c0b4cbb 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -1819,6 +1819,14 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
"one RAPTOR PM per block: extra AWB planned tasks, and "
"inspection tasks, are not imported")
+ inspection_by_fm: dict[int, dict[str, Any]] = {}
+ for t in sched_tasks:
+ if _int(t.get("Type"), 0) != 1 or not _int(t.get("Enabled"), 0):
+ continue
+ fm_i = _int(t.get("FailureModel"), -1)
+ if fm_i >= 0 and fm_i not in inspection_by_fm:
+ inspection_by_fm[fm_i] = t
+
corr_spare_by_fm: dict[int, dict[str, Any]] = {}
for row in corr_spares:
fm_i = _int(row.get("FailureModel"), -1)
@@ -1872,6 +1880,7 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
# ---- ordinary blocks --------------------------------------------------
block_losses: dict[str, int] = {}
block_by_row: dict[int, dict[str, Any]] = {}
+ used_inspections = 0
for i, b in enumerate(blocks):
if i == root_i or i in super_rows:
continue
@@ -1894,6 +1903,20 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
"repair_dist": rdist, "repair_params": rparams,
}
fm_i = _int(b.get("FailureModel"), -1)
+ inspection = inspection_by_fm.get(fm_i)
+ if (inspection is not None and 0 <= fm_i < len(fms)
+ and _int(fms[fm_i].get("FmDormant"), 0)
+ and _int(b.get("LogicMode"), 0) != 1):
+ repair = next((t for t in tasks
+ if _int(t.get("FailureModel"), -1) == fm_i), None)
+ block["repair_dist"], block["repair_params"] = _task_repair_law(repair)
+ block["pre_ldt_dist"] = _R_FIXED
+ block["pre_ldt_params"] = [_inspection_delay(inspection), 0.0, 0.0]
+ if block_losses.get("dormant failures"):
+ block_losses["dormant failures"] -= 1
+ if not block_losses["dormant failures"]:
+ del block_losses["dormant failures"]
+ used_inspections += 1
pm = pm_by_fm.get(fm_i)
if pm is not None:
pm_dist, pm_params = task_law(pm)
@@ -1975,6 +1998,17 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
"AWB marks the block non-maintainable; RAPTOR repair is off",
}.get(feature, "")
report.add(feature, count, detail)
+ if used_inspections:
+ report.notes.append(
+ f"{used_inspections} dormant failure(s) approximated by the "
+ "expected AWB inspection detection delay")
+ enabled_inspections = [t for t in sched_tasks
+ if _int(t.get("Type"), 0) == 1
+ and _int(t.get("Enabled"), 0)]
+ if len(enabled_inspections) > used_inspections:
+ report.add("inspection tasks", len(enabled_inspections) - used_inspections,
+ "enabled inspections without a dormant failure model "
+ "were not used", kind="partial")
dep_count = 0
for row in rule_rows:
dep_row = _int(row.get("DependentBlock"), -1)
@@ -2345,6 +2379,41 @@ def _endpoint(kind: int, index: int, block_id: dict[int, int],
return None
+def _task_repair_law(task: dict[str, Any] | None) -> tuple[int, list[float]]:
+ """AWB corrective task -> RAPTOR repair law."""
+ if task is None:
+ return _R_FIXED, [0.0, 0.0, 0.0]
+ duration = max(0.0, _num(task.get("TaskDuration"))
+ + _num(task.get("RampTime")))
+ dist = _int(task.get("Distribution"), 2)
+ std = max(0.0, _num(task.get("Std")))
+ if dist == 0:
+ return _R_EXPO, [max(1e-9, duration), 0.0, 0.0]
+ if dist == 1:
+ return _R_LOGNORM, [max(1e-9, duration), std, 0.0]
+ if dist == 3:
+ return _R_WEIBULL, [max(1e-9, _num(task.get("Beta"), 2.0)),
+ max(1e-9, duration),
+ max(0.0, _num(task.get("Gamma")))]
+ if std > 0:
+ return _R_NORM, [max(1e-9, duration), std, 0.0]
+ return _R_FIXED, [max(0.0, duration), 0.0, 0.0]
+
+
+def _inspection_delay(task: dict[str, Any]) -> float:
+ """Expected detection delay for a dormant failure under an inspection."""
+ interval = max(1e-9, _num(task.get("TaskInterval"), 8760.0))
+ first = _num(task.get("Offset"), 0.0)
+ first = interval if first <= 0 else min(interval, first)
+ detection = min(1.0, max(0.01, _num(task.get("DetectionP"), 1.0)))
+ inspection_time = max(0.0, _num(task.get("TaskDuration"))
+ + _num(task.get("RampTime")))
+ # A failure appears uniformly in the inspection interval; a perfect
+ # inspection finds it on average half an interval later. A detection
+ # probability below 1 stretches that by 1/p.
+ return first / (2.0 * detection) + inspection_time
+
+
def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901, PLR0912
tasks: list[dict[str, Any]],
losses: dict[str, int]) -> tuple[int, list[float], int, list[float]]:
@@ -2436,11 +2505,6 @@ def _check_import_features(tables: dict[str, AwbTable], report: AwbReport) -> No
len(planned) - len(fms_with_planned),
"RAPTOR has one PM per block; only the first planned "
"task per failure model is imported", kind="partial")
- inspections = [t for t in sched
- if _int(t.get("Type"), 0) == 1 and _int(t.get("Enabled"), 0)]
- if inspections:
- report.add("inspection tasks", len(inspections),
- "AWB inspection tasks are not imported as RAPTOR PM")
calendar_pm = [t for t in planned if _int(t.get("FixedInterval"), 0)]
if calendar_pm:
report.add("calendar-interval PM", len(calendar_pm),
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
index c5640c51..75ba71cf 100644
--- a/tests/unit/test_awb.py
+++ b/tests/unit/test_awb.py
@@ -501,3 +501,27 @@ def test_cli_no_sidecar(tmp_path):
dest = tmp_path / "model.awb"
assert main(["convert", str(src), str(dest), "--no-sidecar"]) == 0
assert not dest.with_name(dest.name + ".raptor.json").exists()
+
+
+def test_dormant_failure_uses_inspection_detection_delay(tmp_path):
+ from raptor.core.fileio import awb as awb_mod
+ path = tmp_path / "inspection.awb"
+ export_awb(_model(), path)
+ tables = read_awb(path)
+ fm = tables["FailureModels"].rows[0]
+ fm["FmDormant"] = 1
+ task = awb_mod._row(
+ "FailureModelScheduledTasks", FailureModel=0, SubIndex=0, Type=1,
+ Description="Inspect dormant pump", TaskId="IN1", Enabled=1,
+ DetectionP=1.0, TaskDuration=1.0, RampTime=0.0,
+ TaskInterval=1000.0, FixedInterval=0, Offset=0.0)
+ tables["FailureModelScheduledTasks"] = AwbTable(
+ "FailureModelScheduledTasks",
+ _SCHEMA["FailureModelScheduledTasks"], [task])
+ write_awb(path, tables)
+ back, report = import_awb(path)
+ pump = next(r for r in _rows(back, "BLOCK_DATA") if r["blockName"] == "Pump")
+ assert pump["RDist"] != "18"
+ assert float(pump["Pre-LDTDist"]) == 19
+ assert 500.0 < float(pump["Param1#1"]) < 502.0
+ assert "inspection detection delay" in " ".join(report.notes).lower()
From b0052ace03669ef23a4fea5b73b882d2bd2d6e72 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:19:00 +1000
Subject: [PATCH 09/15] feat(awb): use the shortest-life mode for multi-mode
Weibull imports
---
raptor/core/fileio/awb.py | 18 +++++++++++++++---
1 file changed, 15 insertions(+), 3 deletions(-)
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index 5c0b4cbb..af64e459 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -1989,7 +1989,7 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
for feature, count in sorted(block_losses.items()):
detail = {
"multi-mode or buffer failure distribution":
- "AWB multi-mode/buffer laws kept their first Weibull mode only",
+ "AWB multi-mode laws kept their shortest-life Weibull mode",
"dormant failures":
"a dormant AWB failure is modelled as never repaired",
"start-up failure probability":
@@ -2442,8 +2442,20 @@ def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901,
elif dist == _AWB_NORMAL:
fdist, fparams = _R_NORM, [mttf, max(0.0, _num(fm.get("FmStd"))), 0.0]
else:
- # Bi-/tri-Weibull, buffer and phased laws have no exact RAPTOR
- # equivalent in the friendly model. Keep the first mode and say so.
+ # Bi-/tri-Weibull and phased laws have no exact RAPTOR equivalent.
+ # The earliest (shortest characteristic life) mode drives most of the
+ # failures, so use it rather than always taking the first mode.
+ modes = [
+ (_num(fm.get("FmEta1"), eta), _num(fm.get("FmBeta1"), beta),
+ _num(fm.get("FmGamma1"), gamma)),
+ (_num(fm.get("FmEta2"), eta), _num(fm.get("FmBeta2"), beta),
+ _num(fm.get("FmGamma2"), gamma)),
+ (_num(fm.get("FmEta3"), eta), _num(fm.get("FmBeta3"), beta),
+ _num(fm.get("FmGamma3"), gamma)),
+ ]
+ modes = [m for m in modes if m[0] > 0]
+ if modes:
+ eta, beta, gamma = min(modes, key=lambda m: m[0])
fdist, fparams = _R_WEIBULL, [beta, eta, gamma]
losses["multi-mode or buffer failure distribution"] = (
losses.get("multi-mode or buffer failure distribution", 0) + 1)
From 97e2232edea5e41318b5c532ab94a925f6968eec Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:26:22 +1000
Subject: [PATCH 10/15] docs(awb): record inspection approximation and
shipped-example recheck
---
docs/AWB_FORMAT.md | 2 +-
docs/AWB_VALIDATION.md | 20 ++++++++++++++++++++
docs/manual.adoc | 2 +-
docs/manual.html | 2 +-
4 files changed, 23 insertions(+), 3 deletions(-)
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index 41329e83..48a3cfc6 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -286,7 +286,7 @@ AWB field was written; the `.raptor.json` sidecar keeps the RAPTOR copy).
| Feature | Why |
|---|---|
| consequences and cost models | RAPTOR has no financial/safety/environmental consequence model |
-| inspection tasks | AWB inspections are not imported as RAPTOR PM |
+| inspection tasks | a dormant failure with an enabled inspection uses the expected detection delay; other inspections remain partial |
| extra planned tasks | RAPTOR has one PM per block; extra AWB tasks are not imported |
| two-level spare holdings | AWB level-1 and level-2 stock are summed |
| spare repair shop | AWB spare repair/recycling is not imported |
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
index de39f979..aaa62e72 100644
--- a/docs/AWB_VALIDATION.md
+++ b/docs/AWB_VALIDATION.md
@@ -116,6 +116,26 @@ losses: capacity is preserved in the sidecar, and the repair law is
mean-matched for AWB. AWB demonstration mode may still refuse to analyse a
project of this size; that is its object limit, not a file-format failure.
+### Shipped AWB examples
+
+Stored AWB results vs RAPTOR on the imported model (100 trials, same
+lifetime):
+
+| AWB project | AWB Am | RAPTOR A | Result |
+|---|---:|---:|---|
+| OilAndGasExample | 0.973217 | 0.974734 | Δ 0.152 pp; agrees |
+| Example1 | 0.088322 | 0.006982 | not comparable |
+| SapDemo | 0.629333 | 0.005037 | not comparable |
+| MaximoDemo | 0.611809 | 0.005037 | not comparable |
+
+`ALTExample` and the `PumpExample` library example have no RBD blocks.
+
+The new inspection approximation improves the model but does not make
+Example1/SapDemo/MaximoDemo comparable: Example1 has its inspection
+disabled, while SapDemo/MaximoDemo still lose PM/inspection timing,
+multi-mode Weibull shape and topology semantics. OilAndGasExample remains
+the clean shipped-AWB comparison.
+
---
## 2. Compatibility screening of all 27 examples
diff --git a/docs/manual.adoc b/docs/manual.adoc
index 57671d5a..0aab87b7 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1689,7 +1689,7 @@ In short:
|Mission phases |partial: durations and block cut/linked rules |partial: durations and cut/linked rules; node/hierarchy and capacity/load rules are not imported
|Out-of-service states |yes: applied to the AWB copy |yes: AWB global logic state becomes a RAPTOR cut/linked state
|Block dependencies |not exported |partial: AWB state dependencies become 100% idle dependencies
-|Preventive maintenance |partial: one planned task per failure model |partial: first enabled planned task; inspections and extra tasks are not imported
+|Preventive maintenance |partial: one planned task per failure model |partial: first enabled planned task; dormant inspections become a detection delay; other inspections/extra tasks are partial
|Spare holdings |partial: level-1 stock and lead time |partial: level 1 + 2 become one pool; repair shop is not imported
|Labour/equipment resources |partial: resource pools and task links |partial: labour/equipment become RAPTOR resources; call-out delay is not imported
|Capacity products and capacity targets |not exported |not imported
diff --git a/docs/manual.html b/docs/manual.html
index 46cb16a9..6f4a38d2 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2514,7 +2514,7 @@ Availability Workbench interchange
Preventive maintenance |
partial: one planned task per failure model |
-partial: first enabled planned task; inspections and extra tasks are not imported |
+partial: first enabled planned task; dormant inspections become a detection delay; other inspections/extra tasks are partial |
Spare holdings |
From 726284645a802897094de05342fe5f72fa7e223f Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:41:12 +1000
Subject: [PATCH 11/15] fix(awb): never let an imported spare pool run dry; fit
competing Weibull modes
AWB level 3 is an unlimited source, but a zero-stock AWB spare was imported
as a RAPTOR pool with no ordering at all, so the first demand left the block
Done (No_spares) for the rest of the run: SapDemo/MaximoDemo/Example1 came
out ~0.5 % available. Pools now always emergency-order after the summed
level 1+2+3 logistic delay, and stocked pools reorder one-for-one.
Bi-/tri-Weibull laws were reduced to the shortest-eta mode, which for a
bi-Weibull included AWB's unused 8760 h third-mode placeholder. They are now
moment-matched (mean and CV) to the competing-risk life of the modes the law
actually uses. This is an approximation, not an exact conversion.
---
raptor/core/fileio/awb.py | 115 ++++++++++++++++++++++++++++++++------
1 file changed, 97 insertions(+), 18 deletions(-)
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index af64e459..3c2354d7 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -1752,24 +1752,43 @@ def task_law(task: dict[str, Any]) -> tuple[int, list[float]]:
spare_doc: list[dict[str, Any]] = []
spare_name: dict[int, str] = {}
used_spares: set[str] = set()
+ stocked_l1_delay = 0
for i, sp in enumerate(spare_rows):
name = _unique(_safe_id(_text(sp.get("Id"), f"Spare{i + 1}"), 20),
used_spares, 20)
stock = max(0, _int(sp.get("CapacityLevel1"), 0)
+ _int(sp.get("CapacityLevel2"), 0))
- arrive = max(1.0, _num(sp.get("LogisticDelayLevel2"), 0.0)
- or _num(sp.get("LogisticDelayLevel3"), 24.0))
- emer = max(1.0, _num(sp.get("LogisticDelayLevel3"), arrive))
+ # AWB level 3 is an unlimited manufacturing source: a demand that
+ # level 1 and level 2 cannot meet waits the level 3 -> 2 -> 1 ->
+ # task delays, and AvSim never runs out (manual, "Spares - Level 3
+ # Properties"). RAPTOR's nearest equivalent is emergency ordering
+ # with that summed delay, plus a one-for-one stock-level reorder
+ # (reorder at stock-1, quantity 1) that refills held stock after
+ # the level 3 -> 1 delay. Without ESO a zero-stock pool would be
+ # permanently empty and every block using it would end "Done".
+ d1 = max(0.0, _num(sp.get("LogisticDelayLevel1"), 0.0))
+ d2 = max(0.0, _num(sp.get("LogisticDelayLevel2"), 0.0))
+ d3 = max(0.0, _num(sp.get("LogisticDelayLevel3"), 0.0))
+ emer = max(1e-6, d1 + d2 + d3)
+ resupply = max(1e-6, d2 + d3)
+ if stock and d1 > 0:
+ stocked_l1_delay += 1
spare_doc.append({
"name": name, "stock": stock,
"new_spares": max(1, _int(sp.get("MinimumReorderQuantity"), 1)),
- "arrive_every": arrive, "eso": 1 if stock else 0,
- "emer_time": emer, "slo": 0, "level": 0, "quantity": 1,
- "slo_time": 24.0, "rso": 0,
+ "arrive_every": resupply, "eso": 1,
+ "emer_time": emer, "slo": 1 if stock else 0,
+ "level": max(0, stock - 1), "quantity": 1,
+ "slo_time": resupply, "rso": 0,
"spare_cost": max(0.0, _num(sp.get("UnitCost"), 1.0)),
"emer_ship_cost": max(0.0, _num(sp.get("TransportationCostLevel2"), 1.0)),
})
spare_name[i] = name
+ report.add("level-1 spare logistic delay on stocked spares",
+ stocked_l1_delay,
+ "AWB's level-1 delay on a spare drawn from stock is not "
+ "modelled; only a stock-out waits the summed delay",
+ kind="partial")
if any(_int(sp.get("CapacityLevel2"), 0) for sp in spare_rows):
report.add("two-level spare holdings", 1,
"AWB level-1 and level-2 stock are summed into one "
@@ -2414,6 +2433,67 @@ def _inspection_delay(task: dict[str, Any]) -> float:
return first / (2.0 * detection) + inspection_time
+def _competing_weibull_fit(modes: list[tuple[float, float, float]]
+ ) -> tuple[float, float, float]:
+ """One Weibull (beta, eta, gamma) approximating competing Weibull modes.
+
+ *modes* are (eta, beta, gamma). The item's life is the minimum of the
+ mode lives. This is a moment match, not an exact conversion: the
+ fitted law has the same mean and coefficient of variation (measured
+ from the earliest location parameter), so failure counts agree but the
+ hazard shape, which matters for PM timing, is only approximate.
+ """
+ if len(modes) == 1:
+ eta, beta, gamma = modes[0]
+ return beta, eta, gamma
+ g0 = min(m[2] for m in modes)
+
+ def survival(t: float) -> float:
+ h = 0.0
+ for eta, beta, gamma in modes:
+ x = t + g0 - gamma
+ if x > 0:
+ h += (x / eta) ** beta
+ return math.exp(-h)
+
+ # Integrate on a log grid out to where the longest-lived mode alone
+ # would have near-zero survival.
+ upper = max(gamma - g0 + eta * 40.0 ** (1.0 / beta)
+ for eta, beta, gamma in modes)
+ lo = min(eta for eta, _, _ in modes) * 1e-6
+ n = 4000
+ ratio = (upper / lo) ** (1.0 / n)
+ ts = [0.0] + [lo * ratio ** i for i in range(n + 1)]
+ m1 = m2 = 0.0
+ prev_t, prev_s = ts[0], survival(ts[0])
+ for t in ts[1:]:
+ cur = survival(t)
+ dt = t - prev_t
+ m1 += 0.5 * (prev_s + cur) * dt
+ m2 += (prev_t * prev_s + t * cur) * dt
+ prev_t, prev_s = t, cur
+ var = max(0.0, m2 - m1 * m1)
+ if m1 <= 0:
+ eta, beta, gamma = min(modes, key=lambda m: m[0])
+ return beta, eta, gamma
+ cv2 = var / (m1 * m1)
+
+ def weibull_cv2(b: float) -> float:
+ g1 = math.gamma(1.0 + 1.0 / b)
+ return math.gamma(1.0 + 2.0 / b) / (g1 * g1) - 1.0
+
+ lo_b, hi_b = 0.05, 50.0 # CV^2 falls as beta rises
+ for _ in range(100):
+ mid = math.sqrt(lo_b * hi_b)
+ if weibull_cv2(mid) > cv2:
+ lo_b = mid
+ else:
+ hi_b = mid
+ beta = math.sqrt(lo_b * hi_b)
+ eta = m1 / math.gamma(1.0 + 1.0 / beta)
+ return beta, eta, g0
+
+
def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901, PLR0912
tasks: list[dict[str, Any]],
losses: dict[str, int]) -> tuple[int, list[float], int, list[float]]:
@@ -2443,19 +2523,18 @@ def _block_data(block: dict[str, Any], fms: list[dict[str, Any]], # noqa: C901,
fdist, fparams = _R_NORM, [mttf, max(0.0, _num(fm.get("FmStd"))), 0.0]
else:
# Bi-/tri-Weibull and phased laws have no exact RAPTOR equivalent.
- # The earliest (shortest characteristic life) mode drives most of the
- # failures, so use it rather than always taking the first mode.
- modes = [
- (_num(fm.get("FmEta1"), eta), _num(fm.get("FmBeta1"), beta),
- _num(fm.get("FmGamma1"), gamma)),
- (_num(fm.get("FmEta2"), eta), _num(fm.get("FmBeta2"), beta),
- _num(fm.get("FmGamma2"), gamma)),
- (_num(fm.get("FmEta3"), eta), _num(fm.get("FmBeta3"), beta),
- _num(fm.get("FmGamma3"), gamma)),
- ]
- modes = [m for m in modes if m[0] > 0]
+ # AWB's modes compete (the item fails at the first of them), so fit
+ # one Weibull to the mean and spread of that competing-risk life.
+ # Only the modes the law uses count: a bi-Weibull's third-mode
+ # columns hold AWB's 8760 h placeholder, not data.
+ n_modes = {_AWB_BI_WEIBULL: 2, _AWB_PHASED_BI: 2,
+ _AWB_TRI_WEIBULL: 3, _AWB_PHASED_TRI: 3}.get(dist, 1)
+ modes = [(_num(fm.get(f"FmEta{k}"), eta), _num(fm.get(f"FmBeta{k}"), beta),
+ _num(fm.get(f"FmGamma{k}"), gamma))
+ for k in range(1, n_modes + 1)]
+ modes = [m for m in modes if m[0] > 0 and m[1] > 0]
if modes:
- eta, beta, gamma = min(modes, key=lambda m: m[0])
+ beta, eta, gamma = _competing_weibull_fit(modes)
fdist, fparams = _R_WEIBULL, [beta, eta, gamma]
losses["multi-mode or buffer failure distribution"] = (
losses.get("multi-mode or buffer failure distribution", 0) + 1)
From cb9e27afd19b0b0f08c38f43ffe6d3b5e40cbb28 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:42:39 +1000
Subject: [PATCH 12/15] test(awb): zero-stock spares stay supplied; competing
Weibull fit
---
tests/unit/test_awb.py | 60 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 60 insertions(+)
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
index 75ba71cf..fffbef70 100644
--- a/tests/unit/test_awb.py
+++ b/tests/unit/test_awb.py
@@ -525,3 +525,63 @@ def test_dormant_failure_uses_inspection_detection_delay(tmp_path):
assert float(pump["Pre-LDTDist"]) == 19
assert 500.0 < float(pump["Param1#1"]) < 502.0
assert "inspection detection delay" in " ".join(report.notes).lower()
+
+
+def test_zero_stock_awb_spare_never_leaves_the_pool_dry(tmp_path):
+ """AWB level 3 is unlimited: a zero-stock spare must still be ordered.
+
+ Before the fix the pool came in with stock 0 and no ordering, so every
+ block using it ended Done (No_spares) at its first failure.
+ """
+ from raptor.core.fileio import awb as awb_mod
+ path = tmp_path / "spares.awb"
+ export_awb(_model(), path)
+ tables = read_awb(path)
+ rows = [awb_mod._row("Spares", Id="ZERO", CapacityLevel1=0,
+ LogisticDelayLevel1=48.0, LogisticDelayLevel2=96.0,
+ LogisticDelayLevel3=480.0),
+ awb_mod._row("Spares", Id="HELD", CapacityLevel1=3,
+ LogisticDelayLevel1=0.0, LogisticDelayLevel2=10.0,
+ LogisticDelayLevel3=20.0)]
+ tables["Spares"] = AwbTable("Spares", _SCHEMA["Spares"], rows)
+ write_awb(path, tables)
+ back, _ = import_awb(path)
+ pools = {r["PoolName"]: r for r in back.sections["SPARE_POOL_DATA"].rows}
+ zero, held = pools["ZERO"], pools["HELD"]
+ assert int(zero["Stock"]) == 0 and int(zero["ESO"]) == 1
+ assert float(zero["EmerTime"]) == pytest.approx(624.0)
+ assert int(held["Stock"]) == 3 and int(held["ESO"]) == 1
+ assert int(held["SLO"]) == 1 and int(held["Level"]) == 2
+ assert float(held["SLOTime"]) == pytest.approx(30.0)
+
+
+def test_competing_weibull_fit_matches_the_minimum_of_the_modes():
+ import math
+
+ from raptor.core.fileio.awb import _competing_weibull_fit
+ # Two equal exponentials compete as one exponential of half the mean.
+ beta, eta, gamma = _competing_weibull_fit([(100.0, 1.0, 0.0),
+ (100.0, 1.0, 0.0)])
+ assert beta == pytest.approx(1.0, rel=1e-3)
+ assert eta == pytest.approx(50.0, rel=1e-3)
+ assert gamma == 0.0
+ # An exponential and a wear-out mode: mean of min(T1, T2) by quadrature.
+ modes = [(20000.0, 1.0, 0.0), (4472.1, 2.0, 1000.0)]
+ beta, eta, _ = _competing_weibull_fit(modes)
+ mean = eta * math.gamma(1.0 + 1.0 / beta)
+ assert mean == pytest.approx(4316.0, rel=0.01)
+
+
+def test_bi_weibull_ignores_the_unused_third_mode(tmp_path):
+ path = tmp_path / "biweibull.awb"
+ export_awb(_model(), path)
+ tables = read_awb(path)
+ fm = tables["FailureModels"].rows[0]
+ fm.update(FmDistribution=2, FmEta1=200000.0, FmBeta1=1.0, FmGamma1=0.0,
+ FmEta2=44721.0, FmBeta2=2.0, FmGamma2=0.0,
+ FmEta3=8760.0, FmBeta3=1.0, FmGamma3=0.0)
+ write_awb(path, tables)
+ back, _ = import_awb(path)
+ pump = next(r for r in _rows(back, "BLOCK_DATA") if r["blockName"] == "Pump")
+ # The placeholder 8760 h mode would have dragged eta down to 8760.
+ assert float(pump["FParam2"]) > 30000.0
From 94c9dab5e8099d43c596841ee5786874d93875f8 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:49:29 +1000
Subject: [PATCH 13/15] fix(awb): imported PM does not wait for pooled spares;
restore block sidecar data
AWB spare logistic delays hold up corrective actions only (manual, Spares -
Overview), but the import linked each AWB planned task to the spare pool, so
every RAPTOR PM waited the whole level 3 -> 1 supply chain (576 h in
Example1). Imported PM no longer draws on the pool; reported as partial.
The sidecar keyed block_extras by RAPTOR ID but apply_sidecar looked blocks
up by name, so no per-block sidecar data was ever restored when the two
differed. Key by block name, and carry PMSpare so a RAPTOR model's own PM
spare setting survives the round trip.
Docs: AWB_FORMAT describes the spare supply mapping and the moment-matched
multi-mode Weibull.
---
docs/AWB_FORMAT.md | 22 ++++++++++++++--------
raptor/core/fileio/awb.py | 26 ++++++++++++++++++++++----
tests/unit/test_awb.py | 15 +++++++++++++--
3 files changed, 49 insertions(+), 14 deletions(-)
diff --git a/docs/AWB_FORMAT.md b/docs/AWB_FORMAT.md
index 48a3cfc6..f1b6b303 100644
--- a/docs/AWB_FORMAT.md
+++ b/docs/AWB_FORMAT.md
@@ -187,22 +187,26 @@ the `Id` label.
|---:|---|---|
| 0 | Exponential | `FmMttf` = mean time to failure |
| 1 | Weibull | `FmEta1` = scale, `FmBeta1` = shape, `FmGamma1` = location |
-| 2 | Bi-Weibull | three modes; RAPTOR keeps the first |
-| 3 | Tri-Weibull | three modes; RAPTOR keeps the first |
+| 2 | Bi-Weibull | two competing modes (mode-3 columns are an unused placeholder); RAPTOR moment-matches one Weibull |
+| 3 | Tri-Weibull | three competing modes; RAPTOR moment-matches one Weibull |
| 4 | Fixed | `FmMttf` = fixed time |
| 5 | Lognormal | `FmMttf` = mean, `FmStd` = standard deviation |
| 6 | Normal | `FmMttf` = mean, `FmStd` = standard deviation |
| 7 | Buffer | stored capacity; no RAPTOR equivalent |
-| 8 | Phased Bi-Weibull | phased; RAPTOR keeps the first mode |
-| 9 | Phased Tri-Weibull | phased; RAPTOR keeps the first mode |
+| 8 | Phased Bi-Weibull | phased; RAPTOR moment-matches the two modes |
+| 9 | Phased Tri-Weibull | phased; RAPTOR moment-matches the three modes |
All times in AWB are **hours**. RAPTOR converts from its model unit with
`raptor/core/units_conv.py` (`days` = 24, `years` = 8760, etc.) and records
the conversion in the summary.
-RAPTOR reads the same enum in reverse. A multi-mode or buffer law becomes
-its first Weibull mode and is listed under "multi-mode or buffer failure
-distribution". A dormant AWB failure (`FmDormant = 1`) becomes a RAPTOR
+RAPTOR reads the same enum in reverse. AWB's Weibull modes compete (the
+item fails at the first of them), so a bi-/tri-Weibull law becomes one
+Weibull with the same mean and coefficient of variation as the competing-risk
+life, located at the earliest mode's location. This is an approximation:
+failure counts agree, but the hazard shape, and so the effect of PM, is only
+close. A buffer law becomes its first mode. Both are listed under
+"multi-mode or buffer failure distribution". A dormant AWB failure (`FmDormant = 1`) becomes a RAPTOR
block with no repair. A non-zero start-up failure probability is reported
but cannot be modelled by RAPTOR.
@@ -289,6 +293,8 @@ AWB field was written; the `.raptor.json` sidecar keeps the RAPTOR copy).
| inspection tasks | a dormant failure with an enabled inspection uses the expected detection delay; other inspections remain partial |
| extra planned tasks | RAPTOR has one PM per block; extra AWB tasks are not imported |
| two-level spare holdings | AWB level-1 and level-2 stock are summed |
+| spare supply chain | AWB level 3 never runs out: every RAPTOR pool emergency-orders after level 1 + 2 + 3 delays, and stocked pools reorder one-for-one after the level 3 + 2 delay |
+| level-1 spare logistic delay on stocked spares | the per-draw level-1 delay on a spare taken from stock is not modelled |
| spare repair shop | AWB spare repair/recycling is not imported |
| labour call-out delay | AWB labour logistics delay is not imported |
| phase capacity/load rules | only AWB phase logic/out-of-service rules are imported |
@@ -300,7 +306,7 @@ AWB field was written; the `.raptor.json` sidecar keeps the RAPTOR copy).
| standby and NOT logic | RAPTOR nodes have no equivalent |
| block consequence links | not imported |
| dormant failures | modelled as never repaired |
-| multi-mode/buffer failure laws | only the first Weibull mode is kept |
+| multi-mode/buffer failure laws | moment-matched to one Weibull (buffer: first mode) |
| non-maintainable blocks | RAPTOR repair is off |
| start-up failure probability | not modelled by RAPTOR |
diff --git a/raptor/core/fileio/awb.py b/raptor/core/fileio/awb.py
index 3c2354d7..3bd95300 100644
--- a/raptor/core/fileio/awb.py
+++ b/raptor/core/fileio/awb.py
@@ -513,15 +513,18 @@ def _sidecar_payload(rbd: RbdFile) -> dict[str, Any]: # noqa: C901, PLR0912, PL
data["comments"] = [dict(c) for c in _section_list(rbd, "COMMENTS")]
block_extras = {}
for b in _section_list(rbd, "BLOCK_DATA"):
- bid = _text(b.get("ID"))
- if bid in ("", "0"):
+ if _text(b.get("ID")) in ("", "0"):
continue
+ # Keyed by name: the export writes the block name as the AWB Id,
+ # the import names the block from it, and apply_sidecar looks the
+ # block up by that name (the RAPTOR ID is renumbered on import).
+ bid = _text(b.get("blockName")) or _text(b.get("ID"))
extra = {k: b.get(k) for k in (
"DepType", "DepNum", "DepNothing", "DepIdle", "DepPM",
"DepFail", "DepPMThresh", "defDepStateIdle", "Phasing",
"SimStart", "AmtExhausted", "SBStress", "GDType", "GDRate",
"GDLimit", "_DutyCycle", "_StartAge", "_RestoreFactor",
- "_RestoreType", "NonOperational", "usesPM", "PMFreq",
+ "_RestoreType", "NonOperational", "usesPM", "PMFreq", "PMSpare",
"Dist", "Param1#3", "Param2#3", "Param3#3",
"initial", "Running", "standby", "idle", "repHold",
"repPerTime", "repFixed", "donePerTime", "doneFixed",
@@ -665,6 +668,10 @@ def apply_sidecar(doc: dict[str, Any], data: dict[str, Any], # noqa: C901, PLR0
if key == "phases":
target["uses_phasing"] = True
target.setdefault("legacy", {}).update(value)
+ elif key == "PMSpare":
+ # The import leaves AWB PM off the spare pool; a RAPTOR
+ # model's own setting comes back from the sidecar.
+ target["pm_spare"] = str(value) == "1"
elif key not in target:
target[key] = value
for nid, extra in (data.get("node_extras") or {}).items():
@@ -1855,6 +1862,7 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
fm_i = _int(row.get("FailureModel"), -1)
corr_labor_by_fm.setdefault(fm_i, row)
sched_spare_by_fm: dict[int, dict[str, Any]] = {}
+ planned_spares = 0
for row in sched_spares:
fm_i = _int(row.get("FailureModel"), -1)
sched_spare_by_fm.setdefault(fm_i, row)
@@ -1948,8 +1956,14 @@ def add_resource(kind: str, i: int, row: dict[str, Any],
"uses_pm": True, "pm_freq": pm_freq,
"pm_duration_dist": pm_dist, "pm_params": pm_params,
"pm_refresh": _num(pm.get("AgeReductionFactor"), 0.0) >= 0.999,
- "pm_spare": fm_i in sched_spare_by_fm,
+ # AWB spare logistic delays hold up corrective actions
+ # only; a planned task's spares are on hand (manual,
+ # "Spares - Overview"). RAPTOR's PM would wait the whole
+ # supply chain for a pooled spare, so do not draw one.
+ "pm_spare": False,
})
+ if fm_i in sched_spare_by_fm:
+ planned_spares += 1
pm_res = sched_labor_by_fm.get(fm_i)
if pm_res is not None:
kind_i = _int(pm_res.get("Labor"), -1)
@@ -2282,6 +2296,10 @@ def add_junction(owner: int, name: str, x: float, y: float) -> int:
project = _rows(tables, "Project")[0] if _rows(tables, "Project") else {}
lifetime = max(1.0, _num(project.get("LifeTime"), 87600.0))
trials = max(1, _int(project.get("AvsimNoSimulationsRequested"), 1000))
+ report.add("planned-task spares", planned_spares,
+ "AWB delays only corrective tasks for spares; imported PM "
+ "does not draw on the spare pool, so planned spare use is "
+ "not counted against stock", kind="partial")
report.counts.update(blocks=len(elements["blocks"]),
nodes=len(elements["nodes"]),
hierarchies=len(elements["hierarchies"]),
diff --git a/tests/unit/test_awb.py b/tests/unit/test_awb.py
index fffbef70..c4a258b1 100644
--- a/tests/unit/test_awb.py
+++ b/tests/unit/test_awb.py
@@ -378,8 +378,19 @@ def test_pm_spares_resources_phases_and_out_of_service_round_trip(tmp_path):
assert pump["Resource1Name"]
assert pump["P 001"].startswith("C:")
assert back.out_of_service.get("block:2") == "cut"
- assert "non-maintainable blocks" not in {
- loss.feature for loss in report.not_in_target}
+ features = {loss.feature for loss in report.not_in_target}
+ assert "non-maintainable blocks" not in features
+ # The sidecar restores RAPTOR's own PM-spare setting on a round trip.
+ assert pump["PMSpare"] == "1"
+ # A plain AWB project (no sidecar): AWB delays only corrective tasks for
+ # spares, so the imported PM must not wait on the pool.
+ path.with_name(path.name + ".raptor.json").unlink()
+ plain, plain_report = import_awb(path)
+ plain_pump = next(r for r in _rows(plain, "BLOCK_DATA")
+ if r["blockName"] == "Pump")
+ assert plain_pump.get("PMSpare", "0") in ("0", "")
+ assert "planned-task spares" in {
+ loss.feature for loss in plain_report.not_in_target}
def test_sidecar_preserves_raptor_only_metadata(tmp_path):
From c0d115e60f10782100d3fdf83ab0b8af6dd25e71 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 07:52:46 +1000
Subject: [PATCH 14/15] docs(awb): shipped-example comparison after the spare
and Weibull fixes
---
docs/AWB_VALIDATION.md | 42 ++++++++++++++++++++++++++++++++++++++++--
1 file changed, 40 insertions(+), 2 deletions(-)
diff --git a/docs/AWB_VALIDATION.md b/docs/AWB_VALIDATION.md
index aaa62e72..29b14ab5 100644
--- a/docs/AWB_VALIDATION.md
+++ b/docs/AWB_VALIDATION.md
@@ -118,11 +118,49 @@ project of this size; that is its object limit, not a file-format failure.
### Shipped AWB examples
-Stored AWB results vs RAPTOR on the imported model (100 trials, same
-lifetime):
+Stored AWB results vs RAPTOR on the imported model (100 trials, AWB's own
+count; same lifetime). Measured 2026-11-20 with the junction-node fix from
+`main` (#339) applied: without it every AWB fan-out is mis-wired.
| AWB project | AWB Am | RAPTOR A | Result |
|---|---:|---:|---|
+| OilAndGasExample | 0.9732 | 0.9747 | agrees (+0.15 pp) |
+| SapDemo | 0.6293 | 0.6522 | agrees within the approximations (+2.3 pp) |
+| Example1 | 0.0883 | 0.0959 | agrees within the approximations (+0.8 pp) |
+| MaximoDemo | 0.6118 | 0.3654 | AWB's stored results look stale (below) |
+
+`ALTExample` and the `PumpExample` library example have no RBD blocks.
+
+Three import defects made Example1/SapDemo/MaximoDemo look "not
+comparable" (≈0.5 % available) before this:
+
+* **Spare pools ran dry.** An AWB spare with no stock came in as a RAPTOR
+ pool with no ordering, so the first demand left the block `Done`
+ (`No_spares`). AWB level 3 is unlimited; pools now emergency-order after
+ the level 1+2+3 delay.
+* **Planned tasks waited for spares.** AWB's spare logistic delays hold
+ up corrective actions only; imported PM no longer draws on the pool.
+* **Bi-Weibull picked a placeholder mode.** The shortest-η rule included
+ the unused third-mode columns (8760 h). Multi-mode laws are now
+ moment-matched to the competing-risk life.
+
+The per-subsystem figures (top-level superblocks, each run on its own) agree
+to within about 2 pp for Example1 and SapDemo. The dormant `PO` block,
+modelled with the inspection detection-delay approximation, gives 0.682 vs
+AWB 0.655 (SapDemo) and 0.183 vs 0.175 (Example1, inspection disabled, never
+repaired). RAPTOR's outage counts run lower than AWB's `W` because AWB
+counts zero-duration PM/inspection outages that RAPTOR does not.
+
+**MaximoDemo.** Its spares carry level-2/3 delays of 96 h and 480 h, like
+Example1's, but AWB's stored per-block spare downtime is only about the
+level-1 delay (for example 45 h over 1.5 demands for the drive shaft), and its
+subsystem results are almost identical to SapDemo's, which has no level-2/3
+delays. RAPTOR's MaximoDemo subsystems instead resemble AWB's own Example1
+results (ELEC 0.67 vs 0.73, MON 0.80 vs 0.80). The stored results were most
+likely computed before those delays were entered. This has not been checked
+by re-running AWB.
+
+---|---:|---:|---|
| OilAndGasExample | 0.973217 | 0.974734 | Δ 0.152 pp; agrees |
| Example1 | 0.088322 | 0.006982 | not comparable |
| SapDemo | 0.629333 | 0.005037 | not comparable |
From c0326a3f10981b3f9f3b8f0377fdb9f76bdeb821 Mon Sep 17 00:00:00 2001
From: Daniel Mulholland
Date: Fri, 20 Nov 2026 08:38:33 +1000
Subject: [PATCH 15/15] docs(awb): regenerate the manual reference after
merging main; spare mapping in the manual
---
docs/manual-reference.adoc | 1 -
docs/manual.adoc | 2 +-
docs/manual.html | 7 +------
3 files changed, 2 insertions(+), 8 deletions(-)
diff --git a/docs/manual-reference.adoc b/docs/manual-reference.adoc
index 919dc7b3..60a11a9f 100644
--- a/docs/manual-reference.adoc
+++ b/docs/manual-reference.adoc
@@ -381,7 +381,6 @@ documentation.
|Control |What it does |Shortcut / value
|New |Create a new blank model (Ctrl+N) |Ctrl+N
|Open |Open an .rbd or .rbds file (Ctrl+O) |Ctrl+O
-|Import Availability Workbench… |Open an Isograph Availability Workbench 5.0 .awb project as a new RAPTOR model; the summary lists what AWB features RAPTOR cannot represent |
|Save |Save (Ctrl+S) |Ctrl+S
|Save As |Save to a new .rbds or .rbd file (Ctrl+Shift+S) |Ctrl+Shift+S
|Close |Close the current model (with save prompt) (Ctrl+W) |Ctrl+W
diff --git a/docs/manual.adoc b/docs/manual.adoc
index bbf5e1b9..f20ef08a 100644
--- a/docs/manual.adoc
+++ b/docs/manual.adoc
@@ -1805,7 +1805,7 @@ In short:
|Out-of-service states |yes: applied to the AWB copy |yes: AWB global logic state becomes a RAPTOR cut/linked state
|Block dependencies |not exported |partial: AWB state dependencies become 100% idle dependencies
|Preventive maintenance |partial: one planned task per failure model |partial: first enabled planned task; dormant inspections become a detection delay; other inspections/extra tasks are partial
-|Spare holdings |partial: level-1 stock and lead time |partial: level 1 + 2 become one pool; repair shop is not imported
+|Spare holdings |partial: level-1 stock and lead time |partial: level 1 + 2 become one pool that emergency-orders after the level 1 + 2 + 3 delay (AWB never runs out); planned tasks do not wait for spares; repair shop is not imported
|Labour/equipment resources |partial: resource pools and task links |partial: labour/equipment become RAPTOR resources; call-out delay is not imported
|Capacity products and capacity targets |not exported |not imported
|Consequence and cost models |not exported |not imported
diff --git a/docs/manual.html b/docs/manual.html
index 5180c3ea..bc506e03 100644
--- a/docs/manual.html
+++ b/docs/manual.html
@@ -2690,7 +2690,7 @@ Availability Workbench interchange
Spare holdings |
partial: level-1 stock and lead time |
-partial: level 1 + 2 become one pool; repair shop is not imported |
+partial: level 1 + 2 become one pool that emergency-orders after the level 1 + 2 + 3 delay (AWB never runs out); planned tasks do not wait for spares; repair shop is not imported |
Labour/equipment resources |
@@ -4188,11 +4188,6 @@ File
Ctrl+O |
-Import Availability Workbench… |
-Open an Isograph Availability Workbench 5.0 .awb project as a new RAPTOR model; the summary lists what AWB features RAPTOR cannot represent |
- |
-
-
Save |
Save (Ctrl+S) |
Ctrl+S |