"""Reproduce AMR potash statistics from the extracted public CSV bundle.""" import csv import json from decimal import Decimal from pathlib import Path HERE=Path(__file__).resolve().parent DATA=HERE/'data' if (HERE/'data').is_dir() else HERE def rows(dataset): with (DATA/f'potash-{dataset}.csv').open(newline='') as handle: return list(csv.reader(handle))[1:] def pct(numerator, denominator): return f'{Decimal(numerator)/Decimal(denominator)*100:.4f}' def verify_mine_tables(): mine=rows('world-mine-production') quantities={name:int(current) for name, _, current, _, _ in mine} world=quantities['World total (rounded)'] for _,prior, current, share, change in mine: assert pct(current,world)==share assert pct(int(current)-int(prior),prior)==change for _,prior,current,delta,change in rows('2024-vintage-comparison'): assert int(current)-int(prior)==int(delta) assert pct(delta,prior)==change return pct(quantities['Canada']+quantities['Russia'],world) def verify_concentration(): stages={} for stage,name in [('Production','kcl-world-production'),('Exports','kcl-world-exports')]: source=rows(name) world=next(int(r[1]) for r in source if r[0] in ('Total','World total')) group=sum(int(r[1]) for r in source if r[0] in ('Canada','Russia','Belarus')) stages[stage]=(group,world,pct(group,world)) for stage, _, group, total, share in rows('kcl-concentration-by-stage'): assert (int(group),int(total),share)==stages[stage] production=stages['Production'][2] exports=stages['Exports'][2] return production,exports,f'{Decimal(exports)-Decimal(production):.4f}' def verify_us_balance(): for year,_,sales, gross, exports, net, displayed_app, app, official, ratio in rows('us-supply-balance'): assert int(net)==int(gross)-int(exports) assert int(displayed_app)==int(sales)+int(net) assert pct(net,app)==ratio if year=='2025 estimate': result=(int(net),int(official),ratio) return result def main(): mine=verify_mine_tables() production,exports,delta=verify_concentration() net,official,ratio=verify_us_balance() assert (mine,production,exports,net,official,ratio)==('51.0204','70.5374','76.9802',5430,92,'92.0339') print(json.dumps({'2025_Canada_and_Russia_mine_share_percent':mine,'2024_three_country_production_share_percent':production, '2024_three_country_export_share_percent':exports,'export_minus_production_percentage_points':delta, '2025_US_net_imports_kt_K2O_equivalent':net,'2025_US_published_reliance_percent':official,'2025_US_rounded_reliance_percent':ratio})) if __name__=='__main__': main()