Chapters

7 Edge Data: Semantic Compression and Pipelines

analytics-ml
edge
acq
sampling

7.1 Start With the Situation

Reducing every sample by the same rule still sends data the application may not need. The team must define meaningful events, measure what semantic compression removes, and prove that the resulting edge pipeline preserves decisions.

7.2 Overview

This route moves from event extraction into algorithm selection, factory validation, and complete edge pipelines.

This is part 2 of 2. Review Edge Data: Sampling and Statistical Compression when you need the first route.

7.3 Learning Objectives

By the end of this chapter, you will be able to:

  • design semantic event extraction
  • select compression from evidence needs
  • validate a multi-sensor edge pipeline

7.4 Chapter Roadmap

Follow the original sections below in order. They begin at the reviewed split boundary and keep every worked example, figure, check, and supporting banner with the section that owns it.

Highest compression, but requires domain knowledge:

from dataclasses import dataclass
from enum import Enum
from typing import Optional

class EventType(Enum):
    THRESHOLD_EXCEEDED = "threshold_exceeded"
    ANOMALY_DETECTED = "anomaly_detected"
    STATE_CHANGE = "state_change"
    PERIODIC_SUMMARY = "periodic_summary"

@dataclass
class SemanticEvent:
    timestamp: int
    device_id: str
    event_type: EventType
    value: float
    context: dict  # Additional info (threshold, previous state, etc.)

class SemanticCompressor:
    def __init__(self, device_id: str, threshold_high: float,
                 threshold_low: float, anomaly_std_factor: float = 3.0):
        self.device_id = device_id
        self.threshold_high = threshold_high
        self.threshold_low = threshold_low
        self.anomaly_std_factor = anomaly_std_factor
        self.history: list[float] = []
        self.last_state: Optional[str] = None
        self.summary_count = 0
        self.summary_sum = 0.0

    def process_sample(self, timestamp: int, value: float) -> list[SemanticEvent]:
        """
        Process a sample and return events (if any).
        Most samples produce NO events - that's the compression.
        """
        events = []

        # Update history for anomaly detection
        self.history.append(value)
        if len(self.history) > 100:
            self.history.pop(0)

        # Track for periodic summary
        self.summary_count += 1
        self.summary_sum += value

        # Check threshold crossing
        current_state = "normal"
        if value > self.threshold_high:
            current_state = "high"
        elif value < self.threshold_low:
            current_state = "low"

        if current_state != self.last_state and self.last_state is not None:
            events.append(SemanticEvent(
                timestamp=timestamp,
                device_id=self.device_id,
                event_type=EventType.STATE_CHANGE,
                value=value,
                context={
                    "previous_state": self.last_state,
                    "new_state": current_state
                }
            ))
        self.last_state = current_state

        # Check for statistical anomaly
        if len(self.history) >= 20:
            mean = sum(self.history) / len(self.history)
            std = (sum((x - mean)**2 for x in self.history) / len(self.history)) ** 0.5
            if std > 0 and abs(value - mean) > self.anomaly_std_factor * std:
                events.append(SemanticEvent(
                    timestamp=timestamp,
                    device_id=self.device_id,
                    event_type=EventType.ANOMALY_DETECTED,
                    value=value,
                    context={
                        "mean": mean,
                        "std": std,
                        "z_score": (value - mean) / std
                    }
                ))

        return events

    def get_periodic_summary(self, timestamp: int) -> SemanticEvent:
        """Call every N minutes to send a heartbeat/summary."""
        avg = self.summary_sum / self.summary_count if self.summary_count > 0 else 0
        event = SemanticEvent(
            timestamp=timestamp,
            device_id=self.device_id,
            event_type=EventType.PERIODIC_SUMMARY,
            value=avg,
            context={
                "sample_count": self.summary_count,
                "period_seconds": 300  # 5 minutes
            }
        )
        self.summary_count = 0
        self.summary_sum = 0.0
        return event

# Example: Temperature sensor, 1 sample/second
# Normal operation: 0 events per sample
# State change: 1 event (~100 bytes)
# 5-minute summary: 1 event (~80 bytes)
#
# Input: 300 samples x 8 bytes = 2400 bytes per 5 minutes
# Output: 1 summary + maybe 0-2 events = 80-280 bytes
# Compression ratio: 10:1 to 30:1 (varies by activity)
Event Compression Simulator

Configure thresholds and signal behavior to see how semantic compression extracts only meaningful events from a continuous sensor stream. Most samples produce zero events — that is the compression.

When to use: Monitoring systems where “nothing happening” is the common case. Alarm systems, threshold monitoring, sparse event streams.

7.5 Algorithm Selection Decision Tree

The decision tree in Figure 7.1 turns the preceding methods into a selection sequence, beginning with what the signal and downstream decision are allowed to lose.

Choose lossless, semantic, window or FFT compression from signal type and fidelity needs, then check memory, latency and energy. Revisit a poor fit and validate the retained evidence.
Figure 7.1: Edge Data Compression Algorithm Selection Decision Tree

Read Figure 7.1 from signal type to fidelity requirement and only then to compute limits. Event-like data can often become sparse semantic records; smooth numeric streams may support delta or window summaries; spectral decisions may justify selected frequency features; audit-grade reconstruction keeps the route lossless. The final resource branch checks whether memory, latency, and energy fit the edge device. This connects the tree to the chapter’s running narrative: compression is an evidence contract chosen from the downstream claim, then tested against device constraints and reconstruction needs.

7.6 Benchmark Results: ESP32 Edge Device

Real measurements on ESP32-WROOM-32 (240 MHz, 520KB RAM):

7.7 Raw JSON

  • 1000 samples: -
  • Compress time: 15 ms (serialize)
  • Output size: 28,000 bytes
  • Power: 2.4 mJ

7.8 GZIP-6

  • 1000 samples: 28,000 bytes
  • Compress time: 85 ms
  • Output size: 8,200 bytes
  • Power: 8.5 mJ

7.9 Window aggregation

  • 1000 samples: 8 bytes/sample
  • Compress time: 2 ms
  • Output size: 48 bytes
  • Power: 0.4 mJ

7.10 FFT Top-10

  • 1000 samples: 4 bytes/sample
  • Compress time: 45 ms
  • Output size: 140 bytes
  • Power: 5.0 mJ

7.11 Semantic

  • 1000 samples: 8 bytes/sample
  • Compress time: 3 ms
  • Output size: 0-100 bytes
  • Power: 0.5 mJ

Key insight: For battery-powered edge devices, window aggregation offers the best power efficiency. FFT is valuable when frequency content matters, but the CPU cost is significant. Semantic compression is ideal for sparse event streams.

7.12 Memory Constraints on Edge Devices

Compression algorithms have memory overhead. Consider carefully on constrained devices:

AlgorithmRAM RequiredNotes
GZIP32-64 kBSliding window + Huffman tables
Window Agg<1 kBJust buffer for current window
FFT (1024 pt)16 kBComplex float buffer + twiddle factors
FFT (4096 pt)64 kBMay not fit on small MCUs
Semantic2-4 kBHistory buffer + state

ESP32 recommendation: Use window aggregation or semantic compression as primary strategy. Reserve FFT for specific signals where frequency analysis is required.

7.13 Common Compression Pitfalls

Over-Aggressive Lossy Compression

The Mistake: Applying high compression ratios uniformly across all sensor data without understanding which information is critical for downstream analytics, permanently destroying signals needed for root cause analysis.

Why It Happens: Bandwidth costs drive aggressive compression targets. Teams optimize for average case without considering anomaly detection requirements. Compression algorithms are chosen based on benchmark performance rather than domain-specific information preservation. The “we can always collect more data later” assumption fails for non-reproducible events.

The Fix: Profile your analytics requirements before choosing compression. For predictive maintenance, preserve frequency-domain information (use FFT compression, not just statistics). For threshold alerting, min/max preservation is critical. For trend analysis, mean and standard deviation suffice. Implement tiered compression: full resolution for anomalies detected locally, heavy compression for steady-state readings. Always retain enough information to answer “why did this alert trigger?” after the fact.

Pitfall: Compression Without Metadata

The Mistake: Compressing sensor data without preserving the metadata needed to decompress or interpret it correctly, creating files that cannot be decoded weeks or months later.

Why It Happens: Metadata seems redundant during development when context is fresh. Schema documentation is maintained separately and drifts over time. Edge device memory constraints pressure developers to strip every unnecessary byte. Compression parameters are hardcoded rather than embedded in output.

The Fix: Always include compression metadata in the payload or use self-describing formats. For FFT compression, include sample rate, window size, and which frequency bins are transmitted. For statistical aggregation, include sample count, window duration, and timestamp precision. Use envelope formats that version the compression scheme: {"compression": "fft-v2", "params": {...}, "data": [...]}. Maintain a compression schema registry that maps version identifiers to decompression algorithms.

Compression Compute Cost

The Mistake: Selecting compression algorithms based purely on compression ratio without accounting for CPU time and energy cost on battery-powered edge devices, resulting in net-negative energy savings.

Why It Happens: Compression benchmarks on desktop hardware show impressive ratios with negligible CPU time. The 1000x difference in computational efficiency between an ESP32 and a laptop is underestimated. Energy cost of computation versus transmission varies by network type (Wi-Fi is cheap to transmit, LoRa is expensive). Algorithm selection copied from cloud/server contexts.

The Fix: Measure end-to-end energy consumption: E_total = E_compute + E_transmit. For LoRaWAN devices where transmission costs 100+ mJ per packet, aggressive compression (even expensive algorithms) saves energy. For Wi-Fi devices where transmission costs 1-5 mJ per packet, simple aggregation beats complex compression. Profile specific algorithms on your target MCU: GZIP on ESP32 consumes 8.5 mJ for 1000 samples versus 0.4 mJ for window aggregation. Choose the algorithm that minimizes total energy, not just bytes transmitted.

Data DoraCheckpoint: Match Compression to Evidence

You now know:

  • Lossless compression preserves audit data, statistical aggregation preserves trends, FFT preserves frequency peaks, and semantic extraction preserves meaningful events.
  • ESP32 limits matter: the benchmark section compares 520 kB RAM, GZIP state, FFT buffers, CPU time, and power rather than bytes alone.
  • Compression metadata is part of the evidence path because a compact payload that cannot be decoded later is not trustworthy telemetry.

7.14 Industrial Edge Pipeline Check

Factory Vibration Monitoring

Your manufacturing plant monitors 50 critical machines using vibration sensors to detect bearing failures before catastrophic breakdown. Each sensor must detect frequencies up to 200 Hz (bearing defects manifest at 50-200 Hz harmonics).

System constraints:

  • Sensor: MEMS accelerometer (+/-16g range)
  • Edge compute: ESP32 gateway with 4MB flash, 520KB RAM
  • Network: 4G cellular with 10 GB/month data cap ($0.10/GB overage)
  • Requirement: Detect anomalies within 1 minute, minimize bandwidth costs

Current naive approach:

  • Sample at 500 Hz (meets Nyquist: 2 x 200 Hz)
  • Stream raw data to cloud continuously
  • Result: 500 samples/sec x 2 bytes x 50 sensors = 50 kB/s = 129 GB/month ($11.90 overage!)

7.15 Data Reduction Tradeoffs

Which edge processing strategy best balances anomaly detection accuracy, bandwidth costs, and latency?

7.16 A. Raw streaming

  • Data transmitted: 5000 samples/10s
  • Bandwidth cost: 129 GB/month ($11.90)
  • Detection latency: Real-time (<1s)
  • Information loss: None (full fidelity)

7.17 B. Downsample to 100 Hz

  • Data transmitted: 5000 samples/10s
  • Bandwidth cost: 129 GB/month ($11.90)
  • Detection latency: Real-time (<1s)
  • Information loss: None (full fidelity)

7.18 C. Time-domain stats

  • Data transmitted: 1000 samples/10s
  • Bandwidth cost: 26 GB/month ($1.60)
  • Detection latency: Real-time (<1s)
  • Information loss: Loses 200+ Hz information (aliasing risk)

7.19 D. FFT + compression

  • Data transmitted: 10 FFT bins/10s
  • Bandwidth cost: 0.26 GB/month ($0)
  • Detection latency: 10 seconds
  • Information loss: Preserves the 50-200 Hz frequency information that matters here

7.20 Edge FFT Cuts Bandwidth

Option D (FFT + compression) achieves 500x bandwidth reduction while preserving anomaly detection capability:

How it works:

# Edge processing pipeline (runs on ESP32 every 10 seconds)
def vibration_pipeline():
    # 1. Collect 10 seconds of data
    samples = collect_samples(rate=500, duration=10)  # 5000 samples

    # 2. Apply FFT (frequency-domain analysis)
    fft_result = numpy.fft.rfft(samples)  # -> 2500 frequency bins

    # 3. Extract critical frequency bins
    #    Bin width = 500 Hz / 5000 samples = 0.1 Hz per bin
    #    Bin index = frequency / bin_width
    bin_width = 500.0 / 5000  # 0.1 Hz per bin
    target_freqs = [50, 80, 110, 140, 170, 200]  # Hz
    bins = [fft_result[int(f / bin_width)] for f in target_freqs]
    # bins at indices [500, 800, 1100, 1400, 1700, 2000]
    # + 4 more bins for comprehensive coverage

    # 4. Transmit 10 values instead of 5000
    transmit_to_cloud(bins)  # 20 bytes vs 10,000 bytes

    return bins

# Data reduction: 5000 samples -> 10 FFT bins = 500x compression
Try It: Edge FFT Pipeline Data Reduction

Adjust the vibration sensor parameters and FFT settings to see how edge FFT compression reduces bandwidth for factory monitoring.

Why this works for anomaly detection:

Read the result as a chain of four checks. Start with the signal representation: in this example, the bearing-fault evidence appears as spectral peaks at harmonics, including 80 Hz and 160 Hz for the stated 2400 RPM machine, rather than as a need to retain every raw time sample. Next, check model fit: the cloud model is trained on the transmitted FFT bins, and the stated comparison is 94% accuracy from those bins against 96% from raw samples. Then check timing: the 10-second aggregation window plus 2-second transmission produces 12 seconds of latency, inside the example’s one-minute requirement. Finally, check the operating budget: 0.26 GB per month remains under the stated data cap, whereas raw streaming incurs the example’s $11.90 overage. Together, those checks justify the reduction for this workload; they do not establish that FFT bins are lossless for a different anomaly model or signal.

The factory example turns the algorithm comparison into an operating choice: keep the frequency evidence, discard the raw waveform volume, and check latency against the maintenance requirement.

Data DoraCheckpoint: Factory Vibration Choice

You now know:

  • The naive 50-sensor approach streams 500 Hz raw data into 129 GB/month, exceeding the 10 GB/month cap.
  • Downsampling and time-domain statistics save bandwidth but remove the 50-200 Hz fault evidence the bearing model needs.
  • FFT plus compression sends 10 bins every 10 seconds, cuts bandwidth by 500x, and keeps total latency under the 1-minute requirement.

Scenario: A manufacturing facility wants to detect bearing faults in motors running at 1800 RPM. Bearing defects produce vibration frequencies at harmonics of the motor speed. You need to determine the minimum sampling rate to capture fault signatures.

Given:

  • Motor speed: 1800 RPM = 30 Hz (revolutions per second)
  • Bearing fault frequencies:
    • 1x: 30 Hz (fundamental, imbalance)
    • 2x: 60 Hz (misalignment)
    • 3x: 90 Hz (looseness)
    • 5x: 150 Hz (bearing outer race defect)
    • 7x: 210 Hz (bearing inner race defect)
  • Highest frequency of interest: 210 Hz (7th harmonic)

Question: What is the minimum sampling rate required, and what sampling rate should you actually use in practice?

Solution:

Step 1: Apply Nyquist theorem

Minimum sampling rate = 2 × highest frequency

f_sample_min = 2 × 210 Hz = 420 Hz

Step 2: Calculate practical sampling rate with safety margin

Industry practice: Use 2.5x to 3x Nyquist for anti-aliasing filter roll-off

f_sample_recommended = 2.5 × 420 Hz = 1,050 Hz
f_sample_practical = 3 × 420 Hz = 1,260 Hz

Round up to convenient power-of-2 or decade value: 1,280 Hz or 1,000 Hz

Step 3: Verify no aliasing occurs

Check if any harmonic would alias into the measurement band:

  • At 1,000 Hz sampling, Nyquist frequency = 500 Hz
  • All fault frequencies (30-210 Hz) are below 500 Hz ✓
  • No aliasing! All harmonics are correctly captured.

Step 4: Calculate data volume

Single sensor:

  • Sample rate: 1,000 Hz
  • Data size: 2 bytes per sample (16-bit ADC)
  • Data rate: 1,000 × 2 = 2,000 bytes/sec = 2 kB/sec
  • Daily data: 2 kB/sec × 86,400 sec = 172.8 MB/day

For 100 motors:

  • Daily data: 100 × 172.8 MB = 17.28 GB/day
  • Monthly data: 17.28 × 30 = 518.4 GB/month

Step 5: Apply edge FFT compression

Rather than stream raw waveforms to cloud:

# Edge processing every 10 seconds
samples_per_window = 1000 Hz × 10 sec = 10,000 samples

# Perform FFT
fft_result = fft(samples)  # 5,000 frequency bins (real FFT)

# Extract only the bins of interest (fault frequencies)
fault_bins = [30, 60, 90, 150, 210]  # Hz
bin_width = 1000 Hz / 10000 samples = 0.1 Hz per bin
selected_bins = [int(f / bin_width) for f in fault_bins]
# Result: bins [300, 600, 900, 1500, 2100]

# Transmit only these 5 bins (10 bytes) instead of 20,000 bytes
compressed_data = [fft_result[b] for b in selected_bins]
compression_ratio = 20,000 / 10 = 2,000x

Step 6: Calculate bandwidth savings

Without compression:

  • 100 motors × 17.28 GB/day = 1.728 TB/day

With edge FFT compression (2,000x):

  • 1.728 TB / 2,000 = 864 MB/day

Cost savings:

  • Cloud ingress: $0.09/GB
  • Uncompressed: 1,728 GB × $0.09 = $155/day = $56,575/year
  • Compressed: 0.864 GB × $0.09 = $0.08/day = $29/year
  • Savings: $56,546/year

Key Insight: For vibration analysis, sample at 2.5-3x Nyquist (not just 2x minimum) to allow for anti-aliasing filter roll-off. Then apply edge FFT compression by transmitting only the frequency bins of interest (harmonics), achieving 1,000-10,000x data reduction while preserving all fault detection capability. The edge gateway does the heavy computation; the cloud receives only the diagnostic features.

Choose the appropriate compression strategy based on signal characteristics, edge compute capabilities, and analytical requirements:

Signal TypeRecommended CompressionTypical RatioEdge CPUBandwidthInformation LossBest For
Slowly changing continuous (temperature, humidity)Statistical aggregation (min/max/mean/std)100-1000xVery Low (1% CPU)99%+ reductionLoses individual samples, keeps trendsEnvironmental monitoring, agriculture
Periodic vibration (motors, pumps)FFT + top-N frequency bins100-5000xHigh (50% CPU)99%+ reductionLoses waveform, keeps frequency spectrumPredictive maintenance, bearing analysis
Event-driven sparse (motion, door switches)Event logging (timestamp + state change only)1000-10000xVery Low99.9%+ reductionLoses “no event” periods (acceptable)Security, occupancy, access control
High-frequency transient (acoustics, ultrasound)Triggered capture + FFT50-500xHigh98%+ reductionLoses non-trigger periodsLeak detection, acoustic monitoring
Bounded range analog (pressure, flow)Delta encoding + GZIP3-10xMedium (10% CPU)70-90% reductionNone (lossless)Critical measurements requiring full fidelity
Audit trail / compliance (access logs, alarms)GZIP compression only2-5xLow (5% CPU)50-80% reductionNone (lossless)Regulatory compliance, security logs

Decision Tree:

Read the tree from information requirements toward implementation cost. Start by asking whether silence itself carries meaning or whether only state changes matter; event logging is appropriate only when the application can interpret the gaps correctly. Next decide whether audit or diagnostic work requires the exact waveform. If it does, keep the transformation lossless and prove that decompression reproduces the source bytes. If a lossy representation is acceptable, inspect the signal: stable frequency components can support FFT features, slow trends can support window statistics, and bounded low-variance values can support delta encoding. At each branch, measure edge CPU and memory cost, reconstructed or retained information, output rate, and end-to-end latency on representative data. Keep a raw review window and a versioned compression rule so that a model or threshold change can be audited. The ratios in the comparison table are illustrative workload ranges, not guarantees for a new sensor stream.

  • is the signal event-driven (state changes only)?

    • YES → Use event logging (transmit only state changes)
    • NO → Continue to step 2
  • do you need to preserve the exact waveform for audit/compliance?

    • YES → Use lossless compression only (GZIP, DEFLATE)
    • NO → Continue to step 3
  • does the signal have strong frequency-domain features?

    • YES (vibration, acoustics) → Use FFT + top-N bins
    • NO → Continue to step 4
  • is the signal slowly changing (< 1% per sample)?

    • YES → Use statistical aggregation over time windows
    • NO → Continue to step 5
  • is the signal bounded with low variance?

    • YES → Use delta encoding + lossless compression
    • NO → Use adaptive sampling rate based on rate-of-change

Example: Multi-Sensor System with Different Compression Strategies:

class EdgeCompressionPipeline:
    def __init__(self):
        self.strategies = {
            'temperature': StatisticalAggregator(window_sec=300),    # 5-min windows
            'vibration': FFTCompressor(top_n=10, window_sec=10),     # Top 10 freq bins
            'motion': EventLogger(),                                 # State changes only
            'pressure': DeltaEncoder() + GZIPCompressor(),           # Lossless delta
            'door': EventLogger(),                                   # State changes only
        }

    def compress_sensor_data(self, sensor_id, raw_samples):
        sensor_type = self.get_sensor_type(sensor_id)
        strategy = self.strategies[sensor_type]
        return strategy.compress(raw_samples)

# Usage example:
pipeline = EdgeCompressionPipeline()

# Temperature: 300 samples → 4 summary values (min/max/mean/std)
temp_compressed = pipeline.compress_sensor_data("temp_01", temp_samples)
# Compression: 300 samples × 2 bytes = 600 bytes → 16 bytes (4 floats)
# Ratio: 37.5x

# Vibration: 10,000 samples → 10 FFT bins
vib_compressed = pipeline.compress_sensor_data("vib_01", vib_samples)
# Compression: 10,000 × 2 bytes = 20 KB → 40 bytes (10 complex floats)
# Ratio: 500x

# Motion: 1000 samples (mostly "no motion") → 3 events ("motion detected" at 3 timestamps)
motion_compressed = pipeline.compress_sensor_data("motion_01", motion_samples)
# Compression: 1000 × 1 byte = 1 KB → 24 bytes (3 events × 8 bytes each)
# Ratio: 42x
Multi-Sensor Compression Pipeline

Configure sensor counts and sampling rates to see how different compression strategies affect total bandwidth for a multi-sensor system.

Buffer Sizing for Each Strategy:

StrategyRAM Required (per sensor)Latency AddedNotes
Statistical Aggregation1-2 kB (circular buffer)5-60 seconds (window duration)Minimal memory, acceptable latency
FFT Compression16-64 kB (FFT working memory)1-10 seconds (FFT window)High memory, fast processing
Event Logging< 1 kB (state machine)None (immediate)Minimal resources, real-time
Delta Encoding4-8 kB (recent history)< 1 secondLow memory, minimal latency

Verification Checklist:

  • Compression ratio measured on representative data (not just ideal cases)
  • CPU usage stays under 60% during peak sensor activity
  • RAM usage leaves 30%+ margin for bursts
  • Decompression/reconstruction tested to verify information preservation
  • Bandwidth reduction measured end-to-end (including protocol overhead)
Sample Vibration Harmonics

The Mistake: Sampling vibration data at only 2x the motor’s fundamental frequency, missing critical high-frequency bearing fault signatures that appear at 5x-7x harmonics.

Real-World Example: A factory deployed vibration sensors with 100 Hz sampling on 30 Hz motors (thinking “2x motor speed is enough”):

Motor: 30 Hz
Bearing outer race fault frequency: 5 × 30 = 150 Hz

At 100 Hz sampling:
- Nyquist = 50 Hz
- 150 Hz aliases to |150 - round(150/100) × 100| = |150 - 200| = 50 Hz
- At exactly the Nyquist frequency, the signal is severely distorted

The bearing fault appeared as an unreliable artifact at the Nyquist boundary.
ML model missed 8 bearing failures before they became catastrophic.
One failure caused $500K in downtime.

Correct Implementation:

def calculate_vibration_sampling_rate(motor_rpm, bearing_type="ball"):
    """
    Calculate sampling rate for bearing fault detection.
    Accounts for all possible fault harmonics.
    """
    motor_hz = motor_rpm / 60

    # Bearing fault frequency multipliers
    fault_harmonics = {
        "ball": [1, 2, 3, 4, 5, 6, 7, 8],      # Ball bearings: up to 8x
        "roller": [1, 2, 3, 4, 5],              # Roller bearings: up to 5x
        "sleeve": [1, 2, 3],                    # Sleeve bearings: up to 3x
    }

    highest_harmonic = max(fault_harmonics[bearing_type])
    highest_frequency = motor_hz * highest_harmonic

    # Safety factor: 3x Nyquist for anti-aliasing filter
    recommended_rate = 3 * 2 * highest_frequency

    return {
        'motor_hz': motor_hz,
        'highest_fault_hz': highest_frequency,
        'nyquist_min': 2 * highest_frequency,
        'recommended': recommended_rate,
    }

# Example usage:
rate_info = calculate_vibration_sampling_rate(motor_rpm=1800, bearing_type="ball")
# Motor: 30 Hz | Highest fault: 240 Hz | Recommended: 1440 Hz (3x Nyquist)
Bearing Vibration Sampling

Adjust motor RPM and bearing type to see how bearing fault harmonics determine the required sampling rate.

Warning Signs: Vibration analysis shows only the fundamental frequency with no harmonics. Bearing failures occur with “no warning” despite continuous monitoring. FFT spectrum looks suspiciously clean.

Prevention: Always analyze the FULL harmonic series for rotating machinery. Sample at 3x Nyquist (not just 2x) to allow for anti-aliasing filter roll-off. Verify by plotting the FFT spectrum and confirming all expected fault harmonics are visible.

7.21 Knowledge Check

Quiz: Sampling and Compression

7.22 Practice Exercises

Objective: Determine optimal sampling rates for different sensor types.

Tasks:

  1. Identify signal characteristics for 4 sensors: temperature (max 0.1 Hz), vibration (max 500 Hz), audio (max 20 kHz), motion IMU (max 50 Hz)
  2. Apply Nyquist theorem: calculate minimum sampling rates
  3. Implement with margin and measure data rate impact

Expected Outcome: Understand the relationship between signal bandwidth and sampling requirements.

Objective: Implement multiple data reduction techniques and compare bandwidth savings.

Tasks:

  1. Collect 1-minute of high-rate sensor data (100 Hz = 6,000 samples)
  2. Apply 4 reduction strategies: downsampling, statistical aggregation, delta encoding, event-based
  3. Transmit reduced data and compare bandwidth
  4. Validate: can you detect a 1C temperature spike with each method?

Expected Outcome: Understand trade-offs between compression ratio and information preservation.

Data DoraCheckpoint: Ready to Apply

You now know:

  • The remaining quizzes ask you to calculate sample rates, select memory-feasible compression, match concepts, order the workflow, label the pipeline, and complete aggregation code.
  • The practice tasks keep the same evidence rule: sample high enough first, then reduce only in ways that preserve the analysis goal.
  • The next audit page extends this chapter into lossless time-series boundaries when exact reconstruction becomes the requirement.

Key Takeaway

Always sample at 2x or higher than the highest frequency of interest (Nyquist theorem) to avoid aliasing artifacts. Then apply edge data reduction — aggregation for slow-changing signals, FFT compression for vibration analysis, or semantic event extraction for sparse event streams — to reduce bandwidth by 10-1000x while preserving the information needed for downstream analytics.

Interactive Quiz: Match Concepts

Interactive Quiz: Sequence the Steps

Label the Diagram

Code Challenge

7.23 Time-Series Compression Audit

The body above covers Nyquist sampling, aggregation, FFT compression, semantic extraction, and edge algorithm selection. Continue to Time-Series Compression and Audit Boundaries when you need the deeper L2 material: delta and delta-of-delta encoders, Gorilla-style XOR compression, columnar layout, lossless-vs-lossy evidence boundaries, and compression metadata required for audit-grade reconstruction.

See how a pasture-monitoring question changes where bytes are processed in the diagram Figure 7.2.

Edge processing path from a six-axis cow-collar stream through fog event extraction to herd-level cloud comparison, with raw anomaly windows retained.
Figure 7.2: Edge processing path from a six-axis cow-collar stream through fog event extraction to herd-level cloud comparison, with raw anomaly windows retained.

In the diagram Figure 7.2, cow-collar motion moves from Measure the raw stream through Fog extracts motion evidence to Cloud compares the herd. The Keep raw windows around anomalies note makes the bargain explicit: compact events travel, while selected waveform evidence remains available for audit.

Before choosing a reducer, price the unreduced six-axis feed with the diagram Figure 7.3.

Six two-byte IMU axes give a 12 B sample, 72,000 B/min at 100 Hz and 103.68 MB/day. Downsampling can miss peaks; event extraction discards waveform shape.
Figure 7.3: Byte calculation for six two-byte IMU axes at 100 hertz, scaling from 12-byte frames to 103.68 megabytes per day and naming evidence lost by reduction.

Read Figure 7.3 from One sample frame to One continuous day: 12 B becomes 72,000 B/min and 103.68 MB/day. The closing Reduction changes the claim panel distinguishes losing hoof-strike peaks from losing the waveform itself.

Use the diagram Figure 7.4 when the design review must decide which motion claim is worth transmitting.

Side-by-side motion reduction choices comparing raw and five-hertz waveform data with packed tilt and change-only state reports.
Figure 7.4: Side-by-side motion reduction choices comparing raw and five-hertz waveform data with packed tilt and change-only state reports.

In the diagram Figure 7.4, the RAW / 5 HZ lane retains Waveform evidence at a measurable radio cost; the TILT / CHANGE lane retains State evidence and reports on change only. The shared Same ID and clock premise prevents a misleading comparison between differently described records.

Scale the sampling policy across the estate before assigning storage tiers in the diagram Figure 7.5.

Estate-scale telemetry calculation from one sensor through one hundred five-sensor fog nodes, with downsampling and tier-specific retention windows.
Figure 7.5: Estate-scale telemetry calculation from one sensor through one hundred five-sensor fog nodes, with downsampling and tier-specific retention windows.

In the diagram Figure 7.5, the sequence One sensor → gateway, Five sensors × 100 fog nodes, and Downsample at fog exposes the jump from 17.28 MB/day to 8.64 GB/day and the reduction to 14.4 MB/day. Its retention panel separates a short replay buffer from ninety-day trends and an explicitly authorized long hold.

7.24 Summary

Edge data acquisition requires careful balance between data fidelity and resource constraints:

  • Nyquist compliance: Sample at 2x or higher than your highest frequency of interest to avoid aliasing
  • Reduction techniques: Aggregation (10-50x), FFT compression (50-500x), and semantic extraction (100-1000x) each serve different use cases
  • Algorithm selection: Match compression to downstream analytics needs - lossless for audit, statistical for trends, FFT for vibration, semantic for events
  • Resource awareness: Consider CPU time and memory on constrained edge devices, not just compression ratio

7.25 Concept Relationships

Sampling and compression determine data fidelity, bandwidth, and power consumption trade-offs:

Sampling Theory (This chapter):

  • Nyquist theorem: sample at 2x highest frequency to avoid aliasing (vibration monitoring: sample at 2.5-3x Nyquist for anti-aliasing filter)
  • Under-sampling causes phantom patterns (150 Hz bearing fault aliased to 30 Hz when sampled at 60 Hz)

Compression Strategies (This chapter):

  • Lossless (GZIP): 2-4x reduction, preserves all data (audit trails, compliance)
  • Lossy statistical (aggregation): 10-100x reduction, preserves trends (environmental monitoring)
  • FFT-based: 50-500x reduction, preserves frequency spectrum (vibration analysis)
  • Semantic (event extraction): 100-1000x reduction, preserves state changes (threshold monitoring)

Power Impact:

  • edge Data Acquisition: Power and Gateways - Compression reduces transmission frequency, directly extending battery life (factory case: 14,400x reduction enables LoRa vs cellular)

Architecture Context:

Data Quality:

  • data Quality and Preprocessing - Validation must occur before compression (compressing invalid data wastes resources)

Key Insight: Compression algorithm selection depends on analytics requirements, not just compression ratio. Vibration monitoring needs FFT compression (preserves frequency info for bearing fault detection) even though aggregation yields higher ratios. Choosing wrong compression permanently destroys the signal needed for analysis.

7.26 What’s Next

See Also

Edge Acquisition Series:

Processing Context:

Data Quality:

  • data Quality and Preprocessing - Validation before compression