{
  "chapter": "AI-16",
  "status": "Stored standalone examples actually executed; interactive client/independent whole/fixed/UI/native review pending",
  "programProcesses": 30,
  "successful": 28,
  "expectedInvalid": 2,
  "storedSVG": 28,
  "authorTargetLaunchesIncludingHistory": 31,
  "history": "Initial30 actual targets=28normal+2expected overlap rejections. One additional realdata-person R execution moved an obscuring legend to the empty center; summary/points/resultJSON remained byte-identical. Current archive30 programs all have matching actual execution evidence.",
  "pairedSummaryMeaning": "14 Python/R implementation pairs, not Korean/English pairs.218 exact/algebraic summary fields and168 plot rows agree;6 undefined plot rows per implementation are omitted as scientific points.",
  "dependencies": {
    "Python": "Python3 standard library Fraction/Decimal plus Matplotlib Agg",
    "R": "Base R plus bundled tools; source programs use pure SHA256 and integer limbs"
  },
  "sourceScope": "Small declared teaching fixtures plus native3CSV-only source reconstructions. Compiled documents, English queries/gold/roles remain authored; no trained encoder, generation, JS engine/model/answer import.",
  "publicProjection": "Code and short summary are embedded. Complete JSON/CSV and original vector SVG are linked external files. Actual commands/raw local tracebacks remain private author evidence. Rejected Python traceback is explicitly projected to its exception message.",
  "wholeCandidateBindings": {
    "body": "728af216cad923de98030262e638fb49d2096250159898dbf2aa42dc08d12c27",
    "cases": "4c1ac4a42281cbb50bd6d193c0bd997603494b692868d716f61744c4dd29b8dc",
    "engine": "2eb101dcfc9894bacfce97032202db0054db34e00cdd5b253886ed1b113cef32",
    "api": "1861a257b28424871ad3873365b3517e2cfa335b0bdd1feed1eee42a73a0029b",
    "source": "24d0e9cebdc6e5e8571bcd6c788cf6c1e2a30490533876e2d03e23fbe7d34327"
  },
  "runs": [
    {
      "api": "context",
      "variant": "context-invalid-overlap",
      "language": "python",
      "codeFile": "ai16-code/fixed/context-invalid-overlap.py",
      "codeSHA256": "970144fcbc44c1b9598e24f7488ec182e818fe87f6c0686357c7190184c6654c",
      "expectedFailure": true,
      "exitCode": 1,
      "plotFile": null
    },
    {
      "api": "context",
      "variant": "context-invalid-overlap",
      "language": "r",
      "codeFile": "ai16-code/fixed/context-invalid-overlap.R",
      "codeSHA256": "00a95ef968d514c1296ab8e6f903ff26b5db638cb8f41d4b26c3b05f26e513f2",
      "expectedFailure": true,
      "exitCode": 1,
      "plotFile": null
    },
    {
      "api": "context",
      "variant": "context-literal-negation",
      "language": "python",
      "codeFile": "ai16-code/fixed/context-literal-negation.py",
      "codeSHA256": "1b6696e43e8d03a6624221b69a12fc0ec498a8c7afb3d813582e5c39598da824",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/context-literal-negation-python/plot.svg"
    },
    {
      "api": "context",
      "variant": "context-literal-negation",
      "language": "r",
      "codeFile": "ai16-code/fixed/context-literal-negation.R",
      "codeSHA256": "e2a3167a77ba19edd0b597898f733527967d2b61301b2da61fbb601531088db8",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/context-literal-negation-r/plot.svg"
    },
    {
      "api": "context",
      "variant": "context-overlap",
      "language": "python",
      "codeFile": "ai16-code/fixed/context-overlap.py",
      "codeSHA256": "c1ac5c75b12323e34f568da6f3373684efa85ab88abf1b572c3b87550ec72938",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/context-overlap-python/plot.svg"
    },
    {
      "api": "context",
      "variant": "context-overlap",
      "language": "r",
      "codeFile": "ai16-code/fixed/context-overlap.R",
      "codeSHA256": "2603ce97b77fc23170f74f4af03821311d026be8b99040222500c0ced80a88ee",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/context-overlap-r/plot.svg"
    },
    {
      "api": "embedding",
      "variant": "embedding-projection-loss",
      "language": "python",
      "codeFile": "ai16-code/fixed/embedding-projection-loss.py",
      "codeSHA256": "8abe329c168becfc8ae103fc68049a94284f8fe3a50e0dc7e8455f404f4b7c6f",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/embedding-projection-loss-python/plot.svg"
    },
    {
      "api": "embedding",
      "variant": "embedding-projection-loss",
      "language": "r",
      "codeFile": "ai16-code/fixed/embedding-projection-loss.R",
      "codeSHA256": "c917aeac59ea38a1fe701be2b3241db50d88517fae0f4e26025dfd8e26417026",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/embedding-projection-loss-r/plot.svg"
    },
    {
      "api": "embedding",
      "variant": "embedding-signed",
      "language": "python",
      "codeFile": "ai16-code/fixed/embedding-signed.py",
      "codeSHA256": "23dd86ccf91f37e6a995cd72bfbca6f7cfc5bac2e886bb36067a7c6621fdb61c",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/embedding-signed-python/plot.svg"
    },
    {
      "api": "embedding",
      "variant": "embedding-signed",
      "language": "r",
      "codeFile": "ai16-code/fixed/embedding-signed.R",
      "codeSHA256": "a6b5eb76a1ab1f511250e88515c2608ba68fe828b03b9cb6046596cb69a42d5f",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/embedding-signed-r/plot.svg"
    },
    {
      "api": "evaluate",
      "variant": "evaluate-multiple-gold",
      "language": "python",
      "codeFile": "ai16-code/fixed/evaluate-multiple-gold.py",
      "codeSHA256": "7e1ab53a3179debf0dc1ccaa3bf2196d4e869d461c478b5c656d4f74f1d486ac",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/evaluate-multiple-gold-python/plot.svg"
    },
    {
      "api": "evaluate",
      "variant": "evaluate-multiple-gold",
      "language": "r",
      "codeFile": "ai16-code/fixed/evaluate-multiple-gold.R",
      "codeSHA256": "8d5bb1545ec5e0499fdf881799e5e96c0cc9ec63722289316ce5b9d7bc1c04e7",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/evaluate-multiple-gold-r/plot.svg"
    },
    {
      "api": "evaluate",
      "variant": "evaluate-no-positive-gold",
      "language": "python",
      "codeFile": "ai16-code/fixed/evaluate-no-positive-gold.py",
      "codeSHA256": "a6eb9af338501b79f3dddc7196831a59635731de5bfa2b932907d123e566146d",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/evaluate-no-positive-gold-python/plot.svg"
    },
    {
      "api": "evaluate",
      "variant": "evaluate-no-positive-gold",
      "language": "r",
      "codeFile": "ai16-code/fixed/evaluate-no-positive-gold.R",
      "codeSHA256": "91797aa9e5d486ae8e6f3d91849dc2fd657a89843aff2368b56ee89aa025d836",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/evaluate-no-positive-gold-r/plot.svg"
    },
    {
      "api": "fusion",
      "variant": "fusion-tie",
      "language": "python",
      "codeFile": "ai16-code/fixed/fusion-tie.py",
      "codeSHA256": "641a0564728b031ebbb0893fbfc4e1db835b2df17ff91a633ae724fb3506c251",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/fusion-tie-python/plot.svg"
    },
    {
      "api": "fusion",
      "variant": "fusion-tie",
      "language": "r",
      "codeFile": "ai16-code/fixed/fusion-tie.R",
      "codeSHA256": "f4e8765343677da12fcb460214fed81148579ce7ce410684f6e9efa9d65d1fe8",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/fusion-tie-r/plot.svg"
    },
    {
      "api": "fusion",
      "variant": "fusion-weights",
      "language": "python",
      "codeFile": "ai16-code/fixed/fusion-weights.py",
      "codeSHA256": "c3bcf86cde73699971924acd722507ce9e7642e984724cb093aeb7663520383d",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/fusion-weights-python/plot.svg"
    },
    {
      "api": "fusion",
      "variant": "fusion-weights",
      "language": "r",
      "codeFile": "ai16-code/fixed/fusion-weights.R",
      "codeSHA256": "e111b3526be6eb4b81fd8a47131e96e0ba23b13b73e8df0a75b6eb0fb1da9fb1",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/fusion-weights-r/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-empty-jaccard",
      "language": "python",
      "codeFile": "ai16-code/fixed/lexical-empty-jaccard.py",
      "codeSHA256": "54ca7dcf84fc1e2fb2b1734d42f76d6bb030504e71b2b1949cdd7ddd2731526e",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-empty-jaccard-python/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-empty-jaccard",
      "language": "r",
      "codeFile": "ai16-code/fixed/lexical-empty-jaccard.R",
      "codeSHA256": "530268d7a5182e7b4944540fed19231fdff939965d9499fad0d3a6318714042f",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-empty-jaccard-r/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-rarity-reversal",
      "language": "python",
      "codeFile": "ai16-code/fixed/lexical-rarity-reversal.py",
      "codeSHA256": "9e626f23e76015248c4d61ee2da8cd9e1f31c7b18e2dd9e8d205009759693701",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-rarity-reversal-python/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-rarity-reversal",
      "language": "r",
      "codeFile": "ai16-code/fixed/lexical-rarity-reversal.R",
      "codeSHA256": "9cdf56e8713825e11c5b8d4e365520ca3e0998f36832519181ba2d8af72d5d1c",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-rarity-reversal-r/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-repetition",
      "language": "python",
      "codeFile": "ai16-code/fixed/lexical-repetition.py",
      "codeSHA256": "7308d41430314a158c9e870bf5b5a1c38531da12f58a3d4f36b01cbcd4f8b746",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-repetition-python/plot.svg"
    },
    {
      "api": "lexical",
      "variant": "lexical-repetition",
      "language": "r",
      "codeFile": "ai16-code/fixed/lexical-repetition.R",
      "codeSHA256": "0170f4578904e901460b259276fb044331ab5953388a78d14e5118b7dff0bbef",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/lexical-repetition-r/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-company",
      "language": "python",
      "codeFile": "ai16-code/fixed/realdata-company.py",
      "codeSHA256": "e1d32d60243983e3dac0e0459aff5d1bfa2a4465e86f4212a69a808d638d777e",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-company-python/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-company",
      "language": "r",
      "codeFile": "ai16-code/fixed/realdata-company.R",
      "codeSHA256": "58bb3094504fa04927cba5c0f1d6f03c3db3c4673f3bdfe3764356935c6597d9",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-company-r/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-country",
      "language": "python",
      "codeFile": "ai16-code/fixed/realdata-country.py",
      "codeSHA256": "fe0ed16525a8873c7f67e78bac33a16a8c37391e2e1d31e9f39f0c8fe979c5c5",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-country-python/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-country",
      "language": "r",
      "codeFile": "ai16-code/fixed/realdata-country.R",
      "codeSHA256": "e94da10daae3659b4ff111e87c237e05764d7c21d56f46a3e61508d1fa75ab68",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-country-r/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-person",
      "language": "python",
      "codeFile": "ai16-code/fixed/realdata-person.py",
      "codeSHA256": "2cc3e86f2af636592a71bebf495a7eb3fb5809dfdc004b11d50ec7e71b6536ae",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-person-python/plot.svg"
    },
    {
      "api": "realdata",
      "variant": "realdata-person",
      "language": "r",
      "codeFile": "ai16-code/fixed/realdata-person.R",
      "codeSHA256": "e2741ffc881b37addb25de63925059fd6d00c4537cac397f166f14d8c7e43b75",
      "expectedFailure": false,
      "exitCode": 0,
      "plotFile": "ai16-fixed/realdata-person-r/plot.svg"
    }
  ],
  "lexical": {
    "python": {
      "lexical-empty-jaccard": {
        "api": "lexical",
        "variant": "lexical-empty-jaccard",
        "title": "An empty set is not an observed zero similarity",
        "language": "python",
        "codeFile": "ai16-code/fixed/lexical-empty-jaccard.py",
        "codeSHA256": "54ca7dcf84fc1e2fb2b1734d42f76d6bb030504e71b2b1949cdd7ddd2731526e",
        "code": "SPEC = {'id': 'lexical-empty-jaccard', 'api': 'lexical', 'title': 'An empty set is not an observed zero similarity', 'args': {'documents': [{'id': 'empty', 'text': ''}, {'id': 'word', 'text': 'red'}], 'query': '', 'method': 'jaccard', 'topK': 2}, 'unit': 'Set Jaccard; empty/empty undefined'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"lexical-empty-jaccard\", \"status\": \"PASS\", \"summaryFields\": 3, \"plotRows\": 2}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/lexical-empty-jaccard-python/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-empty-jaccard-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:empty",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "score:word",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "top",
            "exact": "word",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-empty-jaccard-python/result.json",
        "summaryFile": "ai16-fixed/lexical-empty-jaccard-python/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-empty-jaccard-python/points.csv",
        "plotFile": "ai16-fixed/lexical-empty-jaccard-python/plot.svg",
        "plotSHA256": "ce2388c194b652afa4a2d26952d2b868b1b7c311b8b8363e7d2e256d32332116"
      },
      "lexical-rarity-reversal": {
        "api": "lexical",
        "variant": "lexical-rarity-reversal",
        "title": "A declared rarity weight reverses a ranking",
        "language": "python",
        "codeFile": "ai16-code/fixed/lexical-rarity-reversal.py",
        "codeSHA256": "9e626f23e76015248c4d61ee2da8cd9e1f31c7b18e2dd9e8d205009759693701",
        "code": "SPEC = {'id': 'lexical-rarity-reversal', 'api': 'lexical', 'title': 'A declared rarity weight reverses a ranking', 'args': {'documents': [{'id': 'red-two', 'text': 'red red'}, {'id': 'red-a', 'text': 'red'}, {'id': 'red-b', 'text': 'red'}, {'id': 'red-c', 'text': 'red'}, {'id': 'nebula', 'text': 'nebula'}], 'query': 'red nebula', 'method': 'rarity', 'topK': 5}, 'unit': 'Declared rational rarity score'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"lexical-rarity-reversal\", \"status\": \"PASS\", \"summaryFields\": 6, \"plotRows\": 5}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/lexical-rarity-reversal-python/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-rarity-reversal-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:red-two",
            "exact": "2/5",
            "value": "0.4",
            "state": "ordinary"
          },
          {
            "key": "score:red-a",
            "exact": "1/5",
            "value": "0.2",
            "state": "ordinary"
          },
          {
            "key": "score:red-b",
            "exact": "1/5",
            "value": "0.2",
            "state": "ordinary"
          },
          {
            "key": "score:red-c",
            "exact": "1/5",
            "value": "0.2",
            "state": "ordinary"
          },
          {
            "key": "score:nebula",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "nebula|red-two|red-a|red-b|red-c",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-rarity-reversal-python/result.json",
        "summaryFile": "ai16-fixed/lexical-rarity-reversal-python/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-rarity-reversal-python/points.csv",
        "plotFile": "ai16-fixed/lexical-rarity-reversal-python/plot.svg",
        "plotSHA256": "044cf2364150338865bfd0f0362c65bdb0c9a880dea86218ed119c7c51de026d"
      },
      "lexical-repetition": {
        "api": "lexical",
        "variant": "lexical-repetition",
        "title": "Repeated query and document terms",
        "language": "python",
        "codeFile": "ai16-code/fixed/lexical-repetition.py",
        "codeSHA256": "7308d41430314a158c9e870bf5b5a1c38531da12f58a3d4f36b01cbcd4f8b746",
        "code": "SPEC = {'id': 'lexical-repetition', 'api': 'lexical', 'title': 'Repeated query and document terms', 'args': {'documents': [{'id': 'a', 'text': 'red red book'}, {'id': 'b', 'text': 'red blue'}, {'id': 'c', 'text': 'blue blue book'}], 'query': 'red red book', 'method': 'overlap', 'topK': 3}, 'unit': 'Count-product overlap score'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"lexical-repetition\", \"status\": \"PASS\", \"summaryFields\": 4, \"plotRows\": 3}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/lexical-repetition-python/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-repetition-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "5",
            "value": "5.0",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "2",
            "value": "2.0",
            "state": "ordinary"
          },
          {
            "key": "score:c",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|b|c",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-repetition-python/result.json",
        "summaryFile": "ai16-fixed/lexical-repetition-python/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-repetition-python/points.csv",
        "plotFile": "ai16-fixed/lexical-repetition-python/plot.svg",
        "plotSHA256": "cae6adc2cd66c3b3df7ffc9932d157866c91c21c98c761aeab206791372edec2"
      }
    },
    "r": {
      "lexical-empty-jaccard": {
        "api": "lexical",
        "variant": "lexical-empty-jaccard",
        "title": "An empty set is not an observed zero similarity",
        "language": "r",
        "codeFile": "ai16-code/fixed/lexical-empty-jaccard.R",
        "codeSHA256": "530268d7a5182e7b4944540fed19231fdff939965d9499fad0d3a6318714042f",
        "code": "S <- list(\"id\"=\"lexical-empty-jaccard\",\"api\"=\"lexical\",\"title\"=\"An empty set is not an observed zero similarity\",\"args\"=list(\"documents\"=list(list(\"id\"=\"empty\",\"text\"=\"\"),list(\"id\"=\"word\",\"text\"=\"red\")),\"query\"=\"\",\"method\"=\"jaccard\",\"topK\"=2L),\"unit\"=\"Set Jaccard; empty/empty undefined\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"word\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: lexical-empty-jaccard summary fields 3 plot rows 2 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/lexical-empty-jaccard-r/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-empty-jaccard-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:empty",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "score:word",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "top",
            "exact": "word",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-empty-jaccard-r/result.json",
        "summaryFile": "ai16-fixed/lexical-empty-jaccard-r/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-empty-jaccard-r/points.csv",
        "plotFile": "ai16-fixed/lexical-empty-jaccard-r/plot.svg",
        "plotSHA256": "2bad9a589f926aae8bf7aebe2e280a7a5a88c7dda7050416a032bb826c539e85"
      },
      "lexical-rarity-reversal": {
        "api": "lexical",
        "variant": "lexical-rarity-reversal",
        "title": "A declared rarity weight reverses a ranking",
        "language": "r",
        "codeFile": "ai16-code/fixed/lexical-rarity-reversal.R",
        "codeSHA256": "9cdf56e8713825e11c5b8d4e365520ca3e0998f36832519181ba2d8af72d5d1c",
        "code": "S <- list(\"id\"=\"lexical-rarity-reversal\",\"api\"=\"lexical\",\"title\"=\"A declared rarity weight reverses a ranking\",\"args\"=list(\"documents\"=list(list(\"id\"=\"red-two\",\"text\"=\"red red\"),list(\"id\"=\"red-a\",\"text\"=\"red\"),list(\"id\"=\"red-b\",\"text\"=\"red\"),list(\"id\"=\"red-c\",\"text\"=\"red\"),list(\"id\"=\"nebula\",\"text\"=\"nebula\")),\"query\"=\"red nebula\",\"method\"=\"rarity\",\"topK\"=5L),\"unit\"=\"Declared rational rarity score\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"nebula|red-two|red-a|red-b|red-c\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: lexical-rarity-reversal summary fields 6 plot rows 5 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/lexical-rarity-reversal-r/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-rarity-reversal-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:red-two",
            "exact": "2/5",
            "value": "0.40000000000000002",
            "state": "ordinary"
          },
          {
            "key": "score:red-a",
            "exact": "1/5",
            "value": "0.20000000000000001",
            "state": "ordinary"
          },
          {
            "key": "score:red-b",
            "exact": "1/5",
            "value": "0.20000000000000001",
            "state": "ordinary"
          },
          {
            "key": "score:red-c",
            "exact": "1/5",
            "value": "0.20000000000000001",
            "state": "ordinary"
          },
          {
            "key": "score:nebula",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "nebula|red-two|red-a|red-b|red-c",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-rarity-reversal-r/result.json",
        "summaryFile": "ai16-fixed/lexical-rarity-reversal-r/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-rarity-reversal-r/points.csv",
        "plotFile": "ai16-fixed/lexical-rarity-reversal-r/plot.svg",
        "plotSHA256": "08f194b9f20678b7839d8f678fc250d906c46e248b05d113c1abf0d5838383e3"
      },
      "lexical-repetition": {
        "api": "lexical",
        "variant": "lexical-repetition",
        "title": "Repeated query and document terms",
        "language": "r",
        "codeFile": "ai16-code/fixed/lexical-repetition.R",
        "codeSHA256": "0170f4578904e901460b259276fb044331ab5953388a78d14e5118b7dff0bbef",
        "code": "S <- list(\"id\"=\"lexical-repetition\",\"api\"=\"lexical\",\"title\"=\"Repeated query and document terms\",\"args\"=list(\"documents\"=list(list(\"id\"=\"a\",\"text\"=\"red red book\"),list(\"id\"=\"b\",\"text\"=\"red blue\"),list(\"id\"=\"c\",\"text\"=\"blue blue book\")),\"query\"=\"red red book\",\"method\"=\"overlap\",\"topK\"=3L),\"unit\"=\"Count-product overlap score\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"a|b|c\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: lexical-repetition summary fields 4 plot rows 3 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/lexical-repetition-r/stdout.txt",
        "stderrFile": "ai16-fixed/lexical-repetition-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "5",
            "value": "5",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "2",
            "value": "2",
            "state": "ordinary"
          },
          {
            "key": "score:c",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|b|c",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/lexical-repetition-r/result.json",
        "summaryFile": "ai16-fixed/lexical-repetition-r/summary.csv",
        "plotDataFile": "ai16-fixed/lexical-repetition-r/points.csv",
        "plotFile": "ai16-fixed/lexical-repetition-r/plot.svg",
        "plotSHA256": "20ece7762c16269e17883cfeeeef79c9b10d29ebbe696957edf771f5365829ac"
      }
    }
  },
  "embedding": {
    "python": {
      "embedding-projection-loss": {
        "api": "embedding",
        "variant": "embedding-projection-loss",
        "title": "Positive cosine can display as zero; below one can round to one",
        "language": "python",
        "codeFile": "ai16-code/fixed/embedding-projection-loss.py",
        "codeSHA256": "8abe329c168becfc8ae103fc68049a94284f8fe3a50e0dc7e8455f404f4b7c6f",
        "code": "SPEC = {'id': 'embedding-projection-loss', 'api': 'embedding', 'title': 'Positive cosine can display as zero; below one can round to one', 'args': {'query': ['1e-200', '1e200'], 'candidates': [{'id': 'tiny-axis', 'vector': ['1', '0']}, {'id': 'large-axis', 'vector': ['0', '1']}, {'id': 'zero', 'vector': ['0', '0']}], 'metric': 'cosine'}, 'unit': 'Approximate cosine display; exact algebraic values retained'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"embedding-projection-loss\", \"status\": \"PASS\", \"summaryFields\": 6, \"plotRows\": 3}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/embedding-projection-loss-python/stdout.txt",
        "stderrFile": "ai16-fixed/embedding-projection-loss-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "cosine:tiny-axis",
            "exact": "1*sqrt(1/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)",
            "value": "0.0",
            "state": "nonzero-underflow"
          },
          {
            "key": "cosineSquared:tiny-axis",
            "exact": "1/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
            "value": "0.0",
            "state": "nonzero-underflow"
          },
          {
            "key": "cosine:large-axis",
            "exact": "1*sqrt(100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)",
            "value": "1.0",
            "state": "rounded-unit"
          },
          {
            "key": "cosineSquared:large-axis",
            "exact": "100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
            "value": "1.0",
            "state": "rounded-one"
          },
          {
            "key": "cosine:zero",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "top",
            "exact": "large-axis|tiny-axis",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/embedding-projection-loss-python/result.json",
        "summaryFile": "ai16-fixed/embedding-projection-loss-python/summary.csv",
        "plotDataFile": "ai16-fixed/embedding-projection-loss-python/points.csv",
        "plotFile": "ai16-fixed/embedding-projection-loss-python/plot.svg",
        "plotSHA256": "be53b7a93bad9b86a489f55dd67386558db328cc00274e456269b53550407e39"
      },
      "embedding-signed": {
        "api": "embedding",
        "variant": "embedding-signed",
        "title": "Cosine keeps signs and excludes a zero norm",
        "language": "python",
        "codeFile": "ai16-code/fixed/embedding-signed.py",
        "codeSHA256": "23dd86ccf91f37e6a995cd72bfbca6f7cfc5bac2e886bb36067a7c6621fdb61c",
        "code": "SPEC = {'id': 'embedding-signed', 'api': 'embedding', 'title': 'Cosine keeps signs and excludes a zero norm', 'args': {'query': ['1', '0'], 'candidates': [{'id': 'axis', 'vector': ['1', '0']}, {'id': 'diagonal', 'vector': ['2', '2']}, {'id': 'u', 'vector': ['-1', '2']}, {'id': 'v', 'vector': ['-1', '1']}, {'id': 'zero', 'vector': ['0', '0']}], 'metric': 'cosine'}, 'unit': 'Signed cosine; not relevance probability'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"embedding-signed\", \"status\": \"PASS\", \"summaryFields\": 10, \"plotRows\": 5}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/embedding-signed-python/stdout.txt",
        "stderrFile": "ai16-fixed/embedding-signed-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "cosine:axis",
            "exact": "1*sqrt(1)",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:axis",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "cosine:diagonal",
            "exact": "1*sqrt(1/2)",
            "value": "0.7071067811865476",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:diagonal",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "cosine:u",
            "exact": "-1*sqrt(1/5)",
            "value": "-0.4472135954999579",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:u",
            "exact": "1/5",
            "value": "0.2",
            "state": "ordinary"
          },
          {
            "key": "cosine:v",
            "exact": "-1*sqrt(1/2)",
            "value": "-0.7071067811865476",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:v",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "cosine:zero",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "top",
            "exact": "axis|diagonal|u|v",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/embedding-signed-python/result.json",
        "summaryFile": "ai16-fixed/embedding-signed-python/summary.csv",
        "plotDataFile": "ai16-fixed/embedding-signed-python/points.csv",
        "plotFile": "ai16-fixed/embedding-signed-python/plot.svg",
        "plotSHA256": "3437fd90721daa875b09442f1db7fab648ab608082284bd4f53992191deddcb8"
      }
    },
    "r": {
      "embedding-projection-loss": {
        "api": "embedding",
        "variant": "embedding-projection-loss",
        "title": "Positive cosine can display as zero; below one can round to one",
        "language": "r",
        "codeFile": "ai16-code/fixed/embedding-projection-loss.R",
        "codeSHA256": "c917aeac59ea38a1fe701be2b3241db50d88517fae0f4e26025dfd8e26417026",
        "code": "S <- list(\"id\"=\"embedding-projection-loss\",\"api\"=\"embedding\",\"title\"=\"Positive cosine can display as zero; below one can round to one\",\"args\"=list(\"query\"=list(\"1e-200\",\"1e200\"),\"candidates\"=list(list(\"id\"=\"tiny-axis\",\"vector\"=list(\"1\",\"0\")),list(\"id\"=\"large-axis\",\"vector\"=list(\"0\",\"1\")),list(\"id\"=\"zero\",\"vector\"=list(\"0\",\"0\"))),\"metric\"=\"cosine\"),\"unit\"=\"Approximate cosine display; exact algebraic values retained\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"large-axis|tiny-axis\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: embedding-projection-loss summary fields 6 plot rows 3 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/embedding-projection-loss-r/stdout.txt",
        "stderrFile": "ai16-fixed/embedding-projection-loss-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "cosine:tiny-axis",
            "exact": "1*sqrt(1/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)",
            "value": "0",
            "state": "nonzero-underflow"
          },
          {
            "key": "cosineSquared:tiny-axis",
            "exact": "1/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
            "value": "0",
            "state": "nonzero-underflow"
          },
          {
            "key": "cosine:large-axis",
            "exact": "1*sqrt(100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001)",
            "value": "1",
            "state": "rounded-unit"
          },
          {
            "key": "cosineSquared:large-axis",
            "exact": "100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000/100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
            "value": "1",
            "state": "rounded-one"
          },
          {
            "key": "cosine:zero",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "top",
            "exact": "large-axis|tiny-axis",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/embedding-projection-loss-r/result.json",
        "summaryFile": "ai16-fixed/embedding-projection-loss-r/summary.csv",
        "plotDataFile": "ai16-fixed/embedding-projection-loss-r/points.csv",
        "plotFile": "ai16-fixed/embedding-projection-loss-r/plot.svg",
        "plotSHA256": "01bf93a7c4f214f80c3f911b350d09c690e7d3562d6eaeb6451abe9d43879d7f"
      },
      "embedding-signed": {
        "api": "embedding",
        "variant": "embedding-signed",
        "title": "Cosine keeps signs and excludes a zero norm",
        "language": "r",
        "codeFile": "ai16-code/fixed/embedding-signed.R",
        "codeSHA256": "a6b5eb76a1ab1f511250e88515c2608ba68fe828b03b9cb6046596cb69a42d5f",
        "code": "S <- list(\"id\"=\"embedding-signed\",\"api\"=\"embedding\",\"title\"=\"Cosine keeps signs and excludes a zero norm\",\"args\"=list(\"query\"=list(\"1\",\"0\"),\"candidates\"=list(list(\"id\"=\"axis\",\"vector\"=list(\"1\",\"0\")),list(\"id\"=\"diagonal\",\"vector\"=list(\"2\",\"2\")),list(\"id\"=\"u\",\"vector\"=list(\"-1\",\"2\")),list(\"id\"=\"v\",\"vector\"=list(\"-1\",\"1\")),list(\"id\"=\"zero\",\"vector\"=list(\"0\",\"0\"))),\"metric\"=\"cosine\"),\"unit\"=\"Signed cosine; not relevance probability\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"axis|diagonal|u|v\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: embedding-signed summary fields 10 plot rows 5 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/embedding-signed-r/stdout.txt",
        "stderrFile": "ai16-fixed/embedding-signed-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "cosine:axis",
            "exact": "1*sqrt(1)",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:axis",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "cosine:diagonal",
            "exact": "1*sqrt(1/2)",
            "value": "0.70710678118654757",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:diagonal",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "cosine:u",
            "exact": "-1*sqrt(1/5)",
            "value": "-0.44721359549995793",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:u",
            "exact": "1/5",
            "value": "0.20000000000000001",
            "state": "ordinary"
          },
          {
            "key": "cosine:v",
            "exact": "-1*sqrt(1/2)",
            "value": "-0.70710678118654757",
            "state": "ordinary"
          },
          {
            "key": "cosineSquared:v",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "cosine:zero",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "top",
            "exact": "axis|diagonal|u|v",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/embedding-signed-r/result.json",
        "summaryFile": "ai16-fixed/embedding-signed-r/summary.csv",
        "plotDataFile": "ai16-fixed/embedding-signed-r/points.csv",
        "plotFile": "ai16-fixed/embedding-signed-r/plot.svg",
        "plotSHA256": "5f34746bb35cab8cca744c30811adab4d8b05a2ac87343d23e427fbc84f80ca6"
      }
    }
  },
  "fusion": {
    "python": {
      "fusion-tie": {
        "api": "fusion",
        "variant": "fusion-tie",
        "title": "Exact reciprocal-rank fusion ties",
        "language": "python",
        "codeFile": "ai16-code/fixed/fusion-tie.py",
        "codeSHA256": "641a0564728b031ebbb0893fbfc4e1db835b2df17ff91a633ae724fb3506c251",
        "code": "SPEC = {'id': 'fusion-tie', 'api': 'fusion', 'title': 'Exact reciprocal-rank fusion ties', 'args': {'lists': [{'ids': ['a', 'b', 'c'], 'weight': '1'}, {'ids': ['c', 'b', 'a'], 'weight': '1'}], 'rankOffset': 0, 'topK': 3}, 'unit': 'Reciprocal-rank score; not probability'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"fusion-tie\", \"status\": \"PASS\", \"summaryFields\": 4, \"plotRows\": 3}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/fusion-tie-python/stdout.txt",
        "stderrFile": "ai16-fixed/fusion-tie-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "4/3",
            "value": "1.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "score:c",
            "exact": "4/3",
            "value": "1.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|c|b",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/fusion-tie-python/result.json",
        "summaryFile": "ai16-fixed/fusion-tie-python/summary.csv",
        "plotDataFile": "ai16-fixed/fusion-tie-python/points.csv",
        "plotFile": "ai16-fixed/fusion-tie-python/plot.svg",
        "plotSHA256": "22a4a1d51dae9dd815f396df3a84a674e46aaa5b2ec06a5379e3a91afc587e5c"
      },
      "fusion-weights": {
        "api": "fusion",
        "variant": "fusion-weights",
        "title": "Missing positions and declared list weights",
        "language": "python",
        "codeFile": "ai16-code/fixed/fusion-weights.py",
        "codeSHA256": "c3bcf86cde73699971924acd722507ce9e7642e984724cb093aeb7663520383d",
        "code": "SPEC = {'id': 'fusion-weights', 'api': 'fusion', 'title': 'Missing positions and declared list weights', 'args': {'lists': [{'ids': ['a', 'b'], 'weight': '2'}, {'ids': ['b'], 'weight': '1'}], 'rankOffset': 0, 'topK': 3}, 'unit': 'Weighted reciprocal-rank score'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"fusion-weights\", \"status\": \"PASS\", \"summaryFields\": 3, \"plotRows\": 2}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/fusion-weights-python/stdout.txt",
        "stderrFile": "ai16-fixed/fusion-weights-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "2",
            "value": "2.0",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "2",
            "value": "2.0",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|b",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/fusion-weights-python/result.json",
        "summaryFile": "ai16-fixed/fusion-weights-python/summary.csv",
        "plotDataFile": "ai16-fixed/fusion-weights-python/points.csv",
        "plotFile": "ai16-fixed/fusion-weights-python/plot.svg",
        "plotSHA256": "3785df727d9e37b1fa081169f5bb6519f2dd82d7efb5d86af509b3a252eef571"
      }
    },
    "r": {
      "fusion-tie": {
        "api": "fusion",
        "variant": "fusion-tie",
        "title": "Exact reciprocal-rank fusion ties",
        "language": "r",
        "codeFile": "ai16-code/fixed/fusion-tie.R",
        "codeSHA256": "f4e8765343677da12fcb460214fed81148579ce7ce410684f6e9efa9d65d1fe8",
        "code": "S <- list(\"id\"=\"fusion-tie\",\"api\"=\"fusion\",\"title\"=\"Exact reciprocal-rank fusion ties\",\"args\"=list(\"lists\"=list(list(\"ids\"=list(\"a\",\"b\",\"c\"),\"weight\"=\"1\"),list(\"ids\"=list(\"c\",\"b\",\"a\"),\"weight\"=\"1\")),\"rankOffset\"=0L,\"topK\"=3L),\"unit\"=\"Reciprocal-rank score; not probability\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"a|c|b\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: fusion-tie summary fields 4 plot rows 3 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/fusion-tie-r/stdout.txt",
        "stderrFile": "ai16-fixed/fusion-tie-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "4/3",
            "value": "1.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "score:c",
            "exact": "4/3",
            "value": "1.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|c|b",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/fusion-tie-r/result.json",
        "summaryFile": "ai16-fixed/fusion-tie-r/summary.csv",
        "plotDataFile": "ai16-fixed/fusion-tie-r/points.csv",
        "plotFile": "ai16-fixed/fusion-tie-r/plot.svg",
        "plotSHA256": "71835fd3bf3916d6aa1c1d1d275003a914835a4e450d97af9aa8370977d97e0c"
      },
      "fusion-weights": {
        "api": "fusion",
        "variant": "fusion-weights",
        "title": "Missing positions and declared list weights",
        "language": "r",
        "codeFile": "ai16-code/fixed/fusion-weights.R",
        "codeSHA256": "e111b3526be6eb4b81fd8a47131e96e0ba23b13b73e8df0a75b6eb0fb1da9fb1",
        "code": "S <- list(\"id\"=\"fusion-weights\",\"api\"=\"fusion\",\"title\"=\"Missing positions and declared list weights\",\"args\"=list(\"lists\"=list(list(\"ids\"=list(\"a\",\"b\"),\"weight\"=\"2\"),list(\"ids\"=list(\"b\"),\"weight\"=\"1\")),\"rankOffset\"=0L,\"topK\"=3L),\"unit\"=\"Weighted reciprocal-rank score\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"top\"\r\n\r\n$exact\r\n[1] \"a|b\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: fusion-weights summary fields 3 plot rows 2 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/fusion-weights-r/stdout.txt",
        "stderrFile": "ai16-fixed/fusion-weights-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "score:a",
            "exact": "2",
            "value": "2",
            "state": "ordinary"
          },
          {
            "key": "score:b",
            "exact": "2",
            "value": "2",
            "state": "ordinary"
          },
          {
            "key": "top",
            "exact": "a|b",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/fusion-weights-r/result.json",
        "summaryFile": "ai16-fixed/fusion-weights-r/summary.csv",
        "plotDataFile": "ai16-fixed/fusion-weights-r/points.csv",
        "plotFile": "ai16-fixed/fusion-weights-r/plot.svg",
        "plotSHA256": "c2a0c56eb682e01d2fa1a2e5f3478f339d439a21ecf9dad08de07ed1e528cde0"
      }
    }
  },
  "context": {
    "python": {
      "context-invalid-overlap": {
        "api": "context",
        "variant": "context-invalid-overlap",
        "title": "Reject nonprogressing chunk boundaries",
        "language": "python",
        "codeFile": "ai16-code/fixed/context-invalid-overlap.py",
        "codeSHA256": "970144fcbc44c1b9598e24f7488ec182e818fe87f6c0686357c7190184c6654c",
        "code": "SPEC = {'id': 'context-invalid-overlap', 'api': 'context', 'title': 'Reject nonprogressing chunk boundaries', 'args': {'documents': [{'id': 'source', 'text': 'alpha beta gamma'}], 'chunkSize': 3, 'overlap': 3, 'tokenBudget': 4}, 'expectedFailure': True, 'unit': 'No numeric plot for rejected input'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": true,
        "exitCode": 1,
        "stdout": "",
        "stderr": "ValueError: overlap must be strictly smaller than chunk size\n",
        "stderrIsProjection": true,
        "rawStderrSHA256": "5aeee0a8b7882ceb7f738fa026446ff52b01352cac4453d7fe8bfc157c36ef01",
        "stdoutFile": "ai16-fixed/context-invalid-overlap-python/stdout.txt",
        "stderrFile": "ai16-fixed/context-invalid-overlap-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [],
        "expectedRejection": "overlap must be strictly smaller than chunk size",
        "plotFile": null
      },
      "context-literal-negation": {
        "api": "context",
        "variant": "context-literal-negation",
        "title": "Literal presence alone does not establish support",
        "language": "python",
        "codeFile": "ai16-code/fixed/context-literal-negation.py",
        "codeSHA256": "1b6696e43e8d03a6624221b69a12fc0ec498a8c7afb3d813582e5c39598da824",
        "code": "SPEC = {'id': 'context-literal-negation', 'api': 'context', 'title': 'Literal presence alone does not establish support', 'args': {'documents': [{'id': 'source', 'text': 'The company did not report profit of 100.'}], 'ranking': ['source'], 'chunkSize': 32, 'overlap': 8, 'tokenBudget': 96, 'claims': [{'id': 'q', 'documentID': 'source', 'quote': 'profit of 100'}]}, 'unit': 'Literal indicators; not semantic support probabilities'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"context-literal-negation\", \"status\": \"PASS\", \"summaryFields\": 6, \"plotRows\": 2}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/context-literal-negation-python/stdout.txt",
        "stderrFile": "ai16-fixed/context-literal-negation-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "usedWordTokens",
            "exact": "8",
            "value": "8.0",
            "state": "ordinary"
          },
          {
            "key": "fullChunks",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:1",
            "exact": "8",
            "value": "8.0",
            "state": "ordinary"
          },
          {
            "key": "literalInOriginal:q",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "literalInSelected:q",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "support",
            "exact": "Not evaluated: literal presence is not entailment or truth",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/context-literal-negation-python/result.json",
        "summaryFile": "ai16-fixed/context-literal-negation-python/summary.csv",
        "plotDataFile": "ai16-fixed/context-literal-negation-python/points.csv",
        "plotFile": "ai16-fixed/context-literal-negation-python/plot.svg",
        "plotSHA256": "86e11cde96ddcc125dff3118a7c21cbb042452c121d6d7f9f44f2ab8744bfde3"
      },
      "context-overlap": {
        "api": "context",
        "variant": "context-overlap",
        "title": "Overlap consumes word budget again",
        "language": "python",
        "codeFile": "ai16-code/fixed/context-overlap.py",
        "codeSHA256": "c1ac5c75b12323e34f568da6f3373684efa85ab88abf1b572c3b87550ec72938",
        "code": "SPEC = {'id': 'context-overlap', 'api': 'context', 'title': 'Overlap consumes word budget again', 'args': {'documents': [{'id': 'source', 'text': 'alpha beta gamma delta epsilon'}], 'ranking': ['source'], 'chunkSize': 3, 'overlap': 1, 'tokenBudget': 4, 'claims': [{'id': 'q', 'documentID': 'source', 'quote': 'delta epsilon'}]}, 'unit': 'Selected original word tokens per full chunk'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"context-overlap\", \"status\": \"PASS\", \"summaryFields\": 8, \"plotRows\": 3}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/context-overlap-python/stdout.txt",
        "stderrFile": "ai16-fixed/context-overlap-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "usedWordTokens",
            "exact": "4",
            "value": "4.0",
            "state": "ordinary"
          },
          {
            "key": "fullChunks",
            "exact": "3",
            "value": "3.0",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:1",
            "exact": "3",
            "value": "3.0",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:2",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:3",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "literalInOriginal:q",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "literalInSelected:q",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "support",
            "exact": "Not evaluated: literal presence is not entailment or truth",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/context-overlap-python/result.json",
        "summaryFile": "ai16-fixed/context-overlap-python/summary.csv",
        "plotDataFile": "ai16-fixed/context-overlap-python/points.csv",
        "plotFile": "ai16-fixed/context-overlap-python/plot.svg",
        "plotSHA256": "5e8688b2306b24f5e8fae5f84f26760ddb8c04bd08d8b85265e16a46f662fce9"
      }
    },
    "r": {
      "context-invalid-overlap": {
        "api": "context",
        "variant": "context-invalid-overlap",
        "title": "Reject nonprogressing chunk boundaries",
        "language": "r",
        "codeFile": "ai16-code/fixed/context-invalid-overlap.R",
        "codeSHA256": "00a95ef968d514c1296ab8e6f903ff26b5db638cb8f41d4b26c3b05f26e513f2",
        "code": "S <- list(\"id\"=\"context-invalid-overlap\",\"api\"=\"context\",\"title\"=\"Reject nonprogressing chunk boundaries\",\"args\"=list(\"documents\"=list(list(\"id\"=\"source\",\"text\"=\"alpha beta gamma\")),\"chunkSize\"=3L,\"overlap\"=3L,\"tokenBudget\"=4L),\"expectedFailure\"=TRUE,\"unit\"=\"No numeric plot for rejected input\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": true,
        "exitCode": 1,
        "stdout": "",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\nError: overlap must be strictly smaller than chunk size\r\nExecution halted\r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "6ab485cbe5490f2abfc117003b82562fd3c1ac05a03e616a77db8ff73ee3d20a",
        "stdoutFile": "ai16-fixed/context-invalid-overlap-r/stdout.txt",
        "stderrFile": "ai16-fixed/context-invalid-overlap-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [],
        "expectedRejection": "overlap must be strictly smaller than chunk size",
        "plotFile": null
      },
      "context-literal-negation": {
        "api": "context",
        "variant": "context-literal-negation",
        "title": "Literal presence alone does not establish support",
        "language": "r",
        "codeFile": "ai16-code/fixed/context-literal-negation.R",
        "codeSHA256": "e2a3167a77ba19edd0b597898f733527967d2b61301b2da61fbb601531088db8",
        "code": "S <- list(\"id\"=\"context-literal-negation\",\"api\"=\"context\",\"title\"=\"Literal presence alone does not establish support\",\"args\"=list(\"documents\"=list(list(\"id\"=\"source\",\"text\"=\"The company did not report profit of 100.\")),\"ranking\"=list(\"source\"),\"chunkSize\"=32L,\"overlap\"=8L,\"tokenBudget\"=96L,\"claims\"=list(list(\"id\"=\"q\",\"documentID\"=\"source\",\"quote\"=\"profit of 100\"))),\"unit\"=\"Literal indicators; not semantic support probabilities\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"support\"\r\n\r\n$exact\r\n[1] \"Not evaluated: literal presence is not entailment or truth\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: context-literal-negation summary fields 6 plot rows 2 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/context-literal-negation-r/stdout.txt",
        "stderrFile": "ai16-fixed/context-literal-negation-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "usedWordTokens",
            "exact": "8",
            "value": "8",
            "state": "ordinary"
          },
          {
            "key": "fullChunks",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:1",
            "exact": "8",
            "value": "8",
            "state": "ordinary"
          },
          {
            "key": "literalInOriginal:q",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "literalInSelected:q",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "support",
            "exact": "Not evaluated: literal presence is not entailment or truth",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/context-literal-negation-r/result.json",
        "summaryFile": "ai16-fixed/context-literal-negation-r/summary.csv",
        "plotDataFile": "ai16-fixed/context-literal-negation-r/points.csv",
        "plotFile": "ai16-fixed/context-literal-negation-r/plot.svg",
        "plotSHA256": "8834ebaf8ec864858af5edc81928bc9404fa7cdc5073c1c827f80909ba6724fd"
      },
      "context-overlap": {
        "api": "context",
        "variant": "context-overlap",
        "title": "Overlap consumes word budget again",
        "language": "r",
        "codeFile": "ai16-code/fixed/context-overlap.R",
        "codeSHA256": "2603ce97b77fc23170f74f4af03821311d026be8b99040222500c0ced80a88ee",
        "code": "S <- list(\"id\"=\"context-overlap\",\"api\"=\"context\",\"title\"=\"Overlap consumes word budget again\",\"args\"=list(\"documents\"=list(list(\"id\"=\"source\",\"text\"=\"alpha beta gamma delta epsilon\")),\"ranking\"=list(\"source\"),\"chunkSize\"=3L,\"overlap\"=1L,\"tokenBudget\"=4L,\"claims\"=list(list(\"id\"=\"q\",\"documentID\"=\"source\",\"quote\"=\"delta epsilon\"))),\"unit\"=\"Selected original word tokens per full chunk\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"support\"\r\n\r\n$exact\r\n[1] \"Not evaluated: literal presence is not entailment or truth\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\nnull device \r\n          1 \r\nPASS: context-overlap summary fields 8 plot rows 3 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/context-overlap-r/stdout.txt",
        "stderrFile": "ai16-fixed/context-overlap-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "usedWordTokens",
            "exact": "4",
            "value": "4",
            "state": "ordinary"
          },
          {
            "key": "fullChunks",
            "exact": "3",
            "value": "3",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:1",
            "exact": "3",
            "value": "3",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:2",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "selectedTokens:3",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "literalInOriginal:q",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "literalInSelected:q",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "support",
            "exact": "Not evaluated: literal presence is not entailment or truth",
            "value": "",
            "state": "label"
          }
        ],
        "resultFile": "ai16-fixed/context-overlap-r/result.json",
        "summaryFile": "ai16-fixed/context-overlap-r/summary.csv",
        "plotDataFile": "ai16-fixed/context-overlap-r/points.csv",
        "plotFile": "ai16-fixed/context-overlap-r/plot.svg",
        "plotSHA256": "c197ea48e66e9c133360f28b6b6533c5d1030b0eeb0f708facf5bf488d79e970"
      }
    }
  },
  "evaluate": {
    "python": {
      "evaluate-multiple-gold": {
        "api": "evaluate",
        "variant": "evaluate-multiple-gold",
        "title": "First-hit rank and multi-evidence recovery differ",
        "language": "python",
        "codeFile": "ai16-code/fixed/evaluate-multiple-gold.py",
        "codeSHA256": "7e1ab53a3179debf0dc1ccaa3bf2196d4e869d461c478b5c656d4f74f1d486ac",
        "code": "SPEC = {'id': 'evaluate-multiple-gold', 'api': 'evaluate', 'title': 'First-hit rank and multi-evidence recovery differ', 'args': {'ranking': ['x', 'a', 'b'], 'relevant': ['a', 'b'], 'k': 3}, 'unit': 'Finite binary-relevance metric ratio'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"evaluate-multiple-gold\", \"status\": \"PASS\", \"summaryFields\": 6, \"plotRows\": 4}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/evaluate-multiple-gold-python/stdout.txt",
        "stderrFile": "ai16-fixed/evaluate-multiple-gold-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "precision",
            "exact": "2/3",
            "value": "0.6666666666666666",
            "state": "ordinary"
          },
          {
            "key": "recall",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "RR",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "AP",
            "exact": "7/12",
            "value": "0.5833333333333334",
            "state": "ordinary"
          },
          {
            "key": "positiveGoldCount",
            "exact": "2",
            "value": "2.0",
            "state": "ordinary"
          },
          {
            "key": "requestedK",
            "exact": "3",
            "value": "3.0",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/evaluate-multiple-gold-python/result.json",
        "summaryFile": "ai16-fixed/evaluate-multiple-gold-python/summary.csv",
        "plotDataFile": "ai16-fixed/evaluate-multiple-gold-python/points.csv",
        "plotFile": "ai16-fixed/evaluate-multiple-gold-python/plot.svg",
        "plotSHA256": "0bf05016e6295d751348d47e6abf36c92ccf94d83e83208906492d7ed076a72f"
      },
      "evaluate-no-positive-gold": {
        "api": "evaluate",
        "variant": "evaluate-no-positive-gold",
        "title": "No supplied positives: undefined recall, RR and AP",
        "language": "python",
        "codeFile": "ai16-code/fixed/evaluate-no-positive-gold.py",
        "codeSHA256": "a6eb9af338501b79f3dddc7196831a59635731de5bfa2b932907d123e566146d",
        "code": "SPEC = {'id': 'evaluate-no-positive-gold', 'api': 'evaluate', 'title': 'No supplied positives: undefined recall, RR and AP', 'args': {'ranking': ['a'], 'relevant': [], 'k': 3}, 'unit': 'P is zero; recall, RR and AP undefined'}\n# Small declared AI16 example. SPEC contains inputs, never an answer table.\nfrom pathlib import Path\nfrom fractions import Fraction as Q\nfrom collections import Counter\nfrom decimal import Decimal,localcontext\nimport csv,json,re,unicodedata,math,sys,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nHERE=Path(__file__).resolve().parent\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\na=SPEC['args'];api=SPEC['api']\nif api=='lexical':\n tf={d['id']:Counter(wordlist(d['text']))for d in a['documents']};df=Counter(t for f in tf.values()for t in f);qt=Counter(wordlist(a['query']));scores={}\n for i,d in enumerate(a['documents'],1):\n  f=tf[d['id']];m=a['method']\n  if m=='jaccard':union=set(qt)|set(f);v=Q(len(set(qt)&set(f)),len(union))if union else None\n  else:v=sum((Q(n*f.get(t,0),1+df[t]if m=='rarity'else 1)for t,n in qt.items()),Q(0))\n  scores[d['id']]=v;row=scalar('score:'+d['id'],v);point(d['id'],m,i,row)\n ordered=sorted((id for id in scores if scores[id]is not None),key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='embedding':\n q=list(map(Q,a['query']));qn=dot(q,q);ranking=[]\n for i,c in enumerate(a['candidates'],1):\n  v=list(map(Q,c['vector']));vn=dot(v,v);d=dot(q,v)\n  if not qn or not vn:row=scalar('cosine:'+c['id']);squared=None;sign=None\n  else:\n   squared=d*d/(qn*vn);sign=(d>0)-(d<0)\n   with localcontext()as ctx:ctx.prec=1100;display=float((Decimal(squared.numerator)/Decimal(squared.denominator)).sqrt())*sign\n   state='exact-zero'if d==0 else'nonzero-underflow'if display==0 else'rounded-unit'if abs(display)==1 and squared!=1 else'ordinary'\n   row=scalar('cosine:'+c['id'],value=display,state=state,exact=str(sign)+'*sqrt('+str(squared)+')');scalar('cosineSquared:'+c['id'],squared);ranking.append((c['id'],sign,squared))\n  point(c['id'],'Cosine',i,row)\n # Exact sign-first comparison, with order reversal on negative squares.\n from functools import cmp_to_key\n def compare(x,y):\n  if x[1]!=y[1]:return(y[1]>x[1])-(y[1]<x[1])\n  r=((y[2]>x[2])-(y[2]<x[2]))*x[1]\n  return r or((x[0]>y[0])-(x[0]<y[0]))\n ranking.sort(key=cmp_to_key(compare));scalar('top',state='label',exact='|'.join(r[0]for r in ranking))\nelif api=='fusion':\n scores={};offset=a['rankOffset']\n for l in a['lists']:\n  for i,id in enumerate(l['ids'],1):scores[id]=scores.get(id,Q(0))+Q(l['weight'])/(offset+i)\n for i,(id,v)in enumerate(sorted(scores.items()),1):point(id,'RRF',i,scalar('score:'+id,v))\n ordered=sorted(scores,key=lambda id:(-scores[id],id));scalar('top',state='label',exact='|'.join(ordered[:a['topK']]))\nelif api=='context':\n size=a['chunkSize'];overlap=a['overlap'];budget=a['tokenBudget']\n if overlap>=size:raise ValueError('overlap must be strictly smaller than chunk size')\n remaining=budget;selected=[];doc={d['id']:d['text']for d in a['documents']};rows=[]\n for id in a.get('ranking',list(doc)):\n  text=doc[id];tokens=[(m.start(),m.end())for m in re.finditer(r'[^\\W_]+',text)]\n  for start in range(0,len(tokens),size-overlap):\n   end=min(start+size,len(tokens));n=min(remaining,end-start);prefix=text[tokens[start][0]:tokens[start+n-1][1]]if n else''\n   rows.append((id,start,end,n,prefix));remaining-=n\n   if n:selected.append((id,prefix))\n scalar('usedWordTokens',budget-remaining);scalar('fullChunks',len(rows))\n for i,(id,start,end,n,prefix)in enumerate(rows,1):\n  row=scalar('selectedTokens:'+str(i),n)\n  if SPEC['id']=='context-overlap':point(f'{start}:{end}','Selected word tokens',i,row)\n for c in a.get('claims',[]):\n  first=scalar('literalInOriginal:'+c['id'],int(c['documentID']in doc and c['quote']in doc[c['documentID']]))\n  second=scalar('literalInSelected:'+c['id'],int(any(did==c['documentID']and c['quote']in text for did,text in selected)))\n  if SPEC['id']=='context-literal-negation':point('In original','Literal presence',1,first);point('In context','Literal presence',2,second)\n scalar('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\nelif api=='evaluate':\n m=metric(a['ranking'],a['relevant'],a['k'])\n for i,(key,v)in enumerate(m.items(),1):point(key,'Finite metric',i,scalar(key,v))\n scalar('positiveGoldCount',len(a['relevant']));scalar('requestedK',a['k'])\nelse:raise ValueError('This small-example template has no source-study shortcut')\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"evaluate-no-positive-gold\", \"status\": \"PASS\", \"summaryFields\": 6, \"plotRows\": 4}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/evaluate-no-positive-gold-python/stdout.txt",
        "stderrFile": "ai16-fixed/evaluate-no-positive-gold-python/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "precision",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "recall",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "RR",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "AP",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "positiveGoldCount",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "requestedK",
            "exact": "3",
            "value": "3.0",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/evaluate-no-positive-gold-python/result.json",
        "summaryFile": "ai16-fixed/evaluate-no-positive-gold-python/summary.csv",
        "plotDataFile": "ai16-fixed/evaluate-no-positive-gold-python/points.csv",
        "plotFile": "ai16-fixed/evaluate-no-positive-gold-python/plot.svg",
        "plotSHA256": "18dd2aea89d78efcef5e060b49706533528eb3680087d1c656c92b1d9aa1775a"
      }
    },
    "r": {
      "evaluate-multiple-gold": {
        "api": "evaluate",
        "variant": "evaluate-multiple-gold",
        "title": "First-hit rank and multi-evidence recovery differ",
        "language": "r",
        "codeFile": "ai16-code/fixed/evaluate-multiple-gold.R",
        "codeSHA256": "8d5bb1545ec5e0499fdf881799e5e96c0cc9ec63722289316ce5b9d7bc1c04e7",
        "code": "S <- list(\"id\"=\"evaluate-multiple-gold\",\"api\"=\"evaluate\",\"title\"=\"First-hit rank and multi-evidence recovery differ\",\"args\"=list(\"ranking\"=list(\"x\",\"a\",\"b\"),\"relevant\"=list(\"a\",\"b\"),\"k\"=3L),\"unit\"=\"Finite binary-relevance metric ratio\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"requestedK\"\r\n\r\n$exact\r\n[1] \"3\"\r\n\r\n$value\r\n[1] \"3\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\nnull device \r\n          1 \r\nPASS: evaluate-multiple-gold summary fields 6 plot rows 4 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/evaluate-multiple-gold-r/stdout.txt",
        "stderrFile": "ai16-fixed/evaluate-multiple-gold-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "precision",
            "exact": "2/3",
            "value": "0.66666666666666663",
            "state": "ordinary"
          },
          {
            "key": "recall",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "RR",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "AP",
            "exact": "7/12",
            "value": "0.58333333333333337",
            "state": "ordinary"
          },
          {
            "key": "positiveGoldCount",
            "exact": "2",
            "value": "2",
            "state": "ordinary"
          },
          {
            "key": "requestedK",
            "exact": "3",
            "value": "3",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/evaluate-multiple-gold-r/result.json",
        "summaryFile": "ai16-fixed/evaluate-multiple-gold-r/summary.csv",
        "plotDataFile": "ai16-fixed/evaluate-multiple-gold-r/points.csv",
        "plotFile": "ai16-fixed/evaluate-multiple-gold-r/plot.svg",
        "plotSHA256": "98f604fa95215ec038d3d31cb77bba9260b298878b2ca472e5c22f6aedd7dbb4"
      },
      "evaluate-no-positive-gold": {
        "api": "evaluate",
        "variant": "evaluate-no-positive-gold",
        "title": "No supplied positives: undefined recall, RR and AP",
        "language": "r",
        "codeFile": "ai16-code/fixed/evaluate-no-positive-gold.R",
        "codeSHA256": "91797aa9e5d486ae8e6f3d91849dc2fd657a89843aff2368b56ee89aa025d836",
        "code": "S <- list(\"id\"=\"evaluate-no-positive-gold\",\"api\"=\"evaluate\",\"title\"=\"No supplied positives: undefined recall, RR and AP\",\"args\"=list(\"ranking\"=list(\"a\"),\"relevant\"=list(),\"k\"=3L),\"unit\"=\"P is zero; recall, RR and AP undefined\")\n# Fixed transparent fixture, not a general rational/Unicode API library.\nif(!isTRUE(l10n_info()[['UTF-8']])){if(.Platform$OS.type=='windows')suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'));if(!isTRUE(l10n_info()[['UTF-8']]))stop('UTF8 LC_CTYPE required')}\nmarkUTF8<-function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv<-markUTF8(commandArgs(trailingOnly=TRUE));allArgs<-markUTF8(commandArgs());here<-dirname(normalizePath(sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1]),mustWork=TRUE))\nOUT<-if(length(argv)>1)argv[2]else file.path(dirname(dirname(here)),'ai16-fixed',S$id);dir.create(OUT,recursive=TRUE,showWarnings=FALSE)\ngcd<-function(a,b){a<-abs(a);b<-abs(b);while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){if(d<0){n<- -n;d<- -d};stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2]);rmul<-function(a,b)rat(a[1]*b[1],a[2]*b[2]);rdiv<-function(a,b)rat(a[1]*b[2],a[2]*b[1]);rstr<-function(a)if(a[2]==1)sprintf('%.0f',a[1])else paste(sprintf('%.0f',a),collapse='/')\nparseSmall<-function(s){p<-strsplit(s,'/',fixed=TRUE)[[1]];rat(as.double(p[1]),if(length(p)>1)as.double(p[2])else 1)}\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\nwords<-function(s){m<-gregexpr('[A-Za-z0-9]+',tolower(s),perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(tolower(s),list(m))[[1]]}\nmetrics<-function(ids,gold,k){hits<-0;first<-0;ap<-rat(0);if(min(k,length(ids))>0)for(i in seq_len(min(k,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap<-radd(ap,rat(hits,i))};list(precision=if(k)rat(hits,k)else NULL,recall=if(length(gold))rat(hits,length(gold))else NULL,RR=if(length(gold)){if(first)rat(1,first)else rat(0)}else NULL,AP=if(length(gold))rat(ap[1],ap[2]*length(gold))else NULL)}\na<-S$args;api<-S$api\nif(api=='lexical'){\n docs<-a$documents;tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));qt<-table(words(a$query));values<-list();ids<-vapply(docs,function(d)d$id,'')\n for(i in seq_along(docs)){\n  f<-tf[[i]];score<-rat(0)\n  if(a$method=='jaccard'){u<-union(names(qt),names(f));score<-if(length(u))rat(length(intersect(names(qt),names(f))),length(u))else NULL}\n  else for(term in names(qt)){v<-unname(f[term]);if(is.na(v))v<-0;den<-if(a$method=='rarity')1+as.integer(df[term])else 1;if(is.na(den))den<-1;score<-radd(score,rat(as.integer(qt[term])*v,den))}\n  values[i]<-list(score);addP(ids[i],a$method,i,addS(paste0('score:',ids[i]),score))\n }\n keep<-which(!vapply(values,is.null,TRUE));ord<-keep[order(-vapply(values[keep],function(q)q[1]/q[2],0.0),ids[keep],method='radix')];addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='embedding'){\n candidates<-a$candidates;ids<-vapply(candidates,function(c)c$id,'');sq<-vector('list',length(ids));sgn<-numeric(length(ids));defined<-rep(FALSE,length(ids))\n if(S$id=='embedding-projection-loss'){\n  # Symbolic simplification for the declared positive powers: a=10^A,b=10^B,\n  # a^2/(a^2+b^2)=1/(1+10^(2(B-A))). No huge coefficient is first cast to0.\n  ex<-as.integer(sub('^1e','',unlist(a$query)));power<-2*(ex[2]-ex[1]);stopifnot(power>0);N<-paste0('1',strrep('0',power));D<-paste0('1',strrep('0',power-1),'1')\n  for(i in seq_along(candidates)){\n   c<-candidates[[i]];v<-as.double(unlist(c$vector))\n   if(all(v==0)){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   numerator<-if(v[1]==1)'1'else N;fraction<-paste0(numerator,'/',D);value<-if(v[1]==1)10^(ex[1]-ex[2])else 1/sqrt(1+10^(-power));state<-if(v[1]==1)'nonzero-underflow'else'rounded-unit'\n   addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id),value=value,state=state,exact=paste0('1*sqrt(',fraction,')')))\n   addS(paste0('cosineSquared:',c$id),value=if(v[1]==1)10^(-power)else 1/(1+10^(-power)),state=if(v[1]==1)'nonzero-underflow'else'rounded-one',exact=fraction);defined[i]<-TRUE\n  }\n  # The second axis is strictly larger because B>A, despite rounded0/1.\n  orderIDs<-c(ids[vapply(candidates,function(c)as.double(c$vector[[2]])==1,TRUE)],ids[vapply(candidates,function(c)as.double(c$vector[[1]])==1,TRUE)])\n }else{\n  q<-as.double(unlist(a$query));qn<-sum(q*q)\n  for(i in seq_along(candidates)){c<-candidates[[i]];v<-as.double(unlist(c$vector));vn<-sum(v*v);d<-sum(q*v)\n   if(qn==0||vn==0){addP(c$id,'Cosine',i,addS(paste0('cosine:',c$id)));next}\n   sq[[i]]<-rat(d*d,qn*vn);sgn[i]<-sign(d);defined[i]<-TRUE;value<-sgn[i]*sqrt(sq[[i]][1]/sq[[i]][2]);row<-addS(paste0('cosine:',c$id),value=value,state=if(d==0)'exact-zero'else'ordinary',exact=paste0(sgn[i],'*sqrt(',rstr(sq[[i]]),')'));addP(c$id,'Cosine',i,row);addS(paste0('cosineSquared:',c$id),sq[[i]])\n  }\n  # Exact crossproducts in this bounded small-integer fixture.\n  better<-function(i,j){if(sgn[i]!=sgn[j])return(sgn[i]>sgn[j]);d<-(sq[[i]][1]*sq[[j]][2]-sq[[j]][1]*sq[[i]][2])*sgn[i];if(d!=0)return(d>0);ids[i]<ids[j]}\n  ord<-integer();for(i in which(defined)){at<-which(vapply(ord,function(j)better(i,j),TRUE));if(length(at))ord<-append(ord,i,after=at[1]-1)else ord<-c(ord,i)};orderIDs<-ids[ord]\n }\n addS('top',state='label',exact=paste(orderIDs,collapse='|'))\n}else if(api=='fusion'){\n ids<-sort(unique(unlist(lapply(a$lists,function(l)unlist(l$ids)))),method='radix');values<-setNames(lapply(ids,function(x)rat(0)),ids)\n for(l in a$lists)for(i in seq_along(l$ids)){id<-l$ids[[i]];values[[id]]<-radd(values[[id]],rdiv(parseSmall(l$weight),rat(a$rankOffset+i)))}\n for(i in seq_along(ids))addP(ids[i],'RRF',i,addS(paste0('score:',ids[i]),values[[ids[i]]]))\n ord<-order(-vapply(values,function(q)q[1]/q[2],0.0),ids,method='radix');addS('top',state='label',exact=paste(head(ids[ord],a$topK),collapse='|'))\n}else if(api=='context'){\n size<-a$chunkSize;overlap<-a$overlap;budget<-a$tokenBudget;if(overlap>=size)stop('overlap must be strictly smaller than chunk size')\n docs<-setNames(vapply(a$documents,function(d)d$text,''),vapply(a$documents,function(d)d$id,''));ranking<-if(is.null(a$ranking))names(docs)else unlist(a$ranking);remaining<-budget;chunks<-list();selected<-list()\n for(id in ranking){text<-docs[[id]];m<-gregexpr('[A-Za-z0-9]+',text,perl=TRUE)[[1]];if(m[1]<0)next;starts<-as.integer(m)-1;ends<-starts+attr(m,'match.length')\n  for(start in seq(0,length(starts)-1,size-overlap)){end<-min(start+size,length(starts));n<-min(remaining,end-start);prefix<-if(n)substr(text,starts[start+1]+1,ends[start+n])else'';chunks[[length(chunks)+1]]<-list(id=id,start=start,end=end,n=n,prefix=prefix);remaining<-remaining-n;if(n)selected[[length(selected)+1]]<-list(id=id,text=prefix)}\n }\n addS('usedWordTokens',rat(budget-remaining));addS('fullChunks',rat(length(chunks)))\n for(i in seq_along(chunks)){r<-chunks[[i]];row<-addS(paste0('selectedTokens:',i),rat(r$n));if(S$id=='context-overlap')addP(paste(r$start,r$end,sep=':'),'Selected word tokens',i,row)}\n if(!is.null(a$claims))for(c in a$claims){first<-addS(paste0('literalInOriginal:',c$id),rat(as.integer(c$documentID%in%names(docs)&&grepl(c$quote,docs[[c$documentID]],fixed=TRUE))));second<-addS(paste0('literalInSelected:',c$id),rat(as.integer(any(vapply(selected,function(s)s$id==c$documentID&&grepl(c$quote,s$text,fixed=TRUE),TRUE)))));if(S$id=='context-literal-negation'){addP('In original','Literal presence',1,first);addP('In context','Literal presence',2,second)}}\n addS('support',state='label',exact='Not evaluated: literal presence is not entailment or truth')\n}else if(api=='evaluate'){\n m<-metrics(unlist(a$ranking),unlist(a$relevant),a$k);for(i in seq_along(m))addP(names(m)[i],'Finite metric',i,addS(names(m)[i],m[[i]]));addS('positiveGoldCount',rat(length(a$relevant)));addS('requestedK',rat(a$k))\n}else stop('No source-study shortcut in the small fixed-example template')\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"requestedK\"\r\n\r\n$exact\r\n[1] \"3\"\r\n\r\n$value\r\n[1] \"3\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\nnull device \r\n          1 \r\nPASS: evaluate-no-positive-gold summary fields 6 plot rows 4 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/evaluate-no-positive-gold-r/stdout.txt",
        "stderrFile": "ai16-fixed/evaluate-no-positive-gold-r/stderr.txt",
        "supportFiles": [],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "precision",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "recall",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "RR",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "AP",
            "exact": "",
            "value": "",
            "state": "undefined"
          },
          {
            "key": "positiveGoldCount",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "requestedK",
            "exact": "3",
            "value": "3",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/evaluate-no-positive-gold-r/result.json",
        "summaryFile": "ai16-fixed/evaluate-no-positive-gold-r/summary.csv",
        "plotDataFile": "ai16-fixed/evaluate-no-positive-gold-r/points.csv",
        "plotFile": "ai16-fixed/evaluate-no-positive-gold-r/plot.svg",
        "plotSHA256": "7d8e79a3c3174dc89c66343b9d1d1b898f18c3805062fdc4a12354ab4b940089"
      }
    }
  },
  "realdata": {
    "python": {
      "realdata-company": {
        "api": "realdata",
        "variant": "realdata-company",
        "title": "Company: product aliases and fiscal-year lookup",
        "language": "python",
        "codeFile": "ai16-code/fixed/realdata-company.py",
        "codeSHA256": "e1d32d60243983e3dac0e0459aff5d1bfa2a4465e86f4212a69a808d638d777e",
        "code": "SPEC = {'id': 'realdata-company', 'api': 'realdata', 'title': 'Company: product aliases and fiscal-year lookup', 'args': {'case': 'company'}, 'unit': 'Selected-method RR@3 by authored query ordinal'}\nfrom fractions import Fraction as Q\nimport math,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n#!/usr/bin/env python3\n\"\"\"AI16 factual retrieval study. Python standard library only.\nUsage: python actual-source-study.py [native_source_directory] [output_directory]\nDefaults are relative to this file, not the current working directory.\nReads only three native factual CSVs. Does not read a JS engine, model JSON,\nanswer file, query ledger, or previously calculated result.\nMovieLens transformations retain its original README/citation/use conditions.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nimport csv,hashlib,json,re,sys,unicodedata\n\nHERE=Path(__file__).resolve().parent\nSOURCE=Path(sys.argv[1]).resolve()if len(sys.argv)>1 else HERE.parent.parent/'ai16-sources'\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nNAMES={'country':'actual32-country-observations-2024.csv','person':'movielens-original-movies.csv','company':'actual30-Apple-product-sales-FY2019-2024.csv'}\nEXPECTED={'country':'4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b','person':'5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07','company':'b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598'}\ndef key(prefix,id):return hashlib.sha256((prefix+'|'+id).encode('utf8')).hexdigest()\ndef load(kind):\n p=SOURCE/NAMES[kind];assert hashlib.sha256(p.read_bytes()).hexdigest()==EXPECTED[kind],f'Wrong native snapshot: {p.name}'\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\nraw={k:load(k)for k in NAMES};models={k:dict(documents=[],queries=[])for k in NAMES};ledger=[]\ndef doc(kind,id,text,native,row,answer):\n start=text.rfind(answer);assert start>=0\n models[kind]['documents'].append(dict(id=id,text=text,sourceRow=str(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+len(answer)))\ndef query(kind,id,text,gold,answer,role,group,type):models[kind]['queries'].append(dict(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type))\ncountries=sorted({r['countryISO3']for r in raw['country']},key=lambda s:(key('AI16-country-role',s),s))\nroles={s:'train'if i<8 else'validation'if i<12 else'test'for i,s in enumerate(countries)}\nfor r in raw['country']:\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\";a=r['originalValueToken']\n text=f\"World Bank observation. Country {r['countryName']} ({r['countryISO3']}). Indicator {r['indicatorName']}; code {r['indicatorID']}. Observation year {r['date']}. Recorded value {a} annual percent.\"\n doc('country',id,text,r['countryISO3']+':'+r['indicatorID'],r['sourceRow'],a)\n query('country','query:'+id,f\"What is the recorded {r['indicatorName']} for {r['countryName']} in {r['date']}?\",[id],a,roles[r['countryISO3']],r['countryISO3'],'native-name lookup')\nranked=sorted(enumerate(raw['person'],1),key=lambda z:(key('AI16-person-corpus',z[1]['movieId']),z[1]['movieId']))\nchosen=ranked[:240];chosenIDs={r['movieId']for _,r in chosen}\ntitleQueries=sorted(chosen,key=lambda z:(key('AI16-person-query',z[1]['movieId']),z[1]['movieId']))[:24]\nmovieRoles={r['movieId']:'train'if j<12 else'validation'if j<18 else'test'for j,(_,r)in enumerate(titleQueries)}\nfor i,r in enumerate(raw['person'],1):\n id=r['movieId'];selected=id in chosenIDs\n ledger.append(dict(sourceRow=i,movieId=id,title=r['title'],genres=r['genres'],corpusSHA=key('AI16-person-corpus',id),in240Corpus=str(selected).lower(),querySHA=key('AI16-person-query',id)if selected else'',queryRole=movieRoles.get(id,'')))\n if not selected:continue\n did='MovieLens:movie:'+id;a=r['genres'];text=f\"MovieLens catalog record. Movie ID {id}. Title {r['title']}. Recorded genres {a}.\"\n doc('person',did,text,id,i,a)\n if id in movieRoles:query('person','query:'+did,f\"What genres are recorded for the film {r['title']}?\",[did],a,movieRoles[id],id,'native-name lookup')\nfor i,r in enumerate(raw['company'],1):\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";a=r['originalUSDMillionsToken'];y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n doc('company',id,f\"Apple annual filing observation. Product group {r['product']}. Fiscal year {r['fiscalYear']}. Net sales in nominal USD millions {a}. Filing fiscal year {r['sourceFilingFY']}.\",r['product']+':'+r['fiscalYear'],i,a)\n query('company','query:'+id,f\"What are Apple {r['product']} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],a,role,r['fiscalYear'],'native-name lookup')\nfor r in raw['country']:\n if r['indicatorID']!='NY.GDP.MKTP.KD.ZG':continue\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\"\n query('country','alias:'+id,f\"How fast did the economy expand in {r['countryName']} during {r['date']}?\",[id],r['originalValueToken'],roles[r['countryISO3']],r['countryISO3'],'authored paraphrase challenge')\ntopics={}\nfor _,r in chosen:\n year=re.search(r'\\((\\d{4})\\)\\s*$',r['title'])\n if not year:continue\n for genre in r['genres'].split('|'):\n  if genre!='(no genres listed)':topics.setdefault((year[1],genre),[]).append('MovieLens:movie:'+r['movieId'])\ntopicKeys=sorted(topics,key=lambda z:(key('AI16-person-topic-query',z[0]+'|'+z[1]),z))[:12]\nfor i,(year,genre)in enumerate(topicKeys):\n group=year+'|'+genre;gold=sorted(topics[year,genre]);role='train'if i<6 else'validation'if i<9 else'test'\n query('person','topic:'+group,f'Which movie catalog records list {genre} and a release year of {year}?',gold,' | '.join(gold),role,group,'authored multi-relevant catalog challenge')\nfor r in raw['company']:\n alias={'iPhone':'handset','iPad':'tablet','Mac':'computer'}.get(r['product'])\n if alias is None:continue\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n query('company','alias:'+id,f\"What are Apple {alias} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],r['originalUSDMillionsToken'],role,r['fiscalYear'],'authored paraphrase challenge')\n\ndef tokens(s):\n s=unicodedata.normalize('NFKC',s).lower();out=[];run=[]\n for ch in s:\n  if unicodedata.category(ch)[0]in'LN':run.append(ch)\n  elif run:out.append(''.join(run));run=[]\n if run:out.append(''.join(run))\n return out\ndef originalTokens(s):\n out=[];start=None\n for i,ch in enumerate(s+' '):\n  if unicodedata.category(ch)[0]in'LN':\n   if start is None:start=i\n  elif start is not None:out.append((start,i,s[start:i]));start=None\n return out\ndef metrics(ids,gold,k=3):\n g=set(gold);hits=0;first=None;ap=F(0)\n for i,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or i;ap+=F(hits,i)\n return dict(hits=hits,precision=F(hits,k)if k else None,recall=F(hits,len(g))if g else None,RR=F(1,first)if first else(F(0)if g else None),AP=ap/len(g)if g else None,coverage=F(min(k,len(ids)),k)if k else None)\ndef exact(x):return ''if x is None else str(x)\ndef write(name,rows):\n assert rows\n with(OUT/name).open('w',encoding='utf8',newline='')as f:\n  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n return dict(file=name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256((OUT/name).read_bytes()).hexdigest())\n\n\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\n# Reconstruct a source case from native CSVs; no model JSON or answer import.\nM=models[SPEC['args']['case']];docs=M['documents'];qs=M['queries'];tf={d['id']:Counter(tokens(d['text']))for d in docs};df=Counter(t for f in tf.values()for t in f);study=[]\nfor q in qs:\n qt=Counter(tokens(q['text']));sc={p:{}for p in ['overlap','rarity']}\n for d in docs:\n  terms=[(t,n*tf[d['id']].get(t,0))for t,n in qt.items()]\n  sc['overlap'][d['id']]=Q(sum(n for t,n in terms));sc['rarity'][d['id']]=sum((Q(n,1+df[t])for t,n in terms if n),Q(0))\n orders={p:sorted(sc[p],key=lambda id:(-sc[p][id],id))for p in sc};ranks={p:{id:i for i,id in enumerate(ids,1)}for p,ids in orders.items()};fused={d['id']:Q(1,60+ranks['overlap'][d['id']])+Q(1,60+ranks['rarity'][d['id']])for d in docs};orders['rrf']=sorted(fused,key=lambda id:(-fused[id],id));study.append(dict(query=q,metrics={p:metrics(orders[p],q['gold'])for p in orders}))\nval={p:sum((r['metrics'][p]['RR']for r in study if r['query']['role']=='validation'),Q(0))/sum(r['query']['role']=='validation'for r in study)for p in ['overlap','rarity','rrf']};selected=max(['overlap','rarity','rrf'],key=lambda p:val[p]);test=[r for r in study if r['query']['role']=='test']\nscalar('corpusDocuments',len(docs));scalar('authoredQueries',len(qs));scalar('selectedProfile',state='label',exact=selected);scalar('validationRR',val[selected])\nfor k in ['precision','recall','RR','AP']:scalar('test'+k,sum((r['metrics'][selected][k]for r in test),Q(0))/len(test))\nfor i,r in enumerate(study,1):point(r['query']['id'],r['query']['role'],i,scalar('queryRR:'+r['query']['id'],r['metrics'][selected]['RR']))\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"realdata-company\", \"status\": \"PASS\", \"summaryFields\": 56, \"plotRows\": 48}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/realdata-company-python/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-company-python/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "30",
            "value": "30.0",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "48",
            "value": "48.0",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "overlap",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "1/4",
            "value": "0.25",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2019",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2020",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2021",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2022",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2023",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2024",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2019",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2020",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2021",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2022",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2023",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2019",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2020",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2021",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2022",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2023",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2024",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          }
        ],
        "resultFile": "ai16-fixed/realdata-company-python/result.json",
        "summaryFile": "ai16-fixed/realdata-company-python/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-company-python/points.csv",
        "plotFile": "ai16-fixed/realdata-company-python/plot.svg",
        "plotSHA256": "072c3eea8127506fe1b731163b11bda45a107d2907f3a5450f57fc39a731d942"
      },
      "realdata-country": {
        "api": "realdata",
        "variant": "realdata-country",
        "title": "Country: indicator paraphrase lookup",
        "language": "python",
        "codeFile": "ai16-code/fixed/realdata-country.py",
        "codeSHA256": "fe0ed16525a8873c7f67e78bac33a16a8c37391e2e1d31e9f39f0c8fe979c5c5",
        "code": "SPEC = {'id': 'realdata-country', 'api': 'realdata', 'title': 'Country: indicator paraphrase lookup', 'args': {'case': 'country'}, 'unit': 'Selected-method RR@3 by authored query ordinal'}\nfrom fractions import Fraction as Q\nimport math,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n#!/usr/bin/env python3\n\"\"\"AI16 factual retrieval study. Python standard library only.\nUsage: python actual-source-study.py [native_source_directory] [output_directory]\nDefaults are relative to this file, not the current working directory.\nReads only three native factual CSVs. Does not read a JS engine, model JSON,\nanswer file, query ledger, or previously calculated result.\nMovieLens transformations retain its original README/citation/use conditions.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nimport csv,hashlib,json,re,sys,unicodedata\n\nHERE=Path(__file__).resolve().parent\nSOURCE=Path(sys.argv[1]).resolve()if len(sys.argv)>1 else HERE.parent.parent/'ai16-sources'\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nNAMES={'country':'actual32-country-observations-2024.csv','person':'movielens-original-movies.csv','company':'actual30-Apple-product-sales-FY2019-2024.csv'}\nEXPECTED={'country':'4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b','person':'5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07','company':'b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598'}\ndef key(prefix,id):return hashlib.sha256((prefix+'|'+id).encode('utf8')).hexdigest()\ndef load(kind):\n p=SOURCE/NAMES[kind];assert hashlib.sha256(p.read_bytes()).hexdigest()==EXPECTED[kind],f'Wrong native snapshot: {p.name}'\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\nraw={k:load(k)for k in NAMES};models={k:dict(documents=[],queries=[])for k in NAMES};ledger=[]\ndef doc(kind,id,text,native,row,answer):\n start=text.rfind(answer);assert start>=0\n models[kind]['documents'].append(dict(id=id,text=text,sourceRow=str(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+len(answer)))\ndef query(kind,id,text,gold,answer,role,group,type):models[kind]['queries'].append(dict(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type))\ncountries=sorted({r['countryISO3']for r in raw['country']},key=lambda s:(key('AI16-country-role',s),s))\nroles={s:'train'if i<8 else'validation'if i<12 else'test'for i,s in enumerate(countries)}\nfor r in raw['country']:\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\";a=r['originalValueToken']\n text=f\"World Bank observation. Country {r['countryName']} ({r['countryISO3']}). Indicator {r['indicatorName']}; code {r['indicatorID']}. Observation year {r['date']}. Recorded value {a} annual percent.\"\n doc('country',id,text,r['countryISO3']+':'+r['indicatorID'],r['sourceRow'],a)\n query('country','query:'+id,f\"What is the recorded {r['indicatorName']} for {r['countryName']} in {r['date']}?\",[id],a,roles[r['countryISO3']],r['countryISO3'],'native-name lookup')\nranked=sorted(enumerate(raw['person'],1),key=lambda z:(key('AI16-person-corpus',z[1]['movieId']),z[1]['movieId']))\nchosen=ranked[:240];chosenIDs={r['movieId']for _,r in chosen}\ntitleQueries=sorted(chosen,key=lambda z:(key('AI16-person-query',z[1]['movieId']),z[1]['movieId']))[:24]\nmovieRoles={r['movieId']:'train'if j<12 else'validation'if j<18 else'test'for j,(_,r)in enumerate(titleQueries)}\nfor i,r in enumerate(raw['person'],1):\n id=r['movieId'];selected=id in chosenIDs\n ledger.append(dict(sourceRow=i,movieId=id,title=r['title'],genres=r['genres'],corpusSHA=key('AI16-person-corpus',id),in240Corpus=str(selected).lower(),querySHA=key('AI16-person-query',id)if selected else'',queryRole=movieRoles.get(id,'')))\n if not selected:continue\n did='MovieLens:movie:'+id;a=r['genres'];text=f\"MovieLens catalog record. Movie ID {id}. Title {r['title']}. Recorded genres {a}.\"\n doc('person',did,text,id,i,a)\n if id in movieRoles:query('person','query:'+did,f\"What genres are recorded for the film {r['title']}?\",[did],a,movieRoles[id],id,'native-name lookup')\nfor i,r in enumerate(raw['company'],1):\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";a=r['originalUSDMillionsToken'];y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n doc('company',id,f\"Apple annual filing observation. Product group {r['product']}. Fiscal year {r['fiscalYear']}. Net sales in nominal USD millions {a}. Filing fiscal year {r['sourceFilingFY']}.\",r['product']+':'+r['fiscalYear'],i,a)\n query('company','query:'+id,f\"What are Apple {r['product']} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],a,role,r['fiscalYear'],'native-name lookup')\nfor r in raw['country']:\n if r['indicatorID']!='NY.GDP.MKTP.KD.ZG':continue\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\"\n query('country','alias:'+id,f\"How fast did the economy expand in {r['countryName']} during {r['date']}?\",[id],r['originalValueToken'],roles[r['countryISO3']],r['countryISO3'],'authored paraphrase challenge')\ntopics={}\nfor _,r in chosen:\n year=re.search(r'\\((\\d{4})\\)\\s*$',r['title'])\n if not year:continue\n for genre in r['genres'].split('|'):\n  if genre!='(no genres listed)':topics.setdefault((year[1],genre),[]).append('MovieLens:movie:'+r['movieId'])\ntopicKeys=sorted(topics,key=lambda z:(key('AI16-person-topic-query',z[0]+'|'+z[1]),z))[:12]\nfor i,(year,genre)in enumerate(topicKeys):\n group=year+'|'+genre;gold=sorted(topics[year,genre]);role='train'if i<6 else'validation'if i<9 else'test'\n query('person','topic:'+group,f'Which movie catalog records list {genre} and a release year of {year}?',gold,' | '.join(gold),role,group,'authored multi-relevant catalog challenge')\nfor r in raw['company']:\n alias={'iPhone':'handset','iPad':'tablet','Mac':'computer'}.get(r['product'])\n if alias is None:continue\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n query('company','alias:'+id,f\"What are Apple {alias} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],r['originalUSDMillionsToken'],role,r['fiscalYear'],'authored paraphrase challenge')\n\ndef tokens(s):\n s=unicodedata.normalize('NFKC',s).lower();out=[];run=[]\n for ch in s:\n  if unicodedata.category(ch)[0]in'LN':run.append(ch)\n  elif run:out.append(''.join(run));run=[]\n if run:out.append(''.join(run))\n return out\ndef originalTokens(s):\n out=[];start=None\n for i,ch in enumerate(s+' '):\n  if unicodedata.category(ch)[0]in'LN':\n   if start is None:start=i\n  elif start is not None:out.append((start,i,s[start:i]));start=None\n return out\ndef metrics(ids,gold,k=3):\n g=set(gold);hits=0;first=None;ap=F(0)\n for i,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or i;ap+=F(hits,i)\n return dict(hits=hits,precision=F(hits,k)if k else None,recall=F(hits,len(g))if g else None,RR=F(1,first)if first else(F(0)if g else None),AP=ap/len(g)if g else None,coverage=F(min(k,len(ids)),k)if k else None)\ndef exact(x):return ''if x is None else str(x)\ndef write(name,rows):\n assert rows\n with(OUT/name).open('w',encoding='utf8',newline='')as f:\n  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n return dict(file=name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256((OUT/name).read_bytes()).hexdigest())\n\n\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\n# Reconstruct a source case from native CSVs; no model JSON or answer import.\nM=models[SPEC['args']['case']];docs=M['documents'];qs=M['queries'];tf={d['id']:Counter(tokens(d['text']))for d in docs};df=Counter(t for f in tf.values()for t in f);study=[]\nfor q in qs:\n qt=Counter(tokens(q['text']));sc={p:{}for p in ['overlap','rarity']}\n for d in docs:\n  terms=[(t,n*tf[d['id']].get(t,0))for t,n in qt.items()]\n  sc['overlap'][d['id']]=Q(sum(n for t,n in terms));sc['rarity'][d['id']]=sum((Q(n,1+df[t])for t,n in terms if n),Q(0))\n orders={p:sorted(sc[p],key=lambda id:(-sc[p][id],id))for p in sc};ranks={p:{id:i for i,id in enumerate(ids,1)}for p,ids in orders.items()};fused={d['id']:Q(1,60+ranks['overlap'][d['id']])+Q(1,60+ranks['rarity'][d['id']])for d in docs};orders['rrf']=sorted(fused,key=lambda id:(-fused[id],id));study.append(dict(query=q,metrics={p:metrics(orders[p],q['gold'])for p in orders}))\nval={p:sum((r['metrics'][p]['RR']for r in study if r['query']['role']=='validation'),Q(0))/sum(r['query']['role']=='validation'for r in study)for p in ['overlap','rarity','rrf']};selected=max(['overlap','rarity','rrf'],key=lambda p:val[p]);test=[r for r in study if r['query']['role']=='test']\nscalar('corpusDocuments',len(docs));scalar('authoredQueries',len(qs));scalar('selectedProfile',state='label',exact=selected);scalar('validationRR',val[selected])\nfor k in ['precision','recall','RR','AP']:scalar('test'+k,sum((r['metrics'][selected][k]for r in test),Q(0))/len(test))\nfor i,r in enumerate(study,1):point(r['query']['id'],r['query']['role'],i,scalar('queryRR:'+r['query']['id'],r['metrics'][selected]['RR']))\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"realdata-country\", \"status\": \"PASS\", \"summaryFields\": 56, \"plotRows\": 48}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/realdata-country-python/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-country-python/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "32",
            "value": "32.0",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "48",
            "value": "48.0",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "overlap",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "5/6",
            "value": "0.8333333333333334",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "1/3",
            "value": "0.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "5/6",
            "value": "0.8333333333333334",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "5/6",
            "value": "0.8333333333333334",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:AUS:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:BRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CAN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CHN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:DEU:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:FRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:GBR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IDN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IND:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:JPN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:KOR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:MEX:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:SGP:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:USA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:VNM:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:ZAF:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:AUS:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:BRA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CAN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CHN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:DEU:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:FRA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:GBR:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IDN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IND:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:JPN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:KOR:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:MEX:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:SGP:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:USA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:VNM:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:ZAF:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:AUS:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:BRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:CAN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:CHN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:DEU:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:FRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:GBR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:IDN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:IND:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:JPN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:KOR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:MEX:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:SGP:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:USA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:VNM:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:ZAF:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/realdata-country-python/result.json",
        "summaryFile": "ai16-fixed/realdata-country-python/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-country-python/points.csv",
        "plotFile": "ai16-fixed/realdata-country-python/plot.svg",
        "plotSHA256": "490ac1fa23904e17419be7b1aeac3740a45bd4874c02e5fdfcee0ad17771aff8"
      },
      "realdata-person": {
        "api": "realdata",
        "variant": "realdata-person",
        "title": "Movie catalog: perfect first-hit rank can hide missing positives",
        "language": "python",
        "codeFile": "ai16-code/fixed/realdata-person.py",
        "codeSHA256": "2cc3e86f2af636592a71bebf495a7eb3fb5809dfdc004b11d50ec7e71b6536ae",
        "code": "SPEC = {'id': 'realdata-person', 'api': 'realdata', 'title': 'Movie catalog: perfect first-hit rank can hide missing positives', 'args': {'case': 'person'}, 'unit': 'Selected-method RR@3 by authored query ordinal'}\nfrom fractions import Fraction as Q\nimport math,textwrap\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n#!/usr/bin/env python3\n\"\"\"AI16 factual retrieval study. Python standard library only.\nUsage: python actual-source-study.py [native_source_directory] [output_directory]\nDefaults are relative to this file, not the current working directory.\nReads only three native factual CSVs. Does not read a JS engine, model JSON,\nanswer file, query ledger, or previously calculated result.\nMovieLens transformations retain its original README/citation/use conditions.\n\"\"\"\nfrom pathlib import Path\nfrom fractions import Fraction as F\nfrom collections import Counter\nimport csv,hashlib,json,re,sys,unicodedata\n\nHERE=Path(__file__).resolve().parent\nSOURCE=Path(sys.argv[1]).resolve()if len(sys.argv)>1 else HERE.parent.parent/'ai16-sources'\nOUT=Path(sys.argv[2]).resolve()if len(sys.argv)>2 else HERE.parent.parent/'ai16-fixed'/SPEC['id']\nOUT.mkdir(parents=True,exist_ok=True)\nNAMES={'country':'actual32-country-observations-2024.csv','person':'movielens-original-movies.csv','company':'actual30-Apple-product-sales-FY2019-2024.csv'}\nEXPECTED={'country':'4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b','person':'5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07','company':'b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598'}\ndef key(prefix,id):return hashlib.sha256((prefix+'|'+id).encode('utf8')).hexdigest()\ndef load(kind):\n p=SOURCE/NAMES[kind];assert hashlib.sha256(p.read_bytes()).hexdigest()==EXPECTED[kind],f'Wrong native snapshot: {p.name}'\n with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))\nraw={k:load(k)for k in NAMES};models={k:dict(documents=[],queries=[])for k in NAMES};ledger=[]\ndef doc(kind,id,text,native,row,answer):\n start=text.rfind(answer);assert start>=0\n models[kind]['documents'].append(dict(id=id,text=text,sourceRow=str(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+len(answer)))\ndef query(kind,id,text,gold,answer,role,group,type):models[kind]['queries'].append(dict(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type))\ncountries=sorted({r['countryISO3']for r in raw['country']},key=lambda s:(key('AI16-country-role',s),s))\nroles={s:'train'if i<8 else'validation'if i<12 else'test'for i,s in enumerate(countries)}\nfor r in raw['country']:\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\";a=r['originalValueToken']\n text=f\"World Bank observation. Country {r['countryName']} ({r['countryISO3']}). Indicator {r['indicatorName']}; code {r['indicatorID']}. Observation year {r['date']}. Recorded value {a} annual percent.\"\n doc('country',id,text,r['countryISO3']+':'+r['indicatorID'],r['sourceRow'],a)\n query('country','query:'+id,f\"What is the recorded {r['indicatorName']} for {r['countryName']} in {r['date']}?\",[id],a,roles[r['countryISO3']],r['countryISO3'],'native-name lookup')\nranked=sorted(enumerate(raw['person'],1),key=lambda z:(key('AI16-person-corpus',z[1]['movieId']),z[1]['movieId']))\nchosen=ranked[:240];chosenIDs={r['movieId']for _,r in chosen}\ntitleQueries=sorted(chosen,key=lambda z:(key('AI16-person-query',z[1]['movieId']),z[1]['movieId']))[:24]\nmovieRoles={r['movieId']:'train'if j<12 else'validation'if j<18 else'test'for j,(_,r)in enumerate(titleQueries)}\nfor i,r in enumerate(raw['person'],1):\n id=r['movieId'];selected=id in chosenIDs\n ledger.append(dict(sourceRow=i,movieId=id,title=r['title'],genres=r['genres'],corpusSHA=key('AI16-person-corpus',id),in240Corpus=str(selected).lower(),querySHA=key('AI16-person-query',id)if selected else'',queryRole=movieRoles.get(id,'')))\n if not selected:continue\n did='MovieLens:movie:'+id;a=r['genres'];text=f\"MovieLens catalog record. Movie ID {id}. Title {r['title']}. Recorded genres {a}.\"\n doc('person',did,text,id,i,a)\n if id in movieRoles:query('person','query:'+did,f\"What genres are recorded for the film {r['title']}?\",[did],a,movieRoles[id],id,'native-name lookup')\nfor i,r in enumerate(raw['company'],1):\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";a=r['originalUSDMillionsToken'];y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n doc('company',id,f\"Apple annual filing observation. Product group {r['product']}. Fiscal year {r['fiscalYear']}. Net sales in nominal USD millions {a}. Filing fiscal year {r['sourceFilingFY']}.\",r['product']+':'+r['fiscalYear'],i,a)\n query('company','query:'+id,f\"What are Apple {r['product']} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],a,role,r['fiscalYear'],'native-name lookup')\nfor r in raw['country']:\n if r['indicatorID']!='NY.GDP.MKTP.KD.ZG':continue\n id=f\"WB:{r['countryISO3']}:{r['indicatorID']}:{r['date']}\"\n query('country','alias:'+id,f\"How fast did the economy expand in {r['countryName']} during {r['date']}?\",[id],r['originalValueToken'],roles[r['countryISO3']],r['countryISO3'],'authored paraphrase challenge')\ntopics={}\nfor _,r in chosen:\n year=re.search(r'\\((\\d{4})\\)\\s*$',r['title'])\n if not year:continue\n for genre in r['genres'].split('|'):\n  if genre!='(no genres listed)':topics.setdefault((year[1],genre),[]).append('MovieLens:movie:'+r['movieId'])\ntopicKeys=sorted(topics,key=lambda z:(key('AI16-person-topic-query',z[0]+'|'+z[1]),z))[:12]\nfor i,(year,genre)in enumerate(topicKeys):\n group=year+'|'+genre;gold=sorted(topics[year,genre]);role='train'if i<6 else'validation'if i<9 else'test'\n query('person','topic:'+group,f'Which movie catalog records list {genre} and a release year of {year}?',gold,' | '.join(gold),role,group,'authored multi-relevant catalog challenge')\nfor r in raw['company']:\n alias={'iPhone':'handset','iPad':'tablet','Mac':'computer'}.get(r['product'])\n if alias is None:continue\n id=f\"Apple:{r['product']}:{r['fiscalYear']}\";y=int(r['fiscalYear']);role='train'if y<=2021 else'validation'if y==2022 else'test'\n query('company','alias:'+id,f\"What are Apple {alias} net sales in nominal USD millions for fiscal year {r['fiscalYear']}?\",[id],r['originalUSDMillionsToken'],role,r['fiscalYear'],'authored paraphrase challenge')\n\ndef tokens(s):\n s=unicodedata.normalize('NFKC',s).lower();out=[];run=[]\n for ch in s:\n  if unicodedata.category(ch)[0]in'LN':run.append(ch)\n  elif run:out.append(''.join(run));run=[]\n if run:out.append(''.join(run))\n return out\ndef originalTokens(s):\n out=[];start=None\n for i,ch in enumerate(s+' '):\n  if unicodedata.category(ch)[0]in'LN':\n   if start is None:start=i\n  elif start is not None:out.append((start,i,s[start:i]));start=None\n return out\ndef metrics(ids,gold,k=3):\n g=set(gold);hits=0;first=None;ap=F(0)\n for i,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or i;ap+=F(hits,i)\n return dict(hits=hits,precision=F(hits,k)if k else None,recall=F(hits,len(g))if g else None,RR=F(1,first)if first else(F(0)if g else None),AP=ap/len(g)if g else None,coverage=F(min(k,len(ids)),k)if k else None)\ndef exact(x):return ''if x is None else str(x)\ndef write(name,rows):\n assert rows\n with(OUT/name).open('w',encoding='utf8',newline='')as f:\n  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)\n return dict(file=name,rows=len(rows),columns=len(rows[0]),bodyFields=len(rows)*len(rows[0]),sha256=hashlib.sha256((OUT/name).read_bytes()).hexdigest())\n\n\nsummary=[];points=[]\ndef scalar(key,q=None,value=None,state=None,exact=None):\n if q is not None:\n  q=Q(q);exact=str(q);value=float(q)\n  state='exact-zero'if q==0 else'nonzero-underflow'if value==0 else'rounded-one'if value==1 and q!=1 else'ordinary'\n elif state is None:state='undefined'if value is None else'ordinary'\n row=dict(key=key,exact=''if exact is None else exact,value=''if value is None else repr(value),state=state);summary.append(row);return row\ndef dot(a,b):return sum((x*y for x,y in zip(a,b)),Q(0))\ndef wordlist(s):\n s=unicodedata.normalize('NFKC',s).lower();return re.findall(r'[^\\W_]+',s)\ndef metric(ids,gold,k):\n g=set(gold);hits=0;first=None;ap=Q(0)\n for r,id in enumerate(ids[:k],1):\n  if id in g:hits+=1;first=first or r;ap+=Q(hits,r)\n return dict(precision=Q(hits,k)if k else None,recall=Q(hits,len(g))if g else None,RR=(Q(1,first)if first else Q(0))if g else None,AP=ap/len(g)if g else None)\ndef point(label,series,x,row):points.append(dict(label=label,series=series,x=x,exact=row['exact'],value=row['value'],state=row['state']))\n# Reconstruct a source case from native CSVs; no model JSON or answer import.\nM=models[SPEC['args']['case']];docs=M['documents'];qs=M['queries'];tf={d['id']:Counter(tokens(d['text']))for d in docs};df=Counter(t for f in tf.values()for t in f);study=[]\nfor q in qs:\n qt=Counter(tokens(q['text']));sc={p:{}for p in ['overlap','rarity']}\n for d in docs:\n  terms=[(t,n*tf[d['id']].get(t,0))for t,n in qt.items()]\n  sc['overlap'][d['id']]=Q(sum(n for t,n in terms));sc['rarity'][d['id']]=sum((Q(n,1+df[t])for t,n in terms if n),Q(0))\n orders={p:sorted(sc[p],key=lambda id:(-sc[p][id],id))for p in sc};ranks={p:{id:i for i,id in enumerate(ids,1)}for p,ids in orders.items()};fused={d['id']:Q(1,60+ranks['overlap'][d['id']])+Q(1,60+ranks['rarity'][d['id']])for d in docs};orders['rrf']=sorted(fused,key=lambda id:(-fused[id],id));study.append(dict(query=q,metrics={p:metrics(orders[p],q['gold'])for p in orders}))\nval={p:sum((r['metrics'][p]['RR']for r in study if r['query']['role']=='validation'),Q(0))/sum(r['query']['role']=='validation'for r in study)for p in ['overlap','rarity','rrf']};selected=max(['overlap','rarity','rrf'],key=lambda p:val[p]);test=[r for r in study if r['query']['role']=='test']\nscalar('corpusDocuments',len(docs));scalar('authoredQueries',len(qs));scalar('selectedProfile',state='label',exact=selected);scalar('validationRR',val[selected])\nfor k in ['precision','recall','RR','AP']:scalar('test'+k,sum((r['metrics'][selected][k]for r in test),Q(0))/len(test))\nfor i,r in enumerate(study,1):point(r['query']['id'],r['query']['role'],i,scalar('queryRR:'+r['query']['id'],r['metrics'][selected]['RR']))\n\n# Fixed archive output: exact strings and display states remain distinct.\nwith(OUT/'summary.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['key','exact','value','state']);w.writeheader();w.writerows(summary)\nwith(OUT/'points.csv').open('w',encoding='utf8',newline='')as f:\n w=csv.DictWriter(f,fieldnames=['label','series','x','exact','value','state']);w.writeheader();w.writerows(points)\n(OUT/'result.json').write_text(json.dumps(dict(profile=SPEC['id'],api=SPEC['api'],inputs=SPEC['args'],summary=summary,points=points,scope='Declared fixed example; exact fractions/algebraic expressions separate from binary64 plot projections and undefined states'),ensure_ascii=False,indent=2)+'\\n',encoding='utf8')\nplt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'svg.fonttype':'none'})\nfig,ax=plt.subplots(figsize=(10,6.2));series=list(dict.fromkeys(p['series']for p in points));palette=['#286774','#934b34','#6c6389'];vals=[]\nfor si,s in enumerate(series):\n rr=[p for p in points if p['series']==s and p['value']!=''];x=[p['x']for p in rr];y=[float(p['value'])for p in rr];vals+=y\n ax.scatter(x,y,label=s,color=palette[si%3],s=45,zorder=3)\nfor p in points:\n if p['state']=='undefined':ax.text(p['x'],.97,'Undefined',transform=ax.get_xaxis_transform(),rotation=90,ha='center',va='top',fontsize=12,color='#555')\n if p['state']=='nonzero-underflow':ax.scatter([p['x']],[float(p['value'])],marker='^',s=120,facecolors='none',edgecolors='#934b34',zorder=4);ax.annotate('>0; display underflow',(p['x'],float(p['value'])),xytext=(5,13),textcoords='offset points',fontsize=12)\n if p['state']=='rounded-unit':ax.annotate('Magnitude <1; rounded display',(p['x'],float(p['value'])),xytext=(5,-20),textcoords='offset points',fontsize=12,ha='center')\nif len(points)<=12:ax.set_xticks([p['x']for p in points],[p['label']for p in points],rotation=25 if len(points)>4 else 0)\nlo=min([0]+vals);hi=max([1]+vals);pad=(hi-lo)*.08;ax.set_ylim(lo-pad,hi+pad)\nax.set_title(textwrap.fill(SPEC['title'],76),fontsize=16,pad=15);ax.set_xlabel('Authored query ordinal'if SPEC['api']=='realdata'else'Declared row / candidate / metric',fontsize=14);ax.set_ylabel(textwrap.fill(SPEC['unit'],43),fontsize=14);ax.grid(axis='y',color='#ddd');ax.set_axisbelow(True)\nif len(series)>1:ax.legend(fontsize=12,frameon=False)\nfor s in ['top','right']:ax.spines[s].set_visible(False)\nfig.tight_layout();fig.savefig(OUT/'plot.svg');plt.close(fig)\nprint(json.dumps(dict(profile=SPEC['id'],status='PASS',summaryFields=len(summary),plotRows=len(points)),ensure_ascii=False))\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "{\"profile\": \"realdata-person\", \"status\": \"PASS\", \"summaryFields\": 44, \"plotRows\": 36}\r\n",
        "stderr": "",
        "stderrIsProjection": false,
        "rawStderrSHA256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
        "stdoutFile": "ai16-fixed/realdata-person-python/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-person-python/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "python <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "240",
            "value": "240.0",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "36",
            "value": "36.0",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "rarity",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "25/27",
            "value": "0.9259259259259259",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "11/27",
            "value": "0.4074074074074074",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "41/45",
            "value": "0.9111111111111111",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "41/45",
            "value": "0.9111111111111111",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:468",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:1477",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:2272",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:2577",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:3157",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6280",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6322",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6564",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:7177",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:7394",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:8727",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:8970",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:39449",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:44777",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:45658",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:46948",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:49110",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:56333",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:62383",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:85316",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:93297",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:102666",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:117867",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:133281",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2009|Thriller",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1951|Sci-Fi",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2001|Comedy",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1994|Animation",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1988|Action",
            "exact": "1/3",
            "value": "0.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2003|Fantasy",
            "exact": "0",
            "value": "0.0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:topic:1993|Crime",
            "exact": "1/3",
            "value": "0.3333333333333333",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1986|Romance",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1989|Comedy",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2002|Drama",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2011|Thriller",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1992|Comedy",
            "exact": "1",
            "value": "1.0",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/realdata-person-python/result.json",
        "summaryFile": "ai16-fixed/realdata-person-python/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-person-python/points.csv",
        "plotFile": "ai16-fixed/realdata-person-python/plot.svg",
        "plotSHA256": "6606931d79335e1ee598e47b221be0f42df509d403afb861203161f9ca2abd3a"
      }
    },
    "r": {
      "realdata-company": {
        "api": "realdata",
        "variant": "realdata-company",
        "title": "Company: product aliases and fiscal-year lookup",
        "language": "r",
        "codeFile": "ai16-code/fixed/realdata-company.R",
        "codeSHA256": "58bb3094504fa04927cba5c0f1d6f03c3db3c4673f3bdfe3764356935c6597d9",
        "code": "S <- list(\"id\"=\"realdata-company\",\"api\"=\"realdata\",\"title\"=\"Company: product aliases and fiscal-year lookup\",\"args\"=list(\"case\"=\"company\"),\"unit\"=\"Selected-method RR@3 by authored query ordinal\")\n# AI16 factual retrieval reproduction. Base R + its bundled tools package only.\n# Rscript actual-source-study.R [native_source_directory] [output_directory]\n# Reads three native CSVs, never JS/model JSON/answer tables. It recreates SHA256\n# selection, authored documents/questions, exact ranking keys and finite metrics.\n# It is a source-study program, not a general Unicode NFKC library. All compiled\n# text in this retained study is already NFKC, as checked by the Python source\n# audit. UTF-8 letter/number tokenization and case conversion are applied here.\n# MovieLens README, citation and original use conditions remain applicable.\n\n# The calling environment may supply the Unix name C.UTF-8 on Windows.\n# Do not silently decode non-ASCII native titles in the fallback ASCII locale.\nif(!isTRUE(l10n_info()[['UTF-8']])){\n  if(.Platform$OS.type=='windows') suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'))\n  if(!isTRUE(l10n_info()[['UTF-8']])) stop('Run this UTF-8 source study in a UTF-8 LC_CTYPE locale.')\n}\nmarkUTF8 <- function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv <- markUTF8(commandArgs(trailingOnly=TRUE))\nallArgs <- markUTF8(commandArgs())\nfileArg <- sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1])\nhere <- dirname(normalizePath(fileArg,mustWork=TRUE))\nsourceDir <- if(length(argv)) normalizePath(argv[1],mustWork=TRUE) else file.path(dirname(dirname(here)),'ai16-sources')\noutDir <- if(length(argv)>1) argv[2] else file.path(dirname(dirname(here)),'ai16-fixed',S$id)\ndir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nfiles <- c(country='actual32-country-observations-2024.csv',person='movielens-original-movies.csv',company='actual30-Apple-product-sales-FY2019-2024.csv')\nexpectedMD5 <- c(country='20579b4e1d4e3e016bf3340ab82d117e',person='ed94fab72b62442ef8150d9446e000d6',company='9c72921fbcf7b4617d54c9671b3ca391')\nstopifnot(all(unname(tools::md5sum(file.path(sourceDir,files)))==expectedMD5))\nraw <- lapply(files,function(f)read.csv(file.path(sourceDir,f),colClasses='character',check.names=FALSE,na.strings=NULL,fileEncoding='UTF-8-BOM'))\nstopifnot(identical(vapply(raw,nrow,0L),c(country=32L,person=9742L,company=30L)))\n\n# SHA256 for a batch of the declared ASCII selection messages (one block each).\n# All arithmetic additions fit exactly within binary64; bit operations use safe\n# unsigned 16-bit halves, avoiding R's reserved signed integer NA word.\nu32 <- 4294967296; base <- 65536\nbx <- function(x,y)as.double(bitwXor(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwXor(as.integer(floor(x/base)),as.integer(floor(y/base))))\nba <- function(x,y)as.double(bitwAnd(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwAnd(as.integer(floor(x/base)),as.integer(floor(y/base))))\nbn <- function(x)u32-1-x\nrr <- function(x,n)floor(x/2^n)+(x%%2^n)*2^(32-n)\nhx <- function(s)strtoi(substr(s,1,4),16L)*base+strtoi(substr(s,5,8),16L)\nK <- vapply(strsplit(paste('428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5','d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174','e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da','983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967','27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85','a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070','19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3','748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2'), ' +')[[1]],hx,0.0)\nH <- vapply(strsplit('6a09e667 bb67ae85 3c6ef372 a54ff53a 510e527f 9b05688c 1f83d9ab 5be0cd19',' ')[[1]],hx,0.0)\nshaBatch <- function(strings){\n n<-length(strings); if(!n)return(character()); bytes<-lapply(strings,function(s)as.integer(charToRaw(enc2utf8(s))));stopifnot(all(lengths(bytes)<=55),all(vapply(bytes,function(x)all(x<128),TRUE)))\n block<-matrix(0,n,64)\n for(i in seq_len(n)){m<-length(bytes[[i]]);if(m)block[i,seq_len(m)]<-bytes[[i]];block[i,m+1]<-128;bits<-m*8;block[i,63]<-floor(bits/256);block[i,64]<-bits%%256}\n w<-vector('list',64)\n for(t in 1:16)w[[t]]<-as.vector(block[,(4*t-3):(4*t),drop=FALSE]%*%c(16777216,65536,256,1))\n for(t in 17:64){x<-w[[t-15]];y<-w[[t-2]];s0<-bx(bx(rr(x,7),rr(x,18)),floor(x/8));s1<-bx(bx(rr(y,17),rr(y,19)),floor(y/1024));w[[t]]<-(w[[t-16]]+s0+w[[t-7]]+s1)%%u32}\n v<-lapply(H,function(x)rep(x,n));a<-v[[1]];b<-v[[2]];c<-v[[3]];d<-v[[4]];e<-v[[5]];f<-v[[6]];g<-v[[7]];h<-v[[8]]\n for(t in 1:64){S1<-bx(bx(rr(e,6),rr(e,11)),rr(e,25));ch<-bx(ba(e,f),ba(bn(e),g));t1<-(h+S1+ch+K[t]+w[[t]])%%u32;S0<-bx(bx(rr(a,2),rr(a,13)),rr(a,22));maj<-bx(bx(ba(a,b),ba(a,c)),ba(b,c));t2<-(S0+maj)%%u32;h<-g;g<-f;f<-e;e<-(d+t1)%%u32;d<-c;c<-b;b<-a;a<-(t1+t2)%%u32}\n ans<-list(a,b,c,d,e,f,g,h);out<-rep('',n)\n for(j in 1:8){z<-(ans[[j]]+H[j])%%u32;out<-paste0(out,sprintf('%04x%04x',as.integer(floor(z/base)),as.integer(z%%base)))}\n out\n}\nstopifnot(identical(shaBatch(c('','abc')),c('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855','ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')))\nkey <- function(prefix,id)shaBatch(paste0(prefix,'|',id))\nmodels<-setNames(lapply(files,function(x)list(documents=list(),queries=list())),names(files))\naddDoc<-function(kind,id,text,native,row,answer){\n at<-gregexpr(answer,text,fixed=TRUE)[[1]];stopifnot(at[1]>0);start<-tail(at,1)-1\n models[[kind]]$documents[[length(models[[kind]]$documents)+1]]<<-list(id=id,text=text,sourceRow=as.character(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+nchar(answer,type='chars'))\n}\naddQuery<-function(kind,id,text,gold,answer,role,group,type)models[[kind]]$queries[[length(models[[kind]]$queries)+1]]<<-list(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type)\ncountries<-unique(raw$country$countryISO3);countries<-countries[order(key('AI16-country-role',countries),countries,method='radix')];roles<-setNames(c(rep('train',8),rep('validation',4),rep('test',4)),countries)\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');a<-r$originalValueToken\n addDoc('country',id,paste0('World Bank observation. Country ',r$countryName,' (',r$countryISO3,'). Indicator ',r$indicatorName,'; code ',r$indicatorID,'. Observation year ',r$date,'. Recorded value ',a,' annual percent.'),paste(r$countryISO3,r$indicatorID,sep=':'),r$sourceRow,a)\n addQuery('country',paste0('query:',id),paste0('What is the recorded ',r$indicatorName,' for ',r$countryName,' in ',r$date,'?'),id,a,unname(roles[r$countryISO3]),r$countryISO3,'native-name lookup')\n}\nmovie<-raw$person;corpusSHA<-key('AI16-person-corpus',movie$movieId);chosen<-order(corpusSHA,movie$movieId,method='radix')[1:240];querySHA<-rep('',nrow(movie));querySHA[chosen]<-key('AI16-person-query',movie$movieId[chosen]);qc<-chosen[order(querySHA[chosen],movie$movieId[chosen],method='radix')][1:24];movieRoles<-setNames(c(rep('train',12),rep('validation',6),rep('test',6)),movie$movieId[qc])\nledger<-list()\nfor(i in seq_len(nrow(movie))){r<-movie[i,];selected<-i%in%chosen;role<-unname(movieRoles[r$movieId]);if(is.na(role))role<-''\n ledger[[i]]<-list(sourceRow=i,movieId=r$movieId,title=r$title,genres=r$genres,corpusSHA=corpusSHA[i],in240Corpus=tolower(as.character(selected)),querySHA=querySHA[i],queryRole=role)\n if(!selected)next;id<-paste0('MovieLens:movie:',r$movieId);addDoc('person',id,paste0('MovieLens catalog record. Movie ID ',r$movieId,'. Title ',r$title,'. Recorded genres ',r$genres,'.'),r$movieId,i,r$genres)\n if(nzchar(role))addQuery('person',paste0('query:',id),paste0('What genres are recorded for the film ',r$title,'?'),id,r$genres,role,r$movieId,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';a<-r$originalUSDMillionsToken\n addDoc('company',id,paste0('Apple annual filing observation. Product group ',r$product,'. Fiscal year ',r$fiscalYear,'. Net sales in nominal USD millions ',a,'. Filing fiscal year ',r$sourceFilingFY,'.'),paste(r$product,r$fiscalYear,sep=':'),i,a)\n addQuery('company',paste0('query:',id),paste0('What are Apple ',r$product,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,a,role,r$fiscalYear,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];if(r$indicatorID!='NY.GDP.MKTP.KD.ZG')next;id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');addQuery('country',paste0('alias:',id),paste0('How fast did the economy expand in ',r$countryName,' during ',r$date,'?'),id,r$originalValueToken,unname(roles[r$countryISO3]),r$countryISO3,'authored paraphrase challenge')}\ntopics<-list()\nfor(i in chosen){r<-movie[i,];if(!grepl('\\\\([0-9]{4}\\\\)[[:space:]]*$',r$title))next;year<-sub('.*\\\\(([0-9]{4})\\\\)[[:space:]]*$','\\\\1',r$title)\n for(genre in strsplit(r$genres,'|',fixed=TRUE)[[1]])if(genre!='(no genres listed)'){g<-paste(year,genre,sep='|');topics[[g]]<-c(topics[[g]],paste0('MovieLens:movie:',r$movieId))}}\ngroups<-names(topics);groups<-groups[order(key('AI16-person-topic-query',groups),groups,method='radix')][1:12]\nfor(i in seq_along(groups)){g<-groups[i];p<-strsplit(g,'|',fixed=TRUE)[[1]];gold<-sort(topics[[g]],method='radix');role<-if(i<=6)'train'else if(i<=9)'validation'else'test';addQuery('person',paste0('topic:',g),paste0('Which movie catalog records list ',p[2],' and a release year of ',p[1],'?'),gold,paste(gold,collapse=' | '),role,g,'authored multi-relevant catalog challenge')}\naliases<-c(iPhone='handset',iPad='tablet',Mac='computer')\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];alias<-unname(aliases[r$product]);if(is.na(alias))next;id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';addQuery('company',paste0('alias:',id),paste0('What are Apple ',alias,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,r$originalUSDMillionsToken,role,r$fiscalYear,'authored paraphrase challenge')}\n\n# Nonnegative integer limbs, base 10^6. The common denominator LCM(1..N+60)\n# makes every rarity and RRF ranking comparison exact, including equal scores.\n# Published R fractions may be unreduced; their rational values are exact.\nB<-1e6\ntrim<-function(x){while(length(x)>1&&tail(x,1)==0)x<-head(x,-1);x}\nbmul<-function(x,k){out<-numeric(length(x));carry<-0;for(i in seq_along(x)){v<-x[i]*k+carry;out[i]<-v%%B;carry<-floor(v/B)};while(carry>0){out<-c(out,carry%%B);carry<-floor(carry/B)};trim(out)}\nbadd<-function(x,y){n<-max(length(x),length(y));length(x)<-n;length(y)<-n;x[is.na(x)]<-0;y[is.na(y)]<-0;out<-numeric(n);carry<-0;for(i in seq_len(n)){v<-x[i]+y[i]+carry;out[i]<-v%%B;carry<-floor(v/B)};if(carry)out<-c(out,carry);trim(out)}\nbdiv<-function(x,k){out<-numeric(length(x));carry<-0;for(i in rev(seq_along(x))){v<-carry*B+x[i];out[i]<-floor(v/k);carry<-v%%k};stopifnot(carry==0);trim(out)}\nbstr<-function(x){x<-trim(x);if(length(x)==1)return(sprintf('%.0f',x));paste0(sprintf('%.0f',tail(x,1)),paste(sprintf('%06.0f',rev(head(x,-1))),collapse=''))}\ncommonDenominator<-function(limit){D<-1;for(p in 2:limit){prime<-all(p%%seq_len(max(1,floor(sqrt(p))))[-1]!=0);if(!prime)next;power<-p;while(power*p<=limit)power<-power*p;D<-bmul(D,power)};D}\nrankKeys<-function(keys,ids){str<-vapply(keys,bstr,'');pad<-paste0(strrep('0',max(nchar(str))-nchar(str)),str);order(pad,ids,decreasing=c(TRUE,FALSE),method='radix')}\ngcd<-function(a,b){while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2])\nrstr<-function(x)if(x[2]==1)sprintf('%.0f',x[1])else paste(sprintf('%.0f',x),collapse='/')\nrmean<-function(xs){z<-Reduce(radd,xs,init=c(0,1));rat(z[1],z[2]*length(xs))}\nwords<-function(s){s<-tolower(enc2utf8(s));m<-gregexpr('[\\\\p{L}\\\\p{N}]+',s,perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(s,list(m))[[1]]}\nmetric<-function(ids,gold){hits<-0;first<-0;ap6<-0;for(i in seq_len(min(3,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap6<-ap6+hits*6/i};list(hits=hits,precision=rat(hits,3),recall=rat(hits,length(gold)),RR=if(first)rat(1,first)else rat(0),AP=rat(ap6,6*length(gold)),coverage=rat(min(3,length(ids)),3))}\nrowAppend<-function(x,row)c(x,list(row))\n\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\n# Fresh reconstruction from native files. No precomputed model/answer imported.\nOUT<-outDir;M<-models[[S$args$case]];docs<-M$documents;qs<-M$queries;ids<-vapply(docs,function(d)d$id,'');tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));D<-commonDenominator(length(docs)+60);parts<-lapply(seq_len(length(docs)+60),function(k)bdiv(D,k));study<-list()\nfor(q in qs){qt<-table(words(q$text));ov<-numeric(length(docs));rare<-vector('list',length(docs))\n for(i in seq_along(docs)){v<-tf[[i]][names(qt)];v[is.na(v)]<-0;coef<-as.numeric(qt)*as.numeric(v);ov[i]<-sum(coef);rk<-0;for(j in which(coef>0)){den<-1+as.integer(df[names(qt)[j]]);rk<-badd(rk,bmul(parts[[den]],coef[j]))};rare[[i]]<-rk}\n orders<-list(overlap=order(-ov,ids,method='radix'),rarity=rankKeys(rare,ids));ranks<-lapply(orders,function(o){r<-integer(length(o));r[o]<-seq_along(o);r});rf<-lapply(seq_along(ids),function(i)badd(parts[[60+ranks$overlap[i]]],parts[[60+ranks$rarity[i]]]));orders$rrf<-rankKeys(rf,ids);study[[length(study)+1]]<-list(query=q,metrics=lapply(orders,function(o)metric(ids[o],q$gold)))\n}\nval<-lapply(c('overlap','rarity','rrf'),function(p)rmean(lapply(Filter(function(r)r$query$role=='validation',study),function(r)r$metrics[[p]]$RR)));names(val)<-c('overlap','rarity','rrf');selected<-'overlap'\nfor(p in c('rarity','rrf'))if(val[[p]][1]*val[[selected]][2]>val[[selected]][1]*val[[p]][2])selected<-p\naddS('corpusDocuments',rat(length(docs)));addS('authoredQueries',rat(length(qs)));addS('selectedProfile',state='label',exact=selected);addS('validationRR',val[[selected]])\ntest<-Filter(function(r)r$query$role=='test',study);for(k in c('precision','recall','RR','AP'))addS(paste0('test',k),rmean(lapply(test,function(r)r$metrics[[selected]][[k]])))\nfor(i in seq_along(study)){r<-study[[i]];addP(r$query$id,r$query$role,i,addS(paste0('queryRR:',r$query$id),r$metrics[[selected]]$RR))}\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"corpusDocuments\"\r\n\r\n$exact\r\n[1] \"30\"\r\n\r\n$value\r\n[1] \"30\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"authoredQueries\"\r\n\r\n$exact\r\n[1] \"48\"\r\n\r\n$value\r\n[1] \"48\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"selectedProfile\"\r\n\r\n$exact\r\n[1] \"overlap\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\n$key\r\n[1] \"validationRR\"\r\n\r\n$exact\r\n[1] \"3/4\"\r\n\r\n$value\r\n[1] \"0.75\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\nnull device \r\n          1 \r\nPASS: realdata-company summary fields 56 plot rows 48 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/realdata-company-r/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-company-r/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "30",
            "value": "30",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "48",
            "value": "48",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "overlap",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "1/4",
            "value": "0.25",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "3/4",
            "value": "0.75",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPhone:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Mac:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:iPad:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Wearables, Home and Accessories:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:Apple:Services:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2019",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2020",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2021",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2022",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2023",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPhone:2024",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2019",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2020",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2021",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2022",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2023",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:Mac:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2019",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2020",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2021",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2022",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2023",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:alias:Apple:iPad:2024",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          }
        ],
        "resultFile": "ai16-fixed/realdata-company-r/result.json",
        "summaryFile": "ai16-fixed/realdata-company-r/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-company-r/points.csv",
        "plotFile": "ai16-fixed/realdata-company-r/plot.svg",
        "plotSHA256": "611d63cc06a32b4bf02241baabf53614d7da203cd875623995c2f282a03e5441"
      },
      "realdata-country": {
        "api": "realdata",
        "variant": "realdata-country",
        "title": "Country: indicator paraphrase lookup",
        "language": "r",
        "codeFile": "ai16-code/fixed/realdata-country.R",
        "codeSHA256": "e94da10daae3659b4ff111e87c237e05764d7c21d56f46a3e61508d1fa75ab68",
        "code": "S <- list(\"id\"=\"realdata-country\",\"api\"=\"realdata\",\"title\"=\"Country: indicator paraphrase lookup\",\"args\"=list(\"case\"=\"country\"),\"unit\"=\"Selected-method RR@3 by authored query ordinal\")\n# AI16 factual retrieval reproduction. Base R + its bundled tools package only.\n# Rscript actual-source-study.R [native_source_directory] [output_directory]\n# Reads three native CSVs, never JS/model JSON/answer tables. It recreates SHA256\n# selection, authored documents/questions, exact ranking keys and finite metrics.\n# It is a source-study program, not a general Unicode NFKC library. All compiled\n# text in this retained study is already NFKC, as checked by the Python source\n# audit. UTF-8 letter/number tokenization and case conversion are applied here.\n# MovieLens README, citation and original use conditions remain applicable.\n\n# The calling environment may supply the Unix name C.UTF-8 on Windows.\n# Do not silently decode non-ASCII native titles in the fallback ASCII locale.\nif(!isTRUE(l10n_info()[['UTF-8']])){\n  if(.Platform$OS.type=='windows') suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'))\n  if(!isTRUE(l10n_info()[['UTF-8']])) stop('Run this UTF-8 source study in a UTF-8 LC_CTYPE locale.')\n}\nmarkUTF8 <- function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv <- markUTF8(commandArgs(trailingOnly=TRUE))\nallArgs <- markUTF8(commandArgs())\nfileArg <- sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1])\nhere <- dirname(normalizePath(fileArg,mustWork=TRUE))\nsourceDir <- if(length(argv)) normalizePath(argv[1],mustWork=TRUE) else file.path(dirname(dirname(here)),'ai16-sources')\noutDir <- if(length(argv)>1) argv[2] else file.path(dirname(dirname(here)),'ai16-fixed',S$id)\ndir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nfiles <- c(country='actual32-country-observations-2024.csv',person='movielens-original-movies.csv',company='actual30-Apple-product-sales-FY2019-2024.csv')\nexpectedMD5 <- c(country='20579b4e1d4e3e016bf3340ab82d117e',person='ed94fab72b62442ef8150d9446e000d6',company='9c72921fbcf7b4617d54c9671b3ca391')\nstopifnot(all(unname(tools::md5sum(file.path(sourceDir,files)))==expectedMD5))\nraw <- lapply(files,function(f)read.csv(file.path(sourceDir,f),colClasses='character',check.names=FALSE,na.strings=NULL,fileEncoding='UTF-8-BOM'))\nstopifnot(identical(vapply(raw,nrow,0L),c(country=32L,person=9742L,company=30L)))\n\n# SHA256 for a batch of the declared ASCII selection messages (one block each).\n# All arithmetic additions fit exactly within binary64; bit operations use safe\n# unsigned 16-bit halves, avoiding R's reserved signed integer NA word.\nu32 <- 4294967296; base <- 65536\nbx <- function(x,y)as.double(bitwXor(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwXor(as.integer(floor(x/base)),as.integer(floor(y/base))))\nba <- function(x,y)as.double(bitwAnd(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwAnd(as.integer(floor(x/base)),as.integer(floor(y/base))))\nbn <- function(x)u32-1-x\nrr <- function(x,n)floor(x/2^n)+(x%%2^n)*2^(32-n)\nhx <- function(s)strtoi(substr(s,1,4),16L)*base+strtoi(substr(s,5,8),16L)\nK <- vapply(strsplit(paste('428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5','d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174','e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da','983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967','27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85','a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070','19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3','748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2'), ' +')[[1]],hx,0.0)\nH <- vapply(strsplit('6a09e667 bb67ae85 3c6ef372 a54ff53a 510e527f 9b05688c 1f83d9ab 5be0cd19',' ')[[1]],hx,0.0)\nshaBatch <- function(strings){\n n<-length(strings); if(!n)return(character()); bytes<-lapply(strings,function(s)as.integer(charToRaw(enc2utf8(s))));stopifnot(all(lengths(bytes)<=55),all(vapply(bytes,function(x)all(x<128),TRUE)))\n block<-matrix(0,n,64)\n for(i in seq_len(n)){m<-length(bytes[[i]]);if(m)block[i,seq_len(m)]<-bytes[[i]];block[i,m+1]<-128;bits<-m*8;block[i,63]<-floor(bits/256);block[i,64]<-bits%%256}\n w<-vector('list',64)\n for(t in 1:16)w[[t]]<-as.vector(block[,(4*t-3):(4*t),drop=FALSE]%*%c(16777216,65536,256,1))\n for(t in 17:64){x<-w[[t-15]];y<-w[[t-2]];s0<-bx(bx(rr(x,7),rr(x,18)),floor(x/8));s1<-bx(bx(rr(y,17),rr(y,19)),floor(y/1024));w[[t]]<-(w[[t-16]]+s0+w[[t-7]]+s1)%%u32}\n v<-lapply(H,function(x)rep(x,n));a<-v[[1]];b<-v[[2]];c<-v[[3]];d<-v[[4]];e<-v[[5]];f<-v[[6]];g<-v[[7]];h<-v[[8]]\n for(t in 1:64){S1<-bx(bx(rr(e,6),rr(e,11)),rr(e,25));ch<-bx(ba(e,f),ba(bn(e),g));t1<-(h+S1+ch+K[t]+w[[t]])%%u32;S0<-bx(bx(rr(a,2),rr(a,13)),rr(a,22));maj<-bx(bx(ba(a,b),ba(a,c)),ba(b,c));t2<-(S0+maj)%%u32;h<-g;g<-f;f<-e;e<-(d+t1)%%u32;d<-c;c<-b;b<-a;a<-(t1+t2)%%u32}\n ans<-list(a,b,c,d,e,f,g,h);out<-rep('',n)\n for(j in 1:8){z<-(ans[[j]]+H[j])%%u32;out<-paste0(out,sprintf('%04x%04x',as.integer(floor(z/base)),as.integer(z%%base)))}\n out\n}\nstopifnot(identical(shaBatch(c('','abc')),c('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855','ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')))\nkey <- function(prefix,id)shaBatch(paste0(prefix,'|',id))\nmodels<-setNames(lapply(files,function(x)list(documents=list(),queries=list())),names(files))\naddDoc<-function(kind,id,text,native,row,answer){\n at<-gregexpr(answer,text,fixed=TRUE)[[1]];stopifnot(at[1]>0);start<-tail(at,1)-1\n models[[kind]]$documents[[length(models[[kind]]$documents)+1]]<<-list(id=id,text=text,sourceRow=as.character(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+nchar(answer,type='chars'))\n}\naddQuery<-function(kind,id,text,gold,answer,role,group,type)models[[kind]]$queries[[length(models[[kind]]$queries)+1]]<<-list(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type)\ncountries<-unique(raw$country$countryISO3);countries<-countries[order(key('AI16-country-role',countries),countries,method='radix')];roles<-setNames(c(rep('train',8),rep('validation',4),rep('test',4)),countries)\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');a<-r$originalValueToken\n addDoc('country',id,paste0('World Bank observation. Country ',r$countryName,' (',r$countryISO3,'). Indicator ',r$indicatorName,'; code ',r$indicatorID,'. Observation year ',r$date,'. Recorded value ',a,' annual percent.'),paste(r$countryISO3,r$indicatorID,sep=':'),r$sourceRow,a)\n addQuery('country',paste0('query:',id),paste0('What is the recorded ',r$indicatorName,' for ',r$countryName,' in ',r$date,'?'),id,a,unname(roles[r$countryISO3]),r$countryISO3,'native-name lookup')\n}\nmovie<-raw$person;corpusSHA<-key('AI16-person-corpus',movie$movieId);chosen<-order(corpusSHA,movie$movieId,method='radix')[1:240];querySHA<-rep('',nrow(movie));querySHA[chosen]<-key('AI16-person-query',movie$movieId[chosen]);qc<-chosen[order(querySHA[chosen],movie$movieId[chosen],method='radix')][1:24];movieRoles<-setNames(c(rep('train',12),rep('validation',6),rep('test',6)),movie$movieId[qc])\nledger<-list()\nfor(i in seq_len(nrow(movie))){r<-movie[i,];selected<-i%in%chosen;role<-unname(movieRoles[r$movieId]);if(is.na(role))role<-''\n ledger[[i]]<-list(sourceRow=i,movieId=r$movieId,title=r$title,genres=r$genres,corpusSHA=corpusSHA[i],in240Corpus=tolower(as.character(selected)),querySHA=querySHA[i],queryRole=role)\n if(!selected)next;id<-paste0('MovieLens:movie:',r$movieId);addDoc('person',id,paste0('MovieLens catalog record. Movie ID ',r$movieId,'. Title ',r$title,'. Recorded genres ',r$genres,'.'),r$movieId,i,r$genres)\n if(nzchar(role))addQuery('person',paste0('query:',id),paste0('What genres are recorded for the film ',r$title,'?'),id,r$genres,role,r$movieId,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';a<-r$originalUSDMillionsToken\n addDoc('company',id,paste0('Apple annual filing observation. Product group ',r$product,'. Fiscal year ',r$fiscalYear,'. Net sales in nominal USD millions ',a,'. Filing fiscal year ',r$sourceFilingFY,'.'),paste(r$product,r$fiscalYear,sep=':'),i,a)\n addQuery('company',paste0('query:',id),paste0('What are Apple ',r$product,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,a,role,r$fiscalYear,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];if(r$indicatorID!='NY.GDP.MKTP.KD.ZG')next;id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');addQuery('country',paste0('alias:',id),paste0('How fast did the economy expand in ',r$countryName,' during ',r$date,'?'),id,r$originalValueToken,unname(roles[r$countryISO3]),r$countryISO3,'authored paraphrase challenge')}\ntopics<-list()\nfor(i in chosen){r<-movie[i,];if(!grepl('\\\\([0-9]{4}\\\\)[[:space:]]*$',r$title))next;year<-sub('.*\\\\(([0-9]{4})\\\\)[[:space:]]*$','\\\\1',r$title)\n for(genre in strsplit(r$genres,'|',fixed=TRUE)[[1]])if(genre!='(no genres listed)'){g<-paste(year,genre,sep='|');topics[[g]]<-c(topics[[g]],paste0('MovieLens:movie:',r$movieId))}}\ngroups<-names(topics);groups<-groups[order(key('AI16-person-topic-query',groups),groups,method='radix')][1:12]\nfor(i in seq_along(groups)){g<-groups[i];p<-strsplit(g,'|',fixed=TRUE)[[1]];gold<-sort(topics[[g]],method='radix');role<-if(i<=6)'train'else if(i<=9)'validation'else'test';addQuery('person',paste0('topic:',g),paste0('Which movie catalog records list ',p[2],' and a release year of ',p[1],'?'),gold,paste(gold,collapse=' | '),role,g,'authored multi-relevant catalog challenge')}\naliases<-c(iPhone='handset',iPad='tablet',Mac='computer')\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];alias<-unname(aliases[r$product]);if(is.na(alias))next;id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';addQuery('company',paste0('alias:',id),paste0('What are Apple ',alias,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,r$originalUSDMillionsToken,role,r$fiscalYear,'authored paraphrase challenge')}\n\n# Nonnegative integer limbs, base 10^6. The common denominator LCM(1..N+60)\n# makes every rarity and RRF ranking comparison exact, including equal scores.\n# Published R fractions may be unreduced; their rational values are exact.\nB<-1e6\ntrim<-function(x){while(length(x)>1&&tail(x,1)==0)x<-head(x,-1);x}\nbmul<-function(x,k){out<-numeric(length(x));carry<-0;for(i in seq_along(x)){v<-x[i]*k+carry;out[i]<-v%%B;carry<-floor(v/B)};while(carry>0){out<-c(out,carry%%B);carry<-floor(carry/B)};trim(out)}\nbadd<-function(x,y){n<-max(length(x),length(y));length(x)<-n;length(y)<-n;x[is.na(x)]<-0;y[is.na(y)]<-0;out<-numeric(n);carry<-0;for(i in seq_len(n)){v<-x[i]+y[i]+carry;out[i]<-v%%B;carry<-floor(v/B)};if(carry)out<-c(out,carry);trim(out)}\nbdiv<-function(x,k){out<-numeric(length(x));carry<-0;for(i in rev(seq_along(x))){v<-carry*B+x[i];out[i]<-floor(v/k);carry<-v%%k};stopifnot(carry==0);trim(out)}\nbstr<-function(x){x<-trim(x);if(length(x)==1)return(sprintf('%.0f',x));paste0(sprintf('%.0f',tail(x,1)),paste(sprintf('%06.0f',rev(head(x,-1))),collapse=''))}\ncommonDenominator<-function(limit){D<-1;for(p in 2:limit){prime<-all(p%%seq_len(max(1,floor(sqrt(p))))[-1]!=0);if(!prime)next;power<-p;while(power*p<=limit)power<-power*p;D<-bmul(D,power)};D}\nrankKeys<-function(keys,ids){str<-vapply(keys,bstr,'');pad<-paste0(strrep('0',max(nchar(str))-nchar(str)),str);order(pad,ids,decreasing=c(TRUE,FALSE),method='radix')}\ngcd<-function(a,b){while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2])\nrstr<-function(x)if(x[2]==1)sprintf('%.0f',x[1])else paste(sprintf('%.0f',x),collapse='/')\nrmean<-function(xs){z<-Reduce(radd,xs,init=c(0,1));rat(z[1],z[2]*length(xs))}\nwords<-function(s){s<-tolower(enc2utf8(s));m<-gregexpr('[\\\\p{L}\\\\p{N}]+',s,perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(s,list(m))[[1]]}\nmetric<-function(ids,gold){hits<-0;first<-0;ap6<-0;for(i in seq_len(min(3,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap6<-ap6+hits*6/i};list(hits=hits,precision=rat(hits,3),recall=rat(hits,length(gold)),RR=if(first)rat(1,first)else rat(0),AP=rat(ap6,6*length(gold)),coverage=rat(min(3,length(ids)),3))}\nrowAppend<-function(x,row)c(x,list(row))\n\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\n# Fresh reconstruction from native files. No precomputed model/answer imported.\nOUT<-outDir;M<-models[[S$args$case]];docs<-M$documents;qs<-M$queries;ids<-vapply(docs,function(d)d$id,'');tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));D<-commonDenominator(length(docs)+60);parts<-lapply(seq_len(length(docs)+60),function(k)bdiv(D,k));study<-list()\nfor(q in qs){qt<-table(words(q$text));ov<-numeric(length(docs));rare<-vector('list',length(docs))\n for(i in seq_along(docs)){v<-tf[[i]][names(qt)];v[is.na(v)]<-0;coef<-as.numeric(qt)*as.numeric(v);ov[i]<-sum(coef);rk<-0;for(j in which(coef>0)){den<-1+as.integer(df[names(qt)[j]]);rk<-badd(rk,bmul(parts[[den]],coef[j]))};rare[[i]]<-rk}\n orders<-list(overlap=order(-ov,ids,method='radix'),rarity=rankKeys(rare,ids));ranks<-lapply(orders,function(o){r<-integer(length(o));r[o]<-seq_along(o);r});rf<-lapply(seq_along(ids),function(i)badd(parts[[60+ranks$overlap[i]]],parts[[60+ranks$rarity[i]]]));orders$rrf<-rankKeys(rf,ids);study[[length(study)+1]]<-list(query=q,metrics=lapply(orders,function(o)metric(ids[o],q$gold)))\n}\nval<-lapply(c('overlap','rarity','rrf'),function(p)rmean(lapply(Filter(function(r)r$query$role=='validation',study),function(r)r$metrics[[p]]$RR)));names(val)<-c('overlap','rarity','rrf');selected<-'overlap'\nfor(p in c('rarity','rrf'))if(val[[p]][1]*val[[selected]][2]>val[[selected]][1]*val[[p]][2])selected<-p\naddS('corpusDocuments',rat(length(docs)));addS('authoredQueries',rat(length(qs)));addS('selectedProfile',state='label',exact=selected);addS('validationRR',val[[selected]])\ntest<-Filter(function(r)r$query$role=='test',study);for(k in c('precision','recall','RR','AP'))addS(paste0('test',k),rmean(lapply(test,function(r)r$metrics[[selected]][[k]])))\nfor(i in seq_along(study)){r<-study[[i]];addP(r$query$id,r$query$role,i,addS(paste0('queryRR:',r$query$id),r$metrics[[selected]]$RR))}\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend('topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"corpusDocuments\"\r\n\r\n$exact\r\n[1] \"32\"\r\n\r\n$value\r\n[1] \"32\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"authoredQueries\"\r\n\r\n$exact\r\n[1] \"48\"\r\n\r\n$value\r\n[1] \"48\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"selectedProfile\"\r\n\r\n$exact\r\n[1] \"overlap\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\n$key\r\n[1] \"validationRR\"\r\n\r\n$exact\r\n[1] \"5/6\"\r\n\r\n$value\r\n[1] \"0.83333333333333337\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\nnull device \r\n          1 \r\nPASS: realdata-country summary fields 56 plot rows 48 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/realdata-country-r/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-country-r/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "32",
            "value": "32",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "48",
            "value": "48",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "overlap",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "5/6",
            "value": "0.83333333333333337",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "1/3",
            "value": "0.33333333333333331",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "5/6",
            "value": "0.83333333333333337",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "5/6",
            "value": "0.83333333333333337",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:AUS:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:BRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CAN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CHN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:DEU:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:FRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:GBR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IDN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IND:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:JPN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:KOR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:MEX:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:SGP:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:USA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:VNM:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:ZAF:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:AUS:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:BRA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CAN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:CHN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:DEU:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:FRA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:GBR:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IDN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:IND:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:JPN:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:KOR:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:MEX:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:SGP:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:USA:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:VNM:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:WB:ZAF:FP.CPI.TOTL.ZG:2024",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:AUS:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:BRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:CAN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:CHN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:DEU:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:FRA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:GBR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:IDN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:IND:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:JPN:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:KOR:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:MEX:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:SGP:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:USA:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:VNM:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:alias:WB:ZAF:NY.GDP.MKTP.KD.ZG:2024",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/realdata-country-r/result.json",
        "summaryFile": "ai16-fixed/realdata-country-r/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-country-r/points.csv",
        "plotFile": "ai16-fixed/realdata-country-r/plot.svg",
        "plotSHA256": "6015e65c3a766bdec5eb9d5c4b560f6ac9a619eccc46fc1df53d1a8b4fb96a9f"
      },
      "realdata-person": {
        "api": "realdata",
        "variant": "realdata-person",
        "title": "Movie catalog: perfect first-hit rank can hide missing positives",
        "language": "r",
        "codeFile": "ai16-code/fixed/realdata-person.R",
        "codeSHA256": "e2741ffc881b37addb25de63925059fd6d00c4537cac397f166f14d8c7e43b75",
        "code": "S <- list(\"id\"=\"realdata-person\",\"api\"=\"realdata\",\"title\"=\"Movie catalog: perfect first-hit rank can hide missing positives\",\"args\"=list(\"case\"=\"person\"),\"unit\"=\"Selected-method RR@3 by authored query ordinal\")\n# AI16 factual retrieval reproduction. Base R + its bundled tools package only.\n# Rscript actual-source-study.R [native_source_directory] [output_directory]\n# Reads three native CSVs, never JS/model JSON/answer tables. It recreates SHA256\n# selection, authored documents/questions, exact ranking keys and finite metrics.\n# It is a source-study program, not a general Unicode NFKC library. All compiled\n# text in this retained study is already NFKC, as checked by the Python source\n# audit. UTF-8 letter/number tokenization and case conversion are applied here.\n# MovieLens README, citation and original use conditions remain applicable.\n\n# The calling environment may supply the Unix name C.UTF-8 on Windows.\n# Do not silently decode non-ASCII native titles in the fallback ASCII locale.\nif(!isTRUE(l10n_info()[['UTF-8']])){\n  if(.Platform$OS.type=='windows') suppressWarnings(Sys.setlocale('LC_CTYPE','.UTF-8'))\n  if(!isTRUE(l10n_info()[['UTF-8']])) stop('Run this UTF-8 source study in a UTF-8 LC_CTYPE locale.')\n}\nmarkUTF8 <- function(x){ok<-validUTF8(x);Encoding(x[ok])<-'UTF-8';x}\nargv <- markUTF8(commandArgs(trailingOnly=TRUE))\nallArgs <- markUTF8(commandArgs())\nfileArg <- sub('^--file=','',allArgs[grepl('^--file=',allArgs)][1])\nhere <- dirname(normalizePath(fileArg,mustWork=TRUE))\nsourceDir <- if(length(argv)) normalizePath(argv[1],mustWork=TRUE) else file.path(dirname(dirname(here)),'ai16-sources')\noutDir <- if(length(argv)>1) argv[2] else file.path(dirname(dirname(here)),'ai16-fixed',S$id)\ndir.create(outDir,recursive=TRUE,showWarnings=FALSE)\nfiles <- c(country='actual32-country-observations-2024.csv',person='movielens-original-movies.csv',company='actual30-Apple-product-sales-FY2019-2024.csv')\nexpectedMD5 <- c(country='20579b4e1d4e3e016bf3340ab82d117e',person='ed94fab72b62442ef8150d9446e000d6',company='9c72921fbcf7b4617d54c9671b3ca391')\nstopifnot(all(unname(tools::md5sum(file.path(sourceDir,files)))==expectedMD5))\nraw <- lapply(files,function(f)read.csv(file.path(sourceDir,f),colClasses='character',check.names=FALSE,na.strings=NULL,fileEncoding='UTF-8-BOM'))\nstopifnot(identical(vapply(raw,nrow,0L),c(country=32L,person=9742L,company=30L)))\n\n# SHA256 for a batch of the declared ASCII selection messages (one block each).\n# All arithmetic additions fit exactly within binary64; bit operations use safe\n# unsigned 16-bit halves, avoiding R's reserved signed integer NA word.\nu32 <- 4294967296; base <- 65536\nbx <- function(x,y)as.double(bitwXor(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwXor(as.integer(floor(x/base)),as.integer(floor(y/base))))\nba <- function(x,y)as.double(bitwAnd(as.integer(x%%base),as.integer(y%%base)))+base*as.double(bitwAnd(as.integer(floor(x/base)),as.integer(floor(y/base))))\nbn <- function(x)u32-1-x\nrr <- function(x,n)floor(x/2^n)+(x%%2^n)*2^(32-n)\nhx <- function(s)strtoi(substr(s,1,4),16L)*base+strtoi(substr(s,5,8),16L)\nK <- vapply(strsplit(paste('428a2f98 71374491 b5c0fbcf e9b5dba5 3956c25b 59f111f1 923f82a4 ab1c5ed5','d807aa98 12835b01 243185be 550c7dc3 72be5d74 80deb1fe 9bdc06a7 c19bf174','e49b69c1 efbe4786 0fc19dc6 240ca1cc 2de92c6f 4a7484aa 5cb0a9dc 76f988da','983e5152 a831c66d b00327c8 bf597fc7 c6e00bf3 d5a79147 06ca6351 14292967','27b70a85 2e1b2138 4d2c6dfc 53380d13 650a7354 766a0abb 81c2c92e 92722c85','a2bfe8a1 a81a664b c24b8b70 c76c51a3 d192e819 d6990624 f40e3585 106aa070','19a4c116 1e376c08 2748774c 34b0bcb5 391c0cb3 4ed8aa4a 5b9cca4f 682e6ff3','748f82ee 78a5636f 84c87814 8cc70208 90befffa a4506ceb bef9a3f7 c67178f2'), ' +')[[1]],hx,0.0)\nH <- vapply(strsplit('6a09e667 bb67ae85 3c6ef372 a54ff53a 510e527f 9b05688c 1f83d9ab 5be0cd19',' ')[[1]],hx,0.0)\nshaBatch <- function(strings){\n n<-length(strings); if(!n)return(character()); bytes<-lapply(strings,function(s)as.integer(charToRaw(enc2utf8(s))));stopifnot(all(lengths(bytes)<=55),all(vapply(bytes,function(x)all(x<128),TRUE)))\n block<-matrix(0,n,64)\n for(i in seq_len(n)){m<-length(bytes[[i]]);if(m)block[i,seq_len(m)]<-bytes[[i]];block[i,m+1]<-128;bits<-m*8;block[i,63]<-floor(bits/256);block[i,64]<-bits%%256}\n w<-vector('list',64)\n for(t in 1:16)w[[t]]<-as.vector(block[,(4*t-3):(4*t),drop=FALSE]%*%c(16777216,65536,256,1))\n for(t in 17:64){x<-w[[t-15]];y<-w[[t-2]];s0<-bx(bx(rr(x,7),rr(x,18)),floor(x/8));s1<-bx(bx(rr(y,17),rr(y,19)),floor(y/1024));w[[t]]<-(w[[t-16]]+s0+w[[t-7]]+s1)%%u32}\n v<-lapply(H,function(x)rep(x,n));a<-v[[1]];b<-v[[2]];c<-v[[3]];d<-v[[4]];e<-v[[5]];f<-v[[6]];g<-v[[7]];h<-v[[8]]\n for(t in 1:64){S1<-bx(bx(rr(e,6),rr(e,11)),rr(e,25));ch<-bx(ba(e,f),ba(bn(e),g));t1<-(h+S1+ch+K[t]+w[[t]])%%u32;S0<-bx(bx(rr(a,2),rr(a,13)),rr(a,22));maj<-bx(bx(ba(a,b),ba(a,c)),ba(b,c));t2<-(S0+maj)%%u32;h<-g;g<-f;f<-e;e<-(d+t1)%%u32;d<-c;c<-b;b<-a;a<-(t1+t2)%%u32}\n ans<-list(a,b,c,d,e,f,g,h);out<-rep('',n)\n for(j in 1:8){z<-(ans[[j]]+H[j])%%u32;out<-paste0(out,sprintf('%04x%04x',as.integer(floor(z/base)),as.integer(z%%base)))}\n out\n}\nstopifnot(identical(shaBatch(c('','abc')),c('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855','ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')))\nkey <- function(prefix,id)shaBatch(paste0(prefix,'|',id))\nmodels<-setNames(lapply(files,function(x)list(documents=list(),queries=list())),names(files))\naddDoc<-function(kind,id,text,native,row,answer){\n at<-gregexpr(answer,text,fixed=TRUE)[[1]];stopifnot(at[1]>0);start<-tail(at,1)-1\n models[[kind]]$documents[[length(models[[kind]]$documents)+1]]<<-list(id=id,text=text,sourceRow=as.character(row),nativeID=native,answerText=answer,answerStart=start,answerEnd=start+nchar(answer,type='chars'))\n}\naddQuery<-function(kind,id,text,gold,answer,role,group,type)models[[kind]]$queries[[length(models[[kind]]$queries)+1]]<<-list(id=id,text=text,gold=gold,answerText=answer,role=role,group=group,queryType=type)\ncountries<-unique(raw$country$countryISO3);countries<-countries[order(key('AI16-country-role',countries),countries,method='radix')];roles<-setNames(c(rep('train',8),rep('validation',4),rep('test',4)),countries)\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');a<-r$originalValueToken\n addDoc('country',id,paste0('World Bank observation. Country ',r$countryName,' (',r$countryISO3,'). Indicator ',r$indicatorName,'; code ',r$indicatorID,'. Observation year ',r$date,'. Recorded value ',a,' annual percent.'),paste(r$countryISO3,r$indicatorID,sep=':'),r$sourceRow,a)\n addQuery('country',paste0('query:',id),paste0('What is the recorded ',r$indicatorName,' for ',r$countryName,' in ',r$date,'?'),id,a,unname(roles[r$countryISO3]),r$countryISO3,'native-name lookup')\n}\nmovie<-raw$person;corpusSHA<-key('AI16-person-corpus',movie$movieId);chosen<-order(corpusSHA,movie$movieId,method='radix')[1:240];querySHA<-rep('',nrow(movie));querySHA[chosen]<-key('AI16-person-query',movie$movieId[chosen]);qc<-chosen[order(querySHA[chosen],movie$movieId[chosen],method='radix')][1:24];movieRoles<-setNames(c(rep('train',12),rep('validation',6),rep('test',6)),movie$movieId[qc])\nledger<-list()\nfor(i in seq_len(nrow(movie))){r<-movie[i,];selected<-i%in%chosen;role<-unname(movieRoles[r$movieId]);if(is.na(role))role<-''\n ledger[[i]]<-list(sourceRow=i,movieId=r$movieId,title=r$title,genres=r$genres,corpusSHA=corpusSHA[i],in240Corpus=tolower(as.character(selected)),querySHA=querySHA[i],queryRole=role)\n if(!selected)next;id<-paste0('MovieLens:movie:',r$movieId);addDoc('person',id,paste0('MovieLens catalog record. Movie ID ',r$movieId,'. Title ',r$title,'. Recorded genres ',r$genres,'.'),r$movieId,i,r$genres)\n if(nzchar(role))addQuery('person',paste0('query:',id),paste0('What genres are recorded for the film ',r$title,'?'),id,r$genres,role,r$movieId,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';a<-r$originalUSDMillionsToken\n addDoc('company',id,paste0('Apple annual filing observation. Product group ',r$product,'. Fiscal year ',r$fiscalYear,'. Net sales in nominal USD millions ',a,'. Filing fiscal year ',r$sourceFilingFY,'.'),paste(r$product,r$fiscalYear,sep=':'),i,a)\n addQuery('company',paste0('query:',id),paste0('What are Apple ',r$product,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,a,role,r$fiscalYear,'native-name lookup')\n}\nfor(i in seq_len(nrow(raw$country))){r<-raw$country[i,];if(r$indicatorID!='NY.GDP.MKTP.KD.ZG')next;id<-paste('WB',r$countryISO3,r$indicatorID,r$date,sep=':');addQuery('country',paste0('alias:',id),paste0('How fast did the economy expand in ',r$countryName,' during ',r$date,'?'),id,r$originalValueToken,unname(roles[r$countryISO3]),r$countryISO3,'authored paraphrase challenge')}\ntopics<-list()\nfor(i in chosen){r<-movie[i,];if(!grepl('\\\\([0-9]{4}\\\\)[[:space:]]*$',r$title))next;year<-sub('.*\\\\(([0-9]{4})\\\\)[[:space:]]*$','\\\\1',r$title)\n for(genre in strsplit(r$genres,'|',fixed=TRUE)[[1]])if(genre!='(no genres listed)'){g<-paste(year,genre,sep='|');topics[[g]]<-c(topics[[g]],paste0('MovieLens:movie:',r$movieId))}}\ngroups<-names(topics);groups<-groups[order(key('AI16-person-topic-query',groups),groups,method='radix')][1:12]\nfor(i in seq_along(groups)){g<-groups[i];p<-strsplit(g,'|',fixed=TRUE)[[1]];gold<-sort(topics[[g]],method='radix');role<-if(i<=6)'train'else if(i<=9)'validation'else'test';addQuery('person',paste0('topic:',g),paste0('Which movie catalog records list ',p[2],' and a release year of ',p[1],'?'),gold,paste(gold,collapse=' | '),role,g,'authored multi-relevant catalog challenge')}\naliases<-c(iPhone='handset',iPad='tablet',Mac='computer')\nfor(i in seq_len(nrow(raw$company))){r<-raw$company[i,];alias<-unname(aliases[r$product]);if(is.na(alias))next;id<-paste('Apple',r$product,r$fiscalYear,sep=':');y<-as.integer(r$fiscalYear);role<-if(y<=2021)'train'else if(y==2022)'validation'else'test';addQuery('company',paste0('alias:',id),paste0('What are Apple ',alias,' net sales in nominal USD millions for fiscal year ',r$fiscalYear,'?'),id,r$originalUSDMillionsToken,role,r$fiscalYear,'authored paraphrase challenge')}\n\n# Nonnegative integer limbs, base 10^6. The common denominator LCM(1..N+60)\n# makes every rarity and RRF ranking comparison exact, including equal scores.\n# Published R fractions may be unreduced; their rational values are exact.\nB<-1e6\ntrim<-function(x){while(length(x)>1&&tail(x,1)==0)x<-head(x,-1);x}\nbmul<-function(x,k){out<-numeric(length(x));carry<-0;for(i in seq_along(x)){v<-x[i]*k+carry;out[i]<-v%%B;carry<-floor(v/B)};while(carry>0){out<-c(out,carry%%B);carry<-floor(carry/B)};trim(out)}\nbadd<-function(x,y){n<-max(length(x),length(y));length(x)<-n;length(y)<-n;x[is.na(x)]<-0;y[is.na(y)]<-0;out<-numeric(n);carry<-0;for(i in seq_len(n)){v<-x[i]+y[i]+carry;out[i]<-v%%B;carry<-floor(v/B)};if(carry)out<-c(out,carry);trim(out)}\nbdiv<-function(x,k){out<-numeric(length(x));carry<-0;for(i in rev(seq_along(x))){v<-carry*B+x[i];out[i]<-floor(v/k);carry<-v%%k};stopifnot(carry==0);trim(out)}\nbstr<-function(x){x<-trim(x);if(length(x)==1)return(sprintf('%.0f',x));paste0(sprintf('%.0f',tail(x,1)),paste(sprintf('%06.0f',rev(head(x,-1))),collapse=''))}\ncommonDenominator<-function(limit){D<-1;for(p in 2:limit){prime<-all(p%%seq_len(max(1,floor(sqrt(p))))[-1]!=0);if(!prime)next;power<-p;while(power*p<=limit)power<-power*p;D<-bmul(D,power)};D}\nrankKeys<-function(keys,ids){str<-vapply(keys,bstr,'');pad<-paste0(strrep('0',max(nchar(str))-nchar(str)),str);order(pad,ids,decreasing=c(TRUE,FALSE),method='radix')}\ngcd<-function(a,b){while(b!=0){t<-a%%b;a<-b;b<-t};a}\nrat<-function(n,d=1){stopifnot(d>0);g<-gcd(n,d);c(n/g,d/g)}\nradd<-function(a,b)rat(a[1]*b[2]+b[1]*a[2],a[2]*b[2])\nrstr<-function(x)if(x[2]==1)sprintf('%.0f',x[1])else paste(sprintf('%.0f',x),collapse='/')\nrmean<-function(xs){z<-Reduce(radd,xs,init=c(0,1));rat(z[1],z[2]*length(xs))}\nwords<-function(s){s<-tolower(enc2utf8(s));m<-gregexpr('[\\\\p{L}\\\\p{N}]+',s,perl=TRUE)[[1]];if(m[1]<0)return(character());regmatches(s,list(m))[[1]]}\nmetric<-function(ids,gold){hits<-0;first<-0;ap6<-0;for(i in seq_len(min(3,length(ids))))if(ids[i]%in%gold){hits<-hits+1;if(!first)first<-i;ap6<-ap6+hits*6/i};list(hits=hits,precision=rat(hits,3),recall=rat(hits,length(gold)),RR=if(first)rat(1,first)else rat(0),AP=rat(ap6,6*length(gold)),coverage=rat(min(3,length(ids)),3))}\nrowAppend<-function(x,row)c(x,list(row))\n\nsummary<-list();points<-list()\naddS<-function(key,q=NULL,value=NULL,state=NULL,exact=NULL){\n if(!is.null(q)){exact<-rstr(q);value<-q[1]/q[2];state<-if(q[1]==0)'exact-zero'else if(value==0)'nonzero-underflow'else if(value==1&&q[1]!=q[2])'rounded-one'else'ordinary'}else if(is.null(state))state<-if(is.null(value))'undefined'else'ordinary'\n row<-list(key=key,exact=if(is.null(exact))''else exact,value=if(is.null(value))''else sprintf('%.17g',value),state=state);summary[[length(summary)+1]]<<-row;row\n}\naddP<-function(label,series,x,row)points[[length(points)+1]]<<-list(label=label,series=series,x=x,exact=row$exact,value=row$value,state=row$state)\n# Fresh reconstruction from native files. No precomputed model/answer imported.\nOUT<-outDir;M<-models[[S$args$case]];docs<-M$documents;qs<-M$queries;ids<-vapply(docs,function(d)d$id,'');tf<-lapply(docs,function(d)table(words(d$text)));df<-table(unlist(lapply(tf,names),use.names=FALSE));D<-commonDenominator(length(docs)+60);parts<-lapply(seq_len(length(docs)+60),function(k)bdiv(D,k));study<-list()\nfor(q in qs){qt<-table(words(q$text));ov<-numeric(length(docs));rare<-vector('list',length(docs))\n for(i in seq_along(docs)){v<-tf[[i]][names(qt)];v[is.na(v)]<-0;coef<-as.numeric(qt)*as.numeric(v);ov[i]<-sum(coef);rk<-0;for(j in which(coef>0)){den<-1+as.integer(df[names(qt)[j]]);rk<-badd(rk,bmul(parts[[den]],coef[j]))};rare[[i]]<-rk}\n orders<-list(overlap=order(-ov,ids,method='radix'),rarity=rankKeys(rare,ids));ranks<-lapply(orders,function(o){r<-integer(length(o));r[o]<-seq_along(o);r});rf<-lapply(seq_along(ids),function(i)badd(parts[[60+ranks$overlap[i]]],parts[[60+ranks$rarity[i]]]));orders$rrf<-rankKeys(rf,ids);study[[length(study)+1]]<-list(query=q,metrics=lapply(orders,function(o)metric(ids[o],q$gold)))\n}\nval<-lapply(c('overlap','rarity','rrf'),function(p)rmean(lapply(Filter(function(r)r$query$role=='validation',study),function(r)r$metrics[[p]]$RR)));names(val)<-c('overlap','rarity','rrf');selected<-'overlap'\nfor(p in c('rarity','rrf'))if(val[[p]][1]*val[[selected]][2]>val[[selected]][1]*val[[p]][2])selected<-p\naddS('corpusDocuments',rat(length(docs)));addS('authoredQueries',rat(length(qs)));addS('selectedProfile',state='label',exact=selected);addS('validationRR',val[[selected]])\ntest<-Filter(function(r)r$query$role=='test',study);for(k in c('precision','recall','RR','AP'))addS(paste0('test',k),rmean(lapply(test,function(r)r$metrics[[selected]][[k]])))\nfor(i in seq_along(study)){r<-study[[i]];addP(r$query$id,r$query$role,i,addS(paste0('queryRR:',r$query$id),r$metrics[[selected]]$RR))}\n\nwriteRows<-function(name,rows){d<-do.call(rbind,lapply(rows,function(r)as.data.frame(r,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(d,file.path(OUT,name),row.names=FALSE,fileEncoding='UTF-8')}\nwriteRows('summary.csv',summary);writeRows('points.csv',points)\n# These fixed output strings are printable ASCII (native source data stay in\n# their original UTF8 CSVs). EncodeString supplies quote/backslash escapes.\njs<-function(s)encodeString(as.character(s),quote='\"');obj<-function(r)paste0('{',paste(vapply(names(r),function(k)paste0(js(k),':',js(r[[k]])),''),collapse=','),'}')\nwriteLines(paste0('{\"profile\":',js(S$id),',\"api\":',js(S$api),',\"summary\":[',paste(vapply(summary,obj,''),collapse=','),'],\"points\":[',paste(vapply(points,obj,''),collapse=','),']}'),file.path(OUT,'result.json'),useBytes=TRUE)\ngrDevices::svg(file.path(OUT,'plot.svg'),width=10,height=6.2,pointsize=14,family='sans');par(mar=c(5.3,5.4,4.1,1),las=1)\nx<-vapply(points,function(p)as.double(p$x),0.0);y<-vapply(points,function(p)if(nzchar(p$value))as.double(p$value)else NA_real_,0.0);finite<-is.finite(y);lo<-min(c(0,y[finite]));hi<-max(c(1,y[finite]));pad<-(hi-lo)*.08\nplot(range(x),c(lo-pad,hi+pad),type='n',xaxt=if(length(x)<=12)'n'else's',xlab=if(S$api=='realdata')'Authored query ordinal'else'Declared row / candidate / metric',ylab=paste(strwrap(S$unit,43),collapse='\\n'),main=paste(strwrap(S$title,76),collapse='\\n'),cex.main=1.1,cex.axis=1,cex.lab=1)\nabline(h=pretty(c(lo,hi)),col='#dddddd');series<-unique(vapply(points,function(p)p$series,''));palette<-c('#286774','#934b34','#6c6389')\nfor(i in seq_along(series)){ii<-which(vapply(points,function(p)p$series==series[i],TRUE)&finite);points(x[ii],y[ii],pch=16,col=palette[(i-1)%%3+1],cex=1)}\nif(length(x)<=12)axis(1,at=x,labels=vapply(points,function(p)p$label,''),cex.axis=.9)\nfor(i in seq_along(points)){p<-points[[i]]\n if(p$state=='undefined')text(x[i],hi-.02*(hi-lo),'Undefined',srt=90,adj=c(1,.5),cex=.85,col='#555555')\n if(p$state=='nonzero-underflow'){points(x[i],y[i],pch=2,col='#934b34',cex=1.4);text(x[i],y[i]+.06*(hi-lo),'>0; display underflow',adj=c(.1,0),cex=.8)}\n if(p$state=='rounded-unit')text(x[i],y[i]-.06*(hi-lo),'Magnitude <1; rounded',adj=c(.5,1),cex=.8)\n}\nif(length(series)>1)legend(if(S$id=='realdata-person')'center'else'topright',legend=series,col=palette[seq_along(series)],pch=16,bty='n',cex=.85)\nbox(bty='l');dev.off();cat('PASS:',S$id,'summary fields',length(summary),'plot rows',length(points),'\\n')\n",
        "expectedFailure": false,
        "exitCode": 0,
        "stdout": "$key\r\n[1] \"corpusDocuments\"\r\n\r\n$exact\r\n[1] \"240\"\r\n\r\n$value\r\n[1] \"240\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"authoredQueries\"\r\n\r\n$exact\r\n[1] \"36\"\r\n\r\n$value\r\n[1] \"36\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\n$key\r\n[1] \"selectedProfile\"\r\n\r\n$exact\r\n[1] \"rarity\"\r\n\r\n$value\r\n[1] \"\"\r\n\r\n$state\r\n[1] \"label\"\r\n\r\n$key\r\n[1] \"validationRR\"\r\n\r\n$exact\r\n[1] \"25/27\"\r\n\r\n$value\r\n[1] \"0.92592592592592593\"\r\n\r\n$state\r\n[1] \"ordinary\"\r\n\r\nnull device \r\n          1 \r\nPASS: realdata-person summary fields 44 plot rows 36 \r\n",
        "stderr": "During startup - Warning messages:\r\n1: Setting LC_COLLATE=C.UTF-8 failed \r\n2: Setting LC_CTYPE=C.UTF-8 failed \r\n3: Setting LC_MONETARY=C.UTF-8 failed \r\n4: Setting LC_TIME=C.UTF-8 failed \r\n",
        "stderrIsProjection": false,
        "rawStderrSHA256": "b3aad99a991f98252f3a0842635009f1fbec82b901a63d11a0168dadc69467cb",
        "stdoutFile": "ai16-fixed/realdata-person-r/stdout.txt",
        "stderrFile": "ai16-fixed/realdata-person-r/stderr.txt",
        "supportFiles": [
          {
            "file": "ai16-sources/actual32-country-observations-2024.csv",
            "sha256": "4a544884181b228f4539c859abb874f92ddd77f09b956d1ba9c96d37b6f8587b"
          },
          {
            "file": "ai16-sources/movielens-original-movies.csv",
            "sha256": "5a5f32dd9bb3797b8e728a1b98958789d2b13f294a69fdfbc5727f8a9611aa07"
          },
          {
            "file": "ai16-sources/actual30-Apple-product-sales-FY2019-2024.csv",
            "sha256": "b163b104c02e0362e0d61fdb3bb220350a97e6e25f6eb6098b742bfac2aa5598"
          },
          {
            "file": "ai16-sources/MovieLens-README-original.txt",
            "sha256": "63d22ac138e80fae37021797ed8e1b9424b5239dc576a137422adf783ae3f404"
          },
          {
            "file": "ai16-sources/MovieLens-usage-and-citation.json",
            "sha256": "0a4e5b4bf32ffb0081a4a1383d005e60959a645c900319354bd52c2fc6ec8d30"
          }
        ],
        "invocationTemplate": "Rscript <program-file> <native-source-directory> <output-directory>",
        "summary": [
          {
            "key": "corpusDocuments",
            "exact": "240",
            "value": "240",
            "state": "ordinary"
          },
          {
            "key": "authoredQueries",
            "exact": "36",
            "value": "36",
            "state": "ordinary"
          },
          {
            "key": "selectedProfile",
            "exact": "rarity",
            "value": "",
            "state": "label"
          },
          {
            "key": "validationRR",
            "exact": "25/27",
            "value": "0.92592592592592593",
            "state": "ordinary"
          },
          {
            "key": "testprecision",
            "exact": "11/27",
            "value": "0.40740740740740738",
            "state": "ordinary"
          },
          {
            "key": "testrecall",
            "exact": "41/45",
            "value": "0.91111111111111109",
            "state": "ordinary"
          },
          {
            "key": "testRR",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "testAP",
            "exact": "41/45",
            "value": "0.91111111111111109",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:468",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:1477",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:2272",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:2577",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:3157",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6280",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6322",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:6564",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:7177",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:7394",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:8727",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:8970",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:39449",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:44777",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:45658",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:46948",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:49110",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:56333",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:62383",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:85316",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:93297",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:102666",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:117867",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:query:MovieLens:movie:133281",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2009|Thriller",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1951|Sci-Fi",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2001|Comedy",
            "exact": "1/2",
            "value": "0.5",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1994|Animation",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1988|Action",
            "exact": "1/3",
            "value": "0.33333333333333331",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2003|Fantasy",
            "exact": "0",
            "value": "0",
            "state": "exact-zero"
          },
          {
            "key": "queryRR:topic:1993|Crime",
            "exact": "1/3",
            "value": "0.33333333333333331",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1986|Romance",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1989|Comedy",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2002|Drama",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:2011|Thriller",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          },
          {
            "key": "queryRR:topic:1992|Comedy",
            "exact": "1",
            "value": "1",
            "state": "ordinary"
          }
        ],
        "resultFile": "ai16-fixed/realdata-person-r/result.json",
        "summaryFile": "ai16-fixed/realdata-person-r/summary.csv",
        "plotDataFile": "ai16-fixed/realdata-person-r/points.csv",
        "plotFile": "ai16-fixed/realdata-person-r/plot.svg",
        "plotSHA256": "15b13cd0c6e5bb9d9af2dd9a6f6c53c246ef3ef546b5ff0c03ca5b790e8945ca"
      }
    }
  }
}
