"""Sharp late-death contrasts over all couplings of nested mortality states.

Rows: TAVR potential state; columns: SAVR potential state.
State 0 = dead by L; 1 = survives L, dead by T; 2 = alive at T.
All risks are proportions, not counts or Kaplan-Meier risk-set sizes.
"""
import numpy as np
from scipy.optimize import linprog


def margins(e1, e0, d1, d0):
    if not (0 <= e1 <= d1 <= 1 and 0 <= e0 <= d0 <= 1):
        raise ValueError('Mortality risks must be nested in [0,1].')
    if e1 + e0 >= 1:
        raise ValueError('A positive always-survivor stratum is not guaranteed.')
    return np.array([e1, d1-e1, 1-d1]), np.array([e0, d0-e0, 1-d0])


def sharp_bounds(e1, e0, d1, d0, monotone=False):
    """Charnes-Cooper transform of a 3x3 linear-fractional program.

    Variables: z_ij = p_ij / A and t = 1/A. Normalize sum z_ij over
    i,j in {1,2} to one. Row/column sums of z equal marginal probability*t.
    Objective z_12-z_21 is the late-death risk difference among always survivors.
    With monotone=True, TAVR may protect early survival but cannot harm it:
    harm is TAVR dead and SAVR survives L, so p_01=p_02=0.
    """
    r, c = margins(e1, e0, d1, d0)
    if monotone and e1 > e0 + 1e-12:
        raise ValueError('Monotone early benefit incompatible with the margins.')
    eq, rhs = [], []
    for i in range(3):
        row=np.zeros(10); row[3*i:3*i+3]=1; row[9]=-r[i]
        eq.append(row); rhs.append(0.)
    for j in range(3):
        row=np.zeros(10); row[j:9:3]=1; row[9]=-c[j]
        eq.append(row); rhs.append(0.)
    row=np.zeros(10); row[[4,5,7,8]]=1; eq.append(row); rhs.append(1.)
    variable_bounds=[(0,None)]*10
    if monotone:
        variable_bounds[1]=(0,0); variable_bounds[2]=(0,0)
    objective=np.zeros(10); objective[5]=1; objective[7]=-1
    answer={}
    for label, direction in [('lower',1),('upper',-1)]:
        fit=linprog(direction*objective,A_eq=np.array(eq),b_eq=np.array(rhs),
                    bounds=variable_bounds,method='highs')
        if not fit.success:
            raise RuntimeError(f'LP {label} failed: {fit.message}')
        witness=fit.x[:9].reshape(3,3)/fit.x[9]
        A=witness[1:,1:].sum()
        value=(witness[1,2]-witness[2,1])/A
        if (np.max(abs(witness.sum(axis=1)-r))>1e-8 or
            np.max(abs(witness.sum(axis=0)-c))>1e-8 or
            witness.min() < -1e-8 or abs(witness.sum()-1)>1e-8):
            raise AssertionError('Invalid extremal witness.')
        answer[label]={'value':float(value),'always_survivor_mass':float(A),
                       'witness':witness.tolist()}
    answer['assumption']='monotone_early_TAVR_benefit' if monotone else 'no_early_monotonicity'
    answer['observed_survivor_contrast']=(d1-e1)/(1-e1)-(d0-e0)/(1-e0)
    answer['late_marginal_difference']=d1-d0
    return answer


def closed_form(e1,e0,d1,d0):
    """Closed form in an explicitly checked interior region; otherwise no formula."""
    margins(e1,e0,d1,d0)
    total=e1+e0
    if not (d1 >= total-1e-12 and d0 >= total-1e-12 and
            d0 <= 1-e1+1e-12 and d1 <= 1-e0+1e-12):
        return None
    denominator=1-total
    return ((d1-d0-e1)/denominator,(d1-d0+e0)/denominator)


def fixed_stratum_bounds(e1,e0,d1,d0,common_early_death):
    """Independent algebra using capacities in the always-survivor stratum.

    For fixed common early death D, A=1-e1-e0+D, TAVR-protected
    early survivors P=e0-D, and TAVR-harmed early survivors H=e1-D.
    Allocate all feasible late deaths outside A before counting those inside A.
    """
    D=common_early_death;A=1-e1-e0+D;P=e0-D;H=e1-D
    L1=d1-e1;L0=d0-e0
    return ((max(0,L1-P)-min(L0,A))/A,
            (min(L1,A)-max(0,L0-H))/A)


def one_dimensional_bounds(e1,e0,d1,d0):
    """Independent exact optimization over common early deaths.

    Between the listed breakpoints, each expression is linear-fractional with
    a positive denominator, hence monotone or constant. Its extrema occur at
    a breakpoint or endpoint. This implementation does not call linprog.
    """
    margins(e1,e0,d1,d0)
    B=1-e1-e0; L1=d1-e1; L0=d0-e0
    hi=min(e1,e0)
    candidates=sorted(set([0.,hi]+[v for v in
        [e0-L1,L0-B,L1-B,e1-L0] if 0 <= v <= hi]))
    answers=[fixed_stratum_bounds(e1,e0,d1,d0,v) for v in candidates]
    return min(a[0] for a in answers),max(a[1] for a in answers)


def selected_cohort_bounds(e1,e0,d1,d0,w1,w0,zero_effect=False):
    """Sensitivity to unrestricted outcomes among omitted randomized patients.

    Model assumption: reported risks are true marginal risks within each
    arm's selected subgroup, comprising proportions w1 and w0 of its allocated
    population. The omitted subgroup may occupy any of the three states.
    Selected and allocated groups must have aligned time origins.
    This is a sensitivity model, not an actual ITT estimate or an assertion
    that omitted outcomes were not collected elsewhere in the trial.
    """
    r,c=margins(e1,e0,d1,d0)
    if not(0 < w1 <= 1 and 0 < w0 <= 1):raise ValueError('Invalid selection weights.')
    if (1-w1+w1*e1)+(1-w0+w0*e0)>=1:
        raise ValueError('A positive always-survivor stratum is not guaranteed in this sensitivity model.')
    # sum z=t imposes total population probability one before transformation.
    eq=np.zeros((2,10));eq[0,:9]=1;eq[0,9]=-1
    eq[1,[4,5,7,8]]=1;rhs=np.array([0.,1.])
    ub=[]
    for i in range(3):
        row=np.zeros(10);row[3*i:3*i+3]=-1;row[9]=w1*r[i];ub.append(row)
    for j in range(3):
        row=np.zeros(10);row[j:9:3]=-1;row[9]=w0*c[j];ub.append(row)
    objective=np.zeros(10);objective[5]=1;objective[7]=-1
    if zero_effect:
        eq=np.vstack([eq,objective]);rhs=np.append(rhs,0.)
    answers={}
    for label,sgn in [('lower',1),('upper',-1)]:
        fit=linprog(sgn*objective,A_ub=np.array(ub),b_ub=np.zeros(6),
                    A_eq=eq,b_eq=rhs,bounds=[(0,None)]*10,method='highs')
        if not fit.success:raise RuntimeError(f'Selection sensitivity failed: {fit.message}')
        p=fit.x[:9].reshape(3,3)/fit.x[9]
        if zero_effect:
            # Cancel equal off-diagonal masses to produce identical binary
            # outcomes in every always-survivor, preserving all marginals.
            q=min(p[1,2],p[2,1]);p[1,2]-=q;p[2,1]-=q;p[1,1]+=q;p[2,2]+=q
        A=p[1:,1:].sum()
        rr=p.sum(axis=1);cc=p.sum(axis=0)
        if np.min(rr-w1*r)<-1e-8 or np.min(cc-w0*c)<-1e-8:
            raise AssertionError('Selection witness violates observed subgroup margins.')
        answers[label]={'value':float((p[1,2]-p[2,1])/A),
            'always_survivor_mass':float(A),'witness':p.tolist(),
            'full_TAVR_margins':rr.tolist(),'full_SAVR_margins':cc.tolist(),
            'omitted_TAVR_margins':((rr-w1*r)/(1-w1)).tolist() if w1<1 else None,
            'omitted_SAVR_margins':((cc-w0*c)/(1-w0)).tolist() if w0<1 else None}
    return answers


def selection_only_witness(e1,e0,d1,d0,all_always_survive_horizon=False,common_early_death_min=0.):
    """Find a zero binary late-death contrast in every always-survivor.

    p_12=p_21=0: both potential binary outcomes at T agree among people who
    survive L under both procedures. Exact death times may still differ.
    Setting all_always_survive_horizon also requires p_11=0, so every
    always-survivor remains alive through T under both strategies. Late death
    times in the protected/harmed strata can then follow any marginal pattern.
    Minimize the fraction whose survival through L differs across treatments.
    """
    r,c=margins(e1,e0,d1,d0)
    eq=[];rhs=[]
    for i in range(3):
        row=np.zeros(9);row[3*i:3*i+3]=1;eq.append(row);rhs.append(r[i])
    for j in range(3):
        row=np.zeros(9);row[j:9:3]=1;eq.append(row);rhs.append(c[j])
    vb=[(0,None)]*9;vb[0]=(common_early_death_min,None);vb[5]=(0,0);vb[7]=(0,0)
    if all_always_survive_horizon:vb[4]=(0,0)
    objective=np.zeros(9);objective[0]=-1
    fit=linprog(objective,A_eq=np.array(eq),b_eq=np.array(rhs),bounds=vb,method='highs')
    if not fit.success:
        if fit.status==2:return {'feasible':False,'reason':'No coupling with zero individual binary contrast in always-survivors.'}
        raise RuntimeError(f'Selection-only optimization failed: {fit.message}')
    p=fit.x.reshape(3,3);A=p[1:,1:].sum()
    if np.max(abs(p.sum(axis=1)-r))>1e-8 or np.max(abs(p.sum(axis=0)-c))>1e-8:
        raise AssertionError('Invalid selection-only witness margins.')
    return {'feasible':True,'minimum_early_survival_discordance':float(e1+e0-2*p[0,0]),
            'maximum_common_early_death_mass':float(p[0,0]),
            'TAVR_early_harmed_mass':float(p[0,1]+p[0,2]),
            'TAVR_early_protected_mass':float(p[1,0]+p[2,0]),
            'always_survivor_mass':float(A),'witness':p.tolist(),
            'late_death_mass_in_always_survivors':float(p[1,1]+p[1,2]+p[2,1]),
            'binary_late_contrast_in_always_survivors':float((p[1,2]-p[2,1])/A)}


def box_bounds(risk_box,selection_only=False,all_always_survive_horizon=False):
    """Exact optimization over interval-valued early and late marginal risks.

    risk_box is [e1 interval,e0 interval,d1 interval,d0 interval]. Intervals
    describe deterministic input uncertainty and have no confidence coverage.
    In selection_only mode minimize the population fraction with discordant
    survival at L, requiring equal individual binary late outcomes in A.
    """
    if len(risk_box)!=4:raise ValueError('Four risk intervals are required.')
    for lo,hi in risk_box:
        if not(0<=lo<=hi<=1):raise ValueError('Invalid risk interval.')
    if risk_box[0][1]+risk_box[1][1]>=1:
        raise ValueError('No guaranteed positive always-survivor stratum.')
    masks=[]
    for cells in [[0,1,2],[0,3,6],[0,1,2,3,4,5],[0,1,3,4,6,7]]:
        m=np.zeros(9);m[cells]=1;masks.append(m)
    n=9 if selection_only else 10
    eq=[];rhs=[];ub=[];ub_rhs=[]
    if selection_only:
        eq=[np.ones(9)];rhs=[1.]
        for mask,(lo,hi) in zip(masks,risk_box):
            ub.extend([mask,-mask]);ub_rhs.extend([hi,-lo])
        objective=np.zeros(9);objective[[1,2,3,6]]=1
        vb=[(0,None)]*9;vb[5]=(0,0);vb[7]=(0,0)
        if all_always_survive_horizon:vb[4]=(0,0)
        fit=linprog(objective,A_ub=np.array(ub),b_ub=np.array(ub_rhs),
                    A_eq=np.array(eq),b_eq=np.array(rhs),bounds=vb,method='highs')
        if not fit.success:
            if fit.status==2:return {'feasible':False}
            raise RuntimeError(f'Box null optimization failed: {fit.message}')
        p=fit.x.reshape(3,3)
        return {'feasible':True,'minimum_early_survival_discordance':float(fit.fun),
                'witness':p.tolist()}
    normal=np.zeros(10);normal[:9]=1;normal[9]=-1;eq.append(normal);rhs.append(0.)
    normal=np.zeros(10);normal[[4,5,7,8]]=1;eq.append(normal);rhs.append(1.)
    for mask,(lo,hi) in zip(masks,risk_box):
        top=np.zeros(10);top[:9]=mask;top[9]=-hi
        bot=np.zeros(10);bot[:9]=-mask;bot[9]=lo
        ub.extend([top,bot]);ub_rhs.extend([0.,0.])
    objective=np.zeros(10);objective[5]=1;objective[7]=-1
    out={}
    for label,sgn in [('lower',1),('upper',-1)]:
        fit=linprog(sgn*objective,A_ub=np.array(ub),b_ub=np.array(ub_rhs),
                    A_eq=np.array(eq),b_eq=np.array(rhs),bounds=[(0,None)]*n,method='highs')
        if not fit.success:raise RuntimeError(f'Box LP failed: {fit.message}')
        p=fit.x[:9].reshape(3,3)/fit.x[9];A=p[1:,1:].sum()
        observed=[float(mask@p.ravel()) for mask in masks]
        if any(v<lo-1e-8 or v>hi+1e-8 for v,(lo,hi) in zip(observed,risk_box)):
            raise AssertionError('Box witness outside input intervals.')
        out[label]={'value':float((p[1,2]-p[2,1])/A),'witness':p.tolist(),
                    'marginal_risks_e1_e0_d1_d0':observed}
    return out


def minimum_omitted_surgery_mortality_for_null(e1,e0,d1,d0,w1,w0):
    """Calibrate the omission model, not observed outcomes in omitted patients.

    Minimize death-by-T risk in the omitted surgery subgroup, imposing a
    binary late-death null in all always-survivors and allowing any omitted
    TAVR outcomes. The selected and allocated cohorts must have aligned time
    origins for this mixture interpretation.
    """
    r,c=margins(e1,e0,d1,d0)
    if not(0<w0<1 and 0<w1<=1):raise ValueError('Calibration requires a nonempty omitted surgery group.')
    ub=[];rhs=[]
    for i in range(3):
        row=np.zeros(9);row[3*i:3*i+3]=-1;ub.append(row);rhs.append(-w1*r[i])
    for j in range(3):
        row=np.zeros(9);row[j:9:3]=-1;ub.append(row);rhs.append(-w0*c[j])
    objective=np.zeros(9);objective[[0,1,3,4,6,7]]=1
    vb=[(0,None)]*9;vb[5]=(0,0);vb[7]=(0,0)
    fit=linprog(objective,A_ub=np.array(ub),b_ub=np.array(rhs),
                A_eq=np.ones((1,9)),b_eq=np.array([1.]),bounds=vb,method='highs')
    if not fit.success:raise RuntimeError(f'Omission calibration failed: {fit.message}')
    minimum_S=fit.fun
    # Choose a readable attaining witness: among solutions with minimum
    # omitted surgery mortality, minimize omitted TAVR mortality as well.
    objective_T=np.zeros(9);objective_T[:6]=1
    fit2=linprog(objective_T,A_ub=np.array(ub),b_ub=np.array(rhs),
        A_eq=np.vstack([np.ones(9),objective]),b_eq=np.array([1.,minimum_S]),bounds=vb,method='highs')
    if not fit2.success:raise RuntimeError(f'Calibration witness tie-break failed: {fit2.message}')
    p=fit2.x.reshape(3,3);full_T=p.sum(axis=1);full_S=p.sum(axis=0)
    value=(minimum_S-w0*d0)/(1-w0)
    if value < -1e-8 or value > 1+1e-8:raise AssertionError('Calibration outside probability range.')
    return {'minimum_omitted_SAVR_mortality':float(value),'witness':p.tolist(),
            'witness_tie_break':'Minimize omitted TAVR mortality among minimum-omitted-SAVR-mortality null solutions.',
            'omitted_TAVR_margins':((full_T-w1*r)/(1-w1)).tolist() if w1<1 else None,
            'omitted_SAVR_margins':((full_S-w0*c)/(1-w0)).tolist(),
            'late_death_mass_in_always_survivors_with_discordant_binary_outcomes':float(p[1,2]+p[2,1])}
