"""T750: two-loop sunrise amplitudes with arbitrary masses, positive D=2 units.

Install SageMath, then run `sage -pip install numberdb mpmath`. `sage -python generate.py` verifies all stored
entries without writing. `sage -python generate.py --publish` adds/updates the
numbers of this existing draft; it does not offer or publish the draft.

Parameters are (a,b,c,t), positive ordered masses and real Minkowski momentum
squared 0<=t<(a+b+c)^2. The source scale is one and each propagator has power
one. The quantity is the positive simplex/projective Feynman integral,
not a Bessel integral missing its factor four. Default selection is all
primitive positive integer mass triples of perimeter <=12, with vacuum and
all distinct proper pseudothreshold squares. The natural domain is continuous.

The y integration is analytic, with stable logarithm/atan2 formulas and a
removable-discriminant series. The remaining x=q/(1-q) integral uses mpmath
tanh-sinh at digits+50 and digits+100 decimal working places. The returned
interval is their union with guard widths; this is heuristic agreement,
NOT a certified quadrature bound. All rational inputs are constructed from
exact numerator/denominator pairs, never Python float division.

Private-draft reads and writes need your configured NumberDB API key.
Offline amplitude(params,digits) needs no key.

Optional NUMBERDB_SUNRISE_CACHE points to the attached checkpoint.json.
Only matching-source, matching-method entries of adequate precision are reused.
Remove that variable to recompute. The cache is a reproducibility checkpoint,
not independent mathematical evidence. Independent parameter and Bessel checks
and the precision/coverage notes are attached separately.
"""
import os,sys,json,math,time,hashlib
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField
import mpmath as mp
METHOD='sunrise-parameter-tanh-sinh-agreement-v1'

def selection(perimeter=12):
 for total in range(3,perimeter+1):
  for a in range(1,total//3+1):
   for b in range(a,(total-a)//2+1):
    c=total-a-b
    if math.gcd(a,math.gcd(b,c))!=1:continue
    for t in sorted({0,(a+b-c)**2,(a-b+c)**2,(-a+b+c)**2}):yield dict(a=a,b=b,c=c,t=t)

def compute(params,working):
 with mp.workdps(working):
  inputs=[QQ(str(params[k])) for k in ('a','b','c','t')]
  a,b,c,t=[mp.mpf(str(v.numerator()))/mp.mpf(str(v.denominator())) for v in inputs]
  if not (0<a<=b<=c and 0<=t<(a+b+c)**2):raise ValueError('Require ordered positive masses and 0<=t<(a+b+c)^2')
  def f(q):
   if q==0 or q==1:return mp.mpf(0)
   x=q/(1-q);A=b*b*(x+1);B=(a*a*x+c*c)*(x+1)+(b*b-t)*x;C=x*(a*a*x+c*c);D=B*B-4*A*C
   z=D/(B*B) if B else mp.inf
   if abs(z)<mp.mpf('0.01'):
    # 2*atanh(sqrt(z))/sqrt(D), analytic at D=0.
    term=mp.mpf(1);series=term;j=1
    while True:
     term*=z;add=term/(2*j+1);series+=add
     if abs(add)<mp.eps*abs(series):break
     j+=1
    v=2*series/B
   elif D>0:
    root=mp.sqrt(D);v=2*mp.log((B+root)/(2*mp.sqrt(A*C)))/root
   else:
    root=mp.sqrt(-D);v=2*mp.atan2(root,B)/root
   return v/(1-q)**2
  pts=sorted(set([mp.mpf(0),mp.mpf(1)/10,mp.mpf(1)/2,mp.mpf(9)/10,mp.mpf(1),c/(a+c)]))
  v=mp.quad(f,pts,method='tanh-sinh')
  if not mp.isfinite(v) or v<=0:raise ArithmeticError('Nonfinite or nonpositive amplitude')
  return mp.nstr(v,working)

def amplitude(params,digits=100,evidence=None):
 # Guard the last ten working places: agreement is evidence, not certification.
 field=RealIntervalField(numberdb.bits(digits+100))
 vals=[];texts=[]
 for working in (digits+50,digits+100):
  text=compute(params,working);texts.append(text);v=field(text)
  error=field(10)**(-working+10)*max(field(1),abs(v))
  vals.append(v+field(-error.upper(),error.upper()))
 result=vals[0].union(vals[1])
 if result.absolute_diameter()<=0:raise ArithmeticError('Unexpected exact singleton')
 # Requested significant digits plus ten must be supported by agreement.
 if (result.upper()-result.lower())/min(abs(result.lower()),abs(result.upper()))>=(field(10)**(-digits-10)).lower():
  raise ArithmeticError('Insufficient precision agreement')
 if evidence is not None:evidence.update(working_decimal_digits=[digits+50,digits+100],working_values=texts)
 return result

class Sunrise(numberdb.Generator):
 table='T750';parameters=('a','b','c','t');type='R';digits=100
 rigour='heuristic (agreement-checked)'
 def enumerate(self,perimeter=12):return selection(perimeter)
 def value(self,params,digits):
  key=','.join(str(params[k]) for k in self.parameters);cache_path=os.environ.get('NUMBERDB_SUNRISE_CACHE');cache={}
  if cache_path and Path(cache_path).exists():cache=json.loads(Path(cache_path).read_text())
  item=cache.get(key)
  source_sha=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
  if item and item.get('generator_sha256')!=source_sha:raise ValueError('Checkpoint source mismatch; unset NUMBERDB_SUNRISE_CACHE to recompute')
  if item and item.get('method')==METHOD and item.get('digits',0)>=digits:
   return RealIntervalField(numberdb.bits(digits+100))(QQ(item['lo']),QQ(item['hi']))
  start=time.time();v=amplitude(params,digits)
  if cache_path:
   cache[key]={'generator_sha256':source_sha,'method':METHOD,'digits':digits,'lo':str(QQ(v.lower())),'hi':str(QQ(v.upper())),'seconds':time.time()-start}
   target=Path(cache_path);tmp=target.with_suffix('.tmp');tmp.write_text(json.dumps(cache,indent=2));tmp.replace(target)
  return v

if __name__=='__main__':
 if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
  key=sys.stdin.read().strip()
  if '=' in key and key.split('=',1)[0].isupper():key=key.split('=',1)[1].strip().strip('\"\'')
  os.environ['NUMBERDB_API_KEY']=key
 g=Sunrise()
 if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':g.publish()
 else:print(g.verify(sample=None))
