September 2025 pump inspection priorities

Summary

Inspect P-02 first after three vibration episodes reached danger, peaking at 7.89 mm/s RMS. Inspect P-03 for 24 days of rising daily median vibration in sensor_readings.parquet.

P-02 peak vibration

7.89 mm/s RMS

Maximum of valid running vibration readings. This measure has no ratio components.

P-03 sustained rise

24 days

Elapsed calendar days between September 6 and 30, during which the daily running median rose at every daily comparison. This measure has no ratio components.

P-03 peak vibration

4.4 mm/s RMS

Maximum of valid running vibration readings. This measure has no ratio components.

P-04 missing running vibration

54 readings

Count of running records with a null RMS vibration value on September 10. This measure has no ratio components.

P-03 rose for more than two weeks. P-01 stepped down on September 20.
Only P-02 reached alarm or danger. P-03 first reached caution on September 12.

Charts

Which pumps show sustained changes in running vibration?

daily_vibration · n = 31416

Excluded 3144 · 3,090 stopped readings and 54 running readings with missing vibration.

Which pumps show sustained changes in running vibration?
Observation
120 daily medians use 31,416 five-minute readings from sensor_readings.parquet, rows 1–34,560. The chart shows vibration in mm/s RMS. 3,090 stopped readings and 54 running readings with missing vibration.
Domain interpretation
P-03 rose for more than two weeks. P-01 stepped down on September 20.

When did individual readings breach operating limits?

raw_vibration · n = 31416

Excluded 3144 · 3,090 stopped readings and 54 running readings with missing vibration.

When did individual readings breach operating limits?
Observation
All 31,416 valid operating vibration readings from sensor_readings.parquet, rows 1–34,560, are plotted as dots. 3,090 stopped readings and 54 running readings with missing vibration. Dashed lines mark 2.8, 4.5 and 7.1 mm/s RMS.
Domain interpretation
Only P-02 reached alarm or danger. P-03 first reached caution on September 12.

How did P-02 current behave during its three vibration alarms?

burst_current · n = 60

Excluded 34500 · 34,500 readings outside the three P-02 alarm windows.

How did P-02 current behave during its three vibration alarms?
Observation
60 steady readings at sensor_readings.parquet rows 9615–9633, 11993–12016, 15284–15300 span 28.8–43.2 A. The shaded band is the exploratory 31.53425–40.47675 A range. All 34,500 other readings are outside these windows.
Domain interpretation
Steady current moved above and below its usual range during all three vibration episodes.

Assumptions & limitations

  • All 34,560 records decoded with seven typed fields, four equal row groups and no unread data. The file has matching PAR1 signatures, zero duplicate rows, zero duplicate pump timestamps, zero missing time slots and consistent unit fields. Current and timestamp fields have zero missing values. There are 210 blank commands and 54 blank vibration values across 264 distinct rows.
  • P-02 is the first inspection priority. Review the September 17 stop with the operating log, as only P-02 was stopped from 10:00 through 11:25 local time (18 readings, rows 13,369–13,386). The records establish no cause for the stop or for the earlier and later vibration episodes.
  • P-02 Sep 04, 09:10–10:40 had 19 alarm-or-higher readings, of which 8 reached danger. sensor_readings.parquet rows 9615–9633.
  • P-02 Sep 12, 15:20–17:15 had 24 alarm-or-higher readings, of which 9 reached danger. sensor_readings.parquet rows 11993–12016.
  • P-02 Sep 24, 01:35–02:55 had 17 alarm-or-higher readings, of which 7 reached danger. sensor_readings.parquet rows 15284–15300.
  • P-03 warrants inspection under the two-week rule. The daily running median increased at every daily comparison from September 6 through September 30. The first caution reading was September 12 at 01:00 (row 20,461). Daily medians stayed above caution from September 15 to 30. The peak was 4.397506 mm/s RMS.
  • Verify the P-01 vibration channel and check for any known work at the September 20 midnight change. Rows 5,472–5,473 show the step from 2.048109 to 0.080460 mm/s RMS between consecutive readings. Stable running current makes the low values worth validating with an independent reading.
  • P-04 shows no inspection trigger in the available readings. The vibration channel was unobserved September 10, 11:15–15:40, during 54 running samples. Check that data gap.
  • Vibration thresholds are inclusive and counts are cumulative. Limits apply to all running vibration samples, including restarts. Consecutive breach windows use five-minute adjacency. Window endpoints are sample times.
  • The first 10 minutes are represented by elapsed times of 0 and 5 minutes after each observed stopped-to-running transition. September opens with all pumps already recorded as running, with earlier restart history unavailable.
  • Current flags use each pump’s September steady 25th and 75th percentiles and three interquartile ranges on each side. These screening results carry no engineering limit or diagnosis. Daily medians summarize trend using available operating readings on each local date.
  • A separate distribution view and all-month correlation were omitted because the maintenance decisions depend on the timing of changes and the current excursions during alarms.

Ambiguity log

IDItemStatusAnswer
A01Domain and business processresolvedUser describes four pumps with motor current and vibration readings.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560
A02Maintenance decisionresolvedIdentify September abnormal operation and prioritize next week’s inspection.
Evidence and options
file_evidence
  • User request
A03Row grainresolvedOne observed pump and timestamp per record, at a complete five-minute cadence.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560
A04Units and operating eligibilityresolvedSource field names establish A and mm/s RMS. User confirmed 1 is running and the fallback cutoff is strictly above 20% of rated current where command is blank. Ratings are 42 A and 31 A for P-01 and P-04.
Evidence and options
file_evidence
  • sensor_readings.parquet rows 7,750–7,851 and 29,635–29,742
A05Time basisresolvedFull timestamp coverage in Asia/Seoul establishes the local September 2025 calendar window.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560
A06Vibration and restart exceptionsresolvedUser set caution, alarm and danger thresholds and the two-week inspection rule. User specified a 10-minute inrush exclusion for current.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560
A06aEngineering limits for steady currentunresolvedUser does not have current limits. Pump-specific statistical screening supports inspection triage.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560
affects
  • Interpretation of statistical current flags
A07Missing measurementsresolvedMissing vibration remains unobserved. User resolved command gaps with the current fallback.
Evidence and options
file_evidence
  • sensor_readings.parquet rows 28,648–28,701, plus blank-command windows in A04
A08Join keysnot_applicableOne Parquet table, no join.
Evidence and options
file_evidence
  • sensor_readings.parquet row groups 0–3, rows 1–34,560

Data overview

datasets
  • id
    parquet:1
    format
    parquet
    read_ranges
    • sensor_readings.parquet row groups 0–3, rows 1–34,560 (PAR1 file and footer signatures, schema field names)
    rows
    34560
    columns
    7
row_grain
One source observation per pump every 5 minutes from September 1 00:00 through September 30 23:55 in Asia/Seoul.

Metrics

MetricValueDefinitionNumeratorDenominatorConditionSources
P-01 running readings7,872 readingsOperating state classified from command, with the agreed current fallback for blank commands. This measure has no ratio components.
  • sensor_readings.parquet rows 1–8640
P-01 at or above caution0 %Share of valid running vibration readings at or above 2.8 mm/s RMS in September 2025.07,872
  • sensor_readings.parquet rows 1–1704, 1801–1992, 2089–3720, 3817–4008, 4105–5736, 5833–6024, 6121–7752, 7849–8040, 8137–8640
P-01 at or above alarm0 %Share of valid running vibration readings at or above 4.5 mm/s RMS in September 2025.07,872
  • sensor_readings.parquet rows 1–1704, 1801–1992, 2089–3720, 3817–4008, 4105–5736, 5833–6024, 6121–7752, 7849–8040, 8137–8640
P-01 at or above danger0 %Share of valid running vibration readings at or above 7.1 mm/s RMS in September 2025.07,872
  • sensor_readings.parquet rows 1–1704, 1801–1992, 2089–3720, 3817–4008, 4105–5736, 5833–6024, 6121–7752, 7849–8040, 8137–8640
P-01 peak vibration2.3 mm/s RMSMaximum of valid running vibration readings. This measure has no ratio components.
  • sensor_readings.parquet rows 3379
P-01 unusual steady current0 %Share of steady readings outside the September pump-specific outer Tukey fences (36.92500–47.08375 A).07,856
  • sensor_readings.parquet rows 1–1704, 1803–1992, 2091–3720, 3819–4008, 4107–5736, 5835–6024, 6123–7752, 7851–8040, 8139–8640
P-02 running readings7,854 readingsOperating state classified from command, with the agreed current fallback for blank commands. This measure has no ratio components.
  • sensor_readings.parquet rows 8641–17280
P-02 at or above caution0.7639 %Share of valid running vibration readings at or above 2.8 mm/s RMS in September 2025.607,854
  • sensor_readings.parquet rows 8641–10344, 10441–10632, 10729–12360, 12457–12648, 12745–13368, 13387–14376, 14473–14664, 14761–16392, 16489–16680, 16777–17280
P-02 at or above alarm0.7639 %Share of valid running vibration readings at or above 4.5 mm/s RMS in September 2025.607,854
  • sensor_readings.parquet rows 8641–10344, 10441–10632, 10729–12360, 12457–12648, 12745–13368, 13387–14376, 14473–14664, 14761–16392, 16489–16680, 16777–17280
P-02 at or above danger0.3056 %Share of valid running vibration readings at or above 7.1 mm/s RMS in September 2025.247,854
  • sensor_readings.parquet rows 8641–10344, 10441–10632, 10729–12360, 12457–12648, 12745–13368, 13387–14376, 14473–14664, 14761–16392, 16489–16680, 16777–17280
P-02 peak vibration7.89 mm/s RMSMaximum of valid running vibration readings. This measure has no ratio components.
  • sensor_readings.parquet rows 9631
P-02 unusual steady current0.5615 %Share of steady readings outside the September pump-specific outer Tukey fences (31.53425–40.47675 A).447,836
  • sensor_readings.parquet rows 8641–10344, 10443–10632, 10731–12360, 12459–12648, 12747–13368, 13389–14376, 14475–14664, 14763–16392, 16491–16680, 16779–17280
P-03 running readings7,872 readingsOperating state classified from command, with the agreed current fallback for blank commands. This measure has no ratio components.
  • sensor_readings.parquet rows 17281–25920
P-03 at or above caution53.72 %Share of valid running vibration readings at or above 2.8 mm/s RMS in September 2025.4,2297,872
  • sensor_readings.parquet rows 17281–18984, 19081–19272, 19369–21000, 21097–21288, 21385–23016, 23113–23304, 23401–25032, 25129–25320, 25417–25920
P-03 at or above alarm0 %Share of valid running vibration readings at or above 4.5 mm/s RMS in September 2025.07,872
  • sensor_readings.parquet rows 17281–18984, 19081–19272, 19369–21000, 21097–21288, 21385–23016, 23113–23304, 23401–25032, 25129–25320, 25417–25920
P-03 at or above danger0 %Share of valid running vibration readings at or above 7.1 mm/s RMS in September 2025.07,872
  • sensor_readings.parquet rows 17281–18984, 19081–19272, 19369–21000, 21097–21288, 21385–23016, 23113–23304, 23401–25032, 25129–25320, 25417–25920
P-03 peak vibration4.4 mm/s RMSMaximum of valid running vibration readings. This measure has no ratio components.
  • sensor_readings.parquet rows 25858
P-03 unusual steady current0 %Share of steady readings outside the September pump-specific outer Tukey fences (42.20200–53.81675 A).07,856
  • sensor_readings.parquet rows 17281–18984, 19083–19272, 19371–21000, 21099–21288, 21387–23016, 23115–23304, 23403–25032, 25131–25320, 25419–25920
P-04 running readings7,872 readingsOperating state classified from command, with the agreed current fallback for blank commands. This measure has no ratio components.
  • sensor_readings.parquet rows 25921–34560
P-04 at or above caution0 %Share of valid running vibration readings at or above 2.8 mm/s RMS in September 2025.07,818
  • sensor_readings.parquet rows 25921–27624, 27721–27912, 28009–28647, 28702–29640, 29737–29928, 30025–31656, 31753–31944, 32041–33672, 33769–33960, 34057–34560
P-04 at or above alarm0 %Share of valid running vibration readings at or above 4.5 mm/s RMS in September 2025.07,818
  • sensor_readings.parquet rows 25921–27624, 27721–27912, 28009–28647, 28702–29640, 29737–29928, 30025–31656, 31753–31944, 32041–33672, 33769–33960, 34057–34560
P-04 at or above danger0 %Share of valid running vibration readings at or above 7.1 mm/s RMS in September 2025.07,818
  • sensor_readings.parquet rows 25921–27624, 27721–27912, 28009–28647, 28702–29640, 29737–29928, 30025–31656, 31753–31944, 32041–33672, 33769–33960, 34057–34560
P-04 peak vibration2.4 mm/s RMSMaximum of valid running vibration readings. This measure has no ratio components.
  • sensor_readings.parquet rows 32096
P-04 unusual steady current0 %Share of steady readings outside the September pump-specific outer Tukey fences (27.18700–34.79600 A).07,856
  • sensor_readings.parquet rows 25921–27624, 27723–27912, 28011–29640, 29739–29928, 30027–31656, 31755–31944, 32043–33672, 33771–33960, 34059–34560
P-02 peak on Sep 047.89 mm/s RMSMaximum operating RMS vibration within the consecutive five-minute alarm readings at 09:10–10:40 local time. This measure has no ratio components.
  • sensor_readings.parquet rows 9615–9633
P-02 danger share during Sep 04 alarm42.11 %Share of consecutive alarm-or-higher readings at or above 7.1 mm/s RMS during 09:10–10:40 local time.819
  • sensor_readings.parquet rows 9615–9633
P-02 peak on Sep 127.79 mm/s RMSMaximum operating RMS vibration within the consecutive five-minute alarm readings at 15:20–17:15 local time. This measure has no ratio components.
  • sensor_readings.parquet rows 11993–12016
P-02 danger share during Sep 12 alarm37.5 %Share of consecutive alarm-or-higher readings at or above 7.1 mm/s RMS during 15:20–17:15 local time.924
  • sensor_readings.parquet rows 11993–12016
P-02 peak on Sep 247.79 mm/s RMSMaximum operating RMS vibration within the consecutive five-minute alarm readings at 01:35–02:55 local time. This measure has no ratio components.
  • sensor_readings.parquet rows 15284–15300
P-02 danger share during Sep 24 alarm41.18 %Share of consecutive alarm-or-higher readings at or above 7.1 mm/s RMS during 01:35–02:55 local time.717
  • sensor_readings.parquet rows 15284–15300
P-01 median vibration, September 1–192.1 mm/s RMSMedian among 5,088 valid running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 1–1704, 1801–1992, 2089–3720, 3817–4008, 4105–5472
P-01 median steady current, September 1–1941.98 AMedian among 5,080 steady-running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 1–1704, 1803–1992, 2091–3720, 3819–4008, 4107–5472
P-01 median vibration, September 20–300.08293 mm/s RMSMedian among 2,784 valid running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 5473–5736, 5833–6024, 6121–7752, 7849–8040, 8137–8640
P-01 median steady current, September 20–3042.01 AMedian among 2,776 steady-running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 5473–5736, 5835–6024, 6123–7752, 7851–8040, 8139–8640
P-03 sustained rise24 daysElapsed calendar days between September 6 and 30, during which the daily running median rose at every daily comparison. This measure has no ratio components.
  • sensor_readings.parquet rows 18721–18984, 19081–19272, 19369–21000, 21097–21288, 21385–23016, 23113–23304, 23401–25032, 25129–25320, 25417–25920
P-03 daily median on 2025-09-051.99 mm/s RMSMedian of 288 valid running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 18433–18720
P-03 daily median on 2025-09-062.09 mm/s RMSMedian of 264 valid running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 18721–18984
P-03 daily median on 2025-09-304.2 mm/s RMSMedian of 288 valid running readings. This measure has no ratio components.
  • sensor_readings.parquet rows 25633–25920
P-04 missing running vibration54 readingsCount of running records with a null RMS vibration value on September 10. This measure has no ratio components.
  • sensor_readings.parquet rows 28648–28701
Restart current readings set aside66 readingsCurrent readings at the first observed restart sample and five minutes later across 33 observed restarts. This measure has no ratio components.
  • sensor_readings.parquet rows 1801–1802, 2089–2090, 3817–3818, 4105–4106, 5833–5834, 6121–6122, 7849–7850, 8137–8138, 10441–10442, 10729–10730, 12457–12458, 12745–12746, 13387–13388, 14473–14474, 14761–14762, 16489–16490, 16777–16778, 19081–19082, 19369–19370, 21097–21098, 21385–21386, 23113–23114, 23401–23402, 25129–25130, 25417–25418, 27721–27722, 28009–28010, 29737–29738, 30025–30026, 31753–31754, 32041–32042, 33769–33770, 34057–34058
Readings with any missing field264 readingsCount across all seven source fields. No row has both command and vibration missing. This measure has no ratio components.
  • sensor_readings.parquet rows 7750–7851, 28648–28701, 29635–29742

Reproducibility

filters
  • Use all September source rows. Qualify vibration on running state and nonnull measurement. Qualify current on running state and elapsed time since observed restart.
exclusions
  • scope
    Running vibration and steady current
    source_refs
    • sensor_readings.parquet rows 1705–1800, 1993–2088, 3721–3816, 4009–4104, 5737–5832, 6025–6120, 7753–7848, 8041–8136, 10345–10440, 10633–10728, 12361–12456, 12649–12744, 13369–13386, 14377–14472, 14665–14760, 16393–16488, 16681–16776, 18985–19080, 19273–19368, 21001–21096, 21289–21384, 23017–23112, 23305–23400, 25033–25128, 25321–25416, 27625–27720, 27913–28008, 29641–29736, 29929–30024, 31657–31752, 31945–32040, 33673–33768, 33961–34056
    reason
    Stopped state.
  • scope
    Running vibration
    source_refs
    • sensor_readings.parquet rows 28648–28701
    reason
    RMS vibration is missing.
  • scope
    Steady current
    source_refs
    • sensor_readings.parquet rows 1801–1802, 2089–2090, 3817–3818, 4105–4106, 5833–5834, 6121–6122, 7849–7850, 8137–8138, 10441–10442, 10729–10730, 12457–12458, 12745–12746, 13387–13388, 14473–14474, 14761–14762, 16489–16490, 16777–16778, 19081–19082, 19369–19370, 21097–21098, 21385–21386, 23113–23114, 23401–23402, 25129–25130, 25417–25418, 27721–27722, 28009–28010, 29737–29738, 30025–30026, 31753–31754, 32041–32042, 33769–33770, 34057–34058
    reason
    The first 10 minutes after observed restart.
  • scope
    P-02 current detail figure
    source_refs
    • sensor_readings.parquet rows 1–9614, 9634–11992, 12017–15283, 15301–34560
    reason
    Outside the three P-02 vibration alarm windows.
transforms
  • input
    sensor_readings.parquet
    transform
    Assign 1-based source row positions, sort by asset and time, classify running
    output
    classified rows
    before
    34560
    after
    34560
  • input
    classified rows
    transform
    Select running rows with observed vibration
    output
    valid running vibration
    before
    34560
    after
    31416
  • input
    classified rows
    transform
    Select running rows after removing observed restart transients
    output
    steady current
    before
    34560
    after
    31404
sample_sizes
source
34560
running
31470
valid_running_vibration
31416
steady_current
31404
daily_vibration_groups
120
p02_alarm_detail
60
source_locators
  • sensor_readings.parquet row groups 0–3, rows 1–34,560; one-based physical row positions before sorting

Code

import pandas as pd
import numpy as np

d = pd.read_parquet('../sensor_readings.parquet')
d['row'] = np.arange(1, len(d) + 1)
d = d.sort_values(['asset_id', 'ts'])
g = d.groupby('asset_id')
rated = d.asset_id.map({'P-01': 42, 'P-04': 31})
assert rated[d.run_cmd.isna()].notna().all()
d['running'] = d.run_cmd.eq(1) | (d.run_cmd.isna() & d.current_a.gt(.2 * rated))
prior = g.running.shift()
starts = d.running & prior.eq(False)
latest_start = d.ts.where(starts).groupby(d.asset_id).ffill()
d['transient'] = d.running & (d.ts - latest_start).lt(pd.Timedelta(minutes=10))
d['day'] = d.ts.dt.strftime('%Y-%m-%d')
d['steady'] = d.running & ~d.transient
d['vibration'] = d.vib_rms_mm_s.where(d.running)
d['steady_current'] = d.current_a.where(d.steady)
d['caution'] = d.vibration.ge(2.8)
d['alarm'] = d.vibration.ge(4.5)
d['danger'] = d.vibration.ge(7.1)
daily = d.groupby(['asset_id','day']).agg(vib=('vibration','median'), n=('vibration','count'), amps=('steady_current','median'))
q = g.steady_current.quantile([.25,.5,.75]).unstack()
d['iqr'] = d.asset_id.map(q[.75]-q[.25])
d['lo'] = d.asset_id.map(q[.25])-3*d.iqr
d['hi'] = d.asset_id.map(q[.75])+3*d.iqr
d['current_flag'] = d.steady & ((d.current_a < d.lo) | (d.current_a > d.hi))

def episodes(mask):
    subset = d.loc[mask].copy()
    changes = subset.asset_id.ne(subset.asset_id.shift()) | subset.ts.diff().ne(pd.Timedelta(minutes=5))
    return subset.groupby(changes.cumsum()).agg(asset=('asset_id','first'), start=('ts','first'), end=('ts','last'), n=('row','size'), first=('row','first'), last=('row','last'), vib=('vibration','max'), min_a=('current_a','min'), max_a=('current_a','max'))

if __name__ == '__main__':
    print('quality',d.drop(columns='row').iloc[:,:7].isna().sum(),d.iloc[:,:7].duplicated().sum(),d.iloc[:,:7].isna().any(axis=1).sum())
    print(g[['running','steady','transient','caution','alarm','danger','current_flag']].sum())
    print(g[['vibration','steady_current']].count())
    print(d[d.run_cmd.isna()].groupby('asset_id').running.agg(['sum','size']))
    print(daily.unstack(0).round(3).to_string())
    print(q)
    print(g[['lo','hi']].first())
    for key, mask in [('caution',d.caution),('alarm',d.alarm),('danger',d.danger),('current',d.current_flag),('vibration missing',d.vib_rms_mm_s.isna()),('command missing',d.run_cmd.isna())]:
        print(key)
        print(episodes(mask).to_string(max_rows=100))
    print('peaks')
    print(d.loc[g.vibration.idxmax(),['asset_id','row','ts','vibration']])


import json
from pathlib import Path
import sys

sys.path.insert(0, '.')
from analyze import d, g, q, daily, episodes, starts

import matplotlib
import pandas as pd
matplotlib.use('Agg')
import matplotlib.dates as mdates
import matplotlib.pyplot as plt

src = 'sensor_readings.parquet'
out = Path('delivery/figures')
out.mkdir(parents=True, exist_ok=True)
assets = list(q.index)
colors = dict(zip(assets, ['#516477', '#b5412c', '#12655e', '#63769d']))
charts = []
metrics = []
n_total = len(d)

def loc(data):
    rows = sorted(data.row)
    blocks = []
    for row in rows:
        if blocks and blocks[-1][1] + 1 == row:
            blocks[-1][1] = row
        else:
            blocks.append([row, row])
    return [src + ' rows ' + ', '.join(str(a) if a == b else f'{a}–{b}' for a, b in blocks)]

def chart(id, question, columns, n, reason, observation, interpretation, type='line_time'):
    charts.append(dict(id=id, image_path=f'delivery/figures/{id}.png', type=type,
        question=question, source_columns=columns, n_used=int(n), n_excluded=int(n_total-n),
        exclusion_reason=reason, observation=observation, domain_interpretation=interpretation))

def finish(fig, id):
    fig.savefig(out / f'{id}.png', dpi=160, bbox_inches='tight', facecolor='white')
    plt.close(fig)

def metric(name, definition, value, unit, refs, num=None, den=None):
    if num is None and den is None:
        definition += ' This measure has no ratio components.'
    metrics.append(dict(name=name, definition=definition, value=None if value is None else float(value),
        unit=unit, numerator=num, denominator=den, source_refs=refs,
        depends_on_ambiguity_ids=[], condition=None))

v_ok = d.vibration.notna()
v_n = int(v_ok.sum())
stop_n = int((~d.running).sum())
v_gap = d.running & d.vibration.isna()
current_n = int(d.steady.sum())
restart_n = int(d.transient.sum())

fig, ax = plt.subplots(figsize=(10,4))
for asset in assets:
    series = daily.loc[asset, 'vib']
    ax.plot(range(1,31), series, label=asset, color=colors[asset], marker='o', markersize=3)
ax.axhline(2.8, color='#a56a15', ls='--', label='Caution')
ax.axhline(4.5, color='#a64c3e', ls='--', label='Alarm')
ax.set(xlabel='September 2025 day (Asia/Seoul)', ylabel='Daily median vibration (mm/s RMS)', xticks=[1,5,10,15,20,25,30], ylim=(0,4.8))
ax.legend(ncol=3, loc='lower left', bbox_to_anchor=(0,1.01), frameon=False)
ax.grid(axis='y', alpha=.2)
finish(fig, 'daily_vibration')
v_reason = f'{stop_n:,} stopped readings and {int(v_gap.sum())} running readings with missing vibration.'
chart('daily_vibration', 'Which pumps show sustained changes in running vibration?', ['asset_id','ts','vib_rms_mm_s','run_cmd','current_a'], v_n, v_reason,
    f'120 daily medians use {v_n:,} five-minute readings from {src}, rows 1–34,560. The chart shows vibration in mm/s RMS. {v_reason}',
    'P-03 rose for more than two weeks. P-01 stepped down on September 20.')

fig, axes = plt.subplots(4, 1, figsize=(10,8), sharex=True, sharey=True)
for asset, ax in zip(assets, axes):
    sub = d[d.asset_id.eq(asset) & v_ok]
    ax.scatter(sub.ts, sub.vibration, s=3, alpha=.55, color=colors[asset], linewidth=0)
    for threshold in (2.8,4.5,7.1):
        ax.axhline(threshold, color='#a56a39', linewidth=.6, ls='--')
    ax.set_title(asset, loc='left', fontsize=10)
    ax.set_ylim(0,8.3)
axes[-1].xaxis.set_major_formatter(mdates.DateFormatter('%b %d', tz=d.ts.dt.tz))
axes[-1].set_xlabel('Local time (Asia/Seoul)')
fig.supylabel('Running vibration (mm/s RMS)')
fig.tight_layout()
finish(fig, 'raw_vibration')
chart('raw_vibration','When did individual readings breach operating limits?', ['asset_id','ts','vib_rms_mm_s','run_cmd','current_a'],v_n,v_reason,
    f'All {v_n:,} valid operating vibration readings from {src}, rows 1–34,560, are plotted as dots. {v_reason} Dashed lines mark 2.8, 4.5 and 7.1 mm/s RMS.',
    'Only P-02 reached alarm or danger. P-03 first reached caution on September 12.', 'scatter')

alarm = episodes(d.alarm)
p2 = d[d.asset_id.eq('P-02')]
fig, axes = plt.subplots(1, len(alarm), figsize=(12,3), sharey=True)
plotted = []
for event, ax in zip(alarm.itertuples(), axes):
    sub = p2[p2.steady & p2.ts.between(event.start,event.end)]
    plotted.append(sub)
    ax.plot(sub.ts, sub.current_a, marker='o', markersize=3, color=colors['P-02'])
    ax.axhspan(sub.lo.iloc[0],sub.hi.iloc[0],color='#bdd5ce',alpha=.45)
    ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0,30], tz=d.ts.dt.tz))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M', tz=d.ts.dt.tz))
    ax.set_title(event.start.strftime('%b %d'))
axes[0].set_ylabel('P-02 steady current (A)')
fig.supxlabel('Local time (Asia/Seoul)')
fig.tight_layout()
finish(fig,'burst_current')
n_burst = sum(map(len,plotted))
chart('burst_current','How did P-02 current behave during its three vibration alarms?', ['asset_id','ts','current_a','vib_rms_mm_s','run_cmd'],n_burst,
    f'{n_total-n_burst:,} readings outside the three P-02 alarm windows.',
    f'{n_burst} steady readings at {loc(pd.concat(plotted))[0]} span 28.8–43.2 A. The shaded band is the exploratory 31.53425–40.47675 A range. All {n_total-n_burst:,} other readings are outside these windows.',
    'Steady current moved above and below its usual range during all three vibration episodes.')

for asset, sub in g:
    run = sub[sub.running]
    vib = sub[sub.vibration.notna()]
    steady = sub[sub.steady]
    metric(asset+' running readings','Operating state classified from command, with the agreed current fallback for blank commands.',len(run),'readings',loc(sub))
    for key, label, threshold in [('caution','caution',2.8),('alarm','alarm',4.5),('danger','danger',7.1)]:
        count = int(sub[key].sum())
        metric(f'{asset} at or above {label}',f'Share of valid running vibration readings at or above {threshold} mm/s RMS in September 2025.',
            100*count/len(vib),'%',loc(vib),count,len(vib))
    metric(asset+' peak vibration','Maximum of valid running vibration readings.',vib.vibration.max(),'mm/s RMS',loc(vib.loc[[vib.vibration.idxmax()]]))
    count = int(sub.current_flag.sum())
    lo, hi = steady[['lo','hi']].iloc[0]
    metric(asset+' unusual steady current',f'Share of steady readings outside the September pump-specific outer Tukey fences ({lo:.5f}–{hi:.5f} A).',
        100*count/len(steady),'%',loc(steady),count,len(steady))

notes = []
for row in alarm.itertuples():
    sub = d.loc[d.row.between(row.first,row.last)]
    label = row.start.strftime('%b %d')
    window = row.start.strftime('%H:%M') + '–' + row.end.strftime('%H:%M')
    notes.append(f'P-02 {label}, {window} had {row.n} alarm-or-higher readings, of which {int(sub.danger.sum())} reached danger. {loc(sub)[0]}.')
    metric(f'P-02 peak on {label}',f'Maximum operating RMS vibration within the consecutive five-minute alarm readings at {window} local time.',row.vib,'mm/s RMS',loc(sub))
    metric(f'P-02 danger share during {label} alarm',f'Share of consecutive alarm-or-higher readings at or above 7.1 mm/s RMS during {window} local time.',100*int(sub.danger.sum())/row.n,'%',loc(sub),int(sub.danger.sum()),row.n)

p1 = d[d.asset_id.eq('P-01')]
before = p1[p1.day.lt('2025-09-20')]
after = p1[p1.day.ge('2025-09-20')]
for suffix, sub in [('September 1–19',before),('September 20–30',after)]:
    vib = sub[sub.vibration.notna()]
    steady = sub[sub.steady]
    metric('P-01 median vibration, '+suffix,f'Median among {len(vib):,} valid running readings.',vib.vibration.median(),'mm/s RMS',loc(vib))
    metric('P-01 median steady current, '+suffix,f'Median among {len(steady):,} steady-running readings.',steady.steady_current.median(),'A',loc(steady))

p3 = d[d.asset_id.eq('P-03')]
trend = daily.loc['P-03','vib'].loc['2025-09-06':]
assert trend.diff().dropna().gt(0).all()
metric('P-03 sustained rise','Elapsed calendar days between September 6 and 30, during which the daily running median rose at every daily comparison.',len(trend)-1,'days',loc(p3[p3.day.ge('2025-09-06') & p3.running]))
for day in ('2025-09-05','2025-09-06','2025-09-30'):
    s = p3[p3.day.eq(day) & p3.running]
    metric(f'P-03 daily median on {day}',f'Median of {len(s)} valid running readings.',s.vibration.median(),'mm/s RMS',loc(s))
metric('P-04 missing running vibration','Count of running records with a null RMS vibration value on September 10.',int(v_gap.sum()),'readings',loc(d[v_gap]))
metric('Restart current readings set aside','Current readings at the first observed restart sample and five minutes later across 33 observed restarts.',restart_n,'readings',loc(d[d.transient]))
metric('Readings with any missing field','Count across all seven source fields. No row has both command and vibration missing.',int(d.iloc[:,:7].isna().any(axis=1).sum()),'readings',loc(d[d.iloc[:,:7].isna().any(axis=1)]))

all_ref = src+' row groups 0–3, rows 1–34,560'
def ambiguity(id,item,status,evidence,answer,affects,candidates=(),question=None):
    return dict(id=id, checklist_item=item, status=status, file_evidence=[evidence],
        answer=answer, affects=affects, candidates=list(candidates),question=question)

logs = [
    ambiguity('A01','Domain and business process','resolved',all_ref,'User describes four pumps with motor current and vibration readings.',[]),
    ambiguity('A02','Maintenance decision','resolved','User request','Identify September abnormal operation and prioritize next week’s inspection.',[]),
    ambiguity('A03','Row grain','resolved',all_ref,'One observed pump and timestamp per record, at a complete five-minute cadence.',[]),
    ambiguity('A04','Units and operating eligibility','resolved',src+' rows 7,750–7,851 and 29,635–29,742','Source field names establish A and mm/s RMS. User confirmed 1 is running and the fallback cutoff is strictly above 20% of rated current where command is blank. Ratings are 42 A and 31 A for P-01 and P-04.',[]),
    ambiguity('A05','Time basis','resolved',all_ref,'Full timestamp coverage in Asia/Seoul establishes the local September 2025 calendar window.',[]),
    ambiguity('A06','Vibration and restart exceptions','resolved',all_ref,'User set caution, alarm and danger thresholds and the two-week inspection rule. User specified a 10-minute inrush exclusion for current.',[]),
    ambiguity('A06a','Engineering limits for steady current','unresolved',all_ref,'User does not have current limits. Pump-specific statistical screening supports inspection triage.', ['Interpretation of statistical current flags']),
    ambiguity('A07','Missing measurements','resolved',src+' rows 28,648–28,701, plus blank-command windows in A04','Missing vibration remains unobserved. User resolved command gaps with the current fallback.',[]),
    ambiguity('A08','Join keys','not_applicable',all_ref,'One Parquet table, no join.',[]),
]

scope_quality = (f'All {n_total:,} records decoded with seven typed fields, four equal row groups and no unread data. '
    'The file has matching PAR1 signatures, zero duplicate rows, zero duplicate pump timestamps, zero missing time slots and consistent unit fields. '
    'Current and timestamp fields have zero missing values. There are 210 blank commands and 54 blank vibration values across 264 distinct rows.')
assumptions = [
    scope_quality,
    'P-02 is the first inspection priority. Review the September 17 stop with the operating log, as only P-02 was stopped from 10:00 through 11:25 local time (18 readings, rows 13,369–13,386). The records establish no cause for the stop or for the earlier and later vibration episodes.',
    *notes,
    'P-03 warrants inspection under the two-week rule. The daily running median increased at every daily comparison from September 6 through September 30. The first caution reading was September 12 at 01:00 (row 20,461). Daily medians stayed above caution from September 15 to 30. The peak was 4.397506 mm/s RMS.',
    'Verify the P-01 vibration channel and check for any known work at the September 20 midnight change. Rows 5,472–5,473 show the step from 2.048109 to 0.080460 mm/s RMS between consecutive readings. Stable running current makes the low values worth validating with an independent reading.',
    'P-04 shows no inspection trigger in the available readings. The vibration channel was unobserved September 10, 11:15–15:40, during 54 running samples. Check that data gap.',
    'Vibration thresholds are inclusive and counts are cumulative. Limits apply to all running vibration samples, including restarts. Consecutive breach windows use five-minute adjacency. Window endpoints are sample times.',
    'The first 10 minutes are represented by elapsed times of 0 and 5 minutes after each observed stopped-to-running transition. September opens with all pumps already recorded as running, with earlier restart history unavailable.',
    'Current flags use each pump’s September steady 25th and 75th percentiles and three interquartile ranges on each side. These screening results carry no engineering limit or diagnosis. Daily medians summarize trend using available operating readings on each local date.',
    'A separate distribution view and all-month correlation were omitted because the maintenance decisions depend on the timing of changes and the current excursions during alarms.',
]
spec = dict(title='September 2025 pump inspection priorities',language='en',
    headline='Inspect P-02 first after three vibration episodes reached danger, peaking at 7.89 mm/s RMS. Inspect P-03 for 24 days of rising daily median vibration in sensor_readings.parquet.',
    kpis=['P-02 peak vibration','P-03 sustained rise','P-03 peak vibration','P-04 missing running vibration'],
    key_charts=['daily_vibration','raw_vibration'],
    insights=[
        dict(text='P-02 had 60 alarm-or-higher readings, including 24 at danger, across September 4, 12 and 24.',source=loc(d[d.alarm])[0]),
        dict(text='P-01 median running vibration fell from 2.101 to 0.083 mm/s RMS on either side of September 20. Verify the vibration channel.',source=src+' rows 1–8,640'),
        dict(text='P-04 peaked at 2.40 mm/s RMS. Its 54-record vibration gap on September 10 leaves part of the run unassessed.',source=src+' rows 28,648–28,701 and 32,096')],
    data_overview=dict(datasets=[dict(id='parquet:1',format='parquet',read_ranges=[all_ref+' (PAR1 file and footer signatures, schema field names)'],unread=[],rows=n_total,columns=7)],
        row_grain='One source observation per pump every 5 minutes from September 1 00:00 through September 30 23:55 in Asia/Seoul.'),
    ambiguity_log=logs, charts=charts, metrics=metrics, assumptions_limitations=assumptions,
    reproducibility=dict(filters=['Use all September source rows. Qualify vibration on running state and nonnull measurement. Qualify current on running state and elapsed time since observed restart.'],
        exclusions=[dict(scope='Running vibration and steady current',source_refs=loc(d[~d.running]),reason='Stopped state.'),
            dict(scope='Running vibration',source_refs=loc(d[v_gap]),reason='RMS vibration is missing.'),
            dict(scope='Steady current',source_refs=loc(d[d.transient]),reason='The first 10 minutes after observed restart.'),
            dict(scope='P-02 current detail figure',source_refs=loc(d[~d.row.isin(pd.concat(plotted).row)]),reason='Outside the three P-02 vibration alarm windows.')],
        transforms=[
            dict(input=src,transform='Assign 1-based source row positions, sort by asset and time, classify running',output='classified rows',before=n_total,after=n_total),
            dict(input='classified rows',transform='Select running rows with observed vibration',output='valid running vibration',before=n_total,after=v_n),
            dict(input='classified rows',transform='Select running rows after removing observed restart transients',output='steady current',before=n_total,after=current_n)],
        sample_sizes=dict(source=n_total,running=int(d.running.sum()),valid_running_vibration=v_n,steady_current=current_n,daily_vibration_groups=len(daily),p02_alarm_detail=n_burst),
        source_locators=[all_ref+'; one-based physical row positions before sorting'],
        code=Path('analyze.py').read_text()+'\n\n'+Path('report.py').read_text()))
Path('report-spec.json').write_text(json.dumps(spec,ensure_ascii=False,indent=2))