#!/usr/bin/env python3
"""Deterministic analytical study accompanying the OPM-MEG monograph.
Run with the pinned research plotting environment; no experimental data are used.
"""
import argparse,csv,json,os
from pathlib import Path
os.environ.setdefault('MPLCONFIGDIR','/tmp/tensorfact-matplotlib')
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output',type=Path,help='Directory for CSV, figures and parameter manifest')
args=parser.parse_args()
default=ROOT/'public/research-assets/opm-meg' if (ROOT/'app/data/research.json').is_file() else Path.cwd()/'opm-meg-results'
OUT=args.output or default;OUT.mkdir(parents=True,exist_ok=True)
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':11,'axes.spines.top':False,'axes.spines.right':False,'axes.labelcolor':'#263f49','text.color':'#163442','axes.edgecolor':'#9aada9','svg.fonttype':'none','svg.hashsalt':'opm-meg-v2'})
colors=['#183f54','#578778','#b47d43']
def save(fig,name):
 if name in ['noise-budget', 'motion-envelope', 'correlated-noise']:
  fig.text(.02,-.025,'CALCULATED MODEL / ASSUMED INPUTS — NOT EMPIRICAL MEASUREMENTS',fontsize=8,color='#4f6d61')
 fig.savefig(OUT/(name+'.svg'),bbox_inches='tight',metadata={'Date':None})
 fig.savefig(OUT/(name+'.png'),bbox_inches='tight',dpi=220)
 plt.close(fig)
 p=OUT/(name+'.svg');p.write_text('\n'.join(line.rstrip() for line in p.read_text().replace("'DejaVu Sans'", "'DejaVu Sans', Arial, sans-serif").splitlines())+'\n')
def csvout(name,headers,rows):
 with (OUT/name).open('w',newline='') as f:
  w=csv.writer(f,lineterminator='\n');w.writerow(headers);w.writerows(rows)
f=np.geomspace(1,200,500)
a=(30.,150.);white=10.
asd=[np.sqrt(white**2+(v/f)**2) for v in a]
bands=[(1,40),(8,30),(30,80)]
integrals=[[float(np.sqrt(white**2*(hi-lo)+v*v*(1/lo-1/hi))) for lo,hi in bands] for v in a]
fig,ax=plt.subplots(1,2,figsize=(11,4.5),layout='constrained')
for i,v in enumerate(a):ax[0].loglog(f,asd[i],color=colors[i],lw=2,label=f'a = {v:g} fT Hz$^{{1/2}}$')
ax[0].axhline(white,color='#a3aaa7',ls=':',label='White component: 10 fT/√Hz');ax[0].set(xlabel='Frequency (Hz)',ylabel='Amplitude spectral density (fT/√Hz)',title='A  Assumed noise spectra');ax[0].legend(fontsize=8);ax[0].grid(alpha=.15,which='both')
x=np.arange(3)
for i in range(2):ax[1].bar(x+(i-.5)*.32,integrals[i],.32,color=colors[i],label=f'a = {a[i]:g}')
ax[1].set(xticks=x,xticklabels=['1–40 Hz','8–30 Hz','30–80 Hz'],ylabel='Band-integrated noise (fT RMS)',title='B  Exact PSD integrals');ax[1].legend(fontsize=9);save(fig,'noise-budget')
csvout('noise-spectrum.csv',['frequency_Hz','asd_a30_fT_per_sqrtHz','asd_a150_fT_per_sqrtHz'],zip(f,*asd))
csvout('band-noise.csv',['low_Hz','high_Hz','rms_a30_fT','rms_a150_fT'],[(lo,hi,integrals[0][i],integrals[1][i]) for i,(lo,hi) in enumerate(bands)])
g=np.geomspace(.001,10,300);b=np.geomspace(.00001,1,300)
translation=g*1e-3*1e6 # nT/m * m -> fT
rotation=b*np.deg2rad(1)*1e6
fig,ax=plt.subplots(1,2,figsize=(11,4.5),layout='constrained')
ax[0].loglog(g,translation,color=colors[0],lw=2);ax[0].set(xlabel='Projected gradient (nT/m)',ylabel='Artifact amplitude (fT RMS)',title='A  Translation: 1 mm RMS')
ax[1].loglog(b,rotation,color=colors[1],lw=2);ax[1].set(xlabel='Transverse residual field (nT)',ylabel='Artifact amplitude (fT RMS)',title='B  Rotation: 1° RMS')
for axis in ax:axis.axhline(10,color=colors[2],ls='--',label='Illustrative 10 fT budget');axis.legend(fontsize=8);axis.grid(alpha=.15,which='both')
save(fig,'motion-envelope')
csvout('translation.csv',['gradient_nT_per_m','artifact_fT_rms'],zip(g,translation));csvout('rotation.csv',['residual_nT','artifact_fT_rms'],zip(b,rotation))
n=np.arange(1,257);rhos=[0,.05,.2]
ratios=[np.sqrt(rho+(1-rho)/n) for rho in rhos]
fig,ax=plt.subplots(figsize=(9,4.8),layout='constrained')
for i,rho in enumerate(rhos):ax.loglog(n,1/ratios[i],color=colors[i],lw=2,label=f'Pairwise correlation ρ = {rho:g}')
ax.set(xlabel='Number of equal-weight, aligned observations',ylabel='SNR improvement relative to one observation',title='Correlated noise limits ideal averaging');ax.legend();ax.grid(alpha=.15,which='both');save(fig,'correlated-noise')
csvout('correlated-noise.csv',['observation_count','snr_gain_rho0','snr_gain_rho005','snr_gain_rho02'],zip(n,*[1/r for r in ratios]))
summary={'model_version':'2.1','inputs':{'white_fT_per_sqrtHz':white,'colored_coefficient_fT_sqrtHz':a,'frequency_Hz':[1,200],'bands_Hz':bands,'translation_m_rms':.001,'rotation_deg_rms':1,'artifact_budget_fT_rms':10,'pairwise_correlations':rhos},'results':{'band_noise_fT_rms':integrals,'translation_at_1nT_per_m_fT':1000,'rotation_at_02nT_fT':float(.2*np.deg2rad(1)*1e6),'gradient_budget_nT_per_m':.01,'rotation_field_budget_pT':float(10/(np.deg2rad(1)*1000)),'snr_gain_N64':[float(1/r[63]) for r in ratios]},'assumptions':['One-sided PSD S(f)=w²+(a/f)², brick-wall integration, independent white and colored terms.','Motion examples use small-angle worst-direction projections; both motion amplitudes are specified in the analysis band. Translation and rotation are evaluated separately.','Averaging assumes equal coherent signal and equal noise variance with equicorrelation. This is not a cortical sensor-array forward model.'],'exclusions':['No line interference, gain drift, biological background, head conductivity model, measured control plant or experimental observations.'],'software':{'numpy':np.__version__,'matplotlib':matplotlib.__version__}}
(OUT/'model-parameters.json').write_text(json.dumps(summary,indent=2)+'\n')
print(json.dumps(summary['results'],indent=2))
