RefSeg-CA / source /code /figures_r2.py
nmsofficial's picture
Add verified public availability and human-evaluation guide
9126e0d verified
Raw
History Blame Contribute Delete
16.2 kB
"""Editable publication figures: TikZ layouts and PGFPlots data graphics."""
from pathlib import Path
import json,shutil,math
from PIL import Image
import numpy as np
ROOT=Path(__file__).resolve().parents[1];F=ROOT/'figures';A=ROOT/'results/analysis';OLD=ROOT.parent/'RefSeg_Scale_MVA'
def esc(s):return str(s).replace('_',r'\_').replace('%',r'\%').replace('&',r'\&')
def write(name,body):
(F/(name+'.tex')).write_text('\\documentclass[tikz,border=1.5pt]{standalone}\n\\input{style}\n\\begin{document}\n'+body+'\n\\end{document}\n')
def atlas():
scenes=[json.loads(s) for s in (ROOT/'data/rich_scenes.jsonl').read_text().splitlines()]
families=['attribute','relational','multi_target','negative_action','empty_target'];names=['ATTRIBUTE','RELATION','TARGET SET','ACTION','ABSENCE'];colors=['teal','violet','ochre','rose','ink']
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-108) rectangle (164,8);',r'\node[anchor=west,font=\sffamily\bfseries\fontsize{10}{12}\selectfont] at (0,5) {A richer test of the same five command regimes};']
selections=[]
for j,(family,name,color) in enumerate(zip(families,names,colors)):
x=j*33
lines.append(r'\fill[%s] (%s,0) rectangle (%s,-1);'%(color,x,x+31))
lines.append(r'\node[anchor=north,font=\sffamily\bfseries\fontsize{7.5}{9}\selectfont,text=%s] at (%s,-2) {%s};'%(color,x+15.5,name))
for i in [0,1]:
scene=scenes[(j+5*i)%len(scenes)];sid=scene['scene_id'];pair=next(p for p in scene['pairs'] if p[0]==family);endpoint=1 if family in ['negative_action','empty_target'] else i
query=pair[1][endpoint];count=len(pair[2][endpoint]);y=-10-i*49
rgb=ROOT/'data/rich'/sid/'rich.png';namefile=f'atlas_{i}_{j}.png';shutil.copy2(rgb,F/'assets'/namefile)
lines.append(r'\node[anchor=north west,inner sep=0] at (%s,%s) {\includegraphics[width=31mm]{assets/%s}};'%(x,y,namefile))
lines.append(r'\draw[rule,line width=.3pt] (%s,%s) rectangle (%s,%s);'%(x,y,x+31,y-31))
lines.append(r'\node[anchor=south east,fill=white,inner sep=.7mm,font=\sffamily\bfseries\fontsize{7}{8}\selectfont] at (%s,%s) {$|G|=%s$};'%(x+30.5,y-30.5,count))
lines.append(r'\node[anchor=north west,text width=30mm,align=left,font=\sffamily\fontsize{7.3}{8.8}\selectfont] at (%s,%s) {\textbf{%s}\enspace %s};'%(x,y-33,chr(97+j+5*i),esc(query)))
selections.append(dict(panel=chr(97+j+5*i),scene_id=sid,family=family,query=query,target_count=count,raster=str(rgb.relative_to(ROOT))))
lines.append(r'\end{tikzpicture}');write('Fig2_rich_atlas','\n'.join(lines));(F/'atlas_manifest.json').write_text(json.dumps(selections,indent=2))
def paired_render():
scenes=[json.loads(s) for s in (ROOT/'data/rich_scenes.jsonl').read_text().splitlines()];selected=[scenes[3],scenes[6],scenes[8]]
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (-2,-13) rectangle (164,108);']
for j,title in enumerate(['Flat surface','Rich surface','Shared target mask']):lines.append(r'\node[anchor=south,font=\sffamily\bfseries\fontsize{8}{10}\selectfont] at (%s,100) {%s};'%(24+j*51,title))
for i,scene in enumerate(selected):
y=98-i*35;sid=scene['scene_id'];query=scene['pairs'][1][1][0]
for j,kind in enumerate(['flat','rich','relational_0']):
src=ROOT/'data/rich'/sid/(kind+'.png');dst=F/'assets'/f'paired_{i}_{kind}.png'
im=Image.open(src)
if j==2:
mask=np.asarray(im)>0;a=np.full((*mask.shape,3),246,np.uint8);a[mask]=[20,125,131];im=Image.fromarray(a)
im.save(dst);x=8+j*51
lines.append(r'\node[anchor=north west,inner sep=0] at (%s,%s) {\includegraphics[width=31mm]{assets/%s}};'%(x,y,dst.name))
if j<2:lines.append(r'\draw[link,draw=muted] (%s,%s)--(%s,%s);'%(x+33,y-15.5,x+46,y-15.5))
lines.append(r'\node[anchor=west,text width=150mm,font=\sffamily\fontsize{7.6}{9}\selectfont] at (0,%s) {\textbf{%s}\enspace %s};'%(y-33,chr(97+i),esc(query)))
lines.append(r'\end{tikzpicture}');write('Fig3_paired_render','\n'.join(lines))
def method():
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-11) rectangle (164,88);',r'\fill[paper,rounded corners=1.5mm] (0,63) rectangle (164,88);',r'\node[anchor=west,font=\sffamily\bfseries\fontsize{10}{12}\selectfont] at (4,82) {RefSeg-CA: three questions for one output};']
for x,title,sub,col in [(4,'MASK QUALITY','Is the returned region correct?','teal'),(59,'COMMAND COMPLIANCE','Does the output obey the instruction?','violet'),(115,'RESPONSIVENESS','Does a changed request stay correct?','ochre')]:
lines.append(r'\node[anchor=west,text=%s,font=\sffamily\bfseries\fontsize{7.8}{9}\selectfont] at (%s,75) {%s};'%(col,x,title))
lines.append(r'\node[anchor=north west,text width=47mm,align=left,font=\sffamily\fontsize{8}{10}\selectfont] at (%s,72) {%s};'%(x,sub))
boxes=[(0,43,28,'RGB + expression','Frozen interface','ink'),(34,43,29,'Scope guard',r'Target\\anchor\\relation','violet'),(70,43,28,'Predicted geometry','Eligible target components','teal'),(106,43,27,'Decision gates','Union or select; else fallback','teal'),(140,43,24,'Output mask','Action rule','ink')]
for i,(x,y,w,title,sub,col) in enumerate(boxes):
lines.append(r'\node[box,draw=%s!55,fill=%s!4,minimum width=%s mm,minimum height=23mm,text width=%s mm,anchor=north west,inner sep=1.5mm] (b%s) at (%s,%s) {\textbf{%s}\\[1.3mm]%s};'%(col,col,w,w-3,i,x,y,title,sub))
if i:lines.append(r'\draw[link,draw=teal] (b%s.east)--(b%s.west);'%(i-1,i))
lines.append(r'\node[anchor=west,text=teal,font=\sffamily\bfseries\fontsize{8}{10}\selectfont] at (0,53) {SCOPE-FILTERED ANCHOR PROJECTION};')
lines.append(r'\node[anchor=east,text=muted] at (164,53) {1--3 unique queries; no labels at inference};')
lines.append(r'\draw[route,draw=muted,dashed] (b1.south)--(48.5,14)-|(b4.south);')
lines.append(r'\node[fill=white,text=muted,inner sep=.7mm] at (92,14) {unsupported / ambiguous: preserve full-query output};')
lines.append(r'\node[box,draw=ochre!50,fill=ochre!4,anchor=north west,text width=73mm,inner sep=2mm] at (0,7) {\textbf{Counterfactual audit}\quad Opposite relation, residual score and veto; retained as a measured ablation};')
lines.append(r'\node[box,draw=rose!50,fill=rose!4,anchor=north east,text width=73mm,inner sep=2mm] at (164,7) {\textbf{Separate absence decision}\quad Fit and calibrate on disjoint images; expose positive-mask losses};')
lines.append(r'\end{tikzpicture}');write('Fig1_framework','\n'.join(lines))
def multiplicity():
data=json.loads((A/'phase1_multiplicity.json').read_text());lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (163,78);']
contrasts=[('frozen','CACP $-$ frozen'),('global_direction','CACP $-$ global rule'),('anchor_gate','CACP $-$ anchor only')]
for panel,(model,label) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
dx=panel*83;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,73) {%s\enspace %s};'%(dx,chr(97+panel),label))
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=55mm,height=57mm,xmin=-2,xmax=29,ymin=-.5,ymax=2.7,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={Paired-correctness change (pp)},xmajorgrids,xtick={0,10,20}]'%(dx+20))
lines.append(r'\addplot[muted,dashed] coordinates {(0,-.5)(0,2.7)};')
for j,(key,title) in enumerate(contrasts):
z=data[model][key];y=2-j;lo,hi=[v*100 for v in z['simultaneous_ci']];d=z['delta']*100;color='rose' if key=='anchor_gate' else 'teal'
lines.append(r'\addplot[%s,line width=2.4pt,opacity=.22] coordinates {(%.6f,%s)(%.6f,%s)};'%(color,lo,y,hi,y))
lines.append(r'\addplot[%s,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(%.6f,%s) += (%.6f,0) -= (%.6f,0)};'%(color,d,y,hi-d,d-lo))
lines.append(r'\node[anchor=south west,font=\sffamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,%s) {%s};'%(y+.18,title))
lines.append(r'\node[anchor=north,font=\sffamily\bfseries\fontsize{8}{10}\selectfont,text=%s] at (axis cs:%.6f,%s) {%+.2f};'%(color,d,y-.13,d))
lines.append(r'\end{axis}')
lines.append(r'\node[anchor=west,text=muted] at (0,-13) {Six contrasts; image-cluster bootstrap with Bonferroni-adjusted intervals};');lines.append(r'\end{tikzpicture}');write('Fig4_corrected_contrasts','\n'.join(lines))
def thresholds():
data=json.loads((A/'phase1_threshold_curves.json').read_text());lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
styles=[('frozen','muted','dashed'),('global_direction','ochre','densely dotted'),('anchor_gate','teal','solid'),('cacp','violet','dashdotted')]
for j,(model,label) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
dx=j*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,61) {%s};'%(dx,label))
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=64mm,height=48mm,xmin=.3,xmax=.9,ymin=0,ymax=65,xlabel={IoU threshold $\tau$},ylabel={Correct (\%%)},ymajorgrids,xtick={.3,.5,.7,.9}]'%(dx+10))
for v,col,sty in styles:
s=[r for r in data if r['model']==model and r['variant']==v]
coord=' '.join('(%.3f,%.5f)'%(r['tau'],r['PC']*100) for r in s)
lines.append(r'\addplot[%s,%s,line width=1pt] coordinates {'%(col,sty)+coord+'};')
s=[r for r in data if r['model']==model and r['variant']=='anchor_gate'];coords=' '.join('(%.3f,%.5f)'%(r['tau'],r['Pr']*100) for r in s)
lines.append(r'\addplot[teal,dashed,opacity=.5,line width=.8pt] coordinates {'+coords+'};');lines.append(r'\end{axis}')
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.8}{9}\selectfont] at (0,-17) {\textcolor{muted}{Frozen}\quad\textcolor{ochre}{Global rule}\quad\textcolor{teal}{Anchor only}\quad\textcolor{violet}{CACP}\quad Pale dashed: anchor single-expression accuracy};');lines.append(r'\end{tikzpicture}');write('Fig5_thresholds','\n'.join(lines))
def natural_effects():
vals=[('CLIPSeg',.1081337,.0772914,.1403822,3.43722,2.371,4.474),
('Grounded SAM',.0715455,.0349176,.1077133,2.27420,1.184,3.308)]
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',
r'\path[use as bounding box] (0,-13) rectangle (164,67);',
r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (0,62) {a\enspace Coverage funnel};',
r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (83,62) {b\enspace SFAP effect};']
funnel=[('All expressions',49492,'ink'),('Old grammar',2809,'ochre'),('Scope accepted',1557,'violet'),('Simple relations',382,'teal')]
for i,(lab,n,col) in enumerate(funnel):
y=48-i*13;w=70*(n/49492)**.34
lines.append(r'\fill[%s!13,rounded corners=.7mm] (0,%s) rectangle (%s,%s);'%(col,y,w,y+8))
lines.append(r'\draw[%s,line width=.55pt,rounded corners=.7mm] (0,%s) rectangle (%s,%s);'%(col,y,w,y+8))
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.5}{9}\selectfont] at (2,%s) {%s};'%(y+4,lab))
lines.append(r'\node[anchor=east,font=\sffamily\bfseries\fontsize{7.5}{9}\selectfont,text=%s] at (78,%s) {%s};'%(col,y+4,f'{n:,}'))
lines.append(r'\begin{axis}[journal,at={(88mm,0mm)},anchor=south west,width=72mm,height=52mm,xmin=0,xmax=5.1,ymin=-.5,ymax=3.6,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={gIoU change (percentage points)},xmajorgrids]')
for j,(m,p,plo,phi,a,alo,ahi) in enumerate(vals):
for y,v,lo,hi,col in [(j,p,plo,phi,'muted'),(j+2,a,alo,ahi,'teal')]:
lines.append(r'\addplot[%s,line width=3pt,opacity=.18] coordinates {(%.6f,%s)(%.6f,%s)};'%(col,lo,y,hi,y))
lines.append(r'\addplot[%s,mark=*,mark size=2pt] coordinates {(%.6f,%s)};'%(col,v,y))
for y,lab in enumerate(['Grounded SAM pooled','CLIPSeg pooled','Grounded SAM accepted','CLIPSeg accepted']):
lines.append(r'\node[anchor=east,font=\sffamily\fontsize{6.8}{8}\selectfont,text=ink] at (axis cs:5.0,%s) {%s};'%(y+.20,lab))
lines.append(r'\end{axis}')
lines.append(r'\node[anchor=west,text=muted,font=\sffamily\fontsize{7.3}{9}\selectfont] at (0,-11) {All 49,492 expressions; accepted subset selected by text only. Intervals resample images.};')
lines.append(r'\end{tikzpicture}');write('Fig6_natural_effects','\n'.join(lines))
def absence_tradeoff():
data=[('CLIPSeg','Frozen',71.158,28.397,26.686,'muted'),('CLIPSeg','Source',88.051,22.376,56.089,'rose'),('CLIPSeg',r'5\% bound',73.449,28.468,27.833,'teal'),
('Grounded SAM','Frozen',15.333,53.308,.712,'muted'),('Grounded SAM','Source',29.702,45.132,20.146,'rose'),('Grounded SAM',r'5\% bound',16.215,53.342,.788,'teal')]
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (164,67);']
for panel,model in enumerate(['CLIPSeg','Grounded SAM']):
dx=panel*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,62) {%s};'%(dx,model))
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=68mm,height=49mm,xmin=0,xmax=100,ymin=0,ymax=60,xlabel={No-target accuracy (\%%)},ylabel={Positive mIoU (\%%)},xmajorgrids,ymajorgrids]'%(dx+8))
for m,rule,x,y,fe,col in data:
if m!=model:continue
anch='north east' if rule=='Frozen' else 'south west'
shift='yshift=-1mm' if rule=='Frozen' else 'yshift=1mm'
lines.append(r'\addplot[%s,only marks,mark=*,mark size=2.6pt] coordinates {(%.4f,%.4f)} node[anchor=%s,%s,font=\sffamily\fontsize{7}{8}\selectfont,text=%s] {%s};'%(col,x,y,anch,shift,col,rule))
lines.append(r'\end{axis}')
lines.append(r'\node[anchor=west,text=muted,font=\sffamily\fontsize{7.3}{9}\selectfont] at (0,-12) {Moving right can erase positive masks: source calibration raises N-acc but sharply lowers positive mIoU.};')
lines.append(r'\end{tikzpicture}');write('Fig7_absence_tradeoff','\n'.join(lines))
def rich_performance():
panels=[('Flat',[('CLIPSeg',4.5208,17.4792),('Grounded SAM',.0833,8.0),('ReLA',5.8542,None)]),
('Rich',[('CLIPSeg',3.2708,9.0),('Grounded SAM',.5,17.3333),('ReLA',7.3958,None)])]
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (164,68);']
for j,(title,rows) in enumerate(panels):
dx=j*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,63) {%s render};'%(dx,title))
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=68mm,height=52mm,xmin=0,xmax=20,ymin=-.5,ymax=2.6,ytick=\empty,xlabel={PC$_{0.5}$ (\%%)},xmajorgrids]'%(dx+8))
for y,(model,frozen,sfap) in enumerate(rows[::-1]):
lines.append(r'\node[anchor=east,font=\sffamily\fontsize{7.2}{9}\selectfont] at (axis cs:19.6,%s) {%s};'%(y+.18,model))
if sfap is None:
lines.append(r'\addplot[violet,only marks,mark=diamond*,mark size=2.7pt] coordinates {(%.5f,%s)};'%(frozen,y))
else:
lines.append(r'\addplot[muted,line width=2.6pt,opacity=.2] coordinates {(%.5f,%s)(%.5f,%s)};'%(frozen,y,sfap,y))
lines.append(r'\addplot[muted,only marks,mark=*,mark size=2pt] coordinates {(%.5f,%s)};'%(frozen,y))
lines.append(r'\addplot[teal,only marks,mark=*,mark size=2.8pt] coordinates {(%.5f,%s)};'%(sfap,y))
lines.append(r'\end{axis}')
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.3}{9}\selectfont,text=muted] at (0,-12) {Gray: frozen\quad Teal: SFAP\quad Violet diamond: trained ReLA native output.};')
lines.append(r'\end{tikzpicture}');write('Fig8_rich_performance','\n'.join(lines))
if __name__=='__main__':
atlas();paired_render();method();multiplicity();thresholds();natural_effects();absence_tradeoff();rich_performance()