Lawfare Group → Knowledge Institute → Lawfare Academy
Reproduce the worked examples
Copy the complete code below into a UTF-8 file named verify.py and run python verify.py with Python 3. It uses only the standard library and performs exact or rational synthetic calculations. It does not access a network or learner records. Assertions fail if the expected synthetic results change.
These checks verify the stated arithmetic and query behavior, not independent academic acceptance or production migration safety.
from fractions import Fraction as F
from math import sqrt,exp,log,isclose
import json
def transpose(a):return [list(x) for x in zip(*a)]
def mm(a,b):return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]
def inverse(a):
n=len(a);m=[[F(x) for x in row]+[F(int(i==j)) for j in range(n)] for i,row in enumerate(a)]
for j in range(n):
pivot=next((i for i in range(j,n) if m[i][j]),None)
if pivot is None:raise ValueError('Design is rank deficient; no unique coefficient vector.')
m[j],m[pivot]=m[pivot],m[j];scale=m[j][j];m[j]=[x/scale for x in m[j]]
for i in range(n):
if i!=j:
scale=m[i][j];m[i]=[x-scale*y for x,y in zip(m[i],m[j])]
return [row[n:] for row in m]
def ols(x,y):
x=[[F(v) for v in row] for row in x];y=[F(v) for v in y];xt=transpose(x);a=inverse(mm(xt,x));b=[r[0] for r in mm(mm(a,xt),[[v] for v in y])]
fitted=[sum(v*w for v,w in zip(row,b)) for row in x];e=[v-w for v,w in zip(y,fitted)];sse=sum(v*v for v in e);n=len(y);p=len(b);df=n-p
assert all(sum(row[j]*v for row,v in zip(x,e))==0 for j in range(p))
classic=[[sse/df*v for v in row] for row in a] if df>0 else None
meat=[[sum(ei*ei*row[j]*row[k] for row,ei in zip(x,e)) for k in range(p)] for j in range(p)]
hc0=mm(mm(a,meat),a);hc1=[[F(n,df)*v for v in row] for row in hc0] if df>0 else None
leverage=[mm(mm([row],a),[[v] for v in row])[0][0] for row in x]
return dict(b=b,fitted=fitted,e=e,sse=sse,df=df,a=a,classic=classic,hc1=hc1,leverage=leverage)
xs=list(range(8));ds=[0]*4+[1]*4;errors=[F(-3,2),F(-1,2),F(1,2),F(3,2),F(3,2),F(1,2),F(-1,2),F(-3,2)]
X=[[1,x,d] for x,d in zip(xs,ds)];Y=[10+2*x+5*d+e for x,d,e in zip(xs,ds,errors)]
fit=ols(X,Y);naive=ols([[1,x] for x in xs],Y)
interaction=ols([[1,x,d,x*d] for x,d in zip(xs,ds)],Y)
outlier=ols(X+[[1,20,1]],Y+[100])
groups=sorted(set(ds));scores=[]
for g in groups:scores.append([sum(row[j]*e for row,e,d in zip(X,fit['e'],ds) if d==g) for j in range(3)])
meat=mm(transpose(scores),scores);cr0=mm(mm(fit['a'],meat),fit['a']);factor=F(len(groups),len(groups)-1)*F(len(Y)-1,len(Y)-len(fit['b']));cr1=[[factor*v for v in row] for row in cr0]
series=[12,14,16,18,20,22,40,42]
train=ols([[1,t] for t in range(1,7)],series[:6]);fixed=[train['b'][0]+train['b'][1]*t for t in [7,8]]
rolling=[]
for t in [7,8]:
f=ols([[1,j] for j in range(1,t)],series[:t-1]);rolling.append(f['b'][0]+f['b'][1]*t)
report={'data':list(zip(xs,ds,Y)),'b':fit['b'],'naive':naive['b'],'interaction':interaction['b'],'sse':fit['sse'],'df':fit['df'],'inverse':fit['a'],'classic':fit['classic'],'hc1':fit['hc1'],'cr1':cr1,'leverage':fit['leverage'],'outlier':outlier['b'],'fixedForecasts':fixed,'rollingForecasts':rolling,'fixedMSE':sum((p-y)**2 for p,y in zip(fixed,series[6:]))/2,'rollingMSE':sum((p-y)**2 for p,y in zip(rolling,series[6:]))/2}
checks=[]
def check(name,condition):
assert condition,name
checks.append(name)
check('additive exact coefficients',fit['b']==[10,2,5])
check('normal-equation inverse',mm(mm(transpose(X),X),fit['a'])==[[int(i==j) for j in range(3)] for i in range(3)])
check('SSE and degrees of freedom',fit['sse']==10 and fit['df']==5)
check('naive slope differs',naive['b']==[F(55,6),F(62,21)])
rx=[F(x)-F(3,2) if d==0 else F(x)-F(11,2) for x,d in zip(xs,ds)]
ry=[y-13 if d==0 else y-26 for y,d in zip(Y,ds)]
check('FWL slope',sum(x*y for x,y in zip(rx,ry))==20 and sum(x*x for x in rx)==10)
check('interaction exact fit',interaction['b']==[F(17,2),3,12,-2] and interaction['sse']==0)
for x in [0,2,4,6,8]:
for d in [0,1]:check('centering equivalence '+str((x,d)),F(17,2)+3*x+12*d-2*x*d==F(41,2)+3*(x-4)+4*d-2*(x-4)*d)
check('interaction contrasts',12-2*2==8 and 12-2*6==0)
check('linear contrast covariance',fit['classic'][1][1]+fit['classic'][2][2]+2*fit['classic'][1][2]==F(14,5))
check('separate stipulated interaction covariance',4+16*F(1,4)+8*F(-1,2)==4)
check('classical and HC1 slope variances',fit['classic'][1][1]==F(1,5) and fit['hc1'][1][1]==F(41,125))
check('two-cluster illustrative variance only',cr1[1][1]==F(7,5) and len(groups)==2)
check('leverage projection trace',sum(fit['leverage'])==3 and fit['leverage']==[F(19,40),F(11,40),F(11,40),F(19,40)]*2)
check('valid large account sensitivity',outlier['b']==[F(185,33),F(488,99),F(-205,33)])
try:ols([[1,x,2*x] for x in xs],Y)
except ValueError:checks.append('rank-deficient design rejected')
else:raise AssertionError('rank-deficient design accepted')
check('finite elasticity',isclose(1.1**(-1.5),.8667841720414474))
check('log retransformation',isclose((exp(log(2))+exp(-log(2)))/2,1.25))
check('small sample t interval',isclose(12-2.571*3/sqrt(6),8.851180935020240,abs_tol=.00001))
check('fixed-origin predictions',fixed==[24,26] and report['fixedMSE']==256)
check('fixed benchmark',sum((22-y)**2 for y in series[6:])/2==362)
check('rolling predictions and loss',rolling==[24,F(246,7)] and report['rollingMSE']==F(7424,49))
check('rolling benchmark',sum((p-y)**2 for p,y in zip([22,40],series[6:]))/2==164)
actual=[100,120,80];model=[110,100,90];benchmark=[100]*3
for predictions,mse in [(model,200),(benchmark,F(800,3))]:
check('retained MAE '+str(mse),sum(abs(a-p) for a,p in zip(actual,predictions))==40)
check('retained MSE '+str(mse),sum(F((a-p)**2,3) for a,p in zip(actual,predictions))==mse)
check('retained asymmetric loss '+str(mse),sum(10*max(a-p,0)+2*max(p-a,0) for a,p in zip(actual,predictions))==240)
for demand,expected in [(4,-280),(6,-120),(9,-40)]:check('campaign capacity7 '+str(demand),80*min(demand,7)-600==expected)
check('campaign bound and changed capacity',7*80-600==-40 and 9*80-600==120 and 9*80-600-200==-80)
check('retained mean normal interval',30-1.96*16/sqrt(64)==26.08 and 30+1.96*16/sqrt(64)==33.92)
check('retained multiple regression contrast',4*2-3*1.5==3.5 and 4*2-3*(-1.5)==12.5)
for x in [0,4,12]:
for d in [0,1]:check('retained centered interaction '+str((x,d)),20+2*x+6*d-.5*x*d==44+2*(x-12)-.5*(x-12)*d)
for b,se,lo,hi in [(1.8,.4,1.016,2.584),(1.8,1,-.16,3.76),(2.4,.8,.832,3.968),(2.4,1.5,-.54,5.34)]:check('retained covariance interval '+str((b,se)),isclose(b-1.96*se,lo,abs_tol=1e-9) and isclose(b+1.96*se,hi,abs_tol=1e-9))
for demand,expected in [(1,-850),(6,-100),(11,200)]:check('retained campaign1000 '+str(demand),150*min(demand,8)-1000==expected)
for capacity,vals in [(10,[-1100,-200,-200]),(20,[-1100,700,1600])]:
for demand,expected in zip([5,15,25],vals):check('retained campaign2000 '+str((capacity,demand)),180*min(demand,capacity)-2000==expected)
check('retained sales scenario',3-2*2==-1 and 3-2*2+4==3)
check('incremental campaign threshold',.02*1000*60-1500==-300 and 25*60-1500==0)
if __name__=='__main__':print(json.dumps({'passed':True,'checks':checks,'calculated':report},default=str,indent=2))
Related chapters
- Define the question before choosing an interval or model
- Derive a partial slope and inspect the comparison it uses
- Interpret the contrast the equation actually encodes
- Diagnose the mean and choose uncertainty for the observation process
- Validate using information that existed at the forecast date
- Write an analytical report that survives a changed business fact
- Cumulative clinic: an auditable regression and decision dossier