"""Reproduce derived figures in this AMR statistics package.""" from decimal import Decimal as D from pathlib import Path import csv import json root = Path(__file__).resolve().parent base = root/'data' if (root/'data').is_dir() else root def rows(name): with (base/(name+'.csv')).open(newline='') as f: return list(csv.reader(f))[1:] def fmt(value): return f'{value:.2f}' world = {} for commodity,unit,production,reserves,ratio in rows('world-reserves-to-mine-output'): assert ratio==fmt(D(reserves)/D(production)) world[commodity]=(D(production),D(reserves)) assert len(world)==6 and world['Copper']==(D(23000),D(980000)) matches = {} for commodity,location,unit,production,reserves,output_pct,reserve_pct,gap in rows('selected-country-reserve-and-production-shares'): world_production,world_reserves = world[commodity] flow = D(production)*100/world_production stock = D(reserves)*100/world_reserves assert [fmt(n) for n in (flow,stock,stock-flow)]==[output_pct,reserve_pct,gap] matches[commodity]=[location,output_pct,reserve_pct,gap] assert matches['Phosphate rock']==['Morocco','14.40','68.49','54.09'] print(json.dumps({'selected_country_shares':matches,'copper_reserves_to_output':fmt(world['Copper'][1]/world['Copper'][0])}))