"""Reproduce the published AMR natural graphite calculations.""" from pathlib import Path from decimal import Decimal as D import csv import json def read(stem): parent=Path(__file__).resolve().parent file=parent/(stem+'.csv') if not file.exists(): file=parent/'data'/file.name with file.open() as handle: return list(csv.reader(handle))[1:] def share(a,b): return (D(a)/D(b)*100).quantize(D('.0001')) def change(a,b): return ((D(b)/D(a)-1)*100).quantize(D('.0001')) world=read('graphite-world-mine-output') assert len(world)==20 and world[-1][:3]==['World total','1550000','1800000'] by_country={r[0]:r for r in world[:-1]} china=by_country['China'] assert china[2]=='1400000' crosscheck=read('graphite-china-share-crosscheck') assert crosscheck[0][1]=='82' and D(crosscheck[1][1])==share(china[2],world[-1][2]) for number,key,tons,pct in read('graphite-top-producers'): assert by_country[key][2]==tons and D(pct)==share(tons,world[-1][2]) for country,earlier,later,revision in read('graphite-2024-vintage-revisions'): assert D(revision)==D(later)-D(earlier) assert later==(by_country[country][1] if country!='World total' else world[-1][1]) us=read('graphite-us-natural-balance') assert [r[0] for r in us]==list(map(str,range(2021,2026))) assert all(r[1]=='0' and r[5]=='100' for r in us) assert us[-1][2:5]==['79000','8400','71000'] forms=read('graphite-us-2025-import-forms') assert sum(D(x[1]) for x in forms)==100 for _,pct,tons in forms: assert D(tons)==D(pct)*D(us[-1][2])/100 for _,old,new,pct,*rest in [*read('graphite-us-anode-imports'),*read('graphite-china-export-stages')]: assert D(pct)==change(old,new) assert sum(D(x[1]) for x in read('graphite-us-natural-import-origins'))==100 assert sum(D(x[1]) for x in read('graphite-us-anode-import-origins'))==100 stages=read('graphite-iea-2035-stage-regions') assert len(stages)==7 and next(r for r in stages if r[0]=='Africa')==['Africa','499.7','0.0','0.0'] print(json.dumps({'china_table_percent':crosscheck[1][1], 'china_prose_estimate_percent':crosscheck[0][1], 'us_2025_gross_trade_difference_tonnes':str(D(us[-1][2])-D(us[-1][3])), 'matched_8_month_anode_import_change_percent':read('graphite-us-anode-imports')[0][3]}))