#!/usr/bin/env python3 """Synthetic arithmetic only: no chain queries, wallets, or security grading.""" import csv import io import json from collections import defaultdict from decimal import Decimal, localcontext from fractions import Fraction from pathlib import Path import argparse SAMPLE='id,controller,weight,evidence,observed_on\nV1,A,1,synthetic input,not observed\nV2,A,1,synthetic input,not observed\nV3,B,8,synthetic input,not observed\nV4,,5,unknown in this synthetic input,not observed\n' def validated_rows(text): reader=csv.DictReader(io.StringIO(text), strict=True) try: if reader.fieldnames!=['id','controller','weight','evidence','observed_on']: raise ValueError('Expected exact CSV header') for row in reader: if None in row or any(value is None for value in row.values()): raise ValueError('CSV record ending on line '+str(reader.line_num)+' must have exactly five fields; quote labels containing commas') yield row except csv.Error as error: raise ValueError('Malformed CSV quoting near line '+str(reader.line_num)+': '+str(error)) from error def calculate(text): ids=set();rows=[];weights=[] for row in validated_rows(text): if not row['id'] or row['id'] in ids:raise ValueError('Missing or duplicate ID') weight=Decimal(row['weight']) if not weight.is_finite() or weight<=0:raise ValueError('Expected positive finite weight') ids.add(row['id']);rows.append(row);weights.append(weight) if not rows:raise ValueError('No records') # Preserve every input digit in additions, independently of ambient precision. # Sum precision covers the largest integer place through the smallest fraction # place, plus carry digits. This does not mutate the caller's Decimal context. places=max(x.adjusted()for x in weights)-min(x.as_tuple().exponent for x in weights)+1 with localcontext() as context: context.prec=max(28,places+len(str(len(rows)))+2) groups=defaultdict(lambda:{'ids':0,'weight':Decimal(0)}) for row,weight in zip(rows,weights): label=row['controller'].strip() or None # None is an unknown subtotal, never an asserted common controller. groups[label]['ids']+=1;groups[label]['weight']+=weight total=sum((v['weight']for v in groups.values()),Decimal(0)) def percent(a,b): # Exact hundredths of a percentage, round-half-even (including ties). q=Fraction(a)*10000/Fraction(b);whole,remainder=divmod(q.numerator,q.denominator) if remainder*2>q.denominator or(remainder*2==q.denominator and whole%2):whole+=1 return f'{whole//100}.{whole%100:02d}' totals=[{'controller':k,'meaning':'unknown subtotal, not one controller' if k is None else 'input label, not independently verified', 'ids':v['ids'],'weight':str(v['weight']),'id_percent':percent(v['ids'],len(rows)), 'weight_percent':percent(v['weight'],total)}for k,v in groups.items()] return {'kind':'synthetic arithmetic, not chain observations or a security score','rows':rows,'total_ids':len(rows),'total_weight':str(total),'groups':totals} if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('--input',type=Path);parser.add_argument('--output',type=Path,required=True);args=parser.parse_args() try:result=calculate(args.input.read_text(encoding='utf-8-sig') if args.input else SAMPLE) except ValueError as error:parser.error(str(error)) if args.input is None: assert [(x['id_percent'],x['weight_percent']) for x in result['groups']]==[('50.00','13.33'),('25.00','53.33'),('25.00','33.33')] try:calculate(SAMPLE.replace('V2,A','V1,A')) except ValueError:pass else:raise AssertionError('Duplicate ID accepted') with args.output.open('x',encoding='utf-8') as output:json.dump(result,output,ensure_ascii=False,indent=2);output.write('\n')