#!/usr/bin/env python3 """Reproduce AMR's uranium calculations from the supplied CSV inputs. Uses only Python standard-library modules. --self-test exercises meaningful defect gates. No suppressed origin/material is calculated from a residual or substituted with zero. """ from pathlib import Path from decimal import Decimal as D import csv,json,sys,copy,re R=Path(__file__).resolve().parent;P=R/'data' if (R/'data').is_dir() else R;T=D('0.000051') def read(name): with (P/name).open(newline='') as f:return list(csv.DictReader(f)) def close(a,b,tol=T): a,b=D(str(a)),D(str(b)) if not a.is_finite() or abs(a-b)>tol:raise AssertionError((str(a),str(b))) def pct(a,b):return (D(str(b))/D(str(a))-1)*100 def ratio(a,b):return D(str(a))/D(str(b))*100 # Exact W positions are pinned to the released source groups, including derived W shares. W_EXPECTED={'enrichment-origins-2025.csv': [[0, 2], [0, 3], [2, 2], [2, 3], [6, 2], [6, 3], [7, 2], [7, 3]], 'enrichment-services.csv': [], 'country-origins-2025.csv': [[9, 2], [9, 3], [9, 4], [14, 2], [14, 3], [14, 4], [15, 2], [15, 3], [15, 4], [17, 2], [17, 3], [17, 4], [19, 2], [19, 3], [19, 4], [21, 2], [21, 3], [21, 4]], 'metric-definitions.csv': [[9, 0]], 'purchases-paid-prices.csv': [], 'feed-destination-aggregates.csv': [], 'supplier-versus-origin.csv': [[1, 2]], 'calculation-results.csv': [], 'contract-materials-2025.csv': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6]], 'contract-comparison-2025.csv': [], 'fuel-cycle-quantities.csv': [], 'fuel-loading-origins.csv': [[6, 2], [7, 2]], 'origin-aggregates.csv': [[3, 2], [3, 3], [3, 4], [4, 2], [4, 3], [4, 4]]} def check(data): for name,positions in W_EXPECTED.items(): actual=[[i,k] for i,row in enumerate(data[name]) for k,v in enumerate(row.values()) if v=='W'];assert actual==positions,(name,'W positions changed') p=data['purchases-paid-prices.csv'];assert [int(r['Delivery year']) for r in p]==list(range(2021,2026)) expected=[(46736,'33.91'),(40519,'39.08'),(51625,'43.80'),(55921,'52.71'),(46871,'58.46')] for r,(q,v) in zip(p,expected):close(r['Purchases (thousand lb U3O8e)'],q,0);close(r['Weighted-average paid price (USD per lb U3O8e)'],v,0) origins=data['origin-aggregates.csv'];byyear={} for r in origins:byyear.setdefault(int(r['Delivery year']),{})[r['Origin group']]=r for year,rr in byyear.items(): total=rr['Total']['Purchases (thousand lb U3O8e)'] for r in rr.values(): a=r['Purchases (thousand lb U3O8e)'];sh=r['AMR share of published all-origin purchases (%)'] if a=='W':assert sh=='W' else:close(sh,ratio(a,total)) a,b=rr['U.S. origin']['Purchases (thousand lb U3O8e)'],rr['Foreign origin']['Purchases (thousand lb U3O8e)'] if a!='W' and b!='W':assert abs(D(a)+D(b)-D(total))<=1 # Independent source rounding, no adjustment. assert byyear[2022]['U.S. origin']['Purchases (thousand lb U3O8e)']=='W' country=data['country-origins-2025.csv'];assert len(country)==25 cc={r['Reported origin label']:r for r in country};q='2025 purchases (thousand lb U3O8e)';den=cc['Total Purchases'][q];close(den,46871,0) for label,expectedq in [('Canada',15207),('Kazakhstan',13331),('Australia',7077),('United States',3376),('Total Foreign',43495)]:close(cc[label][q],expectedq,0) for r in country: if r[q]=='W':assert r['AMR share of all-origin purchases (%)']=='W' else:close(r['AMR share of all-origin purchases (%)'],ratio(r[q],den)) # Do not sum public countries against the total: that would expose a residual for W rows. top=D(cc['Canada'][q])+D(cc['Kazakhstan'][q])+D(cc['Australia'][q]) contracts=data['contract-comparison-2025.csv'];con={r['Contract group']:r for r in contracts};cq='Quantity with reported price (thousand lb U3O8e)';cp='Weighted-average paid price (USD per lb U3O8e)' for label,qty,price in [('Spot',5998,'75.83'),('Long-term',40854,'55.91'),('All contracts',46852,'58.46')]:close(con[label][cq],qty,0);close(con[label][cp],price,0) for r in contracts:close(r['AMR share of price-reported quantity (%)'],ratio(r[cq],con['All contracts'][cq])) materials={r['Material type']:r for r in data['contract-materials-2025.csv']} close(materials['U3O8']['Spot paid price (USD per lb U3O8e)'],'76.01',0) close(materials['Total']['Spot paid price (USD per lb U3O8e)'],'75.83',0) assert materials['Natural UF6']['Spot paid price (USD per lb U3O8e)']=='W' weighted=(D(con['Spot'][cq])*D(con['Spot'][cp])+D(con['Long-term'][cq])*D(con['Long-term'][cp]))/D(con['All contracts'][cq]) close(weighted,con['All contracts'][cp],D('0.005')) feed=data['feed-destination-aggregates.csv'];assert [int(r['Delivery year']) for r in feed]==[2023,2024,2025] for r in feed: a,b,total=[D(r[c]) for c in ['Feed to U.S. enrichers (thousand lb U3O8e)','Feed to foreign enrichers (thousand lb U3O8e)','Total feed (thousand lb U3O8e)']];assert abs(a+b-total)<=1 close(r['AMR U.S. destination share (%)'],a/total*100) service=data['enrichment-services.csv'];assert len(service)==5 for r in service: a,b,total=[D(r[c]) for c in ['U.S.-origin enrichment (thousand SWU)','Foreign-origin enrichment (thousand SWU)','Total enrichment purchased (thousand SWU)']];assert abs(a+b-total)<=1 close(r['AMR U.S.-origin share of total SWU (%)'],a/total*100) s=service[-1];close(s['U.S.-origin enrichment (thousand SWU)'],2930,0);close(s['Total enrichment purchased (thousand SWU)'],12710,0);close(s['Nominal weighted-average price (USD per SWU)'],'108.70',0) sc={r['Enrichment service origin']:r for r in data['enrichment-origins-2025.csv']};assert sc['China']['Services purchased (thousand SWU)']=='W';close(sc['Russia']['Services purchased (thousand SWU)'],3284,0) for r in sc.values(): a=r['Services purchased (thousand SWU)'];v=r['AMR share of total SWU (%)'] if a=='W':assert v=='W' else:close(v,ratio(a,12710)) fuel=data['fuel-cycle-quantities.csv'];f=fuel[-1];assert int(f['Year'])==2025 for field,value in [('Delivered purchases (thousand lb U3O8e)',46871),('Natural uranium feed delivered for enrichment (thousand lb U3O8e)',32089),('New fuel loaded (thousand lb U3O8e)',40920)]:close(f[field],value,0) assert 'preliminary' in f['Fuel-loading status'].lower() loading=data['fuel-loading-origins.csv'];assert all('preliminary' in r['Status'].lower() for r in loading if r['Loading year']=='2025') results=data['calculation-results.csv'];vals=[pct(55921,46871),pct('52.71','58.46'),top/D(den)*100,pct('55.91','75.83'),D('75.83')-D('55.91'),ratio(43495,46871)] for r,v in zip(results,vals):close(r['AMR result'],v) return {'three_origin_total_thousand_lb':str(top),'three_origin_share_percent':str(top/D(den)*100),'delivery_volume_change_percent':str(vals[0]),'nominal_paid_price_change_percent':str(vals[1]),'foreign_origin_share_percent':str(vals[5]),'spot_minus_long_term_USD_per_lb':str(vals[4]),'matched_spot_premium_percent':str(vals[3]),'rounded_input_weighted_contract_price':str(weighted),'US_feed_destination_share_percent':str(ratio(11832,32089)),'US_SWU_origin_share_percent':str(ratio(2930,12710)),'confidentiality':'All source W positions retained; no suppressed residual calculated','fuel_loading_2025':'Preliminary'} files=list(W_EXPECTED);data={name:read(name) for name in files};out=check(data) if '--self-test' in sys.argv: mutations=[('purchases-paid-prices.csv',4,'Purchases (thousand lb U3O8e)','46852'),('origin-aggregates.csv',3,'Purchases (thousand lb U3O8e)','0'),('country-origins-2025.csv',2,'2025 purchases (thousand lb U3O8e)','15000'),('contract-comparison-2025.csv',0,'Weighted-average paid price (USD per lb U3O8e)','76.01'),('contract-comparison-2025.csv',0,'AMR share of price-reported quantity (%)','50'),('fuel-cycle-quantities.csv',2,'Fuel-loading status','Final'),('enrichment-services.csv',4,'Total enrichment purchased (thousand SWU)','46871'),('calculation-results.csv',2,'AMR result','76')] for filename,row,col,v in mutations: bad=copy.deepcopy(data);bad[filename][row][col]=v try:check(bad) except AssertionError:continue raise AssertionError('Deliberate defect passed: '+filename+' '+col) out['deliberate_defect_tests_passed']=len(mutations) print(json.dumps(out,indent=2))