Skip to content

Mathematics of the Rules

RAPID AI’s diagnostic intelligence is encoded in 451+ rules. Chapter 25 established the reliability mathematics — Weibull distributions, hazard functions, RUL models — that quantify how machines fail over time. This chapter addresses a different question: how does the system decide what is happening right now? The answer lives in the rule engine — the mathematical machinery that translates natural-language domain knowledge into computable boolean logic, fuses evidence across diagnostic blocks, detects contradictions, and scores imperfections.

Every formula in this chapter maps to production code. The rule evaluator lives in rule_evaluator.py. The natural-language translator lives in diagnostics.py. The fusion engine lives in fusion_engine.py. The entropy engine lives in sedl_engine.py. The contradiction engine lives in cde_engine.py. The prognostic models live in rul_engine.py. The imperfection rules are defined in the domain knowledge library.


26.1 Rule Architecture — The Four Layers

Section titled “26.1 Rule Architecture — The Four Layers”

The 451+ rules are organized into four processing layers, each with a distinct mathematical character. Data flows through them sequentially: GUARD validates, SENSE detects, FUSE aggregates, and ACT decides.

LayerCountMathematical FoundationPurpose
GUARD16Boundary predicates, range validationInput quality gates
SENSE275+Regex-to-expression translation, recursive-descent parsingCondition detection
FUSE66Profile-weighted aggregation, BSR scoring, entropy overrideMulti-signal fusion
ACT38Decision tree traversal, consequence classificationAction selection

GUARD rules are pure threshold predicates. They enforce physical plausibility before any diagnostic logic executes. A GUARD rule takes the form:

GUARD(x) = { PASS if x_min <= x <= x_max
{ FAIL otherwise

For example, a vibration reading of -5.0 mm/s is physically impossible. A temperature reading of 900 C on a bearing sensor indicates a failed sensor, not a burning bearing. GUARD rules reject these before they contaminate downstream analysis.

The 19 GUARD rules cover: sensor range validation (6 rules), timestamp sanity (2 rules), asset configuration completeness (4 rules), and data quality flags (4 rules). When any GUARD rule fails, the diagnostic request is rejected with a data quality error rather than producing a misleading result.

SENSE rules are the heart of the diagnostic engine. Each rule is a boolean expression evaluated against flattened sensor data. The mathematical pipeline is:

Natural Language --> Regex Translation --> Formal Expression --> Recursive Descent Parse --> Boolean Result + Confidence

Section 26.2 covers this pipeline in full detail.

FUSE rules aggregate per-block SENSE results into a system-level severity score using profile-weighted means, Block Score Rules (BSR001-BSR007), and entropy-based override logic. The output is the System Severity Index (SSI), a single number between 0.0 and 1.0. Section 26.3 covers SSI fusion mathematics.

ACT rules traverse a decision tree to select the appropriate maintenance strategy. The tree structure follows classical RCM (Reliability-Centred Maintenance) logic:

IF confidence < 0.60:
strategy = "Inspect / Validate"
ELIF consequence in [Safety, Environmental] AND severity >= 4:
strategy = "Immediate Action / Escalation"
ELIF detectable_online == TRUE:
strategy = "Condition Based Maintenance"
ELIF detectable_offline == TRUE:
strategy = "Scheduled Inspection"
ELIF RUL_days <= replacement_window:
strategy = "Planned Replacement"
ELIF age_related == TRUE:
strategy = "Time-Based Replacement"
ELIF low_consequence AND low_repair_cost:
strategy = "Run to Failure"
ELSE:
strategy = "Engineering Review"

The decision tree is a directed acyclic graph with 38 leaf nodes, each mapping to a specific maintenance task template. The confidence threshold at the root (0.60) acts as a gate: uncertain diagnoses are routed to human review rather than automated action.


26.2 SENSE Rule Mathematics — The _CONDITION_PATTERNS System

Section titled “26.2 SENSE Rule Mathematics — The _CONDITION_PATTERNS System”

The Integrated Master Schema (IMS) contains 451+ rows of domain knowledge authored by Dibyendu De. Each row’s sensor_evidence_logic field is written in natural language:

"IF BPFO rises with temperature THEN suspect outer race defect"

The diagnostic engine must translate this to a formal expression:

"bpfo_amplitude > 0.7 AND bearing_de_temp_c > 80"

The _translate_evidence_logic() function implements a pattern-matching translator with 180+ compiled regular expressions organized by sensor domain:

CategoryPattern CountExample PatternFormal Output
Vibration/Bearing~20bpfo\s+rises?bpfo_amplitude > 0.7
Temperature~20bearing\s+temp\s+risebearing_de_temp_c > 80
Pressure/Process~15suction\s+pressure\s+falls?suction_pressure_bar < 1.5
Current/Electrical~10current\s+rises?current_rms > 1.1
Oil Analysis~10oil\s+debris\s+increasewear_debris_index > 0.6
Inspection/Boolean~25leak(age)?\s+observedleakage_observed > 0
Performance~20efficiency\s+(falls?|drops?)efficiency_pct < 85
Functional Tests~8proof\s+test\s+fails?proof_test_pass < 1
1. Convert evidence_logic to lowercase
2. Strip "IF ... THEN ..." wrapper to extract condition clause
3. Skip sentinel values ("Online", "Offline", "")
4. For each (pattern, formal_expr) in _CONDITION_PATTERNS:
For each non-overlapping match in condition_text:
If span does not overlap with previously used spans:
Append formal_expr to fragments (avoiding duplicates)
Record span as used
5. Return fragments joined with " AND "

The overlap detection prevents double-counting when multiple patterns could match the same text span. The duplicate check on formal_expr prevents the same sensor variable from appearing twice even when matched by different patterns.

Tested against 100 representative IMS rows:

  • 93 rows translate successfully to parseable formal expressions
  • 7 rows are non-translatable: sentinel values (“Online”, “Offline”) and proof-test conditions that require physical testing rather than online sensor data

Expression Evaluation — Recursive Descent Parser

Section titled “Expression Evaluation — Recursive Descent Parser”

The translated expression is evaluated by a recursive-descent parser implementing an LL(1) grammar. The formal grammar:

expression ::= and_expr ( 'OR' and_expr )*
and_expr ::= atom ( 'AND' atom )*
atom ::= '(' expression ')' | comparison
comparison ::= value operator value
value ::= identifier ( '/' identifier )* | number

Time complexity is O(n) where n is the number of tokens. Space complexity is O(d) where d is the maximum nesting depth of parentheses.

A binary match/no-match is insufficient for reliability engineering. Confidence quantifies partial-match strength:

base_confidence = matched_terms / total_terms

Multi-sensor fusion adds a bonus when evidence spans independent sensor categories:

bonus = max(0, n_sensor_categories - 1) * 0.05
final_confidence = min(base_confidence + bonus, 0.95)

The six sensor categories are: vibration, temperature, current/electrical, oil analysis, process parameters, and inspection. The 0.95 cap reflects irreducible epistemic uncertainty — RAPID AI never claims certainty in remote diagnosis.


The System Severity Index (SSI) is Module C’s composite health score. It fuses evidence from multiple diagnostic blocks into a single 0.0-1.0 severity score per asset.

Different asset types weight diagnostic blocks differently. Three profiles are defined:

PROFILE_PUMP_A (centrifugal pump trains):

BlockWeightRationale
foundation0.15Structural resonance contributes but is rarely the primary fault
ac_motor0.10Motor faults propagate downstream
coupling0.10Misalignment and coupling wear
shafts0.10Shaft deflection and runout
afb (anti-friction bearings)0.25Bearings are the dominant wear component
fluid_flow0.30Cavitation, recirculation, hydraulic instability dominate pump failures

PROFILE_GBX_A (gearbox trains):

BlockWeight
foundation0.15
ac_motor0.10
coupling0.10
shafts0.10
gears0.35
afb0.20

PROFILE_FAN_A (fan trains):

BlockWeight
foundation0.15
ac_motor0.15
coupling0.05
shafts0.10
afb0.25
fluid_flow0.30

For a given profile with weights w_k and block scores B_k:

SSI = SUM(w_k * B_k) for k in present_blocks

When blocks are missing (sensors unavailable), weights are renormalized proportionally among the present blocks:

w_k_normalized = w_k / SUM(w_j for j in present_blocks)

This ensures the SSI remains on the 0.0-1.0 scale regardless of how many sensor types are installed. The data_quality_flag is set to "incomplete_data" when required blocks are missing, signaling reduced confidence in the assessment.

Each diagnostic block’s raw evidence is converted to a block score by evaluating seven Block Score Rules in priority order. The first (highest-priority) match determines the block’s score and severity label:

RulePriorityConditionScoreSeverity
BSR0071B_match >= 0.900.90critical
BSR0012trend == “accelerating” AND B.2 confidence >= 0.700.85unstable
BSR0032trend == “step” AND B.2 confidence >= 0.700.80unstable
BSR0053B_match >= 0.70 AND (trend == “stable” OR B.2 confidence < 0.50)0.55watch
BSR0024trend == “drifting” AND B.2 confidence >= 0.600.65degrading
BSR0045trend == “chaotic” AND process_correlation >= 0.700.35watch
BSR0066B_match < 0.30 AND trend == “stable”0.15healthy
(none)99Default fallback0.30watch

When any block’s Module B.3 stability state is Critical_Instability, the SSI system state is forced to at least "warning" regardless of the weighted average. This prevents a catastrophic instability reading from being diluted by healthy readings in other blocks.

SSI RangeSystem StateSeverity LevelAction
0.00 - 0.29healthyhealthyContinue routine monitoring
0.30 - 0.59watchwatchPlan inspection within schedule window
0.60 - 0.79warningwarningReduce load/speed, inspect soon
0.80 - 1.00alarmalarmStop if safe, inspect immediately

26.4 SEDL Entropy Mathematics — Module B.3

Section titled “26.4 SEDL Entropy Mathematics — Module B.3”

The SEDL engine quantifies signal disorder across three dimensions: spectral, temporal, and directional. The mathematics is rooted in Shannon information theory.

For a discrete probability distribution P = {p(x_1), …, p(x_N)}:

H(X) = -SUM[ p(x_i) * ln(p(x_i)) ] for i = 1 to N

Normalized entropy scales this to the [0, 1] range:

H_norm(X) = H(X) / ln(N)

Measures how uniformly energy is distributed across frequency bands:

SE = H_norm(PSD)

where PSD is the power spectral density normalized to a probability distribution. Low SE (< 0.35) means energy is concentrated in a few dominant frequencies — either a healthy tonal signature or a specific defect frequency. High SE (> 0.65) means broadband energy scatter indicating looseness, turbulence, or multiple competing faults.

Measures signal consistency across successive time windows. The time-domain waveform is binned into a histogram (default 64 bins), and Shannon entropy is computed on the bin counts:

TE = H_norm(histogram_counts)

Low TE indicates steady-state operation. High TE (> 0.60) indicates transient events, intermittent contact, or load fluctuations.

Measures how energy is distributed across measurement directions (H, V, A):

DE = H_norm([RMS_H, RMS_V, RMS_A])

Low DE means energy is dominated by one direction (axial = misalignment, radial = unbalance). High DE (> 0.60) means energy is equally distributed, suggesting structural looseness or multiple active faults.

The three entropy measures are combined using empirically determined weights:

WE = 0.5 * SE + 0.3 * TE + 0.2 * DE
SI = 1 - WE = 1 - (0.5 * SE + 0.3 * TE + 0.2 * DE)

Weight rationale:

  • SE (0.5): Spectral shape is the most informative feature for fault detection.
  • TE (0.3): Captures non-stationarity, which indicates developing faults.
  • DE (0.2): Supplements with directional information but is the least discriminating on its own.

Interpretation:

  • SI close to 1.0: Low entropy everywhere. Energy flows through the machine in a predictable, organized pattern. The machine is healthy.
  • SI close to 0.0: High entropy everywhere. Energy is scattered, trapped, or misdirected. The machine is degraded or has multiple active fault mechanisms.

The spectral entropy rate of change detects destabilization:

dSE/dt = (SE_current - SE_previous) / delta_t

A rising dSE/dt (>= 0.02 per unit time) indicates the signal is becoming more disordered — a precursor to instability.

AESF State Classification Rules (SR01-SR05)

Section titled “AESF State Classification Rules (SR01-SR05)”

Five state rules are evaluated in priority order. The highest-priority (lowest number) triggered rule determines the system stability state:

RulePriorityConditionStateSeverity
SR051SI <= 0.40Critical_Instabilityalarm
SR042SE >= 0.65 AND (TE >= 0.60 OR DE >= 0.60) AND SI > 0.40Chaoticwarning
SR033dSE/dt >= 0.02 AND 0.40 < SI < 0.60Destabilizingwarning
SR0240.35 < SE < 0.65 AND dSE/dt < 0.02 AND SI > 0.60Driftingwatch
SR015SE <= 0.35 AND TE < 0.50 AND SI >= 0.70Stablenormal

The five states form an ordered severity progression. Transition between states is governed by the entropy thresholds above, with implicit hysteresis: a machine must cross the threshold values to change state. The key boundaries are:

S0 (Stable): SI >= 0.70, SE <= 0.35
S1 (Drifting): 0.60 < SI, 0.35 < SE < 0.65
S2 (Destabilizing): 0.40 < SI < 0.60, dSE/dt >= 0.02
S3 (Chaotic): SI > 0.40, SE >= 0.65, (TE >= 0.60 OR DE >= 0.60)
S4 (Critical_Instability): SI <= 0.40

The transition from S0 to S4 represents progressive loss of energy organization within the machine. Each transition narrows the remaining useful life window and escalates the recommended intervention urgency.


26.5 Module F RUL Formulas — Remaining Useful Life

Section titled “26.5 Module F RUL Formulas — Remaining Useful Life”

Module F estimates Remaining Useful Life from the current condition state using three models, selected automatically based on degradation characteristics.

IF slope_change < 0.01 AND NLI < 0.3:
model = F001 (Linear)
ELIF slope_change >= 0.01:
model = F002 (Accelerating)
ELIF NLI >= 0.6:
model = F003 (High Instability)
ELSE:
model = F001 (Linear fallback)

Degradation grows at a steady exponential rate in the original domain (linear in log domain):

RUL = (ln(failure_threshold) - ln(current_value)) / slope_log

Worked example: current vibration = 5.0 mm/s, failure threshold = 8.0 mm/s, log-domain slope = 0.05 per day:

RUL = (ln(8.0) - ln(5.0)) / 0.05
= (2.0794 - 1.6094) / 0.05
= 0.4700 / 0.05
= 9.4 days

When the second derivative of the log trend is positive (slope_change >= 0.01), degradation is accelerating:

RUL = ln(failure_threshold / current_value) / (slope_log + slope_change)

The effective slope slope_log + slope_change is a first-order approximation that produces a conservative (shorter) RUL estimate — the safe direction for maintenance planning.

When the non-linearity index NLI >= 0.6, the degradation signal is highly erratic:

Base_RUL = F001 formula (linear estimate)
RUL = Base_RUL * (1 - NLI)

At NLI = 1.0, RUL = 0 (total instability implies imminent failure). The instability itself is treated as evidence that failure is closer than the trend line suggests.

Given the RUL estimate, the 30-day failure probability uses the exponential hazard model:

lambda = 1 / RUL_days
P_raw = 1 - exp(-lambda * 30)
P_adjusted = P_raw * confidence_C

When RUL <= 0, P_raw = 1.0 (certain failure). The confidence adjustment ensures that an uncertain diagnosis does not trigger the same urgency as a confident one.

RI = 100 * severity_S * criticality_K

Range: 0 to 100. Combines “how bad” (severity from Modules A/B/C) with “how important” (asset criticality factor) to produce a single prioritization score.

The confidence of the RUL estimate itself is derived from upstream confidence with penalties for model-data mismatch:

base = confidence_C
IF model == F001 AND NLI >= 0.2:
base *= (1 - NLI * 0.3)
IF model == F003:
base *= 0.8
IF abs(slope_log) < 1e-6:
base = min(base, 0.40)
RUL (days)Recommendation
<= 7Immediate
<= 307-day window
<= 9030-day window
> 90Planned (next scheduled outage)

26.6 Module G CDE Logic — Contradiction Detection Engine

Section titled “26.6 Module G CDE Logic — Contradiction Detection Engine”

The Contradiction Detection Engine (CDE) identifies engineering trade-offs where improving one parameter necessarily worsens another. These are not errors in the data; they are genuine physical constraints that require engineering judgment to resolve.

TypeNamePhysical Trade-Off
CT01Stiffness vs VibrationStiffening reduces resonance amplification but increases force transmission to bearings
CT02Load vs LifeIncreasing load improves throughput but accelerates wear and thermal degradation
CT03Alignment vs Thermal GrowthCold alignment targets differ from hot running alignment due to differential expansion
CT04Filtering vs SensitivityAggressive filtering reduces noise but suppresses early fault precursors
CT05Speed vs StabilityIncreasing speed improves throughput but may cross critical speed bands
CT06Tight Clearance vs SeizureTight bearing clearance improves stiffness but increases heat generation and seizure risk
CT07Rigidity vs IsolationRigid mounting improves accuracy but transmits vibration to adjacent equipment
CT08Cost vs RedundancyMinimizing cost reduces system redundancy and fault tolerance

Triggers gate rule evaluation. Contradiction rules are only evaluated when at least one trigger fires. Each trigger is a boolean predicate:

TR01: system_state in {warning, alarm} AND recurrence_count >= 2
TR02: SSI >= 0.70 AND days_in_state >= 14
TR03: top_contributor == "fluid_flow" AND process_correlation >= 0.70
TR04: top_contributor == "foundation" AND resonance_flag == TRUE
TR05: top_contributor == "gears" AND system_state == "alarm"
TR06: economic_impact_score >= 0.70

Each trigger carries a cooldown period (3-14 days) to prevent alert fatigue.

Each contradiction rule (CDE001-CDE006) has its own confidence function that evaluates the strength of converging evidence. For example, CDE002 (Load vs Life for gearboxes):

indicators = count_of(
gears_score >= 0.70,
motor_current_ratio >= 1.10,
temperature_c >= 75.0
)
IF indicators == 3: confidence = 0.85 (High)
IF indicators == 2: confidence = 0.75 (Medium-High)
IF indicators == 1: confidence = 0.60 (Medium)
IF indicators == 0: confidence = 0.40 (Low)

Each detected contradiction is linked to one or more resolution patterns (RP01-RP07):

PatternActionDomain
RP01Add dampingStructure
RP02Shift operating speedOperations
RP03Perform hot alignmentMaintenance
RP04Improve lubrication or coolingTribology
RP05Switch to adaptive filteringSignal processing
RP06Avoid specific speed bandOperations
RP07Decouple conflicting design objectivesDesign

The selection algorithm is straightforward: each contradiction rule hardcodes its applicable resolution patterns based on the physics of the trade-off. CDE001 (Stiffness vs Vibration) maps to RP01, RP02, RP07. CDE003 (Alignment vs Thermal Growth) maps to RP03, RP07. The mapping is static because the physical trade-off determines which resolution strategies are physically meaningful.

IF no triggers fired:
"Continue routine monitoring"
ELIF triggers fired but no contradiction rules matched:
"Investigate root cause and review system configuration"
ELIF max_severity >= 0.80:
"Immediate engineering review required"
ELIF max_severity >= 0.70:
"Schedule engineering review within 7 days"
ELSE:
"Include in next planned maintenance review"

The Imperfection Analysis Module goes beyond symptom detection to identify structural engineering weaknesses — design flaws, installation errors, and process interaction problems that cause repeated failures.

Imperfection rules are organized by equipment type and classified into five categories:

CategoryDescriptionTypical Rule Count
design_imperfectionGeometry, load, material limits~120
installation_imperfectionAlignment, baseplate, piping~70
operational_imperfectionSpeed, load, lubrication practice~50
process_interaction_imperfectionMachine-to-machine effects~30
maintenance_practice_imperfectionMaintenance-induced defects~30

Each imperfection rule has the same structure as a SENSE rule — a boolean expression evaluated against design data, sensor data, inspection data, and reliability data:

evaluation_logic: "overhang_length / shaft_diameter > 1.5"

The same recursive-descent parser used for diagnostic rules evaluates imperfection rules. The slash operator computes ratios from the input data, enabling engineering ratio checks like shaft overhang, bearing span, and load ratios.

Each imperfection rule carries a severity weight from 1 to 10:

severity_weight: 1-10 (integer)

Severity reflects the engineering impact:

SeverityMeaningExample
1-2Minor cosmetic or efficiency issueSlight surface roughness
3-4Moderate operational impactSuboptimal lubrication method
5-6Significant reliability impactCoupling mismatch
7-8Major reliability or safety concernExcessive shaft overhang, pipe strain
9-10Critical safety or catastrophic failure riskCavitation below NPSH required

The imperfection risk index combines severity with confidence:

risk_index = severity_weight * confidence_score

Range: 0 to 10. This single number prioritizes imperfections for engineering action. An imperfection with severity 9 and confidence 0.70 (risk_index = 6.3) ranks higher than one with severity 5 and confidence 0.90 (risk_index = 4.5).

The FRETTLSM taxonomy provides a structured framework for classifying imperfection root causes across eight categories:

CategoryAbbreviationScope
Forces, Flows, FoundationFDynamic loads, fluid forces, structural support
Reactions, Reactive EnvironmentRChemical attack, corrosion, oxidation
EnvironmentalEAmbient temperature, humidity, dust, contamination
TimeTFatigue cycles, creep, aging, cumulative damage
Temperature and EntropyTThermal gradients, heat generation, entropy production
Lubrication and WearLOil film quality, wear mechanisms, tribology
Surface TopologySSurface finish, contact patterns, fretting
Material, Men, MethodMMaterial selection, human error, process control

Each imperfection rule maps to one or more FRETTLSM categories. When multiple imperfections are detected on the same asset, the category distribution reveals the dominant failure envelope — whether the asset’s problems are primarily structural (F), tribological (L), environmental (E), or operational (M).

For an asset with N detected imperfections, the overall imperfection burden is:

overall_risk = SUM(risk_index_i) / N_max

where N_max is the total number of rules evaluated for that equipment type. This normalizes the score so that assets with more applicable rules are not penalized for having more opportunities for detection.


The mathematical power of the rule engine comes from how information flows across layers. Each layer transforms the representation:

Layer Input Output Transform
----- ----- ------ ---------
GUARD Raw sensor payload Validated sensor dict Boundary predicates
SENSE Validated sensors Per-rule (match, conf) Regex->parse->evaluate
FUSE Per-block scores SSI (0-1), state Profile-weighted mean
ACT SSI, confidence, RUL Strategy, task Decision tree traversal

Confidence is not a single number but a chain of attenuated scores:

C_rule = matched_terms / total_terms (SENSE layer)
C_diagnostic = min(C_rule + multi_sensor_bonus, 0.95) (SENSE layer)
C_module_c = 0.6 * SSI_quality + 0.4 * SEI (FUSE layer)
C_rul = C_diagnostic * model_penalty (Module F)
P_failure = P_raw * C_diagnostic (Module F)

At each stage, confidence can only decrease or stay constant — never increase beyond the 0.95 cap. This ensures that uncertainty accumulates honestly through the pipeline.

For a single diagnostic request, the mathematical operations are:

  1. GUARD: 16 boundary checks (O(1) each)
  2. Translation: Up to 451 natural-language rules translated via 180+ regex patterns (O(P * R) where P = patterns, R = rules for asset type)
  3. Parsing: Each translated expression parsed in O(n) tokens
  4. Confidence: Per-rule confidence + multi-sensor bonus
  5. Fusion: Profile-weighted aggregation of block scores
  6. Entropy: SE, TE, DE computation + SI + state rule evaluation
  7. RUL: Model selection + RUL formula + hazard probability
  8. CDE: 6 trigger evaluations + up to 6 contradiction rules
  9. ACT: Decision tree traversal to maintenance strategy

Total wall-clock time for a typical request (20-60 applicable rules): under 50 milliseconds on commodity hardware. The entire engine runs without external dependencies beyond the Python standard library.


Reference Implementation: Priority Score & State Transitions

Section titled “Reference Implementation: Priority Score & State Transitions”
"""RAPID AI — Priority Scoring & State Machine
Reference implementation for maintenance prioritization.
"""
def priority_score(severity: float, confidence: float,
criticality: float, utilization: float,
safety_multiplier: float = 1.0,
spare_risk: float = 1.0,
maintenance_penalty: float = 1.0) -> float:
"""Compute RAPID AI priority score.
P = 100 × (0.45·S + 0.25·C + 0.20·K + 0.10·U) × M_safe × R_sp × R_mp
Args:
severity: Effective severity [0-1]
confidence: Combined confidence [0-1]
criticality: Asset criticality [0-1]
utilization: Asset utilization [0-1]
safety_multiplier: Safety factor (1.0 = normal, 1.5 = safety-critical)
spare_risk: Spare parts risk multiplier
maintenance_penalty: Overdue maintenance penalty
"""
base = 0.45 * severity + 0.25 * confidence + 0.20 * criticality + 0.10 * utilization
return 100 * base * safety_multiplier * spare_risk * maintenance_penalty
# --- State Transition Machine ---
class HealthStateMachine:
"""Hysteresis-based state transition with persistence windows.
States: Normal → Watch → Alert → Alarm → Critical
Escalation requires 3 consecutive readings above threshold.
De-escalation requires 5 consecutive readings below threshold.
Hysteresis band: ±0.08 around thresholds.
"""
STATES = ["Normal", "Watch", "Alert", "Alarm", "Critical"]
THRESHOLDS = [0.20, 0.40, 0.60, 0.80]
HYSTERESIS = 0.08
ESCALATE_COUNT = 3
DEESCALATE_COUNT = 5
def __init__(self):
self.current_state = 0 # index into STATES
self.consecutive_up = 0
self.consecutive_down = 0
def update(self, ssi: float) -> str:
"""Process new SSI reading, return current state."""
target_state = 0
for i, thresh in enumerate(self.THRESHOLDS):
if ssi > thresh:
target_state = i + 1
if target_state > self.current_state:
# Check hysteresis for escalation
thresh = self.THRESHOLDS[self.current_state]
if ssi > thresh + self.HYSTERESIS:
self.consecutive_up += 1
self.consecutive_down = 0
if self.consecutive_up >= self.ESCALATE_COUNT:
self.current_state = min(target_state, self.current_state + 1)
self.consecutive_up = 0
elif target_state < self.current_state:
# Check hysteresis for de-escalation
thresh = self.THRESHOLDS[self.current_state - 1]
if ssi < thresh - self.HYSTERESIS:
self.consecutive_down += 1
self.consecutive_up = 0
if self.consecutive_down >= self.DEESCALATE_COUNT:
self.current_state = max(target_state, self.current_state - 1)
self.consecutive_down = 0
else:
self.consecutive_up = 0
self.consecutive_down = 0
return self.STATES[self.current_state]

The 451+ rules in RAPID AI are not a flat list of if-then statements. They form a layered mathematical pipeline where each layer applies a distinct class of mathematics:

LayerMathematicsKey Formula
GUARDBoundary predicatesx_min <= x <= x_max
SENSERegex translation + recursive descent parsingbase_confidence = matched / total
FUSEProfile-weighted aggregation + BSR scoringSSI = SUM(w_k * B_k)
SEDLShannon entropy + weighted compositeSI = 1 - (0.5SE + 0.3TE + 0.2*DE)
Module FLog-domain extrapolation + exponential hazardRUL = (ln(T) - ln(V)) / slope
Module GBoolean trigger gating + confidence convergenceconfidence = f(indicator_count)
ImperfectionRatio evaluation + severity weightingrisk_index = severity * confidence
ACTDecision tree traversalif/elif/else cascade

The system is designed for two audiences simultaneously: the domain expert who writes “BPFO rises with temperature” and the software engineer who needs a safe, testable, auditable evaluation pipeline. The mathematics bridges these worlds — translating 28 years of engineering intuition into computable logic without losing the physical meaning that makes the results actionable.


StandardRelevance to This Chapter
ISO 13374 — Condition monitoring and diagnostics of machinesThe four-layer rule architecture (GUARD, SENSE, FUSE, ACT) provides the mathematical implementation of ISO 13374’s processing chain, with each layer’s formulas documented for auditability and reproducibility.
ISO 17359 — General guidelines for condition monitoringThe natural-language-to-expression translation pipeline ensures that domain expert knowledge (expressed in ISO 17359-aligned diagnostic terms) is faithfully converted into computable logic without loss of engineering meaning.
ISO 10816-1/ISO 20816-1 — Mechanical vibration evaluationThe rule evaluation metrics (RMS, directional ratios, ISO zone classification) implement ISO 20816-1’s vibration severity assessment as mathematical inputs to the broader diagnostic rule system.
VersionDateAuthorChanges
2.1.02026-03-17Rick DAdded standards alignment, living doc metadata, changelog
2.0.02026-03-17Rick DEnriched with production codebase content
1.0.02026-03-17Rick DInitial chapter creation