All articles →

100 Exercises / Simulation / Simulation 100 Exercises

Stochastic Processes in Manufacturing | 10 Python Exercises from Markov Chains to Particle Filters

Model equipment states and failures in Python. Explore Markov chains, renewal processes, Brownian motion, Kalman filters and particle filters.

Modeling Equipment States with Stochastic Processes: Python Exercises No.071–No.080

What this article covers

Equipment moves between normal, degraded and failed states. Failures and orders occur irregularly, and sensors add measurement noise. Exercises No.071–No.080 use stochastic processes to model these changes in a fictional precision-parts factory.

Through No.071 to No.080, we connect condition transitions, long-term operating rates, abnormal signs, number of failures, parts replacement, external pricing, equipment deterioration, and sequential condition estimation to support maintenance, inventory, and investment decisions.

This article adapts notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama, with permission from the client companies.
All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.

Introduction: Practical Challenges in Manufacturing Covered in This Article

The target is decision-making that reduces sudden stoppages of major processing equipment while avoiding excessive maintenance and inspection man-hours. Mean failure intervals alone cannot answer questions such as “What will happen next to equipment currently in a deteriorating state?”, “What is the probability that the number of failures will increase next month?”, or “How can the true state be estimated from sensors containing noise?”

We compare possible future equipment states and their probabilities to support maintenance and inventory decisions.

Common situations on site

  • Although the equipment ledger contains a history of failures, the transition structure between normal, degraded and failed states is not organized
  • You can know the average number of breakdowns per month, but you can’t know the probability of running short of spare parts.
  • Vibration and temperature threshold monitoring often results in false alarms and missed failures
  • Fluctuations in market prices and demand are not included in sensitivity analysis for capital investment evaluation.
  • Even with advanced models, the basis for parameters and responsibility for updates may remain unclear

Why is this issue so difficult to judge?

Even if the average value is the same, differences in occurrence variability, dependence on state status, and observed noise will affect the required countermeasures. In stochastic processes, the state at point tt is set as the random variable XtX_t, and the entire sequence (Xt)t≥0(X_t)_{t\geq0} is handled.

In practice, it is important to design (1) what defines a state, (2) whether time is handled discrete or continuous, (3) how to estimate unobservable states, and (4) how to incorporate estimation error into decision-making. It is necessary to evaluate not only model accuracy but also asymmetric losses such as downtime, inspection costs, and out-of-stock costs.

Exercises covered in this article

No.ThemeQuestions in the Manufacturing IndustryMain Outputs
071Markov chainHow will the equipment status transition into the next term?Transition of State Probability
072stationary distributionWhat is the long-term failure and deterioration ratio?Long-term state ratio
073Hidden Markov ModelCan we estimate deterioration that is invisible from the sensor?Filter probability
074Poisson processHow many malfunctions and calls will there be?Number of cases distribution
075Renewal processHow many parts are replaced and replaced?Renewal counts and intervals
076Brownian motionHow to represent the fluctuation of cumulative error?Route distribution
077Geometric Brownian motionHow to evaluate the ratio fluctuations of external pricesPrice Scenario
078Stochastic differential equationHow to represent the mean reversion facility indicator?Degradation Indicator Pathway
079Kalman filterCan continuous states be estimated excluding noise?Estimates and intervals
080particle filterCan state estimates be made even with nonlinear observations?Particle Distribution and Estimated Values

Preparing the Python environment

It does not depend on external data and uses only NumPy, pandas, and matplotlib. The random number generator is initialized with a fixed seed, and rerunning it ensures the same result. Labels in the graph are displayed in English to avoid environmental differences during Markdown conversion.

Run cells in order. [IN: n] marks an input and [OUT: n] its output; cells with no displayed result have no output label. Expand the setup panels to see longer code. Reproduce results by initializing the generator and running the same calls in the same order in the same library environment. Version numbers in outputs describe the recorded run.

Setup code: Environment and random generator (expand)
[IN: 1]
%matplotlib inline

import sys
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from IPython.display import display

SEED = 20260712
rng = np.random.default_rng(SEED)
plt.rcParams.update({"figure.figsize": (8, 4), "axes.grid": True})
print(f"Python     : {sys.version.split()[0]}")
print(f"NumPy      : {np.__version__}")
print(f"pandas     : {pd.__version__}")
print(f"matplotlib : {matplotlib.__version__}")
print(f"random seed: {SEED}")
[OUT: 1]
Python     : 3.14.4
NumPy      : 2.5.1
pandas     : 3.0.3
matplotlib : 3.11.0
random seed: 20260712

Creation of Fictional Data

Assuming the main processing equipment of a precision parts factory, it generates 90 days’ worth of “true deterioration” and vibration sensor values. The true degree of degradation is kept only for verification and is a latent state that cannot be observed in actual operation. In the latter part of the filter, this state is estimated based solely on observations.

Setup code: Fictional data and shared functions (expand)
[IN: 2]
days = 90
t = np.arange(days)
true_health = np.zeros(days)
true_health[0] = 1.0
for i in range(1, days):
    true_health[i] = max(0, true_health[i - 1] + 0.025 + rng.normal(0, 0.045))
vibration = 1.2 + 0.85 * true_health + 0.18 * true_health**2 + rng.normal(0, 0.22, days)
temperature = 42 + 3.2 * true_health + rng.normal(0, 0.8, days)
sensor_df = pd.DataFrame(
    {
        "day": t,
        "true_degradation": true_health,
        "vibration_mm_s": vibration,
        "temperature_C": temperature,
    }
)
display(sensor_df.head().round(3))
print(f"rows={len(sensor_df)}, missing={sensor_df.isna().sum().sum()}")

fig, ax = plt.subplots()
ax.plot(t, vibration, label="Observed vibration", alpha=0.75)
ax.plot(t, 1.2 + 0.85 * true_health + 0.18 * true_health**2, label="Noise-free signal")
ax.set_title("Synthetic equipment sensor data")
ax.set_xlabel("Day")
ax.set_ylabel("Vibration [mm/s]")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 2]
day true_degradation vibration_mm_s temperature_C
0 0 1.000 2.179 44.119
1 1 1.058 2.443 46.809
2 2 1.114 2.385 45.303
3 3 1.158 2.244 44.773
4 4 1.201 2.654 45.412
rows=90, missing=0

Synthetic equipment sensor data

No.071: Predicting Equipment Condition Changes Using Markov Chains

Practical context

The equipment condition during inspection is divided into three levels: Normal, Degraded, and Failed, and the probability of the next week’s condition is predicted. Instead of a single prediction of “failure/non-failure,” the maintenance plan can be shared as the probability of downtime risk.

Modeling approach

The Markov chain is an approximation that “the next state depends only on the current state.” When you define element pij=P(Xt+1=j∣Xt=i)p_{ij}=P(X_{t+1}=j\mid X_t=i) of the transition matrix PP, the state probability vector is updated at πt+1=πtP\boldsymbol{\pi}_{t+1}=\boldsymbol{\pi}_tP. After a malfunction, repairs will restore it to normal or deteriorate settings.

Python example

[IN: 3]
states = ["Normal", "Degraded", "Failed"]
P = np.array([[0.88, 0.11, 0.01], [0.18, 0.68, 0.14], [0.72, 0.28, 0.00]])
display(pd.DataFrame(P, index=states, columns=states).style.format("{:.0%}"))
pi = np.array([1.0, 0.0, 0.0])
history = [pi.copy()]
for _ in range(12):
    pi = pi @ P
    history.append(pi.copy())
markov_df = pd.DataFrame(history, columns=states).assign(week=np.arange(13))
display(markov_df.iloc[[0, 1, 4, 8, 12]].set_index("week").round(4))
fig, ax = plt.subplots()
for s in states:
    ax.plot(markov_df.week, markov_df[s], marker="o", label=s)
ax.set_title("Equipment-state probabilities by Markov chain")
ax.set_xlabel("Week")
ax.set_ylabel("Probability")
ax.set_ylim(0, 1)
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 3]
  Normal Degraded Failed
Normal 88% 11% 1%
Degraded 18% 68% 14%
Failed 72% 28% 0%
Normal Degraded Failed
week
0 1.0000 0.0000 0.0000
1 0.8800 0.1100 0.0100
4 0.7253 0.2372 0.0374
8 0.6872 0.2687 0.0441
12 0.6820 0.2730 0.0450

Equipment-state probabilities by Markov chain

Interpreting the results

Starting from normal operation, the probabilities of being normal, degraded or failed at each week approach a stable mix. These are not cumulative probabilities of having failed at least once by that week. Strong age or load effects require richer states or time-varying transition probabilities.

No.072: Estimating Long-Term Facility State Ratios Using Stationary Distribution

Practical context

Estimate what percentage of equipment will be normal, deteriorated, or fail if the same operation continues for a long time. It serves as a baseline for long-term maintenance personnel, replacement capacity, and downtime losses.

Modeling approach

The stationary distribution satisfies π∗=π∗P\boldsymbol{\pi}^*=\boldsymbol{\pi}^*P and ∑iπi∗=1\sum_i\pi_i^*=1. This finite chain is irreducible and aperiodic, so it converges to a unique stationary distribution from any initial distribution. Also check that transition probabilities are nonnegative and each row sums to one.

Python example

[IN: 4]
A = np.vstack([P.T - np.eye(len(states)), np.ones(len(states))])
b = np.r_[np.zeros(len(states)), 1.0]
stationary, *_ = np.linalg.lstsq(A, b, rcond=None)
stationary_df = pd.DataFrame({"state": states, "stationary_probability": stationary})
display(stationary_df.style.format({"stationary_probability": "{:.2%}"}))
weekly_loss = np.array([0, 350_000, 2_400_000])
expected_loss = stationary @ weekly_loss
print(f"Long-run expected weekly loss: JPY {expected_loss:,.0f}")
fig, ax = plt.subplots()
ax.bar(states, stationary, color=["#4c9f70", "#e0a458", "#d1495b"])
ax.set_title("Long-run equipment-state mix")
ax.set_xlabel("State")
ax.set_ylabel("Stationary probability")
ax.set_ylim(0, 1)
ax.grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 4]
  state stationary_probability
0 Normal 68.12%
1 Degraded 27.37%
2 Failed 4.51%
Long-run expected weekly loss: JPY 204,076

Long-run equipment-state mix

Interpreting the results

Multiply each stationary state probability by its weekly loss and sum to estimate long-run expected loss. Repeat with a proposed maintenance policy’s transition matrix, then compare the reduction with policy cost. This is a long-run reference under unchanged operating rules, not a forecast for a particular week.

No.073: Estimating Potential Degradation with the Hidden Markov Model

Practical context

This is a situation where the true condition of the equipment is not directly visible, and only vibration judgments (Low / Medium / High) are observed. It does not respond to single anomalies, and can update the degradation probability including past observation series.

Modeling approach

The Hidden Markov Model (HMM) combines the transition probabilities of latent states with the observational probabilities for each state. The forward filter iterates between forecast α^t=αt−1P\hat{\alpha}_t=\alpha_{t-1}P and observational correction αt∝α^t⊙b(yt)\alpha_t\propto\hat{\alpha}_t\odot b(y_t).

Python example

[IN: 5]
emissions = np.array([[0.82, 0.16, 0.02], [0.18, 0.62, 0.20], [0.03, 0.22, 0.75]])
obs_names = ["Low", "Medium", "High"]
observations = np.array([0, 0, 1, 0, 1, 1, 2, 1, 2, 2, 1, 2])
alpha = np.array([0.85, 0.14, 0.01])
filtered = []
for y in observations:
    pred = alpha @ P
    alpha = pred * emissions[:, y]
    alpha /= alpha.sum()
    filtered.append(alpha.copy())
hmm_df = pd.DataFrame(filtered, columns=states)
hmm_df["observation"] = [obs_names[i] for i in observations]
hmm_df.index = np.arange(1, len(hmm_df) + 1)
display(hmm_df.tail().round(3))
fig, ax = plt.subplots()
ax.plot(
    hmm_df.index,
    hmm_df.Degraded + hmm_df.Failed,
    marker="o",
    label="P(Degraded or Failed)",
)
ax.axhline(0.7, color="red", linestyle="--", label="Inspection threshold")
ax.set_title("Hidden-state risk inferred from vibration categories")
ax.set_xlabel("Inspection sequence")
ax.set_ylabel("Filtered probability")
ax.set_ylim(0, 1)
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 5]
Normal Degraded Failed observation
8 0.175 0.782 0.044 Medium
9 0.032 0.556 0.412 High
10 0.051 0.597 0.352 High
11 0.162 0.791 0.046 Medium
12 0.031 0.556 0.412 High

Hidden-state risk inferred from vibration categories

Interpreting the results

Repeated high vibration observations increase the filtered probability of degradation or failure. A single medium reading need not return it to normal. Compare missed-failure losses with inspection costs when choosing a probability threshold, such as 70%, for further inspection.

No.074: Estimating the Number of Fault Calls During the Poisson Process

Practical context

We model the number of fault calls occurring at a constant rate from independent equipment groups to calculate the probability of shortages in maintenance personnel and spare parts.

Modeling approach

In a Poisson process with an incidence rate of λ\lambda per unit time, the number of events N(t)N(t) for period tt follows P(N(t)=k)=e−λt(λt)k/k!P(N(t)=k)=e^{-\lambda t}(\lambda t)^k/k!, and the interval between arrivals follows an exponential distribution of average 1/λ1/\lambda. If the incidence rate changes with season or shift, extend to nonhomogeneous Poisson processes and similar processes.

Python example

[IN: 6]
lambda_day = 0.42
sim_counts = rng.poisson(lambda_day * 30, size=20_000)
spares = 17
summary = (
    pd.Series(sim_counts)
    .describe(percentiles=[0.5, 0.8, 0.9, 0.95, 0.99])
    .to_frame("30-day failures")
)
display(summary.round(2))
print(f"P(failures > {spares} spares) = {(sim_counts > spares).mean():.2%}")
fig, ax = plt.subplots()
bins = np.arange(sim_counts.min(), sim_counts.max() + 2) - 0.5
ax.hist(sim_counts, bins=bins, density=True, color="#4c78a8", alpha=0.8)
ax.axvline(spares, color="red", linestyle="--", label=f"Spare stock={spares}")
ax.set_title("Simulated monthly failure-call count")
ax.set_xlabel("Failures in 30 days")
ax.set_ylabel("Probability density")
ax.grid(True, axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 6]
30-day failures
count 20000.00
mean 12.60
std 3.55
min 1.00
50% 12.00
80% 16.00
90% 17.00
95% 19.00
99% 21.00
max 28.00
P(failures > 17 spares) = 8.95%

Simulated monthly failure-call count

Interpreting the results

Stocking only the mean monthly requirement leaves a substantial shortage risk. Compare quantiles and shortage probabilities, such as the stock needed to cover 95% of months. Cascading failures, shared causes and changing rates can make a homogeneous Poisson model understate the risk.

No.075: Reproducing the Lifecycle of Replacement Parts During Renewal

Practical context

After a failure or replacement, the lifespan of the part is reset and it is used again. Model this repetition and estimate the number of annual replacements and budget.

Modeling approach

For independent, identically distributed lifetimes T1,T2,…T_1,T_2,\ldots, define S0=0S_0=0 and renewal times Sn=∑i=1nTiS_n=\sum_{i=1}^nT_i. The replacement count is N(t)=max⁡{n≥0:Sn≤t}N(t)=\max\{n\geq0:S_n\leq t\}. We draw Weibull lifetimes and exclude replacements after day 365. The plot retains the last observed count at its right endpoint.

Python example

[IN: 7]
shape, scale = 2.3, 95.0

def renewal_count(horizon, generator):
    elapsed = 0.0
    count = 0
    times = []
    while True:
        elapsed += scale * generator.weibull(shape)
        if elapsed > horizon:
            break
        count += 1
        times.append(elapsed)
    return count, times

renewals = np.array([renewal_count(365, rng)[0] for _ in range(10_000)])
one_count, one_times = renewal_count(365, np.random.default_rng(SEED + 1))
display(
    pd.Series(renewals)
    .value_counts(normalize=True)
    .sort_index()
    .rename("probability")
    .to_frame()
    .style.format("{:.2%}")
)
print(f"Expected annual replacements: {renewals.mean():.2f}")
fig, ax = plt.subplots()
ax.step(
    [0] + one_times + [365], np.r_[np.arange(one_count + 1), one_count], where="post"
)
ax.scatter(one_times, np.arange(1, one_count + 1), color="red", zorder=3)
ax.set_title("One sample path of component renewals")
ax.set_xlabel("Day")
ax.set_ylabel("Cumulative replacements")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 7]
  probability
1 0.07%
2 5.21%
3 28.66%
4 38.92%
5 19.98%
6 6.07%
7 0.98%
8 0.11%
Expected annual replacements: 3.96

One sample path of component renewals

Interpreting the results

The number of replacements can be tracked not only by average but also by distribution, allowing you to assess the annual budget upward and the required quantity of maintenance items. If there are repairs that do not return to the same condition as new, preventive replacements, or dependent failures of multiple parts, the process is extended from simple renewal models to virtual-age models and competing risks.

No.076: Represents the Minute Fluctuations Accumulated in Brownian Motion

Practical context

The uncertainty of quantity caused by many small influences, such as dimensional correction errors and thermal displacement, is evaluated as a pathway.

Modeling approach

The standard Brownian motion WtW_t is W0=0W_0=0, has independent increments, and is Wt+Δt−Wt∼N(0,Δt)W_{t+\Delta t}-W_t\sim N(0,\Delta t). If you consider the drifted process Xt=μt+σWtX_t=\mu t+\sigma W_t, systematic deviations and random fluctuations can be separated. However, physical boundaries and mean reversion are not included.

Python example

[IN: 8]
n_paths, n_steps, horizon = 5000, 120, 8.0
dt = horizon / n_steps
mu, sigma = 0.018, 0.085
increments = mu * dt + sigma * np.sqrt(dt) * rng.normal(size=(n_paths, n_steps))
paths = np.c_[np.zeros(n_paths), np.cumsum(increments, axis=1)]
time = np.linspace(0, horizon, n_steps + 1)
limit = 0.30
print(
    f"P(|error at horizon| > {limit:.2f}) = {(np.abs(paths[:,-1]) > limit).mean():.2%}"
)
fig, ax = plt.subplots()
for p in paths[:30]:
    ax.plot(time, p, color="#4c78a8", alpha=0.18)
q05, q50, q95 = np.quantile(paths, [0.05, 0.5, 0.95], axis=0)
ax.plot(time, q50, color="black", label="Median")
ax.fill_between(time, q05, q95, alpha=0.25, label="90% range")
ax.axhline(limit, color="red", linestyle="--")
ax.axhline(-limit, color="red", linestyle="--")
ax.set_title("Accumulated process error under Brownian motion")
ax.set_xlabel("Operating time [h]")
ax.set_ylabel("Accumulated error [mm]")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 8]
P(|error at horizon| > 0.30) = 29.82%

Accumulated process error under Brownian motion

Interpreting the results

The reported probability concerns the endpoint at eight hours, not whether the path ever crosses a limit. The 90% band contains pointwise quantiles and is not a simultaneous band for entire paths. Define whether calibration decisions use endpoint exceedance or first crossing during the interval.

No.077: Creating External Price Scenarios with Geometric Brownian Motion

Practical context

For things like electricity and raw materials, we create scenarios that move by rate of change rather than absolute prices, and do not take negative values. It can be used for profitability sensitivity in procurement contracts and capital investments.

Modeling approach

The geometric Brownian motion is dSt=μStdt+σStdWtdS_t=\mu S_tdt+\sigma S_tdW_t, and the solution is St=S0exp⁡{(μ−σ2/2)t+σWt}S_t=S_0\exp\{(\mu-\sigma^2/2)t+\sigma W_t\}. Rather than a forecasting model that guarantees prices, it is a model that creates a distribution of profitability under assumed volatility.

Python example

[IN: 9]
n_paths, months = 10000, 24
dt = 1 / 12
s0, annual_mu, annual_sigma = 100.0, 0.035, 0.22
z = rng.normal(size=(n_paths, months))
log_inc = (annual_mu - 0.5 * annual_sigma**2) * dt + annual_sigma * np.sqrt(dt) * z
price_paths = s0 * np.exp(np.c_[np.zeros(n_paths), np.cumsum(log_inc, axis=1)])
terminal = price_paths[:, -1]
display(
    pd.Series(terminal)
    .quantile([0.05, 0.25, 0.5, 0.75, 0.95])
    .rename("price_index_at_24m")
    .to_frame()
    .round(1)
)
print(f"P(price index > 130) = {(terminal > 130).mean():.2%}")
fig, ax = plt.subplots()
for p in price_paths[:35]:
    ax.plot(np.arange(months + 1), p, alpha=0.15)
ax.plot(
    np.arange(months + 1), np.median(price_paths, axis=0), color="black", label="Median"
)
ax.set_title("Input-price scenarios by geometric Brownian motion")
ax.set_xlabel("Month")
ax.set_ylabel("Price index")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 9]
price_index_at_24m
0.05 61.4
0.25 83.4
0.50 102.4
0.75 125.4
0.95 171.2
P(price index > 130) = 21.32%

Input-price scenarios by geometric Brownian motion

Interpreting the results

There is a difference between the median and upper quantile after 24 months, and a single price assumption alone overlooks upside risk. By calculating the profit and NPV for each route for each investment project, you can compare them with the probability of losing money. Because real prices have mean reversion, jumps, and seasonality, mechanical extrapolation of past volatility is avoided.

No.078: Representing the Degradation Index of Mean Reversion in Stochastic Differential Equations

Practical context

It handles indicators such as temperature and control deviations that return to the standard through control even if shaken by disturbances. You can evaluate deviation times more realistically than just random walks.

Modeling approach

Discretize the Ornstein–Uhlenbeck process dXt=θ(μ−Xt)dt+σdWtdX_t=\theta(\mu-X_t)dt+\sigma dW_t using the Euler–Maruyama method. θ\theta is the recovery speed, μ\mu is the long-term average, and σ\sigma is the disturbance strength. If the Δt\Delta t is too coarse, numerical errors increase, so time-step convergence must be checked.

Python example

[IN: 10]
n_paths, n_steps, dt = 3000, 240, 1 / 24
theta, long_mean, sigma_ou, x0 = 1.4, 2.0, 0.55, 3.2
ou = np.zeros((n_paths, n_steps + 1))
ou[:, 0] = x0
for k in range(n_steps):
    ou[:, k + 1] = (
        ou[:, k]
        + theta * (long_mean - ou[:, k]) * dt
        + sigma_ou * np.sqrt(dt) * rng.normal(size=n_paths)
    )
threshold = 2.8
exceed_hours = (ou[:, 1:] > threshold).sum(axis=1) * dt * 24
print(f"Mean hours above threshold: {exceed_hours.mean():.2f}")
print(f"P(above threshold for >= 8 hours): {(exceed_hours >= 8).mean():.2%}")
fig, ax = plt.subplots()
time_ou = np.arange(n_steps + 1) * dt
for p in ou[:25]:
    ax.plot(time_ou, p, alpha=0.15)
ax.plot(time_ou, np.median(ou, axis=0), color="black", label="Median")
ax.axhline(long_mean, color="green", linestyle="--", label="Long-run mean")
ax.axhline(threshold, color="red", linestyle="--", label="Alarm threshold")
ax.set_title("Mean-reverting equipment indicator")
ax.set_xlabel("Day")
ax.set_ylabel("Condition indicator")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 10]
Mean hours above threshold: 10.48
P(above threshold for >= 8 hours): 58.40%

Mean-reverting equipment indicator

Interpreting the results

Even if the initial value is high, it returns to the average, but disturbances repeatedly cause threshold exceedances. Compared to single overruns, operational KPIs like “cumulative overruns of 8 hours or more” become more stable. Parameters should be estimated for each equipment and operating condition, and the independence and distribution of residuals must be checked.

No.079: Removing Sensor Noise with a Kalman Filter

Practical context

When true degradation cannot be directly measured, past estimates and new sensor values are integrated according to uncertainty. Compared to the raw moving average, the advantage is that you can clearly indicate the range of estimation error.

Modeling approach

Use the linear state model xt=Axt−1+0.025+wtx_t=Ax_{t-1}+0.025+w_t and observation model yt=Hxt+vty_t=Hx_t+v_t. The generated vibration actually contains a quadratic degradation term. We deliberately use yt=(vibrationt−1.2)/0.85y_t=(\mathrm{vibration}_t-1.2)/0.85 to show the bias caused by ignoring it. The Kalman gain is computed from the assumed prediction and observation variances.

Python example

[IN: 11]
y_linear = (vibration - 1.2) / 0.85
A, H, Q, R = 1.0, 1.0, 0.045**2 + 0.01**2, (0.22 / 0.85) ** 2
x_est, cov = 0.8, 0.4
estimates, variances = [], []
for y in y_linear:
    x_pred = A * x_est + 0.025
    p_pred = A * cov * A + Q
    gain = p_pred * H / (H * p_pred * H + R)
    x_est = x_pred + gain * (y - H * x_pred)
    cov = (1 - gain * H) * p_pred
    estimates.append(x_est)
    variances.append(cov)
estimates, variances = np.array(estimates), np.array(variances)
rmse_raw = np.sqrt(np.mean((y_linear - true_health) ** 2))
rmse_kf = np.sqrt(np.mean((estimates - true_health) ** 2))
print(f"Raw-observation RMSE : {rmse_raw:.3f}")
print(f"Kalman-filter RMSE   : {rmse_kf:.3f}")
fig, ax = plt.subplots()
ax.plot(t, y_linear, color="gray", alpha=0.35, label="Converted observation")
ax.plot(t, true_health, color="black", label="True degradation (validation only)")
ax.plot(t, estimates, color="#4c78a8", label="Kalman estimate")
sd = np.sqrt(variances)
ax.fill_between(
    t,
    estimates - 1.96 * sd,
    estimates + 1.96 * sd,
    alpha=0.2,
    label="Approx. 95% interval",
)
ax.set_title("Linear state estimation by Kalman filter")
ax.set_xlabel("Day")
ax.set_ylabel("Degradation index")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 11]
Raw-observation RMSE : 1.372
Kalman-filter RMSE   : 1.249

Linear state estimation by Kalman filter

Interpreting the results

RMSE decreases only from 1.372 to 1.249, and estimates remain far above the true state. Smoothing cannot remove bias from the omitted quadratic term. The plotted 95% interval is conditional on the misspecified linear model and must not be treated as a calibrated interval for maintenance decisions. The next example uses the nonlinear observation equation in a particle filter.

No.080: Estimating Nonlinear Equipment Conditions with Particle Filters

Practical context

When the observation relationship is nonlinear, such as the vibration value increasing quadratively with respect to the degree of degradation, the latent state is sequentially estimated. Because multiple possibilities can be held as particle groups, it can handle situations where distribution is distorted.

Modeling approach

Particle filters approximate the state distribution with many particles xt(i)x_t^{(i)} and weights wt(i)w_t^{(i)}. Repeat predictions, weight updates based on likelihoods, normalization, and resampling. The more particles you have, the more stable the approximation becomes, but the computational complexity also increases.

Python example

[IN: 12]
n_particles = 4000
pf_rng = np.random.default_rng(SEED + 80)
particles = np.clip(pf_rng.normal(0.8, 0.35, n_particles), 0, None)
pf_est, pf_low, pf_high, ess_history = [], [], [], []
for y in vibration:
    particles = np.clip(
        particles + 0.025 + pf_rng.normal(0, 0.045, n_particles), 0, None
    )
    predicted_y = 1.2 + 0.85 * particles + 0.18 * particles**2
    weights = np.exp(-0.5 * ((y - predicted_y) / 0.22) ** 2)
    weights += 1e-300
    weights /= weights.sum()
    pf_est.append(np.sum(weights * particles))
    order = np.argsort(particles)
    sorted_p = particles[order]
    cum_w = np.cumsum(weights[order])
    pf_low.append(np.interp(0.025, cum_w, sorted_p))
    pf_high.append(np.interp(0.975, cum_w, sorted_p))
    ess_history.append(1 / np.sum(weights**2))
    positions = (pf_rng.random() + np.arange(n_particles)) / n_particles
    indexes = np.searchsorted(np.cumsum(weights), positions)
    particles = particles[indexes]
pf_est, pf_low, pf_high = map(np.array, (pf_est, pf_low, pf_high))
print(f"Particle-filter RMSE: {np.sqrt(np.mean((pf_est-true_health)**2)):.3f}")
print(
    f"Mean effective sample size before resampling: {np.mean(ess_history):.0f}/{n_particles}"
)
fig, ax = plt.subplots()
ax.plot(t, true_health, color="black", label="True degradation (validation only)")
ax.plot(t, pf_est, color="#f58518", label="Particle-filter estimate")
ax.fill_between(
    t, pf_low, pf_high, color="#f58518", alpha=0.2, label="95% particle interval"
)
ax.set_title("Nonlinear state estimation by particle filter")
ax.set_xlabel("Day")
ax.set_ylabel("Degradation index")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 12]
Particle-filter RMSE: 0.067
Mean effective sample size before resampling: 3199/4000

Nonlinear state estimation by particle filter

Interpreting the results

By directly using nonlinear vibration models, estimates and intervals close to true degradation can be obtained. The effective sample size is a diagnostic indicator for monitoring particle bias. During implementation, verify particle count, observation likelihood, and resampling methods, and evaluate “how many days in advance an alarm was triggered” based on known failure history.

Practical takeaways

  1. Separate by state, number of cases, and continuous volume: For equipment conditions, the Markov chain is the starting point; for independent occurrences, the Poisson process is the starting point; for continuous fluctuations, the stochastic differential equation is the starting point.
  2. Distinguishing between observed and true states: Sensor values are not regarded as the state itself; observation errors are clearly indicated using HMM, Kalman filters, and particle filters.
  3. Determined by distribution, not average: In addition to the expected number of failures, KPIs include inventory shortage probability, upper quantile, and interval estimation.
  4. Increasing complexity step by step: Based on explainable simple models, it only advances when residuals and decision value improve.
  5. Connecting models to costs: Convert probabilities into stoppage losses, inspection costs, inventory costs, and quality losses to compare measures.

Preparing for practical use

  • Standardize condition definitions, failure codes, time accuracy, and standards for recording replacement and repair
  • Records of missing measurements, sensor replacements, downtime, and changes in operating conditions
  • Separate training periods and future validation periods to prevent data leaks at the equipment and time level
  • Evaluate not only accuracy but also alarm lead time, missed losses, and false alarm response man-hours
  • Confirm parameter ranges and physical constraints with on-site knowledge
  • Design from drift monitoring, regular reestimation, model approval, to standard operations after alerts

If you want to start small, narrow down to one critical equipment series and one decision (e.g., a detailed inspection within 7 days), and proceed with parallel evaluation alongside existing rules.

Conclusion

From No.071 to No.080, we implemented equipment condition transitions, long-term ratios, latent states, number of events, replacement cycles, continuous fluctuations, and sequential estimation. The value of stochastic processes lies not in definitive futures but in showing the possible range and probability, and in quantifying criteria for maintenance, inventory, and investment decisions.

The first practical step is to clarify “which decisions you want to change, in advance, and by which loss criteria” rather than selecting models. Designing the minimum necessary state, observation, and temporal granularity according to that question makes it easier for analysis to translate into operational needs.

Consultations for Corporations

At Surikobo, we support the entire data preparation stage, including equipment maintenance, failure and demand simulation, condition estimation using sensor data, and designing decision-making KPIs in manufacturing. You can consult about designs that do not end with just PoC, but also consider on-site operation, evaluation, and renewal.

📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.