← Back to case study

PROJECT 054 · PYTHON SOURCE

Monitoring outage duration

Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.

Download Python file ↓
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute

META = {'id': 54, 'dataset': 'air', 'title': 'Monitoring outage duration', 'question': 'How long are the longest consecutive missing runs in each monitoring channel?', 'method': 'Complete hourly timeline and consecutive missing-run lengths.', 'action': 'Distinguish short intermittent gaps from extended periods unsuitable for calibration.', 'limitations': 'The -200 sentinel is treated as missing. Reference instruments have incomplete coverage; comparisons use paired observations. Sensor calibration is retrospective, not a health or regulatory compliance assessment. '}

def analyze():
    df = load('air').copy()
    d=df.set_index('timestamp').reindex(pd.date_range(df.timestamp.min(),df.timestamp.max(),freq='h'))
    rows=[]
    for col in ['co_gt','nmhc_gt','nox_gt','no2_gt',*AIR_SENSORS[:5]]:
        absent=d[col].isna();runs=absent.groupby((absent!=absent.shift()).cumsum()).sum()
        rows.append({'field':col,'missing_hours':int(absent.sum()),'longest_missing_hours':int(runs.max())})
    t=pd.DataFrame(rows)
    out=result(t,'field','longest_missing_hours','Consecutive hours','This measures unavailable readings, not a verified device outage cause.')
    return out

if __name__ == "__main__":
    execute(Path(__file__).parent, META, analyze)