#!/usr/bin/env python3 """Reproduce AMR silver arithmetic from the supplied CSVs, using Python standard library. --self-test verifies deliberate numerical, year, hierarchy and definition defects are rejected. Source facts are pinned to the reviewed primary tables; no private PDF is required at runtime. """ from pathlib import Path from decimal import Decimal as D,InvalidOperation import csv,json,copy,sys 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 n(v): try:x=D(str(v)) except InvalidOperation:raise AssertionError('Expected numeric value: '+str(v)) assert x.is_finite();return x def close(a,b,tol=T):assert abs(n(a)-n(b))<=tol,(str(a),str(b)) MINE=[('United States',1050,1100),('Argentina',774,800),('Australia',1050,1000),('Bolivia',1490,1500),('Canada',366,400),('Chile',1200,1400),('China',3430,3400),('India',700,800),('Kazakhstan',850,630),('Mexico',5780,6300),('Peru',3510,3600),('Poland',1320,1300),('Russia',1280,1200),('Sweden',432,400),('Other countries',2110,2100),('World total (rounded)',25300,26000)] FLOW=[(2021,'825.4','191.8','0.0','1.5','1018.7','1102.4','-83.7'),(2022,'833.7','194.6','0.0','1.7','1030.1','1284.1','-254.0'),(2023,'810.7','184.6','0.0','1.6','997.0','1197.0','-200.1'),(2024,'823.6','194.5','0.0','1.5','1019.6','1157.4','-137.9'),(2025,'846.6','197.6','44.7','1.5','1090.4','1130.6','-40.3')] def check(data): m=data['mining-country-panel.csv'];assert len(m)==16 for r,(label,a,b) in zip(m,MINE): assert r['USGS producer group']==label;close(r['Mine output 2024 (metric tonnes silver content)'],a,0);close(r['Mine output 2025 estimate (metric tonnes silver content)'],b,0);close(r['AMR share of rounded 26000-tonne world total (%)'],D(b)/26000*100) by={r['USGS producer group']:r for r in m};top=sum(n(by[c]['Mine output 2025 estimate (metric tonnes silver content)']) for c in ['Mexico','Peru','China']) supply=data['supply-flows-2021-2025.csv'];bal=data['annual-market-balance.csv'];assert len(supply)==len(bal)==5 for r,b,src in zip(supply,bal,FLOW): year,mine,recycle,hedge,official,total,demand,published=src;assert int(r['Year'])==int(b['Year'])==year for field,v in zip(['Mine production (Moz)','Recycling (Moz)','Net hedging supply (Moz)','Net official sector sales (Moz)','Published total supply (Moz)'],[mine,recycle,hedge,official,total]):close(r[field],v,0) assert abs(sum(n(x) for x in [mine,recycle,hedge,official])-n(total))<=D('0.1') for field,v in zip(['Mine production (Moz)','Recycling (Moz)','Published total supply (Moz)','Published total demand (Moz)','Published market balance (Moz)'],[mine,recycle,total,demand,published]):close(b[field],v,0) diff=n(total)-n(demand);close(b['AMR difference of rounded totals (Moz)'],diff,0);close(b['Published balance minus AMR difference (Moz)'],n(published)-diff,0);assert abs(n(published)-diff)<=D('0.1') dem=data['demand-segments-2025.csv'];expected=[('Industrial (total)','657.4'),('Photography','24.2'),('Jewelry','189.3'),('Silverware','42.1'),('Coin and net bar demand','217.7'),('Net hedging demand','0.0'),('Total demand','1130.6')] assert len(dem)==7 for r,(label,v) in zip(dem,expected):assert r['Demand category']==label;close(r['2025 demand (Moz)'],v,0);close(r['AMR share of published total demand (%)'],n(v)/D('1130.6')*100) assert abs(sum(n(r['2025 demand (Moz)']) for r in dem[:-1])-D('1130.6'))<=D('0.1') ind=data['industrial-hierarchy-2025.csv'];expected=[('Industrial (total)','Total demand','657.4'),('Electrical and electronics','Industrial (total)','449.5'),('Photovoltaics','Electrical and electronics','186.6'),('Brazing alloys and solders','Industrial (total)','50.5'),('Other industrial','Industrial (total)','157.4')] assert len(ind)==5 for r,(label,parent,v) in zip(ind,expected): assert r['Category']==label and r['Parent category']==parent;close(r['2025 demand (Moz)'],v,0);close(r['AMR share of industrial demand (%)'],n(v)/D('657.4')*100);close(r['AMR share of total demand (%)'],n(v)/D('1130.6')*100) close(sum(n(ind[k]['2025 demand (Moz)']) for k in [1,3,4]),'657.4',0) comp=data['source-estimate-comparison.csv'];expected=[('USGS MCS 2025',2024,'25000'),('USGS MCS 2026',2024,'25300'),('USGS MCS 2026',2025,'26000'),('World Silver Survey 2026',2024,'823.6'),('World Silver Survey 2026',2025,'846.6')] assert len(comp)==5 for r,(edition,year,v) in zip(comp,expected): assert r['Source edition']==edition and int(r['Observation year'])==year;close(r['Original published value'],v,0) normalized=n(v)*D('32150.7')/1000000 if r['Original unit'].startswith('Metric') else n(v);close(r['AMR comparison basis (Moz)'],normalized) cal=data['calculation-results.csv'];assert len(cal)==9 values=[top/26000*100,D('657.4')/D('1130.6')*100,D('186.6')/D('1130.6')*100,D('186.6')/D('657.4')*100,D('197.6')/(D('846.6')+D('197.6'))*100,D('40.3')/D('846.6')*100,sum(n(b['Published market balance (Moz)']) for b in bal),D('-40.3')-D('278.1'),(D(25300)/25000-1)*100] for r,v in zip(cal,values):close(r['AMR result'],v) assert cal[0]['Input B or operation']=='26000' and cal[2]['Input B or operation']=='1130.6' and cal[3]['Input B or operation']=='657.4' close(cal[7]['Input A'],'-40.3',0);assert cal[7]['Input B or operation']=='- 278.1' metrics={r['Measure']:r for r in data['metric-boundaries.csv']};assert 'excludes manufacturing/process scrap' in metrics['Survey recycling']['Population or denominator'] return {'top_three_mine_tonnes':str(top),'top_three_share_percent':str(values[0]),'industrial_share_of_total_percent':str(values[1]),'PV_share_of_total_percent':str(values[2]),'PV_share_of_industrial_percent':str(values[3]),'recycling_share_of_mine_plus_recycling_percent':str(values[4]),'reported_deficit_equivalent_to_mine_percent':str(values[5]),'five_year_sum_reported_balances_Moz':str(values[6]),'ETP_adjusted_balance_Moz':str(values[7]),'same_2024_world_revision_percent':str(values[8]),'published_2025_balance_Moz':'-40.3','rounded_totals_2025_difference_Moz':'-40.2','inventory':'No inventory level or exhaustion date inferred'} files=['mining-country-panel.csv','supply-flows-2021-2025.csv','demand-segments-2025.csv','industrial-hierarchy-2025.csv','annual-market-balance.csv','source-estimate-comparison.csv','calculation-results.csv','metric-boundaries.csv'];data={name:read(name) for name in files};out=check(data) if '--self-test' in sys.argv: defects=[('mining-country-panel.csv',9,'AMR share of rounded 26000-tonne world total (%)','30'),('mining-country-panel.csv',15,'Mine output 2025 estimate (metric tonnes silver content)','26331'),('industrial-hierarchy-2025.csv',0,'2025 demand (Moz)','844.0'),('annual-market-balance.csv',4,'Published market balance (Moz)','-40.2'),('supply-flows-2021-2025.csv',4,'Published total supply (Moz)','1044.2'),('source-estimate-comparison.csv',0,'Observation year','2025'),('metric-boundaries.csv',1,'Population or denominator','Annual flow; source includes manufacturing/process scrap'),('calculation-results.csv',7,'AMR result','-40.3')] for filename,row,col,value in defects: bad=copy.deepcopy(data);bad[filename][row][col]=value try:check(bad) except AssertionError:continue raise AssertionError('Deliberate defect passed: '+filename+' '+col) out['deliberate_defect_tests_passed']=len(defects) print(json.dumps(out,indent=2))