"""One-anchor normalized similarity loss and one scalar update, not full SimCLR."""
import math,json
KEYS=[[1.,0.],[0.,1.],[-1.,0.]]
def loss_gradient(theta,tau=.5):
    if not math.isfinite(theta) or not math.isfinite(tau) or tau<=0:raise ValueError('finite theta, positive temperature')
    q=[math.cos(theta),math.sin(theta)];dq=[-math.sin(theta),math.cos(theta)]
    logits=[sum(a*b for a,b in zip(q,k))/tau for k in KEYS]
    ds=[sum(a*b for a,b in zip(dq,k))/tau for k in KEYS];peak=max(logits);ex=[math.exp(x-peak) for x in logits];den=sum(ex);p=[x/den for x in ex]
    loss=peak+math.log(den)-logits[0];grad=sum(a*b for a,b in zip(p,ds))-ds[0]
    return loss,grad,p
def provenance_contract(anchor_source,candidate_sources,positive_index):
    if candidate_sources[positive_index]!=anchor_source:raise ValueError('positive view must share authored source in this profile')
    if any(s==anchor_source for i,s in enumerate(candidate_sources) if i!=positive_index):raise ValueError('same-source negative in this profile')
    return True
def demo():
    theta=.4;before,g,p=loss_gradient(theta);after_theta=theta-.1*g;after,_,p2=loss_gradient(after_theta)
    h=1e-6;finite=(loss_gradient(theta+h)[0]-loss_gradient(theta-h)[0])/(2*h)
    assert abs(finite-g)<1e-7 and after<before and abs(sum(p)-1)<1e-12
    assert provenance_contract('A',['A','B','C'],0)
    rejected=0
    for sources in [['B','B','C'],['A','A','C']]:
        try:provenance_contract('A',sources,0)
        except ValueError:rejected+=1
        else:raise AssertionError('invalid authored source profile accepted')
    return {'query_initial_angle_radians':theta,'unit_candidate_vectors':KEYS,'positive_candidate_index':0,'temperature':.5,'one_anchor_loss_before':before,'analytic_angle_gradient':g,'finite_difference_gradient':finite,'learning_rate':.1,'angle_after_one_step':after_theta,'one_anchor_loss_after':after,'candidate_weights_before':p,'candidate_weights_after':p2,'authored_provenance_contract_rejections':rejected,'encoder_training_or_SimCLR_execution':False,'semantic_pair_validation':False}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
