← Files Uni Lecture TutorARCHIVED FILE

skills/automatic-lecture-learning/scripts/ult_math_extended.py

13.4 KB · Nov 30, 2026 · 18:13 UTC

↓ Download file

See the change to this file →

"""Bounded deterministic checks for explicit academic inputs. No evaluation of user code.
All numbers are integers or rational/decimal strings. No automatic parsing of lecture text.
"""
from ult_safe_io import safe_error
import argparse, json, re, sys, math
from fractions import Fraction as F
from ult_math import parse, add, Unsupported, MAX_BITS

MAX_MATRIX=12
MAX_VALUES=1000

def need(ok, msg):
    if not ok: raise Unsupported(msg)

def bounded(v):
    need(v.numerator.bit_length()<=MAX_BITS and v.denominator.bit_length()<=MAX_BITS,'numeric bound exceeded')
    return v

def number(v):
    need(type(v) is int or (type(v) is str and len(v)<=160 and re.fullmatch(r'[+-]?(?:[0-9]+(?:\.[0-9]+)?|[0-9]+/[0-9]+)',v) is not None),'expected bounded exact rational or decimal string')
    try:return bounded(F(v))
    except (ValueError,ZeroDivisionError):raise Unsupported('invalid rational') from None

def equation(left,right,domain='real'):
    need(domain in ('real','rational','complex'),'unsupported domain')
    def rationalize(expr):
        need(type(expr) is str and len(expr)<=256,'expression bound/type')
        return re.sub(r'(?<![A-Za-z0-9_.])[0-9]+\.[0-9]+(?![A-Za-z0-9_.])',lambda m:'('+str(number(m.group()))+')',expr)
    p=add(parse(rationalize(left)),parse(rationalize(right)),-1); degree=max(p,default=0)
    a,b,c=(p.get(i,F(0)) for i in (2,1,0))
    if degree==0:return {'kind':'all' if not c else 'none','domain':domain,'roots':[]}
    if degree==1:return {'kind':'finite','domain':domain,'roots':[str(bounded(-c/b))]}
    need(degree==2,'only linear and quadratic equations supported')
    d=bounded(b*b-4*a*c); center=bounded(-b/(2*a))
    if d==0:return {'kind':'finite','domain':domain,'roots':[str(center)]}
    if d<0 and domain!='complex':return {'kind':'none','domain':domain,'roots':[]}
    rad=abs(d); n,m=math.isqrt(rad.numerator),math.isqrt(rad.denominator)
    if n*n==rad.numerator and m*m==rad.denominator:
        offset=bounded(abs(F(n,m)/(2*a)))
        if d<0:return {'kind':'finite','domain':domain,'roots':[{'real':str(center),'imag':str(-offset)},{'real':str(center),'imag':str(offset)}]}
        return {'kind':'finite','domain':domain,'roots':[str(bounded(center-offset)),str(bounded(center+offset))]}
    if domain=='rational':return {'kind':'none','domain':domain,'roots':[]}
    return {'kind':'radical_pair','domain':domain,'center':str(center),'coefficient':str(bounded(abs(1/(2*a)))),'radicand':str(rad),'imaginary':d<0,'representation':'center ± coefficient * sqrt(radicand)'+(' * i' if d<0 else '')}

def equation_steps(steps,domain='real'):
    need(type(steps) is list and 2<=len(steps)<=64,'equation step count limit')
    def canonical(r):
        if r['kind']=='radical_pair':return ('radical_pair',r['center'],str(bounded(number(r['coefficient'])**2*number(r['radicand']))),r['imaginary'])
        return (r['kind'],json.dumps(r['roots'],sort_keys=True))
    previous=None;checked=[]
    for i,step in enumerate(steps,1):
        need(type(step) is list and len(step)==2,'each step must be [left,right]')
        try:sol=equation(*step,domain=domain)
        except Unsupported as exc:return {'checked_through_step':i-1,'first_solution_set_change':None,'unsupported_step':i,'reason':str(exc),'method_verified':False}
        current=canonical(sol);checked.append({'step':i,'solution_set':sol})
        if previous is not None and current!=previous:return {'checked_through_step':i,'first_solution_set_change':i,'unsupported_step':None,'steps':checked,'method_verified':False}
        previous=current
    return {'checked_through_step':len(steps),'first_solution_set_change':None,'unsupported_step':None,'steps':checked,'method_verified':False,'note':'Equivalent solution sets do not prove each transformation or justification is valid.'}


def transformation_proof(steps, operations, domain='real'):
    """Verify declared equivalent transformations over supported polynomials; not prose proofs."""
    from ult_math import mul, constant, guard
    need(type(steps) is list and 2<=len(steps)<=64 and type(operations) is list and len(operations)==len(steps)-1,'one operation per step required')
    need(domain in ('real','rational','complex'),'unsupported domain')
    def poly(expr):
        need(type(expr) is str and len(expr)<=256,'expression bound/type')
        return parse(re.sub(r'(?<![A-Za-z0-9_.])[0-9]+\.[0-9]+(?![A-Za-z0-9_.])',lambda m:'('+str(number(m.group()))+')',expr))
    checked=[]
    for i,op in enumerate(operations,1):
        try:
            need(type(steps[i-1]) is list and len(steps[i-1])==2 and type(steps[i]) is list and len(steps[i])==2,'step must contain two sides')
            left,right=map(poly,steps[i-1]);nleft,nright=map(poly,steps[i]);need(type(op) is dict and 'kind' in op,'operation required');kind=op['kind']
            if kind in ('add','subtract'):
                need(set(op)=={'kind','expression'},'expression required');v=poly(op['expression']);sign=1 if kind=='add' else -1;expected=add(left,v,sign),add(right,v,sign)
            elif kind in ('multiply','divide'):
                need(set(op)=={'kind','factor'},'constant factor required');v=number(op['factor']);need(v!=0,'nonzero factor required');v=v if kind=='multiply' else 1/v;expected=mul(left,constant(v)),mul(right,constant(v))
            elif kind in ('swap','simplify'):
                need(set(op)=={'kind'},'unexpected operation fields');expected=(right,left) if kind=='swap' else (left,right)
            else:raise Unsupported('unsupported declared transformation')
            if expected!=(nleft,nright):return {'verified':False,'first_mismatch_step':i+1,'unsupported_step':None,'checked_steps':checked,'method_scope':'declared polynomial transformation only'}
            checked.append(i+1)
        except Unsupported as exc:return {'verified':False,'first_mismatch_step':None,'unsupported_step':i+1,'reason':str(exc),'checked_steps':checked}
    return {'verified':True,'first_mismatch_step':None,'unsupported_step':None,'checked_steps':checked,'method_scope':'declared polynomial transformation only','prose_justification_verified':False}


def matrix(v):
    need(type(v) is list and 1<=len(v)<=MAX_MATRIX and all(type(r) is list for r in v),'matrix row bound/type')
    n=len(v[0]);need(1<=n<=MAX_MATRIX and all(len(r)==n for r in v),'rectangular matrix required')
    return [[number(x) for x in r] for r in v]

def elimination(v,inverse=False):
    a=matrix(v);m,n=len(a),len(a[0]);need(not inverse or m==n,'inverse requires square matrix')
    if inverse:a=[row+[F(int(i==j)) for j in range(n)] for i,row in enumerate(a)]
    rank=0;det=F(1);swaps=0
    for col in range(n):
        pivot=next((i for i in range(rank,m) if a[i][col]),None)
        if pivot is None:continue
        if pivot!=rank:a[pivot],a[rank]=a[rank],a[pivot];swaps+=1
        p=a[rank][col];det=bounded(det*p);a[rank]=[bounded(x/p) for x in a[rank]]
        for i in range(m):
            if i==rank or not a[i][col]:continue
            f=a[i][col];a[i]=[bounded(x-bounded(f*y)) for x,y in zip(a[i],a[rank])]
        rank+=1
        if rank==m:break
    out={'rank':rank,'shape':[m,n],'rref':[[str(x) for x in r[:n]] for r in a]}
    if m==n:out['determinant']=str(F(0) if rank<n else (-det if swaps%2 else det))
    if inverse:out['inverse']=None if rank<n else [[str(x) for x in r[n:]] for r in a]
    return out

def complex_op(a,b,op):
    need(type(a) is list and type(b) is list and len(a)==len(b)==2,'complex number = [real, imaginary]')
    x,y=map(number,a);u,v=map(number,b)
    if op=='add':r,i=x+u,y+v
    elif op=='subtract':r,i=x-u,y-v
    elif op=='multiply':r,i=x*u-y*v,x*v+y*u
    elif op=='divide':
        den=bounded(u*u+v*v);need(den!=0,'division by zero');r,i=(x*u+y*v)/den,(y*u-x*v)/den
    else:raise Unsupported('unknown complex operation')
    return [str(bounded(r)),str(bounded(i))]

def stats(values):
    need(type(values) is list and 1<=len(values)<=MAX_VALUES,'sample size limit')
    a=sorted(map(number,values));n=len(a);total=F(0)
    for v in a:total=bounded(total+v)
    mean=bounded(total/n);ss=F(0)
    for v in a:ss=bounded(ss+bounded((v-mean)**2))
    median=bounded((a[(n-1)//2]+a[n//2])/2)
    return {'count':n,'mean':str(mean),'median':str(median),'population_variance':str(bounded(ss/n)),'sample_variance':str(bounded(ss/(n-1))) if n>1 else None,'min':str(a[0]),'max':str(a[-1])}

def compare_numeric(actual,expected,absolute='0',relative='0'):
    a,e,at,rt=map(number,(actual,expected,absolute,relative));need(at>=0 and rt>=0,'tolerances must be nonnegative');diff=bounded(abs(a-e));limit=max(at,bounded(rt*abs(e)))
    return {'equal_within_tolerance':diff<=limit,'absolute_error':str(diff),'tolerance':str(limit),'relative_reference':'expected'}

def dimension(v):
    # seven SI dimensions in fixed order; only exact exponent equality, not unit conversion.
    need(type(v) is list and len(v)==7 and all(type(i) is int and -24<=i<=24 for i in v),'seven bounded integer SI exponents required')
    return v

def dimensional_match(a,b):return {'dimension_equal':dimension(a)==dimension(b),'order':['mass','length','time','current','temperature','amount','luminous_intensity'],'unit_conversion_verified':False}

def logic_equivalent(a,b,variables):
    need(type(variables) is list and len(variables)<=8 and all(type(v) is str and re.fullmatch(r'[A-Z][A-Z0-9]{0,7}',v) for v in variables) and len(set(variables))==len(variables),'invalid variable set')
    from itertools import product
    def compile_node(x,depth=0,counter=None):
        if counter is None:counter=[0]
        counter[0]+=1;need(depth<=24 and counter[0]<=128,'logic expression limit')
        if type(x) is bool:return lambda env:x
        if type(x) is str:
            need(x in variables,'unknown variable');return lambda env:env[x]
        need(type(x) is list and len(x) in (2,3) and type(x[0]) is str,'invalid logic node');op=x[0]
        if op=='not':need(len(x)==2,'not arity');f=compile_node(x[1],depth+1,counter);return lambda env:not f(env)
        need(len(x)==3 and op in ('and','or','xor','implies','iff'),'unknown operator/arity');f=compile_node(x[1],depth+1,counter);g=compile_node(x[2],depth+1,counter)
        return lambda env: {'and':lambda x,y:x and y,'or':lambda x,y:x or y,'xor':lambda x,y:x!=y,'implies':lambda x,y:not x or y,'iff':lambda x,y:x==y}[op](f(env),g(env))
    f,g=compile_node(a),compile_node(b);mismatches=[];n=0
    for values in product((False,True),repeat=len(variables)):
        env=dict(zip(variables,values));n+=1
        if f(env)!=g(env):mismatches.append(env)
    return {'equivalent':not mismatches,'rows':n,'counterexample':mismatches[0] if mismatches else None}

def trace_steps(initial,steps):
    need(type(initial) is dict and len(initial)<=32 and all(type(k) is str and re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,15}',k) for k in initial),'invalid trace variable set')
    need(type(steps) is list and len(steps)<=100,'trace step limit')
    env={k:number(v) for k,v in initial.items()};frames=[]
    def operand(x):
        if type(x) is dict:
            need(set(x)=={'var'} and type(x['var']) is str and x['var'] in env,'unknown trace variable');return env[x['var']]
        return number(x)
    for i,step in enumerate(steps,1):
        need(type(step) is dict and set(step)=={'target','op','args'} and step['target'] in env and type(step['args']) is list,'invalid trace instruction')
        op=step['op'];args=step['args'];need(type(op) is str and ((op=='assign' and len(args)==1) or (op in ('add','sub','mul','div') and len(args)==2)),'unsupported trace instruction')
        v=list(map(operand,args))
        if op=='assign':r=v[0]
        elif op=='add':r=v[0]+v[1]
        elif op=='sub':r=v[0]-v[1]
        elif op=='mul':r=v[0]*v[1]
        else:need(v[1]!=0,'division by zero');r=v[0]/v[1]
        env[step['target']]=bounded(r);frames.append({'step':i,'variables':{k:str(v) for k,v in env.items()}})
    return {'frames':frames,'final':{k:str(v) for k,v in env.items()},'semantics':'exact rational assignments; not a programming language interpreter'}


def dispatch(data):
    need(type(data) is dict and type(data.get('operation')) is str,'expected operation object')
    funcs={'equation':(equation,{'left','right'},{'domain'}),'equation_steps':(equation_steps,{'steps'},{'domain'}),'transformation_proof':(transformation_proof,{'steps','operations'},{'domain'}),'matrix':(elimination,{'v'},{'inverse'}),'complex':(complex_op,{'a','b','op'},set()),'statistics':(stats,{'values'},set()),'numeric':(compare_numeric,{'actual','expected'},{'absolute','relative'}),'dimensions':(dimensional_match,{'a','b'},set()),'logic':(logic_equivalent,{'a','b','variables'},set()),'trace':(trace_steps,{'initial','steps'},set())}
    need(data['operation'] in funcs,'unsupported operation');fn,required,optional=funcs[data['operation']];args={k:v for k,v in data.items() if k!='operation'};need(required<=set(args)<=required|optional,'unexpected/missing fields')
    if 'inverse' in args:need(type(args['inverse']) is bool,'inverse must be boolean')
    return {'supported':True,'operation':data['operation'],'result':fn(**args),'student_work_verified':False}

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('request');a=p.parse_args()
    try:
        from ult_safe_io import read_json
        data=read_json(a.request,100000)

        print(json.dumps(dispatch(data),ensure_ascii=True,allow_nan=False));return 0
    except (Unsupported,ValueError,TypeError,OSError,RecursionError,OverflowError) as e:print(json.dumps({'supported':False,'reason':safe_error(e)}));return 2
if __name__=='__main__':sys.exit(main())

SHA-256: 4fb9241f9f6c921a48b5889394c7f839ed2a2155e876991455c3c77d11ea0e64