#!/usr/bin/env python3
"""CurriVerse X QR lab / آزمایش QR. Standard-library only.
Run / اجرا: python3 ee-qr.py 1 2 3 4
Inputs k,a,b,c: [-4,6] in steps of 0.5; negative fractions accepted.
"""
import argparse
from fractions import Fraction
import json
import math

TOL=1e-9


def value(text):
    try:v=Fraction(text)
    except (ValueError,ZeroDivisionError):
        raise argparse.ArgumentTypeError('Use a number or half-unit fraction such as -1/2.')
    if not -4<=v<=6 or (2*v).denominator!=1:
        raise argparse.ArgumentTypeError('Use values from -4 to 6 in steps of 0.5.')
    return float(v)


def dot(u,v):return sum(x*y for x,y in zip(u,v))


def analyze(k,a,b,c):
    u=[1.0,0.0,1.0];v=[1.0,k,1.0];y=[a,b,c]
    r11=math.sqrt(dot(u,u));q1=[x/r11 for x in u]
    r12=dot(q1,v);w=[v[i]-r12*q1[i] for i in range(3)]
    dependent=k==0  # Exact structural condition for this fixed family.
    if dependent:
        q=[q1];r=[[r11,r12]];z=[dot(q1,y)]
        coefficients=None
    else:
        r22=math.sqrt(dot(w,w));q2=[x/r22 for x in w]
        q=[q1,q2];r=[[r11,r12],[0.0,r22]];z=[dot(q1,y),dot(q2,y)]
        beta2=z[1]/r22;beta1=(z[0]-r12*beta2)/r11
        coefficients=[beta1,beta2]
    fitted=[sum(q[j][i]*z[j] for j in range(len(q))) for i in range(3)]
    residual=[y[i]-fitted[i] for i in range(3)]
    reconstructed=[[sum(q[j][i]*r[j][col] for j in range(len(q))) for col in range(2)] for i in range(3)]
    original=[[u[i],v[i]] for i in range(3)]
    recon_error=max(abs(reconstructed[i][j]-original[i][j]) for i in range(3) for j in range(2))
    orth_error=max(abs(dot(q[i],q[j])-(1 if i==j else 0)) for i in range(len(q)) for j in range(len(q)))
    normal=[dot(u,residual),dot(v,residual)]
    assert recon_error<TOL and orth_error<TOL and max(map(abs,normal))<TOL
    if coefficients is not None:
        assert max(abs(coefficients[0]*u[i]+coefficients[1]*v[i]-fitted[i]) for i in range(3))<TOL
    return {'rank':len(q),'q_columns':q,'r':r,'r22':0.0 if dependent else r[1][1],
            'coefficients':coefficients,'coefficient_sum':z[0]/r11 if dependent else None,
            'fitted':fitted,'residual':residual,'sse':dot(residual,residual),
            'reconstruction_error':recon_error,'orthonormality_error':orth_error,
            'normal_checks':normal,'tolerance':TOL}


def main():
    parser=argparse.ArgumentParser(usage='%(prog)s [--json] k a b c',description='Two-column Gram–Schmidt, QR checks, and least squares.')
    parser.add_argument('--json',action='store_true');args,inputs=parser.parse_known_args()
    if len(inputs)!=4:parser.error('Provide exactly four values: k,a,b,c.')
    try:values=[value(x) for x in inputs]
    except argparse.ArgumentTypeError as error:parser.error(str(error))
    r=analyze(*values)
    if args.json:print(json.dumps(r));return
    print('Rank:',r['rank']);print('Q columns:',r['q_columns']);print('R:',r['r'])
    print('Coefficients:',r['coefficients'] if r['coefficients'] is not None else 'not unique; beta1+beta2='+str(r['coefficient_sum']))
    print('Fit:',r['fitted']);print('SSE:',r['sse'])
    print('Max reconstruction error:',r['reconstruction_error'])
    print('Max orthonormality error:',r['orthonormality_error'])
    print('A transpose residual:',r['normal_checks']);print('Tolerance:',TOL)


if __name__=='__main__':main()
