Using Spaxiom for Real-Time Defect Detection and Statistical Process Control
Joe Scanlin
November 2025
Spaxiom is a sensor abstraction layer and runtime that translates billions of heterogeneous sensor streams into structured, semantic events. It provides a spatial-temporal DSL for defining zones, entities, and conditions, making it easy to build context-aware applications across industries.
INTENT (Intelligent Network for Temporal & Embodied Neuro-symbolic Tasks) is Spaxiom's high-level event vocabulary. Instead of overwhelming AI agents with raw sensor data, Spaxiom emits compact, meaningful events that agents can immediately understand and act upon.
Manufacturing defects cost industries $8 trillion annually worldwide, with 60–80% of quality issues traceable to process variation rather than equipment failure. Traditional quality control relies on end-of-line sampling inspection (checking 1–5% of units after production), discovering defects hours after the root cause occurred and requiring expensive scrap/rework of entire production batches. The challenge is that machine vision systems for defect detection operate on standalone inspection stations with proprietary software, programmable logic controllers (PLCs) managing process parameters (temperature, pressure, speed) use isolated industrial protocols like Modbus or EtherNet/IP, dimensional measurement tools (calipers, coordinate measuring machines) log to separate quality management databases, and environmental sensors tracking ambient conditions connect to building automation systems—leaving AI-powered statistical process control algorithms unable to correlate real-time process parameters with quality outcomes across fragmented manufacturing execution systems (MES).
Spaxiom fuses in-line machine vision inspection (surface defects, dimensional accuracy, assembly verification), process telemetry from PLCs (temperature profiles, pressure curves, cycle times, tool wear counters), material traceability data (lot numbers, supplier batches, material certifications), and environmental conditions (humidity, temperature affecting material properties) into one intelligent quality management platform. Instead of discovering defects during final inspection, it calculates a real-time "Process Capability Index" (Cpk) that detects statistical drift 30–120 minutes before defect rates escalate, predicting when process mean is shifting toward specification limits or when process variance is increasing due to tool wear, material variation, or environmental changes. This sends predictive quality alerts like "injection molding cell 3 cavity pressure variance increasing 40%—inspect mold for flash buildup before defect rate exceeds 2%" or "welding station 7 heat-affected zone dimensions trending toward lower spec limit—recalibrate power settings now," helping manufacturers transition from reactive inspection to proactive process control, reducing scrap rates by 40–60%, improving first-pass yield by 15–25%, and enabling real-time adaptive process adjustments that maintain six-sigma quality levels (3.4 defects per million opportunities) through continuous multi-parameter optimization.
Manufacturing quality defects impose massive costs: direct losses from scrap and rework, warranty claims, product recalls, and reputational damage. Studies estimate global manufacturing defect costs at $8 trillion annually, with automotive recalls alone exceeding $20 billion per year. Traditional quality approaches—end-of-line inspection sampling 1–5% of production—discover defects hours after causative process shifts occurred, requiring entire batch scrapping when systematic problems are identified. Root cause analysis is hindered by temporal gaps between process execution and inspection feedback.
Modern manufacturing generates extensive sensor data across production equipment, but integration across systems remains fragmented:
Legacy manufacturing systems operate in silos: machine vision stations use vendor-specific software (Cognex, Keyence) with limited integration, PLCs communicate via proprietary industrial protocols (Modbus, Profinet, EtherNet/IP) not easily accessible to analytics platforms, quality management systems (QMS) receive manually-entered inspection data with hours of lag. Spaxiom enables closed-loop statistical process control by fusing real-time process parameters with quality outcomes, detecting process drift before defects occur through multivariate correlation: rising mold temperature + increasing cycle time + material lot change = predict dimensional out-of-spec parts in next 50 units, trigger preventive adjustment rather than reactive scrap.
The manufacturing quality domain defines semantic events that abstract sensor data into actionable production control decisions:
ProcessDriftDetected: Statistical process control (SPC) violation identified when process mean shifts toward specification limits or process variance increases beyond control chart thresholds. Uses Western Electric Rules or Nelson Rules to distinguish true process shifts from random variation. Severity classified as {EARLY_WARNING, ACTION_REQUIRED, IMMEDIATE_STOP}.DefectRateEscalating: Real-time defect detection rate (from machine vision or in-line inspection) exceeding acceptable quality level (AQL), typically >2% for critical defects or >5% for minor defects. Includes defect classification (dimensional, cosmetic, assembly) and probable root cause inference (tool wear, material issue, process parameter drift).ToolWearThresholdApproaching: Cutting tool, mold cavity, or welding electrode approaching end of useful life based on usage counters, part quality trends (increasing dimensional variation), or direct wear measurement (acoustic emission analysis, force monitoring). Predictive event fires before tool failure causes defect spike.MaterialVariationDetected: Incoming material batch exhibits properties (viscosity, hardness, moisture content) outside expected range based on supplier certification or in-line testing. Triggers process parameter adjustment (temperature, pressure compensation) to maintain output quality despite feedstock variation.EnvironmentalImpact: Ambient conditions (temperature, humidity) deviating from optimal range for process, affecting material behavior (resin cure rate, paint drying time, metal expansion). Enables real-time process adaptation (adjust oven temperature to compensate for cold ambient air) or production pause (humidity too high for moisture-sensitive materials).TraceabilityAlert: Quality issue detected requiring lot identification for recall scope determination. Correlates defective units with material batch, production shift, equipment used to isolate contaminated population.These events enable automated line stops for critical defects, real-time process parameter adjustments (adaptive control), predictive maintenance scheduling, and material batch quarantine before use in production.
Manufacturing quality is quantified through process capability indices that compare process output variation to specification tolerances. The fundamental metric is Cpk (Process Capability Index):
where:
Cpk Interpretation:
Control Chart Limits: Statistical Process Control uses control charts to detect when process shifts from stable state:
where UCL/LCL are Upper/Lower Control Limits. Data points outside control limits indicate special cause variation (process shift, tool failure) requiring investigation. Points within control limits represent common cause variation (normal random fluctuation).
Western Electric Rules: Detect process drift before control limit breach:
Real-Time Capability Tracking: Spaxiom computes rolling Cpk over sliding time window (e.g., last 100 parts) to detect degradation trends:
Negative velocity (declining Cpk) indicates process degradation requiring intervention before capability becomes unacceptable.
The ProductionLine class demonstrates multi-sensor fusion for real-time statistical process control:
from spaxiom import Sensor, Intent, Fusion, Metric
import math
import statistics
from collections import deque
class ProductionLine:
def __init__(self, line_id, process_name, usl, lsl, target):
self.line_id = line_id
self.process_name = process_name
self.usl = usl # Upper specification limit
self.lsl = lsl # Lower specification limit
self.target = target # Target value (nominal)
# Sensor streams
self.vision_system = Sensor("machine_vision_defect_detection")
self.plc_controller = Sensor("plc_process_parameters")
self.cmm_metrology = Sensor("coordinate_measuring_machine")
self.material_tracker = Sensor("rfid_material_tracking")
self.environmental = Sensor("ambient_conditions")
self.vibration_monitor = Sensor("tool_vibration_analysis")
# INTENT events
self.process_drift = Intent("ProcessDriftDetected")
self.defect_escalation = Intent("DefectRateEscalating")
self.tool_wear = Intent("ToolWearThresholdApproaching")
self.material_variation = Intent("MaterialVariationDetected")
# Fusion metrics
self.cpk = Metric("process_capability_index", range=(0, 3))
self.cpk_velocity = Metric("cpk_trend", unit="per_100_parts")
self.defect_rate = Metric("defect_rate_ppm", unit="ppm")
# Statistical tracking (rolling window)
self.measurement_history = deque(maxlen=100) # Last 100 parts
self.defect_count_window = deque(maxlen=100)
self.cpk_history = deque(maxlen=50)
# Process baselines
self.baseline_mean = target
self.baseline_std = (usl - lsl) / 12 # Assume 6-sigma spread initially
self.tool_cycle_count = 0
self.tool_life_limit = 5000 # cycles before replacement
def _calculate_cpk(self, data):
"""Compute process capability index from measurement data"""
if len(data) < 30: # Need sufficient data
return None
mean = statistics.mean(data)
std = statistics.stdev(data)
if std == 0: # Prevent division by zero
return 3.0 # Perfect capability if no variation
# Cpu: distance to upper spec limit
cpu = (self.usl - mean) / (3 * std)
# Cpl: distance to lower spec limit
cpl = (mean - self.lsl) / (3 * std)
# Cpk is minimum (worst case)
cpk = min(cpu, cpl)
return cpk
def _check_western_electric_rules(self, data):
"""Detect process shifts using Western Electric control chart rules"""
if len(data) < 8:
return None
mean = statistics.mean(data)
std = statistics.stdev(data)
# Calculate zones (1σ, 2σ, 3σ from mean)
recent = list(data)[-8:]
# Rule 4: Eight consecutive points on one side of mean
above_mean = sum(1 for x in recent if x > mean)
if above_mean == 8 or above_mean == 0:
return "RULE_4_PROCESS_SHIFT"
# Rule 3: Four of five consecutive points beyond 1σ
if len(recent) >= 5:
last_five = recent[-5:]
beyond_1sigma = sum(1 for x in last_five if abs(x - mean) > std)
if beyond_1sigma >= 4:
return "RULE_3_TRENDING"
# Rule 2: Two of three consecutive points beyond 2σ
if len(recent) >= 3:
last_three = recent[-3:]
beyond_2sigma = sum(1 for x in last_three if abs(x - mean) > 2 * std)
if beyond_2sigma >= 2:
return "RULE_2_DRIFT_WARNING"
# Rule 1: One point beyond 3σ (control limit)
if abs(recent[-1] - mean) > 3 * std:
return "RULE_1_OUT_OF_CONTROL"
return None
@Fusion.rule
def analyze_process_capability(self):
"""Compute Cpk and detect process drift"""
if len(self.measurement_history) < 30:
return None
# Calculate current Cpk
cpk_value = self._calculate_cpk(self.measurement_history)
self.cpk.update(cpk_value)
self.cpk_history.append(cpk_value)
# Calculate Cpk velocity (trend)
if len(self.cpk_history) >= 10:
recent_cpk = list(self.cpk_history)[-10:]
cpk_delta = recent_cpk[-1] - recent_cpk[0]
velocity = cpk_delta / 10 # Change per 10 measurements
self.cpk_velocity.update(velocity)
else:
velocity = 0
# Alert on declining capability
if cpk_value < 1.0:
severity = "IMMEDIATE_STOP"
elif cpk_value < 1.33:
severity = "ACTION_REQUIRED"
elif cpk_value < 1.67 or velocity < -0.01:
severity = "EARLY_WARNING"
else:
severity = None
if severity:
self.process_drift.emit(
line_id=self.line_id,
process=self.process_name,
cpk=cpk_value,
cpk_velocity=velocity,
severity=severity,
mean=statistics.mean(self.measurement_history),
std=statistics.stdev(self.measurement_history),
action="STOP_LINE" if severity == "IMMEDIATE_STOP" else "INVESTIGATE_ADJUST_PROCESS"
)
# Check Western Electric rules for early drift detection
rule_violation = self._check_western_electric_rules(self.measurement_history)
if rule_violation:
Intent.emit("ControlChartViolation",
line_id=self.line_id,
rule=rule_violation,
action="INVESTIGATE_SPECIAL_CAUSE")
return cpk_value
@Fusion.rule
def monitor_defect_rate(self):
"""Track real-time defect rate and escalation"""
if len(self.defect_count_window) < 20:
return None
# Calculate defects per million opportunities (DPMO)
defect_count = sum(self.defect_count_window)
total_parts = len(self.defect_count_window)
defect_rate_ppm = (defect_count / total_parts) * 1_000_000
self.defect_rate.update(defect_rate_ppm)
# Alert thresholds
if defect_rate_ppm > 20000: # >2% defect rate
severity = "CRITICAL"
elif defect_rate_ppm > 5000: # >0.5% defect rate
severity = "ELEVATED"
else:
severity = None
if severity:
self.defect_escalation.emit(
line_id=self.line_id,
defect_rate_ppm=defect_rate_ppm,
severity=severity,
recent_defects=defect_count,
action="STOP_LINE_INVESTIGATE_ROOT_CAUSE" if severity == "CRITICAL" else "INCREASE_INSPECTION_FREQUENCY"
)
return defect_rate_ppm
@Sensor.on_data("coordinate_measuring_machine")
def track_dimensional_accuracy(self, part_id, measurement, feature):
"""Record critical dimension measurements for SPC"""
self.measurement_history.append(measurement)
# Check individual part against spec limits
if measurement < self.lsl or measurement > self.usl:
Intent.emit("OutOfSpecPart",
line_id=self.line_id,
part_id=part_id,
feature=feature,
measurement=measurement,
spec_limits=(self.lsl, self.usl),
action="QUARANTINE_PART_INVESTIGATE_CAUSE")
self.analyze_process_capability()
@Sensor.on_data("machine_vision_defect_detection")
def inspect_visual_defects(self, part_id, defect_detected, defect_type, confidence):
"""Real-time vision inspection results"""
# Track defect occurrence (binary: 1 = defect, 0 = pass)
self.defect_count_window.append(1 if defect_detected else 0)
if defect_detected and confidence > 0.8:
Intent.emit("VisualDefectDetected",
line_id=self.line_id,
part_id=part_id,
defect_type=defect_type,
confidence=confidence,
action="REJECT_PART_LOG_FOR_ANALYSIS")
self.monitor_defect_rate()
@Sensor.on_data("plc_process_parameters")
def monitor_process_conditions(self, temperature, pressure, cycle_time):
"""Track process parameter stability"""
# Increment tool usage counter
self.tool_cycle_count += 1
# Check for parameter drift (simplified)
# In production: maintain control charts for each parameter
baseline_temp = 250 # °C for example injection molding
temp_deviation = abs(temperature - baseline_temp)
if temp_deviation > 10: # >10°C deviation
Intent.emit("ProcessParameterDrift",
line_id=self.line_id,
parameter="temperature",
value=temperature,
baseline=baseline_temp,
action="RECALIBRATE_HEATER")
# Tool wear prediction
if self.tool_cycle_count > self.tool_life_limit * 0.85:
remaining_cycles = self.tool_life_limit - self.tool_cycle_count
self.tool_wear.emit(
line_id=self.line_id,
tool_cycle_count=self.tool_cycle_count,
tool_life_limit=self.tool_life_limit,
remaining_cycles=remaining_cycles,
action=f"SCHEDULE_TOOL_REPLACEMENT_WITHIN_{remaining_cycles}_CYCLES"
)
@Sensor.on_data("rfid_material_tracking")
def track_material_batch(self, material_lot, supplier, cert_properties):
"""Monitor material traceability and property variation"""
# Check if material properties match certification
expected_viscosity = cert_properties.get("viscosity_expected", 1000)
actual_viscosity = cert_properties.get("viscosity_actual", 1000)
deviation_pct = abs(actual_viscosity - expected_viscosity) / expected_viscosity
if deviation_pct > 0.1: # >10% viscosity deviation
self.material_variation.emit(
line_id=self.line_id,
material_lot=material_lot,
supplier=supplier,
property="viscosity",
deviation_pct=deviation_pct,
action="ADJUST_PROCESS_TEMP_TO_COMPENSATE"
)
@Sensor.on_data("ambient_conditions")
def monitor_environmental_impact(self, ambient_temp_c, humidity_pct):
"""Detect environmental conditions affecting process"""
# Temperature affects material properties and dimensional stability
if ambient_temp_c < 18 or ambient_temp_c > 28:
Intent.emit("EnvironmentalImpact",
line_id=self.line_id,
condition="temperature",
value=ambient_temp_c,
optimal_range=(20, 25),
action="ADJUST_PROCESS_COMPENSATION_OR_PAUSE_PRODUCTION")
# Humidity affects adhesives, coatings, hygroscopic materials
if humidity_pct > 70:
Intent.emit("EnvironmentalImpact",
line_id=self.line_id,
condition="humidity",
value=humidity_pct,
action="PAUSE_MOISTURE_SENSITIVE_OPERATIONS")
# Example instantiation for injection molding line
molding_line = ProductionLine(
line_id="INJECTION_MOLD_LINE_3",
process_name="Part_Diameter_mm",
usl=50.15, # Upper spec limit
lsl=49.85, # Lower spec limit
target=50.0 # Nominal dimension
)
Figure A.12 presents a comprehensive 8-hour production monitoring scenario demonstrating early process drift detection in an injection molding operation. The visualization integrates four critical quality control dimensions: dimensional measurement trending with statistical control limits, Process Capability Index (Cpk) evolution tracking manufacturing capability degradation, defect rate escalation from machine vision inspection, and root cause correlation timeline. The annotated sequence shows how Western Electric Rule violations detected at Hour 4.5 trigger process investigation 2 hours before defect rate exceeds 2%, enabling corrective mold cleaning that prevents 1,200 scrap parts and $18,000 material loss compared to reactive end-of-shift inspection discovery.
Figure A.12: Integrated statistical process control (SPC) system detecting process drift in injection molding line (8-hour production shift, 50mm diameter plastic parts). Panel 1: X-bar control chart tracking part diameter measurements. Specification limits: USL = 50.15mm, LSL = 49.85mm, target = 50.0mm (±0.15mm tolerance). Control limits set at ±3σ (UCL/LCL). Initial baseline: process centered at 50.0mm with σ = 0.05mm. Gradual upward trend visible starting Hour 2: measurements drift from 50.0mm toward 50.1mm. Western Electric Rule 3 violation detected at Hour 4.5: four of five consecutive measurements beyond +1σ from mean, indicating special cause variation (non-random process shift). Traditional threshold alarms would not trigger until measurement exceeds UCL (50.15mm), which would occur Hour 6.5. Spaxiom fires ProcessDriftDetected alert 2 hours earlier based on trending pattern. Corrective action at Hour 5.5 (mold cleaning) restores process to centerline. Panel 2: Process Capability Index (Cpk) computed over rolling 100-part window. Baseline Cpk = 1.82 (five-sigma quality, excellent capability). Cpk degrades to 1.38 at Hour 4.5 as process mean shifts and variance increases slightly. Cpk velocity = -0.012 per hour indicates declining capability trend. Alert threshold Cpk <1.67 triggers ProcessDriftDetected with severity "EARLY_WARNING". Post-correction, Cpk recovers to 1.78. Traditional end-of-line sampling (measuring 1 in 20 parts with 2-hour lag) would detect degradation Hour 6.5, by which time Cpk <1.33 (marginal capability). Panel 3: Real-time defect rate from machine vision inspection system checking 100% of parts for flash (excess material at parting line). Defect rate escalates from baseline 400 ppm (0.04%, excellent) to peak 18,000 ppm (1.8%) at Hour 5 before corrective action. Dashed red line shows counterfactual: without early SPC intervention, defect rate would exceed 20,000 ppm (2%, critical threshold) by Hour 6. Proactive mold cleaning at Hour 5.5 arrests escalation, defect rate returns to <1,000 ppm by Hour 7. Panel 4: Root cause investigation timeline. Process drift alert Hour 4.5 → immediate mold inspection (technician deploys borescope) → flash buildup discovered on cavity wall (material degradation residue from previous high-temperature run, gradually accumulating and distorting part dimensions) → mold extracted and cleaned Hour 5.5 (30-minute downtime) → process restored. Cost-benefit: Early intervention prevented 1,200 scrap parts (3 hours remaining in shift × 400 parts/hour production rate) valued at $18,000 ($15 material cost per part). Traditional end-of-shift inspection would discover problem during final quality audit, requiring entire 8-hour batch quarantine and inspection (3,200 parts), with estimated 30% scrap rate = $14,400 additional loss. System ROI: $32,400 loss avoidance per occurrence.
Manufacturing facilities using Spaxiom-based real-time SPC have demonstrated:
The Cpk-based Process Capability Index provides a standardized, universally-recognized quality metric that quantifies manufacturing process performance relative to engineering specifications. By exposing actionable events like ProcessDriftDetected (SPC rule violations with severity and velocity analysis), DefectRateEscalating (real-time vision inspection trends), ToolWearThresholdApproaching (predictive maintenance for quality-critical tooling), and MaterialVariationDetected (feedstock property deviations requiring process compensation), Spaxiom enables closed-loop quality control where production parameters dynamically adapt to maintain output within specification despite disturbances. Integration with MES (Manufacturing Execution Systems) and ERP (Enterprise Resource Planning) platforms enables automated material traceability: when quality issues are detected, system instantly identifies affected lot numbers, production timestamps, and equipment used for precise recall scope determination and root cause analysis. Critical innovation: machine learning models trained on historical process-quality correlations enable predictive capability forecasting—system learns that "temperature +5°C + humidity >65% + material lot supplier_B" combination predicts dimensional drift 90 minutes ahead, triggering preemptive process adjustments before first defect occurs. This transforms quality from post-production inspection (detect and sort) to in-process control (predict and prevent), fundamentally shifting manufacturing paradigm from reactive firefighting to proactive optimization achieving six-sigma performance (99.99966% yield) through continuous multi-parameter adaptive control.