"""A year of failure records for one site: bad-actor list, indicators and a check of the gain."""
from scipy.stats import chi2, poisson
import matplotlib.pyplot as plt
YEAR = 8400.0 # hours in a year at the site
TECH_HOUR = 1500.0 # currency units
STOCK_LOSS = 230000.0 # stock and disruption when cooling is lost
PLANNED_HOURS = 420.0 # technician hours of planned work in the year
# machine, failure mode, class, true rate a year, mean stop (h), parts,
# technician hours, loss per stop hour, chance that stock is lost
# class A: safety or environment, B: the cold room is at risk, C: operations and cost
("Compressor 1", "Valve failure", "C", 0.40, 9.0, 28000.0, 8.0, 0.0, 0.0),
("Compressor 1", "Blocked condenser", "B", 0.50, 4.0, 0.0, 4.0, 0.0, 0.2),
("Compressor 1", "Control sensor failure", "B", 0.25, 3.0, 2000.0, 2.0, 0.0, 0.5),
("Compressor 1", "Oil loss", "C", 0.20, 4.0, 4000.0, 4.0, 0.0, 0.0),
("Compressor 1", "Contactor failure", "C", 0.15, 2.0, 6000.0, 2.0, 0.0, 0.0),
("Compressor 1", "Loss of refrigerant", "A", 0.15, 10.0, 18000.0, 8.0, 0.0, 0.0),
("Compressor 1", "Bearing wear", "C", 0.10, 12.0, 126000.0, 16.0, 0.0, 0.0),
("Compressor 1", "Motor winding failure", "C", 0.05, 12.0, 126000.0, 16.0, 0.0, 0.0),
("Compressor 2", "Fault found on test", "C", 0.50, 3.0, 5000.0, 2.0, 0.0, 0.0),
("Conveyor", "Bearing failure", "C", 2.00, 5.0, 4500.0, 6.0, 12000.0, 0.0),
("Conveyor", "Belt runs off centre", "C", 10.0, 0.3, 0.0, 1.0, 12000.0, 0.0),
("Conveyor", "Jam at the transfer", "C", 8.00, 0.15, 0.0, 0.5, 12000.0, 0.0),
("Borehole pump", "Pump failure", "C", 0.50, 10.0, 28000.0, 8.0, 0.0, 0.0),
("Borehole pump", "Motor overload trip", "C", 3.00, 1.0, 0.0, 1.0, 0.0, 0.0),
("Generator", "Fault found on test", "C", 0.20, 2.0, 4000.0, 2.0, 0.0, 0.0),
MACHINES = ["Compressor 1", "Compressor 2", "Conveyor", "Borehole pump", "Generator"]
# hours in service (compressor 1, conveyor) and running hours from the counter (pump);
# the two standby machines are judged by their tests
RUN_HOURS = {"Compressor 1": 8400.0, "Conveyor": 8400.0, "Borehole pump": 2900.0}
TESTS = {"Compressor 2": 50, "Generator": 13}
"""One year of failure records: (day, index of the mode, stop hours, cost) for each event."""
rng = np.random.default_rng(seed)
for k, (_, _, _, rate, stop, parts, tech, hourly, p_stock) in enumerate(MODES):
for _ in range(rng.poisson(rate)):
day = int(rng.integers(1, 351))
hours = round(float(rng.gamma(4.0, stop / 4.0)), 2)
stock = STOCK_LOSS if rng.random() < p_stock else 0.0
cost = parts + tech * TECH_HOUR + hours * hourly + stock
events.append((day, k, hours, cost))
"""Expected cost a year of mode k under the model that generated the record."""
_, _, _, rate, stop, parts, tech, hourly, p_stock = MODES[k]
return rate * (parts + tech * TECH_HOUR + stop * hourly + p_stock * STOCK_LOSS)
total = sum(e[3] for e in events)
print(f"The record: {len(events)} events, cost {total:,.0f}")
print(" day machine failure mode class stop h cost")
for day, k, hours, cost in events:
print(f" {day:3d} {MODES[k][0]:13s} {MODES[k][1]:22s} {MODES[k][2]} "
f"{hours:5.2f} {cost:7,.0f}")
# ---------- Application 1: the bad-actor list ----------
print("\nApplication 1: by machine")
ev = [e for e in events if MODES[e[1]][0] == m]
c = sum(e[3] for e in ev)
print(f" {m:13s} {len(ev):2d} events {sum(e[2] for e in ev):5.1f} h stopped "
f"{c:8,.0f} {100 * c / total:5.1f} %")
n_mode = np.zeros(len(MODES), dtype=int)
c_mode = np.zeros(len(MODES))
for _, k, _, cost in events:
seen = [k for k in np.argsort(-c_mode, kind="stable") if n_mode[k] > 0]
safety = [k for k in seen if MODES[k][2] == "A"]
ranked = [k for k in seen if MODES[k][2] != "A"]
ranked_total = c_mode[ranked].sum()
print("Pareto list by cost (class A is taken out and acted on first)")
print(f" A {MODES[k][0]:13s} {MODES[k][1]:22s} {n_mode[k]:2d} events "
f"repair {c_mode[k]:,.0f} not ranked by cost")
for r, k in enumerate(ranked, start=1):
print(f" {r:2d} {MODES[k][0]:13s} {MODES[k][1]:22s} {n_mode[k]:2d} events "
f"{c_mode[k]:8,.0f} {100 * c_mode[k] / ranked_total:5.1f} % "
f"cumulative {100 * cum / ranked_total:5.1f} %")
print(f" ranked cost {ranked_total:,.0f}; the top three modes: "
f"{100 * c_mode[top3].sum() / ranked_total:.1f} % of the cost, "
f"{n_mode[top3].sum()} of {n_mode[ranked].sum()} events")
by_count = [k for k in np.argsort(-n_mode, kind="stable")][:3]
print(" top three by number of events: " + ", ".join(
f"{MODES[k][1]} ({n_mode[k]}, {100 * c_mode[k] / ranked_total:.1f} % of the cost)"
print("What one year cannot show: the model behind the record")
order_true = sorted(range(len(MODES)), key=lambda k: -true_cost(k))
print(f" {MODES[k][0]:13s} {MODES[k][1]:22s} expected {MODES[k][3]:5.2f} a year, "
f"{true_cost(k):8,.0f} a year; in the record {n_mode[k]:2d}, {c_mode[k]:8,.0f}")
true_total = sum(true_cost(k) for k in range(len(MODES)))
sims = np.array([sum(e[3] for e in site_year(s)) for s in range(1000, 6000)])
print(f" expected cost of unreliability {true_total:,.0f} a year; in 5,000 generated years "
f"80 % lie between {np.percentile(sims, 10):,.0f} and {np.percentile(sims, 90):,.0f}")
# ---------- Application 2: the indicators ----------
print("\nApplication 2: indicators for the year")
ev = [e for e in events if MODES[e[1]][0] == m]
stop = sum(e[2] for e in ev)
mtbf = RUN_HOURS[m] / len(ev) if ev else float("nan")
print(f" {m:13s} {len(ev):2d} failures in {RUN_HOURS[m]:,.0f} hours: "
f"MTBF {mtbf:,.0f} h, stopped {stop:.1f} h, "
f"availability {1 - stop / YEAR:.5f}")
print(f" {m:13s} {len(ev)} of {TESTS[m]} tests found a fault: "
f"{TESTS[m] - len(ev)} of {TESTS[m]} good starts")
n1 = sum(1 for e in events if MODES[e[1]][0] == "Compressor 1")
print(f" Compressor 1, 90 % interval for the MTBF from {n1} failures: "
f"{2 * YEAR / chi2.ppf(0.95, 2 * n1 + 2):,.0f} to {2 * YEAR / chi2.ppf(0.05, 2 * n1):,.0f} h")
unplanned = sum(MODES[e[1]][6] for e in events)
print(f" cost of unreliability: {total:,.0f} (ranked modes {ranked_total:,.0f})")
print(f" technician hours: unplanned {unplanned:.1f}, planned {PLANNED_HOURS:.0f}, "
f"planned share {100 * PLANNED_HOURS / (PLANNED_HOURS + unplanned):.1f} %")
print(f" unplanned events: {len(events)}, one in {350 / len(events):.1f} days")
print("Did an action work? Chance of so good a year with no real change")
for name, after in (("Bearing failure", 1), ("Bearing failure", 0),
("Belt runs off centre", 6), ("Belt runs off centre", 4)):
base = n_mode[[m[1] for m in MODES].index(name)]
what = "none" if after == 0 else f"{after} or fewer"
print(f" {name:21s} {base:2d} in this year, {what} in the next: "
f"{poisson.cdf(after, base):.3f}")
print(f" bearings over three years, 6 expected, 2 or fewer: {poisson.cdf(2, 6):.3f}")
# ---------- Plot ----------
fig, ax = plt.subplots(figsize=(9, 5))
labels = [MODES[k][1] for k in ranked]
ax.bar(range(len(ranked)), c_mode[ranked])
ax.set_xticks(range(len(ranked)))
ax.set_xticklabels(labels, rotation=60, ha="right")
ax.set_ylabel("cost in the year (currency units)")
ax2.plot(range(len(ranked)), 100 * np.cumsum(c_mode[ranked]) / ranked_total,
color="black", marker="o")
ax2.set_ylabel("cumulative share (%)")
ax.set_title("Pareto list of failure modes by cost, one year")
fig.savefig("programme_from_records.png", dpi=120)
print("Saved programme_from_records.png")