"""Original teaching figures from explicit functions and the existing toy fitter.
Requires NumPy, Matplotlib, installed Noto Sans TC/CJK TC, and practice/lime_local_surrogate.py."""
from pathlib import Path
import importlib.util,json,hashlib
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager
P=Path(__file__).resolve().parent
font=font_manager.findfont(font_manager.FontProperties(family=['Noto Sans TC','Noto Sans CJK TC']),fallback_to_default=False)
font_manager.fontManager.addfont(font)
font_family=font_manager.FontProperties(fname=font).get_name()
plt.rcParams.update({'font.family':font_family,'font.size':15,'axes.labelsize':14,'xtick.labelsize':13,'ytick.labelsize':14,'axes.spines.top':False,'axes.spines.right':False,'axes.edgecolor':'#bdc6c8','axes.linewidth':.7,'text.color':'#263942','axes.labelcolor':'#53656b','xtick.color':'#64767a','ytick.color':'#53656b','figure.facecolor':'white','axes.facecolor':'white','svg.hashsalt':'sunny-lime-teaching-v1','savefig.facecolor':'white'})
TEAL='#187A87';AMBER='#D28A3C';INK='#263942';GRAY='#a9b5b8'
out=P/'images';out.mkdir(exist_ok=True)
metadata={'style':'Academic Editorial Minimalism','font':'Noto Sans TC / Noto Sans CJK TC','palette':{'black_box':TEAL,'surrogate':AMBER},'figures':[]}
def save(fig,name,kind,question,data):
 fig.savefig(out/(name+'.svg'),metadata={'Date':None,'Creator':'Sunny Data Science; reproducible teaching figure'})
 fig.savefig(out/(name+'.png'),dpi=160)
 # Mobile uses the same artists/data with a narrower canvas and readable labels.
 fig.set_size_inches(4.2,4.2 if 'approximation' in name else (3.1 if 'coefficients' in name else 4.3))
 ax=fig.axes[0]
 if 'approximation' in name:
  ax.set_position([.09,.16,.87,.55]);ax.legend(loc='lower left',bbox_to_anchor=(0,1.12),ncol=1,frameon=False,fontsize=12,handlelength=1.7)
 elif 'coefficients' in name:ax.set_position([.20,.26,.72,.67])
 else:
  ax.set_position([.36,.20,.60,.60]);ax.legend(loc='lower left',bbox_to_anchor=(-.40,1.05),ncol=2,frameon=False,fontsize=12,handletextpad=.4,columnspacing=1)
 fig.savefig(out/(name+'-mobile.svg'),metadata={'Date':None,'Creator':'Sunny Data Science; mobile layout, same data'})
 fig.savefig(out/(name+'-mobile.png'),dpi=160)
 for suffix in ['.svg','-mobile.svg']:
  f=out/(name+suffix);f.write_text('\n'.join(line.rstrip() for line in f.read_text().splitlines())+'\n')
 plt.close(fig)
 metadata['figures'].append({'file':name+'.svg','kind':kind,'reader_question':question,'data':data,'mobile_file':name+'-mobile.svg','mobile_sha256':hashlib.sha256((out/(name+'-mobile.svg')).read_bytes()).hexdigest(),'sha256':hashlib.sha256((out/(name+'.svg')).read_bytes()).hexdigest()})
# Concept only: independent illustrative continuous function, not the 2-word model.
x=np.linspace(-2,2,401);q=.30;scale=.45
f=lambda t:.42+.15*t+.16*np.sin(2.5*t)+.03*t*t
weights=np.exp(-((x-q)/scale)**2);X=np.column_stack([np.ones_like(x),x])
beta=np.linalg.solve(X.T@(weights[:,None]*X),X.T@(weights*f(x)))
g=X@beta
fig,ax=plt.subplots(figsize=(6.6,3.8));fig.subplots_adjust(left=.10,right=.96,bottom=.17,top=.77)
ax.axvspan(q-scale,q+scale,color='#edf2f2',zorder=0)
ax.plot(x,f(x),color=TEAL,lw=2.0,label='原模型（示意）')
ax.plot(x,g,color=AMBER,lw=1.4,ls=(0,(4,3)),alpha=.65)
sel=abs(x-q)<=scale
ax.plot(x[sel],g[sel],color=AMBER,lw=2.0,label='簡單代理模型')
ax.scatter([q],[f(q)],s=36,c=INK,zorder=5)
ax.annotate('要解釋的輸入',xy=(q,f(q)),xytext=(.04,.56),textcoords='axes fraction',fontsize=13,color=INK,arrowprops={'arrowstyle':'-','color':GRAY,'lw':.8})
ax.text(q,.99,'較重視的附近',ha='center',va='top',transform=ax.get_xaxis_transform(),fontsize=12,color='#64767a')
ax.set(xlim=(-2,2),ylim=(-.02,1.02),xlabel='輸入位置（示意）');ax.set_yticks([]);ax.set_xticks([]);ax.spines['left'].set_visible(False)
ax.legend(loc='lower left',bbox_to_anchor=(-.02,1.14),ncol=2,frameon=False,fontsize=12,handlelength=1.7,columnspacing=1)
save(fig,'teaching-01-local-approximation','concept','為什麼簡單模型只能近似附近？',{'identity':'illustrative continuous function; not a real classifier or the 2-word toy','function':'.42+.15*t+.16*sin(2.5*t)+.03*t*t','query':q,'weight_kernel':'exp(-((t-query)/.45)^2)','surrogate_intercept':float(beta[0]),'surrogate_slope':float(beta[1]),'shaded_band':'visual emphasis only; not a trust threshold or hard kernel cutoff'})
# Reuse the actual existing fitter rather than type rounded values into plots.
source=P/'practice/lime_local_surrogate.py'
spec=importlib.util.spec_from_file_location('toy',source);toy=importlib.util.module_from_spec(spec);spec.loader.exec_module(toy)
neighbors=[(1.,1.),(1.,0.),(0.,1.),(0.,0.)]
y=np.array([toy.black_box(z) for z in neighbors]);w=np.array([np.exp(-toy.cosine_distance(toy.QUERY,z)**2/toy.SIGMA**2) for z in neighbors]);Z=np.array([[1.,*z] for z in neighbors])
normal=Z.T@(w[:,None]*Z);rhs=Z.T@(w*y);b=np.array(toy.solve_linear_system(normal.tolist(),rhs.tolist()));pred=Z@b
assert np.max(np.abs(normal@b-rhs))<1e-10
fig,ax=plt.subplots(figsize=(6.6,3.2));fig.subplots_adjust(left=.22,right=.90,bottom=.26,top=.94)
ax.barh([1,0],b[1:],height=.34,color=AMBER)
for pos,value in zip([1,0],b[1:]):ax.text(value+.012,pos,f'+{value:.3f}',va='center',fontsize=15,color=INK)
ax.set(yticks=[1,0],yticklabels=['亮','維修'],xlim=(0,.68),ylim=(-.55,1.55),xlabel='代理模型係數');ax.set_xticks([0,.2,.4,.6]);ax.tick_params(axis='y',length=0,pad=12);ax.spines['left'].set_visible(False)
ax.grid(axis='x',color='#edf0f0',lw=.7);ax.set_axisbelow(True)
save(fig,'teaching-02-surrogate-coefficients','computed toy output','最後的局部解釋長什麼樣？',{'identity':'hand-specified 2-feature black box; actual weighted OLS coefficients; not a trained customer-service model','intercept':float(b[0]),'bright':float(b[1]),'repair':float(b[2]),'display_precision':3,'not_deletion_deltas':True})
fig,ax=plt.subplots(figsize=(6.6,4.2));fig.subplots_adjust(left=.31,right=.95,bottom=.20,top=.81)
positions=np.arange(4)[::-1]
for pos,fy,gy in zip(positions,y,pred):ax.plot([fy,gy],[pos,pos],color=GRAY,lw=1.1,zorder=1)
ax.scatter(y,positions,s=48,color=TEAL,label='原模型',zorder=3)
ax.scatter(pred,positions,s=35,color=AMBER,marker='s',label='代理模型',zorder=4)
ax.set(yticks=positions,yticklabels=['兩詞都保留\n（本次目標）','只保留亮','只保留維修','兩詞都關閉'],xlim=(-.03,1.03),ylim=(-.55,3.55),xlabel='維修類分數');ax.set_xticks([0,.25,.5,.75,1]);ax.tick_params(axis='y',length=0,pad=10);ax.spines['left'].set_visible(False)
ax.grid(axis='x',color='#edf0f0',lw=.7);ax.set_axisbelow(True)
ax.legend(loc='lower left',bbox_to_anchor=(0,1.04),ncol=2,frameon=False,fontsize=13,handletextpad=.5)
save(fig,'teaching-03-local-fidelity','computed toy comparison','哪些輸入上代理貼近原模型，哪些偏差較大？',{'identity':'same actual 4-row toy fit as coefficient figure; not empirical classification accuracy','rows':[{'input':list(z),'black_box':float(fy),'surrogate':float(gy),'absolute_error':float(abs(fy-gy)),'locality_weight':float(wi)} for z,fy,gy,wi in zip(neighbors,y,pred,w)]})
(P/'teaching-figures.json').write_text(json.dumps(metadata,ensure_ascii=False,indent=2)+'\n')
print('Rendered 3 SVG/PNG teaching figures from explicit data and functions.')
