"""QuantumCleanse 2026 — reproducible numerical research suite.

Exohood Labs' computational reassessment of its April 2024 lunar-water concept.
The accompanying README credits Helios (Exania) as the scientific knowledge
analysis model used in the research workflow. This Python program separately
implements the numerical modelling and machine-learning experiments with
NumPy, SciPy and scikit-learn. It is not the Helios model itself.

Every output is a conditional simulation based on explicitly stated
assumptions, not an experimental measurement or potability certification.
Running the suite generates results_2026.json with the same 16 analyses.
"""
import json, time, itertools, warnings
import numpy as np
from scipy.stats import norm, spearmanr
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier, IsolationForest
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, recall_score, precision_score, roc_auc_score, brier_score_loss
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern, ConstantKernel
warnings.filterwarnings('ignore')
SEED = 2026
rng = np.random.default_rng(SEED)
SIGMA = 5.670374419e-08
R = 8.314

def r(x, n=3):
    if isinstance(x, (np.floating, float)):
        return round(float(x), n)
    if isinstance(x, (np.integer,)):
        return int(x)
    return x

def pct(a):
    return {'p5': r(np.percentile(a, 5)), 'p50': r(np.median(a)), 'p95': r(np.percentile(a, 95))}
REL = {'H2S': 16.75, 'NH3': 6.03, 'SO2': 3.19, 'C2H4': 3.12, 'CO2': 2.17, 'CH3OH': 1.55, 'CH4': 0.65}
MW = {'H2O': 18.015, 'H2S': 34.08, 'NH3': 17.03, 'SO2': 64.07, 'C2H4': 28.05, 'CO2': 44.01, 'CH3OH': 32.04, 'CH4': 16.04}
SP = list(REL)
MASS = {k: REL[k] / 100 * MW[k] / MW['H2O'] for k in SP}
LIM = {'H2S': 0.05, 'NH3': 1.0, 'SO2': 0.5, 'C2H4': 1.0, 'CO2': 50.0, 'CH3OH': 40.0, 'CH4': 5.0}
STAGES = {'cold_trap': {'CH4': (0.97, 0.995), 'C2H4': (0.9, 0.98), 'CO2': (0.8, 0.95), 'H2S': (0.5, 0.8), 'SO2': (0.2, 0.5), 'NH3': (0.1, 0.3), 'CH3OH': (0, 0.1)}, 'degassing': {'CH4': (0.9, 0.99), 'C2H4': (0.9, 0.99), 'CO2': (0.85, 0.97), 'H2S': (0.85, 0.97), 'SO2': (0.3, 0.6), 'NH3': (0.1, 0.3), 'CH3OH': (0, 0.05)}, 'ion_exchange': {'H2S': (0.9, 0.99), 'SO2': (0.97, 0.995), 'NH3': (0.95, 0.995), 'CO2': (0.9, 0.99), 'CH3OH': (0, 0.05)}, 'reverse_osmosis': {'H2S': (0.9, 0.98), 'SO2': (0.97, 0.995), 'NH3': (0.85, 0.95), 'CO2': (0.6, 0.9), 'CH3OH': (0.25, 0.45), 'CH4': (0.3, 0.6), 'C2H4': (0.3, 0.6)}, 'UV_H2O2': {'CH3OH': (0.95, 0.995), 'C2H4': (0.9, 0.99), 'H2S': (0.5, 0.8), 'NH3': (0.1, 0.3), 'SO2': (0, 0.2), 'CH4': (0.3, 0.6)}}
EXTRA = {'alkaline_scrubbing_oxidation': {'H2S': (0.99, 0.999), 'SO2': (0.99, 0.999), 'CO2': (0.9, 0.99)}, 'ammonia_stripping': {'NH3': (0.95, 0.99)}, 'aqueous_catalytic_oxidation': {'CH3OH': (0.99, 0.999), 'C2H4': (0.99, 0.999), 'CH4': (0.9, 0.99), 'NH3': (0.5, 0.9)}}
E_STAGE = {'cold_trap': (0.05, 0.2), 'degassing': (0.01, 0.03), 'ion_exchange': (0.005, 0.02), 'reverse_osmosis': (0.003, 0.01), 'UV_H2O2': (0.005, 0.03), 'alkaline_scrubbing_oxidation': (0.01, 0.05), 'ammonia_stripping': (0.02, 0.08), 'aqueous_catalytic_oxidation': (0.05, 0.15)}

def extraction_mc(n, rng):
    w = np.clip(rng.normal(0.056, 0.029, n), 0.01, 0.15)
    cp = rng.uniform(0.6, 0.8, n)
    dT = rng.uniform(250, 330, n)
    eta = rng.uniform(0.35, 0.6, n)
    L = 2830.0
    E = (1 / w * cp * dT + L) / eta / 3600
    return dict(w=w, cp=cp, dT=dT, eta=eta, E=E)

def run_train(stage_list, n, rng, passes=1):
    conc = {k: np.full(n, MASS[k] * 1000000.0) for k in SP}
    trace = {}
    energy = np.zeros(n)
    allst = {**STAGES, **EXTRA}
    for p in range(passes):
        for st in stage_list:
            for k in SP:
                lo, hi = allst[st].get(k, (0, 0))
                conc[k] = conc[k] * (1 - rng.uniform(lo, hi, n))
            energy += rng.uniform(*E_STAGE[st], n)
            trace[f'p{p + 1}_{st}'] = {k: r(np.median(conc[k]), 4) for k in SP}
    return (conc, energy, trace)
STUDIES = {}
T0 = time.time()

def e01():
    """How contaminated is the source lunar water before treatment? Results are conditional on the assumptions declared in this function."""
    n = 20000
    w = np.clip(rng.normal(0.056, 0.029, n), 0.01, 0.15)
    regolith_per_kg_water = 1 / w
    contaminant_total = sum(MASS.values())
    return {'research_question': 'How contaminated is the source lunar water before treatment?', 'claim_2024': 'The source composition is not characterised: neither contaminants nor concentrations are specified.', 'method_2026': 'Convert LCROSS molar abundances into contaminant mass and use Monte Carlo sampling for regolith water content.', 'assumptions': {'source': 'Colaprete et al. (2010), Science 330:463, Cabeus impact plume', 'water_wt_pct': '5.6 ± 2.9 (truncated normal, 1–15%)', 'note': 'An impact plume is not identical to in-situ ice; the plume data are the direct observational input used here.'}, 'results': {'contaminants_g_per_kg_water': {k: r(MASS[k] * 1000, 1) for k in SP}, 'total_contaminants_g_per_kg_water': r(contaminant_total * 1000, 1), 'seawater_comparison_g_per_kg': 35, 'times_seawater_load': r(contaminant_total * 1000 / 35, 1), 'kg_regolith_per_kg_water': pct(regolith_per_kg_water)}, 'interpretation': 'The modelled volatile load (~620 g/kg) is about 18 times the salinity of seawater. Much of it consists of gases (H2S, CO2, CH4 and C2H4) that should be separated in the vapour phase BEFORE liquid-water treatment. A 99% mass-removal figure alone does not establish water safety.'}

def e02():
    """How much energy does extracting 1 kg of water from regolith require? Results are conditional on the assumptions declared in this function."""
    d = extraction_mc(50000, rng)
    sens = {k: r(spearmanr(d[k], d['E']).statistic) for k in ['w', 'cp', 'dT', 'eta']}
    hr = rng.uniform(0.3, 0.6, 50000)
    E_hr = (1 / d['w'] * d['cp'] * d['dT'] * (1 - hr) + 2830) / d['eta'] / 3600
    return {'research_question': 'How much energy does extracting 1 kg of water from regolith require?', 'claim_2024': 'A 30% reduction in energy use was claimed without a baseline or absolute consumption figure.', 'method_2026': 'Use 50,000-run Monte Carlo thermal balances, global Spearman sensitivity analysis and a heat-recovery scenario.', 'assumptions': {'cp_kJ_kgK': '0.6-0.8', 'dT_K': '250-330', 'oven_efficiency': '0.35-0.60', 'sublimation_heat_kJ_per_kg': 2830, 'heat_recovery': '30-60 %'}, 'results': {'kWh_per_kg_without_recovery': pct(d['E']), 'kWh_per_kg_with_recovery': pct(E_hr), 'heat_recovery_savings_pct': r(100 * (1 - np.median(E_hr) / np.median(d['E'])), 1), 'spearman_sensitivity': sens}, 'interpretation': 'Regolith water concentration (w) drives most uncertainty, while control algorithms have little influence over the underlying heat requirement. Savings near 30% may be plausible through HARDWARE heat recovery, not intrinsically through AI or quantum computing.'}

def e03():
    """Does more than 99% purification produce safe water, and which treatment train meets the study criteria? Results are conditional on the assumptions declared in this function."""
    n = 5000
    base = list(STAGES)
    configs = {'A_2024_train_one_pass': (base, 1), 'B_2024_train_two_passes': (base, 2), 'C_improved': (['cold_trap', 'degassing', 'alkaline_scrubbing_oxidation', 'ammonia_stripping', 'ion_exchange', 'reverse_osmosis', 'UV_H2O2', 'aqueous_catalytic_oxidation'], 1), 'D_improved_with_polishing': (['cold_trap', 'degassing', 'alkaline_scrubbing_oxidation', 'ammonia_stripping', 'ion_exchange', 'reverse_osmosis', 'UV_H2O2', 'aqueous_catalytic_oxidation', 'ion_exchange', 'reverse_osmosis'], 1)}
    out = {}
    tot_in = sum(MASS.values()) * 1000000.0
    for name, (st, p) in configs.items():
        conc, en, trace = run_train(st, n, rng, p)
        rem = 1 - sum(conc.values()) / tot_in
        ok = np.all([conc[k] <= LIM[k] for k in SP], axis=0)
        logs = {k: r(np.log10(MASS[k] * 1000000.0 / np.median(conc[k])), 2) for k in SP}
        out[name] = {'stages': st, 'passes': p, 'mass_removal_pct': pct(100 * rem), 'all_limits_met_pct': r(100 * ok.mean(), 1), 'exceeds_limit_by_species_pct': {k: r(100 * (conc[k] > LIM[k]).mean(), 1) for k in SP}, 'median_log_reduction': logs, 'median_final_concentration_mg_per_L': {k: r(np.median(conc[k]), 4) for k in SP}, 'purification_energy_kWh_per_kg': pct(en)}
        if name == 'C_improved':
            out[name]['median_stage_trace_mg_per_L'] = trace
    need = {k: r(np.log10(MASS[k] * 1000000.0 / LIM[k]), 2) for k in SP}
    return {'research_question': 'Does more than 99% purification produce safe water, and which treatment train meets the study criteria?', 'claim_2024': 'Purification above 99% was claimed without defining whether it meant mass removal, individual substances or safety-threshold compliance.', 'method_2026': 'Run 5,000 Monte Carlo cases per configuration across four treatment trains; measure the probability of meeting ALL assumed thresholds rather than bulk mass removal alone.', 'assumptions': {'stage_efficiencies': 'Uniform removal-efficiency ranges by stage and species (see STAGES and EXTRA in the code)', 'limits_mg_per_L': LIM, 'required_log_reduction': need}, 'results': out, 'interpretation': 'Mass removal can be misleading: the one-pass baseline removes over 99.9% of contaminant mass yet meets all illustrative limits in 0% of simulated cases. Two baseline passes (B), or an improved train with final polishing (D), meet every tested limit in 100% of simulated runs. The single-pass improved train (C) still exceeds H2S and NH3 thresholds in a material share of cases. Redundant treatment stages matter more than an algorithm.'}

def e04():
    """Can reverse osmosis receive untreated lunar source water directly? Results are conditional on the assumptions declared in this function."""
    n = 5000
    pre = ['cold_trap', 'degassing', 'ion_exchange']
    conc, _, _ = run_train(pre, n, rng, 1)
    T = 298
    osm = sum((conc[k] / MW[k] for k in SP)) / 1000 * 1000
    pi_bar = osm * R * T / 100000.0
    conc0 = {k: np.full(n, MASS[k] * 1000000.0) for k in SP}
    osm0 = sum((conc0[k] / MW[k] for k in SP))
    return {'research_question': 'Can reverse osmosis receive untreated lunar source water directly?', 'claim_2024': 'Separation technologies were not specified.', 'method_2026': "Use the van 't Hoff equation (i=1, a conservative simplification) on the composition entering the membrane.", 'assumptions': {'T_K': T, 'practical_membrane_limit_bar': '~70–80 (seawater reverse-osmosis reference)'}, 'results': {'osmotic_pressure_without_pretreatment_bar': r(np.median(osm0) * R * T / 100000.0, 1), 'osmotic_pressure_after_pretreatment_bar': pct(pi_bar)}, 'interpretation': 'Without pretreatment, osmotic pressure would be hundreds of bar and impractical for standard reverse osmosis. After cold trapping, degassing and ion exchange, it falls to a brackish-water range; reverse osmosis is best positioned as a polishing step.'}

def e05():
    """How much energy is needed to keep water liquid across the stated lunar temperature range? Results are conditional on the assumptions declared in this function."""
    n = 10000
    Tin = 293.0
    A = 4.84
    eps = rng.uniform(0.005, 0.03, n)
    envs = {'lunar_night_100K': 100, 'lunar_day_400K': 400, 'shadowed_crater_40K': 40}
    res = {}
    for nm, Te in envs.items():
        Q = eps * SIGMA * A * (Tin ** 4 - Te ** 4)
        res[nm] = {'W_heating_positive_cooling_negative': pct(Q)}
    Qn = eps * SIGMA * A * (Tin ** 4 - 100 ** 4)
    Qd = eps * SIGMA * A * (400 ** 4 - Tin ** 4)
    hrs = 14.75 * 24
    res['energy_per_lunar_cycle_kWh'] = {'night_heating': pct(Qn * hrs / 1000), 'day_cooling': pct(Qd * hrs / 1000)}
    Econg = 1000 * (4186.0 * 20 + 334000.0)
    Q40 = eps * SIGMA * A * (283 ** 4 - 40 ** 4)
    res['days_to_full_freezing_without_heater_in_crater'] = pct(Econg / Q40 / 86400)
    return {'research_question': 'How much energy is needed to keep water liquid across the stated lunar temperature range?', 'claim_2024': 'Thermal regulation from −173°C to 127°C was discussed without quantitative performance figures.', 'method_2026': 'Apply a radiative thermal balance with multi-layer insulation (MLI) and Monte Carlo sampling of effective emissivity.', 'assumptions': {'tank': '1 m³ spherical tank at 293 K', 'eps_MLI': '0.005-0.03', 'supports_conduction_excluded': True}, 'results': res, 'interpretation': 'With efficient MLI, modelled storage heating or cooling demand is on the order of tens to hundreds of watts. Extraction-furnace energy (E02), not the insulated tank, is the more significant engineering issue.'}

def e06():
    """How much water can be lost through seals when operating in a vacuum? Results are conditional on the assumptions declared in this function."""
    n = 10000
    Pv = 2339.0
    leak = 10 ** rng.uniform(-8, -5, n)
    nseals = rng.integers(30, 120, n)
    q = leak * (Pv / 101325) * nseals
    kg_year = q * MW['H2O'] / 1000 / (R * 293) * 31560000.0
    return {'research_question': 'How much water can be lost through seals when operating in a vacuum?', 'claim_2024': 'Low-pressure sealing was proposed without performance specifications.', 'method_2026': 'Apply the ideal-gas equation to log-uniform seal-leak rates and sampled seal counts.', 'assumptions': {'leak_per_seal_Pa_m3_per_s': '1e-8 to 1e-5', 'seals': '30-120'}, 'results': {'kg_water_lost_per_year': pct(kg_year), 'probability_loss_above_1kg_per_year_pct': r(100 * (kg_year > 1).mean(), 1)}, 'interpretation': 'For the assumed aerospace-grade seals, losses are negligible. Moving parts exposed to dust present the more important practical sealing risk (see E07).'}

def e07():
    """How often would lunar regolith dust force filter replacement? Results are conditional on the assumptions declared in this function."""
    n = 10000
    reg_kg_day = rng.uniform(100, 600, n)
    entrain = 10 ** rng.uniform(-6, -4, n)
    cap_g = rng.uniform(200, 1000, n)
    load = reg_kg_day * 1000 * entrain
    days = cap_g / load
    return {'research_question': 'How often would lunar regolith dust force filter replacement?', 'claim_2024': 'Regolith-resistant components were proposed without test data.', 'method_2026': 'Use a filtration-cake loading model with Monte Carlo uncertainty in fines carryover and filter capacity.', 'assumptions': {'regolith_kg_per_day': '100-600', 'entrained_fraction': '1e-6 a 1e-4', 'filter_capacity_g': '200-1000'}, 'results': {'days_between_replacements': pct(days), 'filters_per_year': pct(365 / days), 'probability_replacement_under_7_days_pct': r(100 * (days < 7).mean(), 1)}, 'interpretation': 'The uncertainty spans approximately three orders of magnitude. Entrained fine dust is a parameter that MUST be measured experimentally. Predictive maintenance using pressure-drop observations is a plausible role for AI.'}
CH = np.linspace(1.2, 2.7, 200)
CENT = {'H2S': 2.63, 'NH3': 2.0, 'SO2': 2.46, 'C2H4': 1.62, 'CO2': 2.01, 'CH3OH': 2.27, 'CH4': 2.32}

def spectra(n, snr, rng, unknown=False):
    y = (rng.random(n) < 0.5).astype(int)
    X = np.zeros((n, 200))
    for k, c in CENT.items():
        a = rng.lognormal(-3, 1, n)
        if k in ('H2S', 'NH3', 'CH3OH'):
            a = np.where(y == 1, a + rng.uniform(0.05, 0.3, n), a)
        X += a[:, None] * np.exp(-((CH - c) / 0.03) ** 2)
    X += 0.1 * np.exp(-((CH - 1.95) / 0.08) ** 2)
    if unknown:
        X += rng.uniform(0.05, 0.3, n)[:, None] * np.exp(-((CH - 1.45) / 0.03) ** 2)
    X += rng.normal(0, 0.1 / snr * 3, X.shape)
    return (X, y)

def e08():
    """Is the reported 98.7% accuracy for contaminant detection credible? Results are conditional on the assumptions declared in this function."""
    models = {'logistic_regression': make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)), 'random_forest': RandomForestClassifier(300, n_jobs=-1, random_state=0), 'gradient_boosting': HistGradientBoostingClassifier(max_iter=300, random_state=0), 'MLP_neural_network': make_pipeline(StandardScaler(), MLPClassifier((128, 64), max_iter=400, random_state=0))}
    snrs = [3, 10, 30, 100]
    table = {}
    for snr in snrs:
        X, y = spectra(6000, snr, rng)
        Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0)
        table[f'SNR_{snr}'] = {}
        for nm, m in models.items():
            m.fit(Xtr, ytr)
            p = m.predict(Xte)
            pr = m.predict_proba(Xte)[:, 1]
            table[f'SNR_{snr}'][nm] = {'accuracy_pct': r(100 * accuracy_score(yte, p), 1), 'recall_pct': r(100 * recall_score(yte, p), 1), 'precision_pct': r(100 * precision_score(yte, p), 1), 'false_negatives_pct': r(100 * (1 - recall_score(yte, p)), 1), 'AUC': r(roc_auc_score(yte, pr), 4), 'Brier': r(brier_score_loss(yte, pr), 4)}
    X, y = spectra(6000, 1000000.0, rng)
    m = HistGradientBoostingClassifier(max_iter=300, random_state=0).fit(X[:4200], y[:4200])
    ceiling = accuracy_score(y[4200:], m.predict(X[4200:]))
    X, y = spectra(12000, 30, rng)
    Xte, yte = (X[10000:], y[10000:])
    lc = {}
    for ntr in [100, 300, 1000, 3000, 10000]:
        m = HistGradientBoostingClassifier(max_iter=300, random_state=0).fit(X[:ntr], y[:ntr])
        lc[ntr] = r(100 * accuracy_score(yte, m.predict(Xte)), 1)
    Xn, _ = spectra(3000, 30, rng)
    Xu, _ = spectra(500, 30, rng, unknown=True)
    from sklearn.decomposition import PCA
    pca = PCA(12).fit(Xn[:2500])

    def resid(X):
        return ((X - pca.inverse_transform(pca.transform(X))) ** 2).sum(1)
    thr = np.percentile(resid(Xn[:2500]), 99)
    fp = (resid(Xn[2500:]) > thr).mean()
    tp = (resid(Xu) > thr).mean()
    iso = IsolationForest(n_estimators=300, contamination=0.02, random_state=0).fit(Xn[:2500])
    fp_iso = (iso.predict(Xn[2500:]) == -1).mean()
    tp_iso = (iso.predict(Xu) == -1).mean()
    return {'research_question': 'Is the reported 98.7% accuracy for contaminant detection credible?', 'claim_2024': 'Contaminant-detection accuracy of 98.7% was stated without a dataset, target classes or sensor definition.', 'method_2026': 'Generate synthetic near-infrared spectra for seven LCROSS species with overlapping water bands; compare four classifiers, false-negative and calibration metrics, learning curves and anomaly detectors.', 'assumptions': {'channels': 200, 'wavelength_range_um': '1.2-2.7', 'positive_class': 'H2S, NH3 or CH3OH exceeding the study threshold', 'background': 'Lognormal background with physically plausible spectral class overlap'}, 'results': {'models_by_SNR': table, 'noiseless_ceiling_accuracy_pct': r(100 * ceiling, 1), 'learning_curve_accuracy_pct_by_sample_count': lc, 'unknown_species_anomalies': {'PCA_residual': {'detection_pct': r(100 * tp, 1), 'false_alarms_pct': r(100 * fp, 1)}, 'isolation_forest': {'detection_pct': r(100 * tp_iso, 1), 'false_alarms_pct': r(100 * fp_iso, 1)}}}, 'interpretation': 'Classification accuracy saturates because of physically overlapping classes, not solely because of the algorithm. False negatives are especially important to water safety, yet were not reported in the 2024 study. A single accuracy figure without defined classes and sensors cannot be verified. For unseen contaminants, the physics-informed PCA spectral residual performs better than generic Isolation Forest in this simulation; method selection matters more than merely claiming to use AI.'}

def e09():
    """How much does intelligent control improve upon classical control? Results are conditional on the assumptions declared in this function."""
    dt, steps = (10.0, 4320)
    C, k = (500000.0, 15.0)
    Tset, Tenv, Pmax = (360.0, 40.0, 15000.0)

    def sim(ctrl, rng):
        T, integ, prev = (355.0, 7500.0 / 0.5, 0.0)
        E, err2 = (0.0, 0.0)
        for t in range(steps):
            load = 2500 + 1500 * np.sin(2 * np.pi * t / 360) + rng.normal(0, 300)
            if ctrl == 'PID':
                e = Tset - T
                d = (e - prev) / dt
                prev = e
                P = 400 * e + 0.5 * integ
                if 0 < P < Pmax:
                    integ += e * dt
            else:
                load_hat = 2500 + 1500 * np.sin(2 * np.pi * (t + 1) / 360)
                P = C * (Tset - T) / (dt * 6) + k * (T - Tenv) + load_hat
            P = float(np.clip(P, 0, Pmax))
            T += dt / C * (P - k * (T - Tenv) - load)
            E += P * dt
            err2 += (T - Tset) ** 2
        return (E / 3600000.0, np.sqrt(err2 / steps))
    res = {}
    for ctrl in ['PID', 'MPC']:
        Es, errs = zip(*[sim(ctrl, np.random.default_rng(s)) for s in range(10)])
        res[ctrl] = {'energy_kWh_12h': pct(np.array(Es)), 'RMS_error_K': pct(np.array(errs))}
    res['MPC_vs_PID_savings_pct'] = r(100 * (1 - res['MPC']['energy_kWh_12h']['p50'] / res['PID']['energy_kWh_12h']['p50']), 2)
    return {'research_question': 'How much does intelligent control improve upon classical control?', 'claim_2024': 'Automatic AI parameter adjustment was credited with a 25% efficiency improvement.', 'method_2026': 'Simulate a first-order extraction-oven thermal model under variable loads, comparing a tuned PID controller with load-predictive MPC over ten replicates.', 'assumptions': {'C_J_K': C, 'k_W_K': k, 'temperature_setpoint_K': Tset, 'P_max_W': Pmax}, 'results': res, 'interpretation': 'Predictive control substantially improves temperature stability, which can improve process quality, but barely affects energy consumption because the physical heat demand remains. A 25% control-only efficiency gain would require an inefficient baseline.'}
LO = np.array([280, 0.2, 1.0])
HI = np.array([420, 1.5, 10.0])

def proc_cost(x, rng=None):
    T, uv, p = x
    E = (1 / 0.056 * 0.7 * (T - 40) + 2830) / 0.45 / 3600 + 0.15 * uv + 0.02 * (10 - p)
    rec = 1 / (1 + np.exp(-(T - 300) / 15))
    pen = 5 * max(0, 0.8 - uv) ** 2 + 0.3 * max(0, p - 6) ** 2
    v = E / rec + pen
    return v + (rng.normal(0, 0.05) if rng is not None else 0)

def bo(budget, rng):
    X = LO + (HI - LO) * rng.random((6, 3))
    y = np.array([proc_cost(x, rng) for x in X])
    gp = GaussianProcessRegressor(ConstantKernel() * Matern(nu=2.5, length_scale_bounds=(0.01, 100.0)), normalize_y=True, alpha=0.01)
    while len(y) < budget:
        gp.fit((X - LO) / (HI - LO), y)
        c = rng.random((3000, 3))
        mu, sd = gp.predict(c, return_std=True)
        z = (y.min() - mu) / (sd + 1e-09)
        ei = (y.min() - mu) * norm.cdf(z) + sd * norm.pdf(z)
        xn = LO + (HI - LO) * c[ei.argmax()]
        X = np.vstack([X, xn])
        y = np.append(y, proc_cost(xn, rng))
    return proc_cost(X[y.argmin()])

def e10():
    """How much energy can AI-assisted operating-point optimisation save? Results are conditional on the assumptions declared in this function."""
    base = proc_cost(np.array([400, 1.2, 5]))
    grid = [np.array(g) for g in itertools.product(np.linspace(280, 420, 60), np.linspace(0.2, 1.5, 30), np.linspace(1, 10, 20))]
    true_opt = min((proc_cost(g) for g in grid))
    bos, rss = ([], [])
    for s in range(12):
        g = np.random.default_rng(100 + s)
        bos.append(bo(30, g))
        R_ = LO + (HI - LO) * g.random((30, 3))
        ys = [proc_cost(x, g) for x in R_]
        rss.append(proc_cost(R_[int(np.argmin(ys))]))
    bos, rss = (np.array(bos), np.array(rss))
    return {'research_question': 'How much energy can AI-assisted operating-point optimisation save?', 'claim_2024': 'Dynamic process optimisation was proposed as part of a 30% energy reduction.', 'method_2026': 'Compare Bayesian optimisation (Gaussian process with expected improvement) against random search across 30 evaluations and 12 replicates, using a 36,000-point grid as the reference optimum.', 'assumptions': {'cost_function': 'kWh/kg adjusted for water recovery plus quality penalty (simplified model)', 'baseline_setpoint': [400, 1.2, 5]}, 'results': {'baseline_setpoint_kWh_per_kg': r(base), 'grid_optimum_kWh_per_kg': r(true_opt), 'theoretical_maximum_savings_pct': r(100 * (1 - true_opt / base), 1), 'bayesian_optimisation_kWh_per_kg': pct(bos), 'random_search_kWh_per_kg': pct(rss), 'bayesian_optimisation_savings_pct': pct(100 * (1 - bos / base)), 'random_search_savings_pct': pct(100 * (1 - rss / base)), 'bayesian_optimisation_gap_to_optimum_pct': pct(100 * (bos / true_opt - 1))}, 'interpretation': 'Bayesian optimisation approaches the optimum with relatively few trials, which matters when tests are expensive. The total savings are bounded by the improvement margin over the chosen baseline. A 30% saving would require a substantially inefficient starting configuration.'}

def e11():
    """What plant capacity would a sustained lunar base require? Results are conditional on the assumptions declared in this function."""
    n = 20000
    d = extraction_mc(n, rng)
    _, e_pur, _ = run_train(['cold_trap', 'degassing', 'alkaline_scrubbing_oxidation', 'ammonia_stripping', 'ion_exchange', 'reverse_osmosis', 'UV_H2O2', 'aqueous_catalytic_oxidation'], n, rng)
    demand = rng.uniform(2.5, 4.0, n)
    o2 = rng.uniform(0.0, 0.95, n)
    recov = rng.uniform(0.93, 0.98, n)
    extr_eff = rng.uniform(0.6, 0.9, n)
    out = {}
    for crew in [2, 4, 6, 10, 20]:
        makeup = crew * (demand * (1 - recov) + o2)
        reg = makeup / (d['w'] * extr_eff)
        kW = makeup * (d['E'] / extr_eff + e_pur) / 24
        out[f'crew_{crew}'] = {'new_water_kg_per_day': pct(makeup), 'regolith_kg_per_day': pct(reg), 'average_power_kW': pct(kW), 'new_water_tonnes_per_year': pct(makeup * 365 / 1000)}
    return {'research_question': 'What plant capacity would a sustained lunar base require?', 'claim_2024': 'Long-term human presence was described as viable without system sizing.', 'method_2026': 'Combine per-crew mass and energy balances with ECLSS recycling assumptions and Monte Carlo outputs from E02 and E03(C).', 'assumptions': {'demand_kg_per_person_per_day': '2.5-4.0', 'water_for_O2': '0–0.95 kg/person/day, depending on closure of the O2 loop', 'recycling': '93-98 %', 'extraction_efficiency': '60-90 %'}, 'results': out, 'interpretation': 'Recycling substantially reduces new-water demand. Oxygen production, and possibly propellant production (not modelled here), can dominate demand. The model indicates kilowatt-scale power requirements, potentially compatible with crater-rim solar generation or surface fission, subject to engineering design.'}

def e12():
    """Could separated contaminants be recovered as useful resources? Results are conditional on the assumptions declared in this function."""
    per_t = {'sulfur_S_kg': MASS['H2S'] * 32.06 / 34.08 + MASS['SO2'] * 32.06 / 64.07, 'nitrogen_N_kg': MASS['NH3'] * 14.01 / 17.03, 'carbon_C_kg': MASS['C2H4'] * 24.02 / 28.05 + MASS['CO2'] * 12.01 / 44.01 + MASS['CH3OH'] * 12.01 / 32.04 + MASS['CH4'] * 12.01 / 16.04, 'methane_plus_ethylene_fuel_kg': MASS['CH4'] + MASS['C2H4']}
    return {'research_question': 'Could separated contaminants be recovered as useful resources?', 'claim_2024': 'Potential co-products were not assessed.', 'method_2026': 'Apply elemental mass balance per metric tonne of raw water.', 'assumptions': {'recovery': 'Theoretical 100% upper bound'}, 'results': {'kg_per_tonne_water': {k: r(v * 1000, 1) for k, v in per_t.items()}}, 'interpretation': 'The model indicates about 355 kg of sulfur and 47 kg of nitrogen per tonne of water feed, assuming theoretical full recovery. Nitrogen may be valuable for lunar agriculture and habitat atmosphere. Thinking of the process as volatile-resource refining rather than disposal-only purification changes the resource assessment.'}

def e13():
    """Could the plant operate for one year without intervention? Results are conditional on the assumptions declared in this function."""
    comps = {'oven': 20000, 'trap_compressor': 15000, 'vacuum_pump': 12000, 'RO_membrane': 8000, 'UV_lamp': 9000, 'catalytic_reactor': 15000, 'sensor_NIR': 30000, 'valves': 25000, 'controller': 50000}
    H, n = (8766, 4000)
    mttr = 24.0

    def sim(redund):
        avail = np.zeros(n)
        for i in range(n):
            down = 0.0
            for c, m in comps.items():
                fails = rng.poisson(H / m)
                if redund:
                    p_both = 1 - np.exp(-mttr / m)
                    down += sum((mttr for _ in range(fails) if rng.random() < p_both))
                else:
                    down += fails * mttr * rng.uniform(0.5, 2.0)
            avail[i] = 1 - down / H
        return avail
    a0, a1 = (sim(False), sim(True))
    return {'research_question': 'Could the plant operate for one year without intervention?', 'claim_2024': 'Robust lunar performance was asserted without reliability test data.', 'method_2026': 'Model Poisson component failures with and without N+1 component redundancy.', 'assumptions': {'MTBF_h': comps, 'MTTR_h': mttr}, 'results': {'availability_without_redundancy_pct': pct(100 * a0), 'availability_N_plus_1_pct': pct(100 * a1), 'expected_failures_per_year': r(sum((H / m for m in comps.values())), 2)}, 'interpretation': 'Under the assumptions, about five failures a year are expected without redundancy, leading to roughly 1–3% downtime. Simulated availability exceeds 99.99% with N+1 redundancy. Spares, system redundancy and telemetry-based maintenance matter more than algorithmic improvements alone.'}

def e14():
    """Is quantum computing needed for this particular treatment system? Results are conditional on the assumptions declared in this function."""
    res = {}
    for nv in [12, 16, 20]:
        g = np.random.default_rng(nv)
        Q = g.normal(0, 1, (nv, nv))
        Q = (Q + Q.T) / 2
        t0 = time.time()
        best = np.inf
        bits = np.arange(2 ** nv)
        for chunk in np.array_split(bits, max(1, 2 ** nv // 65536)):
            Xb = (chunk[:, None] >> np.arange(nv) & 1).astype(float)
            v = np.einsum('ij,jk,ik->i', Xb, Q, Xb)
            best = min(best, v.min())
        t_bf = time.time() - t0
        hits, t0 = (0, time.time())
        for rep in range(50):
            x = g.integers(0, 2, nv).astype(float)
            e = x @ Q @ x
            for it in range(3000):
                Tt = 2.0 * (1 - it / 3000) + 0.001
                i = g.integers(nv)
                x2 = x.copy()
                x2[i] = 1 - x2[i]
                e2 = x2 @ Q @ x2
                if e2 < e or g.random() < np.exp((e - e2) / Tt):
                    x, e = (x2, e2)
            hits += abs(e - best) < 1e-09
        res[f'{nv}_variables'] = {'exact_optimum': r(best), 'brute_force_time_seconds': r(t_bf, 3), 'classical_simulated_annealing_hit_rate_pct': r(100 * hits / 50, 1), 'mean_annealing_time_seconds': r((time.time() - t0) / 50, 4)}
    return {'research_question': 'Is quantum computing needed for this particular treatment system?', 'claim_2024': 'Quantum molecular simulation and faster optimisation were proposed without a specified algorithm or hardware.', 'method_2026': 'Express batch scheduling as a QUBO problem and compare exact classical search with classical simulated annealing.', 'assumptions': {'realistic_size': 'On the order of a few tens of binary variables for a plant of this size'}, 'results': res, 'interpretation': 'At the tested plant-planning scale, classical methods are sufficient; some small instances can be solved very quickly. Classical DFT and machine-learning potentials remain standard options for modelling these small molecules. These examples do not establish an operational advantage for quantum hardware.'}

def e15():
    """Is blockchain the appropriate way to record treatment telemetry? Results are conditional on the assumptions declared in this function."""
    rec_bytes, hz = (256, 1.0)
    rtt = 2.56
    out = {'signed_hash_chained_log': {'confirmation_latency_seconds': 0.001, 'overhead_bytes_per_record': 64 + 32, 'GB_per_year': r((rec_bytes + 96) * hz * 31560000.0 / 1000000000.0, 2)}, 'blockchain_with_Earth_validators': {'minimum_confirmation_latency_seconds': r(rtt * 2, 2), 'approx_overhead_bytes_per_record': 600, 'GB_per_year': r((rec_bytes + 600) * hz * 31560000.0 / 1000000000.0, 2), 'requires_continuous_link': True}}
    return {'research_question': 'Is blockchain the appropriate way to record treatment telemetry?', 'claim_2024': 'Blockchain and smart contracts were proposed for secure data management.', 'method_2026': 'Compare communication latency and record overhead, including Earth–Moon signal travel time.', 'assumptions': {'telemetry': 'One 256-byte record per second', 'RTT_s': rtt}, 'results': out, 'interpretation': 'A signed, hash-linked append-only log can provide tamper-evident evidence without distributed consensus or a continuous Earth link. In this single-operator scenario, blockchain adds latency and data overhead without a demonstrated operational benefit. Tamper evidence is not a universal guarantee of immutability.'}

def e16():
    """Can the lunar water-treatment concept be adapted to Mars? Results are conditional on the assumptions declared in this function."""
    n = 10000
    perc_wt = rng.uniform(0.004, 0.006, n)
    water_wt = rng.uniform(0.02, 0.05, n)
    perc_mg_L = perc_wt / water_wt * 1000000.0
    limit = 0.015
    logs_needed = np.log10(perc_mg_L / limit)
    achieved = rng.uniform(2, 3, n) + rng.uniform(2, 4, n)
    return {'research_question': 'Can the lunar water-treatment concept be adapted to Mars?', 'claim_2024': 'Adaptation to Mars was proposed as a future direction.', 'method_2026': 'Estimate perchlorate loads in extracted Martian soil water and the resulting required log reductions.', 'assumptions': {'perchlorate_soil_wt_pct': '0.4-0.6 (Phoenix)', 'soil_water_wt_pct': '2-5', 'limit_mg_per_L': limit}, 'results': {'perchlorate_in_water_mg_per_L': pct(perc_mg_L), 'required_log_reduction': pct(logs_needed), 'probability_meets_limit_with_IX_and_reduction_pct': r(100 * (achieved >= logs_needed).mean(), 1)}, 'interpretation': 'The critical Martian contaminant differs: perchlorate poses toxicological risks and is not adequately treated by the modelled lunar train. Adaptation would require dedicated stages; the source chemistry must determine the process design.'}

def main():
    funcs = [e01, e02, e03, e04, e05, e06, e07, e08, e09, e10, e11, e12, e13, e14, e15, e16]
    names = ['E01_feedwater_characterisation', 'E02_extraction_energy', 'E03_purification_train', 'E04_osmotic_pressure', 'E05_thermal_management', 'E06_vacuum_seals', 'E07_regolith_dust_filters', 'E08_AI_detection', 'E09_PID_vs_MPC_control', 'E10_Bayesian_optimisation', 'E11_mission_sizing', 'E12_byproducts', 'E13_reliability', 'E14_quantum_computing', 'E15_blockchain', 'E16_Mars']
    for nm, f in zip(names, funcs):
        t = time.time()
        STUDIES[nm] = f()
        STUDIES[nm]['calculation_seconds'] = r(time.time() - t, 1)
        print(f"{nm:32s} ok ({STUDIES[nm]['calculation_seconds']} s)", flush=True)
    R3, R8, R10, R2 = (STUDIES['E03_purification_train']['results'], STUDIES['E08_AI_detection']['results'], STUDIES['E10_Bayesian_optimisation']['results'], STUDIES['E02_extraction_energy']['results'])
    best_acc = max((v['accuracy_pct'] for s in R8['models_by_SNR'].values() for v in s.values()))
    claim_summary = [{'claim_2024': 'More than 99% purification', 'assessment_2026': 'Mass removal is high, but that does not establish water safety', 'evidence': f"{R3['A_2024_train_one_pass']['mass_removal_pct']['p50']}% mass removed; {R3['A_2024_train_one_pass']['all_limits_met_pct']}% meet thresholds (baseline train) versus {R3['D_improved_with_polishing']['all_limits_met_pct']}% (improved polished train D)"}, {'claim_2024': '98.7% contaminant detection', 'assessment_2026': 'Not reproduced under the synthetic-sensor assumptions', 'evidence': f"Best classification accuracy: {best_acc}%; modelled noiseless ceiling: {R8['noiseless_ceiling_accuracy_pct']} %"}, {'claim_2024': '30% lower energy use', 'assessment_2026': 'Heat-recovery hardware can deliver substantial savings; AI optimisation makes a smaller contribution', 'evidence': f"Heat-recovery scenario: {R2['heat_recovery_savings_pct']}%; Bayesian-optimisation saving: {R10['bayesian_optimisation_savings_pct']['p50']} %"}, {'claim_2024': '25% higher efficiency', 'assessment_2026': 'Cannot be verified without an original benchmark', 'evidence': f"MPC versus PID: {STUDIES['E09_PID_vs_MPC_control']['results']['MPC_vs_PID_savings_pct']}% energy difference"}, {'claim_2024': 'Quantum computing', 'assessment_2026': 'Not needed at the tested operational scale', 'evidence': 'See analysis E14'}, {'claim_2024': 'Blockchain', 'assessment_2026': 'A signed log is a viable alternative in the single-operator scenario', 'evidence': 'See analysis E15'}]
    out = {'meta': {'title': 'QuantumCleanse — 2026 Computational Reassessment', 'original_study': {'title': 'Advancing lunar habitation through water purification', 'publisher': 'Exohood Labs Inc', 'date': '2024-04-02', 'url': 'https://exohood.com/advancing-lunar-habitation-for-water-purification-in-extraterrestrial-environments'}, 'review_date': '2026-11-22', 'random_seed': SEED, 'research_ai_model': {'name': 'Helios', 'provider': 'Exania', 'reported_role': 'Scientific knowledge analysis across literature, technical datasets and interdisciplinary research questions', 'attribution_basis': 'Source README provided with this study', 'scope_note': 'The source materials do not provide Helios model version, prompts, interaction logs, or proof of specific intermediate AI operations. Numerical results are generated by the Python suite, not by invoking Helios during reproduction.'}, 'why_this_update': ['The original publication did not include underlying data, sample size, benchmark definition or methods; its headline percentages cannot be independently reanalysed.', 'By 2026, open numerical models can be built using published LCROSS composition and standard Monte Carlo, machine-learning, Bayesian-optimisation and predictive-control tools.', 'Each 2024 statement is reframed as a quantitative question with assumptions that readers can inspect, alter and rerun.', 'Ambiguous metrics such as purification percentage or accuracy are supplemented with safety-oriented quantities such as all-threshold compliance and false-negative rates.', 'The added complexity of quantum computing and blockchain is compared against conventional engineering and signed-record alternatives.'], 'notice': 'All findings are conditional simulation results under stated assumptions, not measurements or laboratory validation. Validate against volatile-doped lunar regolith simulant (e.g. LHS-1), calibrated instrumentation and appropriate mission water-quality requirements.', 'total_runtime_seconds': r(time.time() - T0, 1)}, 'claims_2024_vs_2026': claim_summary, 'studies': STUDIES}
    json.dump(out, open('results_2026.json', 'w'), indent=2, ensure_ascii=False, default=lambda o: r(o) if not isinstance(o, np.ndarray) else o.tolist())
    print(json.dumps(claim_summary, indent=2, ensure_ascii=False))
if __name__ == '__main__':
    main()
