#!/usr/bin/env python3 # Standalone reproducible teaching model; edit --params-json for alternate inputs. """Deterministic teaching models. No instrument or material validation is implied. Dependencies: Python 3, NumPy, SciPy, Matplotlib. SI/convenience units are explicit. """ import math import numpy as np from scipy.special import erf from scipy.integrate import trapezoid def series(name, x, y, xu, yu, plot=True): return dict(name=name,x=np.asarray(x,dtype=float).tolist(),y=np.asarray(y,dtype=float).tolist(),x_unit=xu,y_unit=yu,plot=plot) def result(lines, outputs, warnings=None): return dict(ok=True,series=lines,outputs={k:float(v) for k,v in outputs.items()},warnings=warnings or []) def need(condition, message): if not condition: raise ValueError(message) def indentation_cycle(p): hmax=1000*math.sqrt(p['peak_load']/p['loading_k']) hf=p['residual_fraction']*hmax;m=p['unload_exponent'] need((1-p['residual_fraction'])/(m+1)<=1/3,'Parameters produce negative dissipation; increase residual fraction or unloading exponent.') u=np.linspace(0,1,401) hload=hmax*u;pload=p['peak_load']*u*u hunload=hf+(hmax-hf)*u[::-1];punload=p['peak_load']*u[::-1]**m win=trapezoid(pload,hload);wout=-trapezoid(punload,hunload) return result([series('Loading',hload,pload,'nm','mN'),series('Unloading',hunload,punload,'nm','mN')], dict(peak_depth=hmax,residual_depth=hf,unloading_stiffness=m*p['peak_load']/(hmax-hf),work_in=win,work_recovered=wout,work_dissipated=win-wout)) def thermal_drift(p): t=np.linspace(0,p['duration'],601) truth=p['depth']+p['creep']*np.log1p(t/p['tau']) reference=p['rate']*t+p['noise']*np.sin(6*np.pi*t/p['duration']) fitted=float(np.sum((t-t.mean())*(reference-reference.mean()))/np.sum((t-t.mean())**2)) measured=truth+p['rate']*t;corrected=measured-fitted*t return result([series('True synthetic depth',t,truth,'s','nm'),series('Measured with drift',t,measured,'s','nm'),series('Corrected',t,corrected,'s','nm')], dict(fitted_rate=fitted,known_rate=p['rate'],rmse_before=np.sqrt(np.mean((measured-truth)**2)),rmse_after=np.sqrt(np.mean((corrected-truth)**2)))) def heat_diffusion(p): n=int(p['nodes']);dx=p['length']/(n-1);r=p['diffusivity']*p['dt']/dx**2 need(r<=.5+1e-12,'Unstable explicit step: alpha*dt/dx^2 must be <= 0.5.') steps=int(math.ceil(p['time']/p['dt']-1e-12));need(steps<=20000,'Limit is 20,000 time steps; increase dt within the stability limit or reduce time.') x=np.linspace(0,p['length'],n);initial=p['base']+p['amplitude']*np.sin(np.pi*x/p['length']);u=initial.copy() for k in range(steps): dt=min(p['dt'],max(0,p['time']-k*p['dt']));rn=p['diffusivity']*dt/dx**2 previous=u.copy();u[1:-1]=previous[1:-1]+rn*(previous[:-2]-2*previous[1:-1]+previous[2:]);u[0]=u[-1]=p['base'] exact=p['base']+p['amplitude']*math.exp(-p['diffusivity']*math.pi**2*p['time']/p['length']**2)*np.sin(np.pi*x/p['length']) return result([series('Initial',x,initial,'mm','degC'),series('FTCS numerical',x,u,'mm','degC'),series('Analytical eigenmode',x,exact,'mm','degC')], dict(stability_number=r,time_steps=steps,max_error=np.max(np.abs(u-exact)),center_temperature=np.interp(p['length']/2,x,u),dx=dx)) def beam_bending(p): x=np.linspace(0,p['length'],401);a=np.minimum(x,p['length']-x);I=p['width']*p['height']**3/12;E=p['modulus']*1000 y=p['force']*a*(3*p['length']**2-4*a*a)/(48*E*I) delta=p['force']*p['length']**3/(48*E*I) warnings=[] if delta/p['length']>.01 or p['length']/p['height']<10: warnings.append('Check small-deflection and slender-beam assumptions; this is not a shear-deformable beam model.') return result([series('Downward deflection',x,y,'mm','mm')],dict(max_deflection=delta,max_stress=3*p['force']*p['length']/(2*p['width']*p['height']**2),second_moment=I),warnings) def tensile_response(p): E=p['modulus']*1000;H=p['tangent'];ey=p['yield_stress']/E;em=p['max_strain']/100 need(H<=E,'Post-yield tangent modulus must not exceed elastic modulus.') strain=np.sort(np.unique(np.r_[np.linspace(0,em,501),ey if eymid:lo=mid else:hi=mid peak_x=(lo+hi)/2 # Local refinement preserves narrow peaks even when their separation is large. # Repeated abscissae are harmless and retained for deterministic cross-language arrays. x=np.sort(np.r_[np.linspace(-extent,extent,1001),np.linspace(-a-3*p['fwhm'],-a+3*p['fwhm'],401),np.linspace(a-3*p['fwhm'],a+3*p['fwhm'],401),[-peak_x,0,peak_x]]) continuous=lambda z:np.exp(-.5*((z-p['separation']/2)/sigma)**2)+np.exp(-.5*((z+p['separation']/2)/sigma)**2) y=continuous(x);peak=float(continuous(peak_x));k=math.ceil(extent/p['pixel'])+1;need(2*k+1<=4001,'Pixel grid exceeds 4,001 samples; increase pixel size.') sample=(np.arange(-k,k+1)+p['phase'])*p['pixel'];sample=sample[np.abs(sample)<=extent+p['pixel']/2] sampled=np.zeros_like(sample) for c in [-p['separation']/2,p['separation']/2]: sampled+=sigma*math.sqrt(math.pi/2)/p['pixel']*(erf((sample+p['pixel']/2-c)/(math.sqrt(2)*sigma))-erf((sample-p['pixel']/2-c)/(math.sqrt(2)*sigma))) return result([series('Continuous Gaussian pair',x,y/peak,'um','relative intensity'),series('Pixel aperture average',sample,sampled/peak,'um','relative intensity')], dict(pixels_per_fwhm=p['fwhm']/p['pixel'],midpoint_to_peak=float(continuous(0)/peak),nyquist=1000/(2*p['pixel']))) def roughness_profile(p): x=np.linspace(0,p['length'],2001) need(p['length']/2000<=min(p['wavelength1'],p['wavelength2'])/10,'Need >=10 samples per shortest wavelength; reduce evaluation length or increase wavelengths.') z=p['amplitude1']*np.sin(2*np.pi*x/p['wavelength1'])+p['amplitude2']*np.sin(2*np.pi*x/p['wavelength2']+.7)+p['slope']*x b=np.sum((x-x.mean())*(z-z.mean()))/np.sum((x-x.mean())**2);a=z.mean()-b*x.mean();residual=z-(a+b*x) return result([series('Synthetic raw profile',x,z,'mm','um'),series('Linear detrend only',x,residual,'mm','um')], dict(mean_absolute=np.mean(np.abs(residual)),rms=np.sqrt(np.mean(residual**2)),peak_to_valley=np.ptp(residual),fitted_slope=b)) def roundness_harmonics(p): theta=np.arange(720)*2*np.pi/720;phase=p['phase']*np.pi/180 need(p['radius']*1000>abs(p['eccentricity'])+abs(p['amplitude2'])+abs(p['amplitude3']),'Nominal radius must exceed all harmonic amplitudes combined.') raw=p['eccentricity']*np.cos(theta)+p['amplitude2']*np.cos(2*theta)+p['amplitude3']*np.cos(3*theta+phase) a0=raw.mean();a1=2*np.mean(raw*np.cos(theta));b1=2*np.mean(raw*np.sin(theta));corrected=raw-a0-a1*np.cos(theta)-b1*np.sin(theta) return result([series('Raw radial deviation',theta*180/np.pi,raw,'degree','um'),series('First harmonic removed',theta*180/np.pi,corrected,'degree','um')], dict(radial_span=np.ptp(corrected),rms=np.sqrt(np.mean(corrected**2)),first_harmonic=math.hypot(a1,b1))) def spectral_absorbance(p): wavelength=np.linspace(300,800,1001) a1=p['path']*p['concentration1']*1e-6*15000*np.exp(-.5*((wavelength-p['center1'])/25)**2) a2=p['path']*p['concentration2']*1e-6*10000*np.exp(-.5*((wavelength-p['center2'])/35)**2) total=a1+a2;idx=int(np.argmax(total)) return result([series('Component 1',wavelength,a1,'nm','absorbance'),series('Component 2',wavelength,a2,'nm','absorbance'),series('Additive absorbance',wavelength,total,'nm','absorbance')], dict(peak_absorbance=total[idx],peak_wavelength=wavelength[idx],minimum_transmittance=10**(-total[idx]))) def chromatography_peaks(p): need(p['retention2']>p['retention1'],'Peak 2 retention time must exceed peak 1.') need(p['retention1']>=6*p['sigma1'] and p['retention2']>=6*p['sigma2'],'Retentions must be >=6 sigma so the simulated run does not truncate peaks before time zero.') end=max(p['retention1']+6*p['sigma1'],p['retention2']+6*p['sigma2']) n=int(math.ceil(end/min(p['sigma1'],p['sigma2'])*12))+1;need(n<=20001,'More than 20,001 samples required; reduce run duration or broaden the peaks.') t=np.linspace(0,end,n) peak=lambda area,mu,sigma:area/(sigma*math.sqrt(2*math.pi))*np.exp(-.5*((t-mu)/sigma)**2) y1=peak(p['area1'],p['retention1'],p['sigma1']);y2=peak(p['area2'],p['retention2'],p['sigma2']) return result([series('Gaussian peak 1',t,y1,'min','signal'),series('Gaussian peak 2',t,y2,'min','signal'),series('Sum of peaks',t,y1+y2,'min','signal')], dict(resolution=(p['retention2']-p['retention1'])/(2*(p['sigma1']+p['sigma2'])),integrated_area=trapezoid(y1+y2,t),expected_area=p['area1']+p['area2'])) def normal_pairs(seed,n): state=int(seed);values=[] for _ in range(n): state=(16807*state)%2147483647;u1=state/2147483647 state=(16807*state)%2147483647;u2=state/2147483647 r=math.sqrt(-2*math.log(u1));angle=2*math.pi*u2;values.append((r*math.cos(angle),r*math.sin(angle))) return np.asarray(values) def uncertainty_monte_carlo(p): n=int(p['trials']);z=normal_pairs(p['seed'],n) f=p['force']+p['u_force']*z[:,0];a=p['area']+p['u_area']*(p['rho']*z[:,0]+math.sqrt(1-p['rho']**2)*z[:,1]) need(np.all(a>0),'A sampled area is non-positive. Use a physically appropriate positive distribution; samples are not silently discarded.') values=f/a;mean=values.mean();sd=values.std(ddof=1);nominal=p['force']/p['area'] aa=p['u_force']/p['area'];bb=p['force']*p['u_area']/p['area']**2;first=math.sqrt((aa-bb)**2+2*(1-p['rho'])*aa*bb) if values.max()==values.min(): centers=np.array([mean]);density=np.array([1.]);warnings=['Degenerate distribution: all simulated results coincide.'] else: edges=np.linspace(values.min(),values.max(),51);counts,_=np.histogram(values,bins=edges);centers=(edges[:-1]+edges[1:])/2;density=counts/(n*(edges[1]-edges[0]));warnings=[] degenerate=values.max()==values.min() return result([series('Degenerate point mass' if degenerate else 'Monte Carlo density',centers,density,'MPa','probability' if degenerate else '1/MPa'),series('Individual trials',np.arange(1,n+1),values,'trial','MPa',False)], dict(mean=mean,standard_deviation=sd,lower95=np.quantile(values,.025),upper95=np.quantile(values,.975),nominal=nominal,first_order_uncertainty=first,trials=n),warnings) MODELS={ 'indentation-cycle':indentation_cycle,'thermal-drift':thermal_drift,'heat-diffusion':heat_diffusion,'beam-bending':beam_bending, 'tensile-response':tensile_response,'optical-angle':optical_angle,'resolution-sampling':resolution_sampling, 'roughness-profile':roughness_profile,'roundness-harmonics':roundness_harmonics,'spectral-absorbance':spectral_absorbance, 'chromatography-peaks':chromatography_peaks,'uncertainty-monte-carlo':uncertainty_monte_carlo} def calculate(identifier,values,spec): p={} for field in spec['inputs']: value=values.get(field['key']) need(isinstance(value,(int,float)) and not isinstance(value,bool) and math.isfinite(value),'Every input must be a finite number.') need(field['min']<=value<=field['max'],'Input outside declared numeric guard range: '+field['key']) if field['step']==1: need(float(value).is_integer(),'Integer required: '+field['key']) p[field['key']]=value return MODELS[identifier](p) SPEC={'id': 'optical-angle', 'title': {'zh': '角度—横向位移射线几何', 'en': 'Angle-to-displacement ray geometry', 'ru': 'Угол и поперечное смещение луча'}, 'description': '扫描偏转光线角度,对比准确的正切几何与小角度线性近似。这里的θ是实际光线偏转角;若研究平面反射镜,其反射光线角通常为镜面转角的两倍。', 'formula': 'δ=L tanθ;δ_small≈Lθ;θ[rad]=θ[arcsec]π/(180×3600)', 'inputs': [{'key': 'length', 'label': '传播距离', 'unit': 'mm', 'value': 500, 'min': 0.001, 'max': 1000000.0, 'step': 'any'}, {'key': 'angle', 'label': '扫描半角', 'unit': 'arcsec', 'value': 1000, 'min': 0.001, 'max': 100000, 'step': 'any'}], 'outputs': [{'key': 'max_displacement', 'label': '端点横移', 'unit': 'µm'}, {'key': 'small_angle_error', 'label': '小角度近似端点差', 'unit': 'µm'}, {'key': 'relative_error', 'label': '端点相对差', 'unit': '%'}], 'assumptions': ['单程平面射线几何,无折射和镜头畸变;401个扫描角。'], 'limitations': ['不能把单程Ltanθ直接当成反射自准直整机标定式。', '不包括空气折射、支架漂移和双轴串扰。'], 'method': '正切函数直接计算并与一阶泰勒近似比较。', 'validation': '检查奇对称及θ→0的线性极限。', 'source_urls': ['https://www.nist.gov/publications/simple-method-high-precision-calibration-angle-encoder-using-electronic-nulling'], 'category_ids': ['autocollimation', 'stationmeter0'], 'artifact_paths': {'python': '/downloads/simulations/optical-angle.py', 'matlab': '/downloads/simulations/optical_angle.m', 'csv': '/downloads/simulations/optical-angle.csv', 'png': '/assets/simulation-results/optical-angle.png'}, 'local_artifact_paths': {'python': 'simulations/output/optical-angle.py', 'matlab': 'simulations/output/optical_angle.m', 'csv': 'simulations/output/optical-angle.csv', 'png': 'simulations/output/optical-angle.png'}, 'execution': {'python': '已实际运行,详见验证报告', 'matlab': '提供可复现源码;当前环境无MATLAB/Octave,未执行'}} if __name__ == '__main__': import argparse,csv,json from pathlib import Path import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt parser=argparse.ArgumentParser(description='Reproducible teaching model, not product validation.') parser.add_argument('--output-dir',default=str(Path(__file__).parent)) parser.add_argument('--params-json',help='JSON file overriding declared numeric inputs') args=parser.parse_args();outdir=Path(args.output_dir);outdir.mkdir(parents=True,exist_ok=True) inputs={x['key']:x['value'] for x in SPEC['inputs']} if args.params_json: inputs.update(json.loads(Path(args.params_json).read_text())) r=calculate(SPEC['id'],inputs,SPEC) with (outdir/(SPEC['id']+'.csv')).open('w',newline='',encoding='utf-8') as f: writer=csv.writer(f);writer.writerow(['series','x','y','x_unit','y_unit']) for line in r['series']: writer.writerows([line['name'],x,y,line['x_unit'],line['y_unit']] for x,y in zip(line['x'],line['y'])) plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'axes.spines.top':False,'axes.spines.right':False,'axes.titleweight':'bold'}) fig,ax=plt.subplots(figsize=(10,6),dpi=160);colors=['#153d58','#008f9b','#d28a22'] for j,line in enumerate(r['series']): if not line['plot']:continue if 'Pixel aperture' in line['name']: ax.plot(line['x'],line['y'],'o-',markersize=4,color=colors[j%3],label=line['name']) else:ax.plot(line['x'],line['y'],color=colors[j%3],lw=1.8,label=line['name']) ax.set_title(SPEC['title']['en'],loc='left',pad=20) ax.set_xlabel(r['series'][0]['x_unit']);ax.set_ylabel(r['series'][0]['y_unit']);ax.grid(alpha=.18);ax.legend(fontsize=9) fig.text(.08,.025,'MICROCRE | Synthetic teaching model | Python/SciPy executed | Not product validation',fontsize=9,color='#536774') fig.tight_layout(rect=[0,.05,1,1]);fig.savefig(outdir/(SPEC['id']+'.png'));plt.close(fig) summary=dict(id=SPEC['id'],inputs=inputs,input_units={f['key']:f['unit'] for f in SPEC['inputs']},outputs=r['outputs'],output_units={f['key']:f['unit'] for f in SPEC['outputs']},warnings=r['warnings'],series_points={s['name']:len(s['x']) for s in r['series']},execution='Python/SciPy executed',matlab_execution='NOT executed in MATLAB/Octave',assumptions=SPEC['assumptions'],limitations=SPEC['limitations'],source_urls=SPEC['source_urls']) (outdir/(SPEC['id']+'-summary.json')).write_text(json.dumps(summary,ensure_ascii=False,indent=2)+'\n') print(json.dumps(dict(id=SPEC['id'],outputs=r['outputs'])))