"""Owned homogeneous degree2 kernel, exact overcomplete map and sqrt2 compressed check."""
from fractions import Fraction as F
import math,json
def validate(x):
    if len(x)!=2 or any(type(v)not in (int,F) for v in x):raise ValueError('two exact rational coordinates required')
def dot(x,y):return sum(a*b for a,b in zip(x,y))
def phi4(x):
    validate(x);a,b=x;return [a*a,a*b,b*a,b*b]
def phi3_scaled(x):
    validate(x);a,b=map(float,x);return [a*a,math.sqrt(2)*a*b,b*b]
def wrong_phi3(x):
    validate(x);a,b=x;return [a*a,a*b,b*b]
def kernel(x,z):
    validate(x);validate(z);return dot(x,z)**2
def demo():
    X=[[F(1),F(2)],[F(3),F(-1)],[F(0),F(1)]];Phi=[phi4(x) for x in X]
    Gram=[[dot(a,b) for b in Phi] for a in Phi];direct=[[kernel(x,z) for z in X] for x in X];assert Gram==direct==[[25,1,4],[1,100,1],[4,1,1]]
    for x in X:
        for z in X:assert abs(dot(phi3_scaled(x),phi3_scaled(z))-float(kernel(x,z)))<1e-12
    wrong=dot(wrong_phi3(X[0]),wrong_phi3(X[1]));assert wrong==7 and kernel(X[0],X[1])==1
    c=[F(1),F(-1),F(2)];quadratic=sum(c[i]*Gram[i][j]*c[j] for i in range(3) for j in range(3));feature_combo=[sum(c[i]*Phi[i][j] for i in range(3)) for j in range(4)];norm=dot(feature_combo,feature_combo);assert quadratic==norm==139
    q=[F(2),F(1)];qkernels=[kernel(q,x) for x in X];assert qkernels==[16,25,1] and qkernels==[dot(phi4(q),row) for row in Phi]
    rejected=[]
    for name,x in [('wrong_dimension',[F(1)]),('boolean_coordinate',[True,F(1)])]:
        try:phi4(x)
        except ValueError:rejected.append(name)
        else:raise AssertionError(name)
    return {'kernel_definition':'(x dot z)^2, degree2 gamma1 offset0; not API defaults','training_inputs':X,'exact_overcomplete_phi4':Phi,'exact_Gram_by_feature_inner_product':Gram,'exact_Gram_by_kernel':direct,'compressed_phi3_float':[[round(v,12) for v in phi3_scaled(x)] for x in X],'compressed_phi3_tolerance':1e-12,'wrong_unscaled_cross_term_inner_product':wrong,'correct_pair_inner_product':kernel(X[0],X[1]),'coefficient_vector':c,'feature_linear_combination':feature_combo,'c_transpose_K_c':quadratic,'squared_norm_Phi_transpose_c':norm,'new_query':q,'new_query_training_similarities':qkernels,'two_invalid_input_contracts_rejected':rejected,'SVM_regression_training_or_sklearn_executed':False}
if __name__=='__main__':print(json.dumps(demo(),default=str,indent=2))
