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.
"""Original Quality and Productivity synthetic verification plus a preserved
laboratory with explicit SQLite connection closure for Windows. No network or
learner tables. Run in a writable directory; all SQLite records are temporary
fictional orders/payments/refunds used only to test transaction behavior.
These checks are not actual causal, quality, professional or academic approval.
"""
from fractions import Fraction as F
from pathlib import Path
import tempfile,unittest,io,json,math
SOURCE = '"""Lawfare Academy — original synthetic decision laboratory.\nPython 3.10+ standard library. Run: python laboratory.py selftest\nRun: python laboratory.py demonstrate\nNo remote services, real customer data, trained model or external actions.\n"""\nfrom contextlib import closing\nimport argparse\nimport itertools\nimport math\nimport sqlite3\nimport tempfile\nimport unittest\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nfrom threading import Barrier\n\ndef ols(x,y,x0):\n if len(x)!=len(y) or len(x)<=2:raise ValueError(\'At least three paired observations required\')\n if not all(math.isfinite(v)for v in [*x,*y,x0]):raise ValueError(\'Finite inputs required\')\n n=len(x);xb=sum(x)/n;yb=sum(y)/n\n sxx=sum((v-xb)**2 for v in x)\n if sxx==0:raise ValueError(\'Slope not identified\')\n b1=sum((a-xb)*(b-yb)for a,b in zip(x,y))/sxx;b0=yb-b1*xb\n residual=[b-b0-b1*a for a,b in zip(x,y)]\n s2=sum(e*e for e in residual)/(n-2);leverage=1/n+(x0-xb)**2/sxx\n return dict(intercept=b0,slope=b1,residuals=residual,sse=sum(e*e for e in residual),prediction=b0+b1*x0,\n mean_se=math.sqrt(s2*leverage),new_observation_se=math.sqrt(s2*(1+leverage)))\n\ndef rolling_errors(series,window=3):\n if window<1 or len(series)<=window:raise ValueError(\'A past window and later observations are required\')\n naive=[];average=[]\n for origin in range(window,len(series)):\n past=series[origin-window:origin]\n naive.append(series[origin]-past[-1])\n average.append(series[origin]-sum(past)/len(past))\n return naive,average\n\ndef asymmetric_loss(errors,under=3,over=1):\n if under<0 or over<0:raise ValueError(\'Loss weights must be nonnegative\')\n return sum(e*under if e>=0 else -e*over for e in errors)\n\ndef mm1(arrival,service):\n if not 0<arrival<service:raise ValueError(\'Requires 0 < arrival < service for the stationary model\')\n w=1/(service-arrival)\n return dict(utilization=arrival/service,system_hours=w,waiting_hours=w-1/service,number=arrival*w)\n\ndef p_limits(p,n):\n if not 0<=p<=1 or not isinstance(n,int) or n<=0:raise ValueError(\'Valid baseline and positive integer sample size required\')\n se=math.sqrt(p*(1-p)/n)\n return max(0,p-3*se),min(1,p+3*se)\n\ndef zero_failure_upper(n,alpha=.05):\n if not isinstance(n,int)or n<=0 or not 0<alpha<1:raise ValueError(\'Invalid trial count or tail probability\')\n return 1-alpha**(1/n)\n\ndef mix_optimum(resource_b=180):\n """Enumerate continuous two-variable vertices; not an integer optimizer."""\n lines=[(10,20,240),(15,10,resource_b),(1,0,0),(0,1,0)]\n points=[]\n for (a,b,c),(d,e,f) in itertools.combinations(lines,2):\n det=a*e-b*d\n if det==0:continue\n x=(c*e-b*f)/det;y=(a*f-c*d)/det\n if x>=-1e-9 and y>=-1e-9 and 10*x+20*y<=240+1e-9 and 15*x+10*y<=resource_b+1e-9:\n points.append((30*x+40*y,x,y))\n return max(points)\n\ndef classification(tp,fp,fn,tn,false_negative_cost=50,false_positive_cost=2):\n values=[tp,fp,fn,tn]\n if any(not isinstance(v,int)or isinstance(v,bool)or v<0 for v in values)or sum(values)==0:raise ValueError(\'Nonnegative integer counts required\')\n return dict(accuracy=(tp+tn)/sum(values),precision=tp/(tp+fp)if tp+fp else None,\n sensitivity=tp/(tp+fn)if tp+fn else None,\n loss=fn*false_negative_cost+fp*false_positive_cost,alerts=tp+fp)\n\ndef create_ledger(path):\n db=sqlite3.connect(path)\n db.executescript(\'\'\'\n PRAGMA foreign_keys=ON;\n CREATE TABLE orders(id INTEGER PRIMARY KEY, created_date TEXT NOT NULL);\n CREATE TABLE payments(id TEXT PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id), amount INTEGER NOT NULL CHECK(amount>0), event_date TEXT NOT NULL);\n CREATE TABLE refunds(id TEXT PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id), amount INTEGER NOT NULL CHECK(amount>0), event_date TEXT NOT NULL);\n CREATE TABLE audit(refund_id TEXT NOT NULL UNIQUE REFERENCES refunds(id));\n INSERT INTO orders VALUES(1,\'2026-01-02\'),(2,\'2025-12-01\');\n INSERT INTO payments VALUES(\'P1\',1,5000,\'2026-01-31\'),(\'P2\',1,5000,\'2026-02-01\'),(\'P3\',2,4000,\'2026-01-15\');\n INSERT INTO refunds VALUES(\'R1\',1,1000,\'2026-02-03\'),(\'R2\',1,2000,\'2026-02-04\');\n INSERT INTO audit VALUES(\'R1\'),(\'R2\');\n \'\'\');db.commit();db.close()\n\ndef refund(path,event_id,order_id,amount,date=\'2026-02-10\',fail_audit=False):\n if not isinstance(amount,int)or isinstance(amount,bool)or amount<=0:raise ValueError(\'Positive integer cents required\')\n db=sqlite3.connect(path,timeout=5,isolation_level=None)\n db.execute(\'PRAGMA foreign_keys=ON\')\n try:\n db.execute(\'BEGIN IMMEDIATE\')\n prior=db.execute(\'SELECT order_id,amount,event_date FROM refunds WHERE id=?\',(event_id,)).fetchone()\n if prior:\n if prior!=(order_id,amount,date):raise ValueError(\'Conflicting operation identifier\')\n db.commit();return \'retry\'\n paid=db.execute(\'SELECT COALESCE(SUM(amount),0) FROM payments WHERE order_id=?\',(order_id,)).fetchone()[0]\n returned=db.execute(\'SELECT COALESCE(SUM(amount),0) FROM refunds WHERE order_id=?\',(order_id,)).fetchone()[0]\n if returned+amount>paid:raise ValueError(\'Refund exceeds recorded payment capacity\')\n db.execute(\'INSERT INTO refunds VALUES(?,?,?,?)\',(event_id,order_id,amount,date))\n db.execute(\'INSERT INTO audit VALUES(?)\',(None if fail_audit else event_id,))\n db.commit();return \'committed\'\n except BaseException:\n db.rollback();raise\n finally:db.close()\n\ndef cash_net(db,start,end):\n return db.execute(\'\'\'SELECT COALESCE(SUM(cents),0) FROM (\n SELECT amount AS cents FROM payments WHERE event_date>=? AND event_date<?\n UNION ALL\n SELECT -amount AS cents FROM refunds WHERE event_date>=? AND event_date<?\n )\'\'\',(start,end,start,end)).fetchone()[0]\n\nclass LaboratoryTests(unittest.TestCase):\n def setUp(self):\n self.tmp=tempfile.TemporaryDirectory();self.path=Path(self.tmp.name)/\'synthetic.sqlite\';create_ledger(self.path)\n def tearDown(self):self.tmp.cleanup()\n def test_01_ols_and_prediction_uncertainty(self):\n m=ols([1,2,3,4,5,6],[2,4,3,4,7,7],3.5)\n self.assertEqual(m[\'residuals\'],[0,1,-1,-1,1,0]);self.assertAlmostEqual(m[\'sse\'],4)\n self.assertAlmostEqual(m[\'mean_se\'],math.sqrt(1/6));self.assertAlmostEqual(m[\'new_observation_se\'],math.sqrt(7/6))\n self.assertGreater(m[\'new_observation_se\'],m[\'mean_se\'])\n def test_02_ols_boundary_and_extrapolation(self):\n with self.assertRaises(ValueError):ols([1,1,1],[2,3,4],1)\n with self.assertRaises(ValueError):ols([1,2],[2,3],2)\n m=ols([1,2,3,4,5,6],[2,4,3,4,7,7],7)\n self.assertAlmostEqual(m[\'prediction\'],8);self.assertAlmostEqual(m[\'mean_se\'],math.sqrt(13/15))\n def test_03_time_order_and_loss(self):\n a,b=rolling_errors([10,12,11,14,13,15]);self.assertEqual(a,[3,-1,2])\n self.assertAlmostEqual(sum(abs(e)for e in b)/3,2)\n self.assertAlmostEqual(asymmetric_loss(a),16);self.assertAlmostEqual(asymmetric_loss(b),18)\n # Changing a later point must not alter a forecast issued earlier.\n a2,b2=rolling_errors([10,12,11,14,13,150]);self.assertEqual(a[0],a2[0]);self.assertEqual(b[0],b2[0])\n def test_04_queue_stability_and_units(self):\n self.assertAlmostEqual(mm1(4,5)[\'system_hours\'],1)\n self.assertAlmostEqual(mm1(4,6.5)[\'waiting_hours\'],.4-1/6.5)\n for rates in [(5,5),(6,5),(0,5)]:\n with self.assertRaises(ValueError):mm1(*rates)\n def test_05_capacity_vertices(self):\n self.assertEqual(mix_optimum(),(540,6,9));self.assertEqual(mix_optimum(210),(570,9,7.5))\n def test_06_quality_denominators_and_limits(self):\n self.assertAlmostEqual((2+18)/(50+150),.1)\n low,high=p_limits(.04,100);self.assertEqual(low,0);self.assertLess(high,.1)\n self.assertLess(p_limits(.04,400)[1],high)\n def test_07_zero_failures_do_not_prove_zero_risk(self):\n self.assertGreater(zero_failure_upper(60),.04)\n self.assertGreater(zero_failure_upper(298),.01);self.assertLessEqual(zero_failure_upper(299),.01)\n def test_08_policy_ranking_changes_with_loss(self):\n a=classification(80,90,20,810);b=classification(90,180,10,720)\n self.assertGreater(a[\'accuracy\'],b[\'accuracy\']);self.assertGreater(a[\'loss\'],b[\'loss\'])\n self.assertLess(classification(80,90,20,810,false_positive_cost=10)[\'loss\'],classification(90,180,10,720,false_positive_cost=10)[\'loss\'])\n self.assertIsNone(classification(0,0,1,9)[\'precision\'])\n def test_09_period_vs_cohort_and_join_multiplication(self):\n with closing(sqlite3.connect(self.path)) as db:\n self.assertEqual(cash_net(db,\'2026-01-01\',\'2026-02-01\'),9000)\n self.assertEqual(cash_net(db,\'2026-02-01\',\'2026-03-01\'),2000)\n wrong=db.execute(\'SELECT SUM(p.amount)-SUM(r.amount) FROM payments p JOIN refunds r USING(order_id) WHERE p.order_id=1\').fetchone()[0]\n self.assertEqual(wrong,14000)\n paid=db.execute(\'SELECT SUM(amount) FROM payments WHERE order_id=1\').fetchone()[0]\n returned=db.execute(\'SELECT SUM(amount) FROM refunds WHERE order_id=1\').fetchone()[0]\n self.assertEqual(paid-returned,7000)\n self.assertEqual(db.execute(\'SELECT SUM(DISTINCT amount) FROM payments WHERE order_id=1\').fetchone()[0],5000)\n def test_10_exact_retry_and_conflicting_identity(self):\n self.assertEqual(refund(self.path,\'R3\',1,1000),\'committed\')\n self.assertEqual(refund(self.path,\'R3\',1,1000),\'retry\')\n with self.assertRaises(ValueError):refund(self.path,\'R3\',1,2000)\n self.assertEqual(refund(self.path,\'R4\',1,1000),\'committed\')\n with closing(sqlite3.connect(self.path)) as db:self.assertEqual(db.execute(\'SELECT SUM(amount) FROM refunds WHERE order_id=1\').fetchone()[0],5000)\n def test_11_audit_failure_rolls_back_actual_rows(self):\n with self.assertRaises(sqlite3.IntegrityError):refund(self.path,\'FAIL\',1,1000,fail_audit=True)\n with closing(sqlite3.connect(self.path)) as db:\n self.assertEqual(db.execute(\'SELECT COUNT(*) FROM refunds WHERE id=?\',(\'FAIL\',)).fetchone()[0],0)\n self.assertEqual(db.execute(\'SELECT COUNT(*) FROM audit\').fetchone()[0],2)\n self.assertEqual(db.execute(\'SELECT SUM(amount) FROM refunds\').fetchone()[0],3000)\n def test_12_competing_actual_connections(self):\n barrier=Barrier(2)\n def work(id):\n barrier.wait()\n try:return refund(self.path,id,1,4000)\n except ValueError:return \'rejected\'\n with ThreadPoolExecutor(max_workers=2)as pool:results=list(pool.map(work,[\'CONCURRENT-A\',\'CONCURRENT-B\']))\n self.assertCountEqual(results,[\'committed\',\'rejected\'])\n with closing(sqlite3.connect(self.path)) as db:\n self.assertEqual(db.execute(\'SELECT SUM(amount) FROM refunds\').fetchone()[0],7000)\n self.assertEqual(db.execute(\'SELECT COUNT(*) FROM audit\').fetchone()[0],3)\n def test_13_input_contract_and_parameterized_identity(self):\n for value in [0,-1,1.5,True]:\n with self.assertRaises(ValueError):refund(self.path,\'INVALID\',1,value)\n hostile="R\'); DROP TABLE orders; --"\n self.assertEqual(refund(self.path,hostile,1,100),\'committed\')\n with closing(sqlite3.connect(self.path)) as db:self.assertEqual(db.execute(\'SELECT COUNT(*) FROM orders\').fetchone()[0],2)\n def test_14_over_refund_preserves_state(self):\n with self.assertRaises(ValueError):refund(self.path,\'TOO-MUCH\',1,7001)\n with closing(sqlite3.connect(self.path)) as db:self.assertEqual(db.execute(\'SELECT SUM(amount) FROM refunds\').fetchone()[0],3000)\n def test_15_quality_break_even(self):\n needed=.9+(500+4000/12)/20000\n self.assertAlmostEqual(needed,.9416666666666667)\n self.assertAlmostEqual(12*((.94-.9)*20000-500)-4000,-400)\n def test_16_review_capacity_and_workflow_cost(self):\n self.assertAlmostEqual(60*.3*4/60,1.2)\n self.assertAlmostEqual(60*.5*5/60/2,1.25)\n self.assertAlmostEqual((8-(2+3+.2*5))*1000/60*30-800,200)\n\ndef demonstrate():\n print(\'Synthetic examples; model assumptions are part of the lessons.\')\n print(\'Queue\',mm1(4,5));print(\'Product mix\',mix_optimum());print(\'No-failure upper bound\',zero_failure_upper(60))\n print(\'Regression\',ols([1,2,3,4,5,6],[2,4,3,4,7,7],3.5))\n print(\'Policy A\',classification(80,90,20,810));print(\'Policy B\',classification(90,180,10,720))\n with tempfile.TemporaryDirectory()as directory:\n p=Path(directory)/\'ledger.sqlite\';create_ledger(p)\n with closing(sqlite3.connect(p)) as db:print(\'January cash-period net cents\',cash_net(db,\'2026-01-01\',\'2026-02-01\'))\n\nif __name__==\'__main__\':\n parser=argparse.ArgumentParser(description=__doc__);parser.add_argument(\'command\',choices=[\'selftest\',\'demonstrate\'])\n args=parser.parse_args()\n if args.command==\'demonstrate\':demonstrate()\n else:\n result=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(LaboratoryTests))\n raise SystemExit(0 if result.wasSuccessful()else 1)\n'
ns={'__name__':'academy_synthetic_laboratory'}
exec(compile(SOURCE,'preserved-laboratory-windows-corrected.py','exec'),ns)
old_temp=tempfile.tempdir
with tempfile.TemporaryDirectory(prefix='academy-quality-',dir=Path.cwd()) as sandbox:
assert Path(sandbox).resolve().parent==Path.cwd().resolve()
tempfile.tempdir=sandbox
stream=io.StringIO()
try:result=unittest.TextTestRunner(stream=stream,verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(ns['LaboratoryTests']))
finally:tempfile.tempdir=old_temp
assert result.wasSuccessful(),stream.getvalue()
assert result.testsRun==16
results={}
def near(n,value,target,tol=0.000002):
assert abs(float(value)-target)<tol,(n,float(value),target)
results[n]=float(value)
# New integrated physical and cash bridge.
assert 500+100==600 and 500+40+30==570
near('first_pass_proposed',F(960,570),1.6842105263)
near('final_proposed',F(1000,570),1.754385965)
near('final_productivity_improvement',F(600,570)-1,0.0526315789)
assert (100-40)*20-500==700
assert 12*700-4000==4400
assert 500+60+30==590 and (100-60)*20-500==300
assert 12*300-4000==-400
factor=sum(F(100,101)**t for t in range(1,13))
near('finite_monthly_value',700*factor-4000,3878.554231439)
threshold=F(9,10)+(500+4000/factor)/20000
results['discounted_yield_break_even']=float(threshold)
assert abs(float((20000*(threshold-F(9,10))-500)*factor-4000))<1e-8
assert (F(12,200)-F(100,1000))-(F(16,200)-F(80,800))==F(-2,100)
# Native productivity and system-boundary records.
near('first_pass_original',F(80,100),.8)
near('first_pass_revised',F(99,91),1.087912)
near('final_revised',F(110,91),1.208791)
near('supplier30_final',F(110,121),.909091)
near('supplier10_final',F(110,101),1.089109)
assert F(100,500)==F(110,550)==F(120,600)==F(1,5)
assert F(120,500)==F(6,25)
# Native finite resources, queues, specification and factorial contrasts.
assert 10*6+20*9==240 and 15*6+10*9==180 and 30*6+40*9==540
assert 10*9+20*F(15,2)==240 and 15*9+10*F(15,2)==210
assert 30*9+40*F(15,2)-30==540
assert min(12,8,10)==8 and min(12,11,10)==10
assert 8*F(9,10)==F(36,5) and 8*F(5,2)==20
for arrival,service,system in [(4,5,F(1)),(4,6,F(1,2)),(5,6,F(1)),(3,6,F(1,3)),(F(11,2),6,F(2))]:
assert 1/(F(service)-arrival)==system
near('queue_target_waiting',F(2,5)-F(2,13),.246153846)
assert F(80,20)==4 and F(60,20)==3
assert F(10,100)==F(1,10) and F(20,100)==F(1,5)
assert F(8,100)==F(2,25) and F(24,100)==F(6,25)
near('p_upper100',.04+3*math.sqrt(.04*.96/100),.098787754)
near('p_upper400',.04+3*math.sqrt(.04*.96/400),.069393877)
near('centered_cp',F(2)/(6*F(1,5)),1.666666667)
near('shifted_cpk',F(2,5)/(3*F(1,5)),.666666667)
assert F(2+18,50+150)==F(1,10)
assert (F(2,50)+F(18,150))/2==F(8,100)
assert 2/math.sqrt(4)==1 and 2/math.sqrt(16)==.5
assert F(8+2,2)-F(12+10,2)==-6
assert F(10+2,2)-F(12+8,2)==-4
assert (2-10)-(8-12)==-4
assert F(8+9,2)-F(12+10,2)==F(-5,2)
assert (9-10)-(8-12)==3
assert (8-12)-(7-10)==-1 and (8-12)-(4-10)==2
assert (6-12)-(5-10)==-1
# Every retained intervention threshold and captured-value example.
assert (100-40)*20-500==700 and F(4000,700)==F(40,7)
near('undiscounted_yield_break_even',F(9,10)+(500+F(4000,12))/20000,.941666667)
five=40*80-F(5000,60)*40-1000
two=40*80-F(2000,60)*40-1000
near('five_minute_checklist',five,-1133.333333)
near('two_minute_checklist',two,866.666667)
assert math.ceil((F(5000,60)*40+1000)/80)==55
assert (3*40-90)/60*30-20==-5
assert (3*50-90)/60*30-20==10
assert math.floor(F(130,3))+1==44
assert 2*20-60==-20 and 2*40-60==20 and F(60,2)==30
print(json.dumps(dict(passed=True,preservedCorrectedLaboratoryGroups=result.testsRun,portableConnectionCleanup=True,results=results,scope='Synthetic calculation and temporary transaction checks; not actual quality, learner, causal or academic verification'),indent=2))