-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotebook.py
More file actions
1859 lines (1553 loc) · 76 KB
/
Copy pathnotebook.py
File metadata and controls
1859 lines (1553 loc) · 76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""# ADCS Lifecycle Demo: Bidirectional Requirements Traceability
A walkthrough of satellite attitude control system design — from receiving
requirements through symbolic analysis, numerical simulation, evidence
binding, human attestation, and audit.
"""
import marimo
__generated_with = "0.22.5"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
def __(mo):
mo.md("""
# ADCS Lifecycle Demo
## Bidirectional Requirements Traceability with Reproducible Evidence
This notebook walks through the complete lifecycle of verifying an
**Attitude Determination and Control System (ADCS)** for a geostationary
communications satellite.
We follow the perspective of the **controls engineering team** — one
disciplinary team within a larger satellite design program. Our job is
to demonstrate that the ADCS meets its requirements, with evidence that
any auditor can interrogate and reproduce.
### Core Principle
> **Evidence does not verify requirements; evidence supports a human
> judgment that requirements are satisfied.**
Models are imperfect representations of physical systems. Symbolic proofs
and simulation results are claims true *within the model*. The engineer
judges model adequacy and evidence sufficiency. Only human attestation
connects evidence to requirement satisfaction.
""")
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Prologue: The Integration Ontology
Before we write a single line of analysis code, we have an
epistemological question to settle: **what counts as a satisfactory
requirement?**
A naive demo would invent terms — `rtm:modelAdequacy`, a custom
"satisfaction" predicate, a bespoke evidence vocabulary. This demo
deliberately does the opposite. The `rtm:` namespace introduces **no
novel epistemic vocabulary.** It is a thin *integration ontology* over
established standards:
| Layer | Vocabulary | Role |
| ------------ | ------------------------------------ | -------------------------------------------------------- |
| W3C / IETF | `prov:`, `dcterms:`, `earl:`, `sh:` | Provenance + assertion + outcome + SHACL closure |
| OMG / SysML | `sysml:` ↔ `omg-sysml:` | Structural model (aliased to OMG SysMLv2 OWL rendering) |
| Community | `gsn:`, `p-plan:` | Assurance argument structure + declarative process model |
| Tool interop | `oslc_rm:`, `oslc_qm:` | Aliases for DOORS Next / Jama / RQM |
The adequacy/sufficiency split is **not novel** either — it's the
canonical Hawkins–Habli Assurance Claim Point categorization.
"Adequacy" is a `gsn:Assumption`; "sufficiency" is a
`gsn:Justification`. Both attach to the attestation via
`gsn:inContextOf`. The text content lives on those GSN nodes in
`gsn:statement`.
The pipeline runs this assembly as its first act — narrating which
upstream ontologies were imported, how many terms we reference, and
what closure rules will be enforced downstream.
""")
return
@app.cell(hide_code=True)
def __(mo):
import json as _json
from pathlib import Path as _Path
_manifest = _json.loads(_Path("ontology/assembly_manifest.json").read_text())
_import_rows = []
for _name in sorted(_manifest["imports"]):
_info = _manifest["imports"][_name]
_import_rows.append(
f"| {_name} | {_info['total_triples']:>5} | {_info['referenced_count']} |"
)
mo.md(
"### Assembly manifest (data-driven, not hand-written)\n\n"
f"Built `{_manifest['build_time']}` from `ontology/rtm-edit.ttl`.\n\n"
"| Upstream | Triples | TBox refs in `rtm-edit.ttl` |\n"
"|---|---:|---:|\n"
+ "\n".join(_import_rows) + "\n\n"
f"- **SysMLv2 equivalence axioms** (sysml: ↔ omg-sysml:): "
f"{_manifest['artifact']['equivalence_axioms']}\n"
f"- **Local rtm: integration glue:** "
f"{_manifest['artifact']['subclass_axioms']} subclass + "
f"{_manifest['artifact']['subproperty_axioms']} subproperty axioms "
f"(no novel epistemic terms)\n"
f"- **Artifact SHA-256:** `{_manifest['artifact']['sha256'][:24]}...`\n\n"
"**About the third column.** *TBox refs* counts how many distinct "
"terms from each upstream namespace appear in our integration "
"ontology source `rtm-edit.ttl` — i.e. how often that vocabulary "
"is used as the target of a `rdfs:subClassOf` / `rdfs:subPropertyOf` "
"alignment axiom. **P-PLAN reads 0** because P-PLAN is used at the "
"*instance / runtime* layer rather than the TBox alignment layer: "
"the plan definition lives in `pipeline/plan.ttl` (instance data, "
"10 `p-plan:Step` instances) and per-stage `p-plan:Activity` "
"triples are emitted at runtime by `traceability.plan_execution`. "
"Vendoring an upstream is not the same as subclassing it.\n\n"
"The manifest is the build-step provenance record. Stage 0 of the "
"pipeline verifies that `rtm.ttl` still hashes to this manifest "
"value — drift between the source `rtm-edit.ttl` and the committed "
"artifact fails the pipeline with a clear remediation hint."
)
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
### Named-graph quadstore layout
The runtime holds the RTM as an `rdflib.Dataset` (a quadstore) with
one named graph per content layer — sized to match how Flexo MMS
partitions projects/branches. SPARQL queries use
`Dataset(default_union=True)` so existing queries match across the
union without `GRAPH` clauses.
```text
<rtm:ontology> TBox + shapes + individuals
<rtm:plan> P-PLAN process model (one Step per pipeline stage)
<adcs:structural> SysMLv2 instance data
<adcs:context> Stable gsn:Context / gsn:Assumption individuals
<adcs:evidence> rtm:Evidence artifacts
<adcs:attestations> rtm:Attestation events
<adcs:plan-execution> p-plan:Activity instances (one per stage)
<adcs:audit> Forward/backward/bidirectional audit summary
```
Stage 7 persists the Dataset to disk (`output/rtm.{ttl,trig}`) or to a
real quadstore (Flexo MMS / Apache Jena Fuseki) via pluggable
backends. Either way, every named graph round-trips cleanly.
""")
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 1: The Assignment
You are Dr. Michael Zargham, lead controls engineer on the GeoSat
communications satellite program. Systems engineering has allocated
four requirements to your ADCS subsystem, each derived from
satellite-level requirements.
Your team owns the ADCS — reaction wheels, star tracker, IMU, and the
PD attitude controller. You consume interface parameters (mass, orbit,
panel geometry) from other teams but don't control them.
```
Satellite (system-of-interest)
├── ADCS ← YOUR SCOPE
├── Power ← interface: power budget
├── Communications ← interface: antenna pointing
├── Thermal ← interface: wheel heat dissipation
└── Structure ← interface: mass properties
```
Let's load the structural model and see what we're working with.
""")
return
@app.cell(hide_code=True)
def __():
import sys
sys.path.insert(0, ".")
from rdflib import Graph
from ontology.prefixes import bind_prefixes, SYSML, RTM, ADCS, SAT, PROV
from traceability.queries import query_to_dicts
return Graph, bind_prefixes, SYSML, RTM, ADCS, SAT, PROV, query_to_dicts, sys
@app.cell(hide_code=True)
def __(Graph, bind_prefixes):
from analysis.load_params import load_structural_graph, load_params
struct_graph = load_structural_graph()
params = load_params(struct_graph)
return struct_graph, params, load_structural_graph, load_params
@app.cell(hide_code=True)
def __(mo, params):
_param_rows = "\n".join(
f"| {k} | {v:.6g} |" for k, v in sorted(params.items())
)
mo.md(
"### Structural Parameters (from RDF via SPARQL)\n\n"
"All parameters flow from the SysMLv2 structural model — nothing is "
"hardcoded. If systems engineering updates the satellite mass, our "
"entire analysis chain re-derives from the new value.\n\n"
"| Parameter | Value |\n"
"|-----------|-------|\n"
f"{_param_rows}"
)
return
@app.cell(hide_code=True)
def __(mo, struct_graph, query_to_dicts):
_req_query = """
SELECT ?name ?text WHERE {
?req a sysml:RequirementDefinition ;
sysml:declaredName ?name ;
sysml:text ?text .
FILTER(STRSTARTS(?name, "REQ-"))
}
ORDER BY ?name
"""
_reqs = query_to_dicts(struct_graph, _req_query)
_deriv_query = """
SELECT ?child ?parent WHERE {
?c sysml:declaredName ?child ;
rtm:derivedFrom ?p .
?p sysml:declaredName ?parent .
}
ORDER BY ?child
"""
_derivs = query_to_dicts(struct_graph, _deriv_query)
_deriv_map = {r["child"]: r["parent"] for r in _derivs}
_alloc_query = """
SELECT ?reqName ?elementName WHERE {
?req sysml:declaredName ?reqName ;
sysml:ownedRelationship ?rel .
?rel a sysml:SatisfyRequirementUsage ;
sysml:satisfyingElement ?el .
?el sysml:declaredName ?elementName .
FILTER(STRSTARTS(?reqName, "REQ-"))
}
ORDER BY ?reqName ?elementName
"""
_allocs = query_to_dicts(struct_graph, _alloc_query)
_alloc_map = {}
for _a in _allocs:
_alloc_map.setdefault(_a["reqName"], []).append(_a["elementName"])
_req_rows = []
for _r in _reqs:
_name = _r["name"]
_text = _r["text"].strip().replace("\n", " ")[:80]
_parent = _deriv_map.get(_name, "—")
_elements = ", ".join(_alloc_map.get(_name, []))
_req_rows.append(f"| {_name} | {_text}... | {_parent} | {_elements} |")
_req_table = "\n".join(_req_rows)
mo.md(
"### ADCS Requirements\n\n"
"Four requirements allocated to us, each derived from a satellite-level "
"parent requirement and satisfied by specific design elements:\n\n"
"| ID | Requirement | Derived From | Satisfied By |\n"
"|----|------------|-------------|-------------|\n"
f"{_req_table}"
)
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 2: Symbolic Analysis
Before running any simulation, we derive formal results symbolically
using SymPy. Every quantity is computed from the structural parameters —
the inertia tensor via parallel axis theorem, eigenvalues for stability
analysis, and bounds for pointing error and wheel momentum.
These are claims true *within our model*. Whether the model adequately
represents the physical satellite is a judgment we'll make during
attestation.
""")
return
@app.cell(hide_code=True)
def __(params):
from analysis.symbolic import (
run_symbolic_analysis,
build_inertia_tensor_symbolic,
evaluate_inertia,
stability_margins,
)
sym_result = run_symbolic_analysis(params)
return sym_result, run_symbolic_analysis, build_inertia_tensor_symbolic, evaluate_inertia, stability_margins
@app.cell(hide_code=True)
def __(mo, sym_result):
_Ixx, _Iyy, _Izz = sym_result.inertia
_margins = sym_result.stability_margins
mo.md(f"""
### Composite Inertia Tensor
Derived via parallel axis theorem (bus + 2 solar panels + antenna):
| Axis | Inertia (kg-m^2) | Dominant contributor |
|------|-----------------|---------------------|
| Ixx | {_Ixx:.1f} | Solar panels (offset along Y) |
| Iyy | {_Iyy:.1f} | Bus (panels add little on this axis) |
| Izz | {_Izz:.1f} | Solar panels (offset along Y) |
The panels dominate Ixx and Izz because their center of mass is far
from the satellite center — the parallel axis term grows as distance
squared.
### Stability Margins (REQ-003)
Closed-loop eigenvalues for each axis (PD controller, linearized):
| Axis | Re(lambda) | Margin vs -0.010 |
|------|-----------|-----------------|
| X | {_margins['x']:.4f} rad/s | {'PASS' if _margins['x'] <= -0.010 else 'MARGINAL'} |
| Y | {_margins['y']:.4f} rad/s | {'PASS' if _margins['y'] <= -0.010 else 'MARGINAL'} |
| Z | {_margins['z']:.4f} rad/s | {'PASS' if _margins['z'] <= -0.010 else 'MARGINAL'} |
All axes satisfy REQ-003 (Re(lambda) <= -0.010 rad/s).
""")
return
@app.cell(hide_code=True)
def __(mo, sym_result):
_pb = sym_result.pointing_budget
_gg = sym_result.gravity_gradient
_wm = sym_result.wheel_momentum
mo.md(f"""
### Pointing Budget (REQ-001)
| Metric | Value |
|--------|-------|
| Steady-state error (gravity gradient) | {_pb['theta_ss_deg']:.6f} deg |
| Star tracker noise floor | {_pb['st_floor_deg']:.6f} deg |
| Settling time (4/|Re(lambda)|) | {_pb['settling_time_s']:.1f} s |
The steady-state pointing error is well below 0.1 deg. However, the
**settling time is {_pb['settling_time_s']:.0f}s** — exceeding the 120s target.
This is a real finding that the engineer must address during attestation.
### Gravity Gradient (REQ-004)
| Metric | Value |
|--------|-------|
| tau_gg_x | {_gg['tau_gg_x']:.2e} N.m |
| tau_gg_y | {_gg['tau_gg_y']:.2e} N.m |
| Actuator capacity | {_gg['tau_max']} N.m |
Gravity gradient torques at GEO are **orders of magnitude** below
actuator capacity.
### Wheel Momentum (REQ-002)
| Metric | Value |
|--------|-------|
| Peak momentum (10 deg slew) | {_wm['h_peak']:.3f} N.m.s |
| Rated capacity | {_wm['h_max']} N.m.s |
| Margin | {_wm['margin']:.3f} N.m.s |
""")
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
### Formal Proofs
Each requirement gets a ProofScript — a chain of SymPy lemmas, each
independently re-verifiable. The proof is bound to the structural model
via content hash: if the model changes, the proof hash changes, alerting
auditors to re-verify.
""")
return
@app.cell(hide_code=True)
def __(struct_graph):
from evidence.hashing import hash_structural_model, hash_proof
from analysis.build_proofs import build_all_proofs
from analysis.proof_scripts import verify_proof, ProofStatus
model_hash = hash_structural_model(struct_graph)
proofs = build_all_proofs(model_hash)
proof_results = {}
for _req_id, _script in proofs.items():
_result = verify_proof(_script, model_hash)
proof_results[_req_id] = _result
return model_hash, proofs, proof_results, hash_structural_model, hash_proof, build_all_proofs, verify_proof, ProofStatus
@app.cell(hide_code=True)
def __(mo, proofs, proof_results, ProofStatus):
_rows = []
for _req_id in sorted(proofs.keys()):
_script = proofs[_req_id]
_result = proof_results[_req_id]
_status = "VERIFIED" if _result.status == ProofStatus.VERIFIED else "FAILED"
_lemmas = ", ".join(l.name for l in _script.lemmas)
_rows.append(f"| {_req_id} | {_status} | {_script.claim[:60]}... | {_lemmas} |")
_proof_table = "\n".join(_rows)
mo.md(
"| Requirement | Status | Claim | Lemmas |\n"
"|-------------|--------|-------|--------|\n"
f"{_proof_table}\n\n"
"All proofs pass. Each can be serialized to JSON, stored, and re-verified "
"by anyone — no trust in the original analyst required."
)
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 3: Numerical Simulation
Symbolic analysis tells us what the model *should* do. Numerical
simulation shows what it *actually does* when we integrate the full
nonlinear dynamics. We run two scenarios:
1. **Step response** — 10-degree initial attitude error, observe settling
2. **Disturbance rejection** — near-zero error, observe gravity gradient effects
""")
return
@app.cell(hide_code=True)
def __(params):
from analysis.numerical import run_step_response, run_disturbance_rejection
step_result = run_step_response(params)
step_summary = step_result.summary()
dist_result = run_disturbance_rejection(params)
dist_summary = dist_result.summary()
return step_result, step_summary, dist_result, dist_summary, run_step_response, run_disturbance_rejection
@app.cell(hide_code=True)
def __(mo, step_result, step_summary):
import matplotlib.pyplot as plt
import numpy as np
_fig, _axes = plt.subplots(2, 2, figsize=(12, 8))
_axis_colors = {"X": "#1f77b4", "Y": "#2ca02c", "Z": "#9467bd"} # blue, green, purple
_limit_color = "#d62728" # red reserved exclusively for requirement limits
# Attitude error
_q_vec = np.linalg.norm(step_result.q[:, :3], axis=1)
_theta_deg = np.degrees(2 * _q_vec)
_axes[0, 0].semilogy(step_result.t, _theta_deg, color=_axis_colors["X"], linewidth=1.5, label='Attitude error')
_axes[0, 0].axhline(0.1, color=_limit_color, linestyle='--', linewidth=1, label='REQ-001 limit (0.1 deg)')
_axes[0, 0].set_xlabel('Time (s)')
_axes[0, 0].set_ylabel('Attitude Error (deg)')
_axes[0, 0].set_title('Pointing Convergence')
_axes[0, 0].set_ylim(bottom=1e-3)
_axes[0, 0].legend(fontsize=8)
_axes[0, 0].grid(True, alpha=0.3, which='both')
# Angular velocity
for _i, (_axis, _c) in enumerate(_axis_colors.items()):
_axes[0, 1].plot(step_result.t, np.degrees(step_result.omega[:, _i]),
color=_c, linewidth=1, label=f'{_axis}-axis')
_axes[0, 1].set_xlabel('Time (s)')
_axes[0, 1].set_ylabel('Angular Rate (deg/s)')
_axes[0, 1].set_title('Angular Velocity')
_axes[0, 1].legend(fontsize=8)
_axes[0, 1].grid(True, alpha=0.3)
# Control torque
for _i, (_axis, _c) in enumerate(_axis_colors.items()):
_axes[1, 0].plot(step_result.t, step_result.tau_ctrl[:, _i],
color=_c, linewidth=1, label=f'{_axis}-axis')
_axes[1, 0].axhline(step_result.config.max_torque, color=_limit_color, linestyle='--',
linewidth=1, alpha=0.7, label='Torque limit')
_axes[1, 0].axhline(-step_result.config.max_torque, color=_limit_color, linestyle='--',
linewidth=1, alpha=0.7)
_axes[1, 0].set_xlabel('Time (s)')
_axes[1, 0].set_ylabel('Torque (N.m)')
_axes[1, 0].set_title('Control Torque')
_axes[1, 0].legend(fontsize=8)
_axes[1, 0].grid(True, alpha=0.3)
# Wheel momentum
_h_mag = np.linalg.norm(step_result.h_wheel, axis=1)
_axes[1, 1].plot(step_result.t, _h_mag, color=_axis_colors["X"], linewidth=1.5, label='|h| (total)')
_axes[1, 1].axhline(step_result.config.max_momentum, color=_limit_color, linestyle='--',
linewidth=1, label='REQ-002 limit (4.0 N.m.s)')
_axes[1, 1].set_xlabel('Time (s)')
_axes[1, 1].set_ylabel('Momentum (N.m.s)')
_axes[1, 1].set_title('Wheel Angular Momentum')
_axes[1, 1].legend(fontsize=8)
_axes[1, 1].grid(True, alpha=0.3)
_fig.suptitle('Step Response: 10-degree Slew Maneuver', fontsize=14, fontweight='bold')
plt.tight_layout()
mo.md(f"""
### Step Response Results
| Metric | Value |
|--------|-------|
| Final pointing error | {step_summary['final_error_deg']:.4f} deg |
| Peak pointing error | {step_summary['peak_error_deg']:.1f} deg |
| Settling time | {step_summary['settling_time_s']:.1f} s |
| Peak wheel momentum | {step_summary['peak_wheel_momentum']:.3f} N.m.s |
| Peak control torque | {step_summary['peak_control_torque']:.4f} N.m |
""")
_fig
return np, plt
@app.cell(hide_code=True)
def __(mo, dist_summary):
mo.md(f"""
### Disturbance Rejection Results
| Metric | Value |
|--------|-------|
| Peak error (GG disturbance) | {dist_summary['peak_error_deg']:.6f} deg |
| Final angular rate | {dist_summary['final_omega_norm']:.2e} rad/s |
Gravity gradient effects are negligible at GEO — confirming REQ-004.
""")
return
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 4: Evidence Binding
Now we bind our computational results to the RDF traceability graph.
Every evidence artifact gets a content hash, a model hash (binding it
to the structural model version), and PROV-O provenance (who/what
produced it, when).
Each evidence artifact **addresses** a specific requirement — recording
the structural intent that "this proof was constructed to evaluate
REQ-003." But `rtm:addresses` is not `rtm:attests`. The evidence
says *what was analyzed*; only human attestation says *whether it's
sufficient*. An evidence artifact can address a requirement and still
lead to a declined attestation — as we'll see with REQ-001.
""")
return
@app.cell(hide_code=True)
def __(mo, model_hash, proofs, proof_results, step_summary, dist_summary, params, ProofStatus):
from evidence.binding import bind_proof_evidence, bind_simulation_evidence, bind_computation_engines
from evidence.hashing import hash_proof as _hp, hash_evidence, hash_simulation
from pipeline.dataset import graph_for, triples_by_graph
from traceability.rtm import load_base_dataset, verify_evidence_completeness
# rtm_graph is now an rdflib.Dataset with named graphs. Existing
# SPARQL queries still work via default_union; new audit / closure-
# rule / backend code uses the explicit named-graph views.
rtm_graph = load_base_dataset()
_ev = graph_for(rtm_graph, "evidence")
bind_computation_engines(_ev)
for _rid, _script in proofs.items():
_ph = _hp(_script, model_hash)
_ch = hash_evidence(model_hash, proof_hash=_ph)
bind_proof_evidence(
_ev, f"EV-PROOF-{_rid}", f"SA-{_rid}", _rid,
model_hash, _ph, _ch,
f"Symbolic proof: {_script.claim}",
source_file="analysis/build_proofs.py",
)
_sh = hash_simulation({"type": "step_response"}, step_summary)
for _rid, _desc in [
("REQ-001", f"Step response: settling={step_summary['settling_time_s']:.1f}s, final_error={step_summary['final_error_deg']:.4f} deg"),
("REQ-002", f"Peak wheel momentum: {step_summary['peak_wheel_momentum']:.3f} N.m.s (limit={params['maxMomentum']})"),
]:
bind_simulation_evidence(
_ev, f"EV-SIM-{_rid}", f"NS-{_rid}", _rid,
model_hash, _sh, _desc, source_file="analysis/numerical.py",
)
_dh = hash_simulation({"type": "disturbance_rejection"}, dist_summary)
bind_simulation_evidence(
_ev, "EV-SIM-REQ-004", "NS-REQ-004", "REQ-004",
model_hash, _dh,
f"Disturbance rejection: peak_error={dist_summary['peak_error_deg']:.6f} deg",
source_file="analysis/numerical.py",
)
_issues = verify_evidence_completeness(rtm_graph)
_counts = triples_by_graph(rtm_graph)
_count_rows = "\n".join(
f"| `<{_iri.rsplit('/', 1)[-1]}>` | {_n} |"
for _iri, _n in sorted(_counts.items())
)
mo.md(
"### Evidence artifacts in their named graph\n\n"
f"- **4 proof artifacts** (hash-bound to model `{model_hash[:16]}...`)\n"
f"- **3 simulation results**\n"
f"- All emitted into `<adcs:evidence>` — kept distinct from the structural "
f"and ontology layers so SPARQL queries can scope by graph, and the "
f"Phase J Flexo backend can push each layer as its own branch.\n"
f"- Evidence completeness: **{'PASS' if not _issues else 'ISSUES: ' + str(_issues)}**\n\n"
"**Per-graph triple counts after Act 4:**\n\n"
"| Named graph | Triples |\n"
"|---|---:|\n"
+ _count_rows + "\n\n"
"Every artifact carries `rtm:contentHash`, `rtm:modelHash`, and a "
"PROV-O provenance chain. The model hash ensures that if the model "
"changes (Act 8), all evidence must be re-produced and re-verified."
)
return rtm_graph, bind_proof_evidence, bind_simulation_evidence, bind_computation_engines, hash_evidence, hash_simulation, load_base_dataset, verify_evidence_completeness
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 5: Attestation (GSN + EARL outcomes)
Evidence alone doesn't satisfy requirements. The engineer makes two
judgments per requirement — and we record them using **established
assurance-case vocabulary**, not novel terms:
- **Adequacy** → a `gsn:Assumption` (Hawkins–Habli "asserted context")
stating the model adequately represents the physical system for
this requirement. Text on `gsn:statement`.
- **Sufficiency** → a `gsn:Justification` (Hawkins–Habli "asserted
inference") stating the evidence is sufficient to conclude
satisfaction. Text on `gsn:statement`.
- **Outcome** → an `earl:outcome` from EARL's five-valued lattice:
`earl:passed` / `earl:failed` / `earl:cantTell` / `earl:inapplicable`
/ `earl:untested`. Better than binary pass/fail because "models are
imperfect" — `cantTell` and `inapplicable` are first-class.
- **Qualified association** → a `prov:Association` carrying the
engineer's `prov:hadRole` (`rtm:role-AttestingEngineer`) and the
`prov:hadPlan` they followed (the standard attestation procedure).
REQ-001 below is **attested-with-failed**, not silently omitted —
the audit trail records the declination as a well-formed attestation
so closure-rule shapes can validate against an audit-complete graph.
""")
return
@app.cell(hide_code=True)
def __(rtm_graph, step_summary, params, mo):
from traceability.attestation import request_attestation, OUTCOME_FAILED
_adequacy = {
"REQ-001": ("Step-response simulation is adequate for evaluating pointing-"
"accuracy settling time at this point in the lifecycle."),
"REQ-002": ("Energy-based momentum bound is conservative. "
"Reaction wheel model adequate for peak momentum estimation."),
"REQ-003": ("Linearized stability analysis via Routh-Hurwitz is adequate for this design point. "
"Nonlinear effects are second-order for small angles around the operating point."),
"REQ-004": ("Linearized gravity gradient model adequate for GEO orbit. "
"Higher-order terms negligible at geostationary altitude."),
}
_sufficiency = {
"REQ-001": (f"Evidence is sufficient to conclude REQ-001 is NOT yet satisfied: "
f"settling time {step_summary['settling_time_s']:.0f}s exceeds the 120s "
f"requirement. Action item: retune gains (Kp: {params['Kp']:.0f}→4, "
f"Kd: {params['Kd']:.0f}→30) and re-verify."),
"REQ-002": ("Both symbolic bound (0.81 N.m.s) and numerical simulation confirm "
"peak momentum well below 4.0 N.m.s rated capacity. Large margin."),
"REQ-003": ("Routh-Hurwitz proof confirms asymptotic stability for ALL positive J, Kp, Kd — "
"this is a parametric result, not just for one design point. "
"Numerical eigenvalues confirm margins exceed -0.010 rad/s on all axes."),
"REQ-004": ("Gravity gradient torques at GEO are ~1e-6 N.m, four orders of magnitude below "
"0.1 N.m actuator capacity. Simulation confirms negligible pointing impact. "
"Overwhelming margin."),
}
# REQ-001: explicit DECLINATION as earl:failed — keeps the audit
# trail complete so the closure-rule suite validates.
request_attestation(
rtm_graph, "REQ-001", "Dr. Michael Zargham (@mzargham)",
auto_attest=True,
model_adequacy=_adequacy["REQ-001"],
evidence_sufficiency=_sufficiency["REQ-001"],
outcome=OUTCOME_FAILED,
)
# REQ-002, REQ-003, REQ-004 — outcome defaults to earl:passed
for _rid in ["REQ-002", "REQ-003", "REQ-004"]:
request_attestation(
rtm_graph, _rid, "Dr. Michael Zargham (@mzargham)",
auto_attest=True,
model_adequacy=_adequacy[_rid],
evidence_sufficiency=_sufficiency[_rid],
)
mo.md("""
### Attestation outcomes
| Requirement | Outcome | Reasoning |
|---|---|---|
| REQ-001 | `earl:failed` | Settling time ~262s > 120s requirement; action item recorded |
| REQ-002 | `earl:passed` | Peak momentum well within 4.0 N.m.s |
| REQ-003 | `earl:passed` | Routh-Hurwitz parametric stability proof |
| REQ-004 | `earl:passed` | Gravity gradient torques 4 orders below actuator capacity |
All four attestations are well-formed: each carries an adequacy
`gsn:Assumption`, a sufficiency `gsn:Justification`, an EARL outcome,
a qualified association naming the engineer's role and the procedure
followed, and references to the evidence consulted. REQ-001 is
*attested with `earl:failed`* — the audit graph records the gap
explicitly rather than hiding it as "missing."
""")
return request_attestation
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 6: Closure-Rule Validation + Audit (initial)
Before the program's chief systems engineer reviews the work, two
automated checks ratify that the RTM graph itself is well-formed and
internally consistent:
1. **Closure-rule suite (SHACL).** Ten machine-checkable invariants —
every attestation has both an adequacy Assumption and a sufficiency
Justification, every evidence artifact has hashes and references a
requirement, every analysis activity has an associated agent, etc.
Plus a runtime re-verification check that re-hashes every proof.
2. **Forward / Backward / Bidirectional audit.** Forward and backward
run *independently* so the failure mode names which direction
broke. Bidirectional is the derived conjunction.
If any closure rule fails, the audit module's "fresh graph" claim
can't be trusted. The two checks together are what an auditor would
run before asking any substantive question.
""")
return
@app.cell(hide_code=True)
def __(rtm_graph, mo):
from traceability.verification import verify as _verify
_report = _verify(rtm_graph, skip_reverification=False)
_summary = "\n".join(" " + l for l in _report.summary_lines())
mo.md(
"### Closure-rule suite (Stage 6.5)\n\n"
"```\n"
f"{_summary}\n"
"```\n\n"
"Ten invariants enforced — nine SHACL shapes + one runtime "
"re-verification check. The shapes target distinct layers of the "
"graph: attestation well-formedness, plan-instantiation correctness, "
"evidence completeness, requirement structure, GSN argument well-"
"formedness, PROV provenance shape, outcome semantics, "
"forward/backward traceability, and named-graph integrity."
)
return
@app.cell(hide_code=True)
def __(rtm_graph, mo):
from traceability.audit import audit as _audit_fn, render_report as _render
audit_report = _audit_fn(rtm_graph)
mo.md(
"### Audit (Stage 7a)\n\n"
"```\n"
f" {audit_report.forward.summary()}\n"
f" {audit_report.backward.summary()}\n"
f" Bidirectional: {'PASS' if audit_report.bidirectional().passed else 'FAIL'}\n"
f" Orphans: {'none' if not audit_report.orphans.any else 'see report'}\n"
"```\n\n"
"**Two orthogonal questions, not one.** The audit decouples\n\n"
"- **traceability** — *is the structural chain intact?* "
"Forward asks if every requirement is reached by evidence + an "
"attestation; backward asks if every attestation's evidence "
"actually addresses its claimed requirement. Bidirectional is "
"the conjunction. These are structural facts about the graph.\n"
"- **coverage status** — *is the requirement satisfied?* "
"Outcome-derived per cell of the coverage matrix: "
"`covered+passed` / `covered+failed` / `covered+cantTell` / "
"`uncovered`. These are the engineering verdicts captured in "
"each attestation's `earl:outcome`.\n\n"
"**The v1 verdict (this stage).** Traceability passes — the "
"chain is structurally sound, no orphans, every attestation "
"lines up with its evidence. **REQ-001 is `covered+failed` and "
"this is the *expected* output of v1**: the engineering analysis "
"produced a real finding (settling time > spec) and the audit "
"surfaces it as a coverage gap rather than hiding it behind "
"'unattested'. Act 8 — Design Iteration — is the response, and "
"Act 10's audit shows the same matrix flipping to all "
"`covered+passed`."
)
return audit_report, _render
@app.cell(hide_code=True)
def __(audit_report, mo):
_rows = "\n".join(
f"| {c.requirement} | {c.evidence} | {c.status} |"
for c in audit_report.coverage
)
mo.md(
"**Coverage matrix**\n\n"
"| Requirement | Evidence | Status |\n"
"|---|---|---|\n"
+ _rows
)
return
@app.cell(hide_code=True)
def __(rtm_graph, mo):
from interrogate.explain import explain_requirement
explanations = {}
for _rid in ["REQ-001", "REQ-002", "REQ-003", "REQ-004"]:
explanations[_rid] = explain_requirement(rtm_graph, _rid)
return explanations, explain_requirement
@app.cell(hide_code=True)
def __(explanations, mo):
mo.md(f"""
### "How do you know REQ-003 is satisfied?"
```
{explanations["REQ-003"]}
```
The proof was **re-executed live** during this interrogation. The auditor
doesn't need to trust the original analyst — they can see each lemma
verified independently, right now.
""")
return
@app.cell(hide_code=True)
def __(explanations, mo):
mo.md(f"""
### "What does the audit say about REQ-001?"
```
{explanations["REQ-001"]}
```
REQ-001 is **`covered+failed` at v1** — the structural trace from
requirement → evidence → attestation is complete (which is why
forward/backward both PASS), and the engineer recorded an
`earl:failed` outcome with a precise reason (settling time > spec)
and an action item (retune gains).
This is the lifecycle state the demo is *designed* to produce at
v1. The auditor sees three things separately:
1. **The trace is intact.** No "missing attestation", no orphan
evidence — the graph is internally consistent.
2. **The engineering verdict is recorded.** Outcome = `earl:failed`,
with adequacy and sufficiency text on linked GSN nodes.
3. **The next action is in the record.** The sufficiency
`gsn:Justification` carries the corrective recommendation, so
the design iteration in Act 8 has a documented starting point.
""")
return
@app.cell(hide_code=True)
def __(rtm_graph, mo):
from interrogate.reproduce import reproduce_all_evidence
_repro = reproduce_all_evidence(rtm_graph)
_proof_rows = []
for _p in _repro["proofs"]:
_match = "MATCH" if _p["hash_match"] else "MISMATCH"
_proof_rows.append(f"| {_p['requirement']} | {_p['status'].value} | {_match} |")
_repro_table = "\n".join(_proof_rows)
_n_sims = len(_repro['simulations'])
mo.md(
"### Reproducibility Audit\n\n"
"The auditor re-executes ALL computational evidence:\n\n"
"**Proof Re-verification:**\n\n"
"| Requirement | Status | Hash Match |\n"
"|-------------|--------|-----------|\n"
f"{_repro_table}\n\n"
f"**Simulation Reproduction:** {_n_sims} simulations re-run successfully.\n\n"
"Every proof re-verifies. Every hash matches. The evidence is "
"reproducible — not because we say so, but because the auditor "
"just confirmed it."
)
return reproduce_all_evidence
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 7: The Traceability Graph
The complete v1 RTM as a directed graph. Requirements (blue) flow
through design elements (green) to evidence (orange/yellow) to
attestations (red). Every edge is a queryable RDF triple in git.
What you should see at v1:
- **All four requirements have full chains** to evidence and an
attestation node — that's why Act 6's audit reported the trace
as PASS. The chain is structurally complete for every
requirement.
- **REQ-001's attestation carries `earl:failed`** in the outcome —
the engineering verdict — even though its trace looks just like
the other three at the graph level. Outcome lives on the
attestation node as a property, not in the link shape.
The `print_rtm_summary` block below makes this distinction
explicit: requirements are categorized as ATTESTED with their
EARL outcome surfaced, separating "trace intact + verdict pending
work" from "trace incomplete."
""")
return
@app.cell(hide_code=True)
def __(rtm_graph):
from interrogate.visualize import build_rtm_figure
rtm_fig = build_rtm_figure(rtm_graph, figsize=(18, 10))
rtm_fig
return rtm_fig, build_rtm_figure
@app.cell(hide_code=True)
def __(rtm_graph, mo):
from traceability.rtm import print_rtm_summary
_summary = print_rtm_summary(rtm_graph)
mo.md(f"""
### Final Status
```
{_summary}
```
""")
return print_rtm_summary
@app.cell(hide_code=True)
def __(mo):
mo.md("""
---
## Act 8: Design Iteration
The open finding on REQ-001 drives action. We need to increase the
derivative gain Kd to reduce settling time. Rather than editing a file