← Back to case study

PROJECT 051 · PYTHON SOURCE

Random-variable negative controls

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': 51, 'dataset': 'energy', 'title': 'Random-variable negative controls', 'question': 'How do source-supplied random controls compare with measured variables in an association screen?', 'method': 'Rank correlations for declared controls and selected real measurements; audit control duplication.', 'action': 'Use negative controls to question apparent signals before selecting features.', 'limitations': 'Measurements come from one home over a limited period. Energy is Wh per recorded 10-minute interval. This is not a representative household sample; tariffs and occupancy labels are unavailable. '}

def analyze():
    df = load('energy').copy()
    t=associations(df,'appliances',['rv1','rv2','t1','rh_1','t_out','lights'])
    control=pd.DataFrame([{'check':'rv1 equals rv2','matching_rows':int(df.rv1.eq(df.rv2).sum()),'total_rows':len(df)}])
    out=result(t,'feature','spearman_rho','Spearman correlation','rv1 and rv2 are explicitly source-generated random controls, not physical measurements. The remaining energy and sensor observations are real.',extra={'control_audit':control})
    return out

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