#!/usr/bin/env python3
"""Generate deterministic visuals for Chapter 3 equations."""
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[3]; OUT=ROOT/"assets/figures/svg"; OUT.mkdir(parents=True,exist_ok=True)
RED="#7f1d1d"; TEAL="#0f6f70"
def save(name): plt.tight_layout(); plt.savefig(OUT/name,format="svg",metadata={"Date":None}); plt.close()
# 3.1 sampled source
fs=8000; f=500; n=np.arange(32); x=.8*np.sin(2*np.pi*f*n/fs+np.pi/6)
plt.figure(figsize=(9,4)); plt.stem(n,x,linefmt=RED,markerfmt="o",basefmt="k-"); plt.title("Eq. 3.1: A=.8, f=500 Hz, fs=8000 Hz, phase=π/6"); plt.xlabel("Sample n"); plt.ylabel("x[n]"); save("eq-3-1-sampled-source.svg")
# 3.2 rate law
r=np.linspace(.5,2,200); fig,ax=plt.subplots(1,2,figsize=(9,4)); ax[0].plot(r,r*440,color=RED); ax[0].plot(r,2/r,color=TEAL); ax[0].set(xlabel="Rate r",title="Frequency (Hz) and duration (s)"); ax[1].plot(r,12*np.log2(r),color=RED); ax[1].set(xlabel="Rate r",ylabel="Semitones",title="Pitch shift"); save("eq-3-2-tape-rate.svg")
# 3.3 montage
fig,ax=plt.subplots(figsize=(9,3)); colors=[RED,TEAL,"#b07d21"]; start=0
for i,(length,c) in enumerate(zip([4,3,5],colors),1): ax.broken_barh([(start,length)],(.25,.5),facecolor=c); ax.text(start+length/2,.5,f"slice {i}",ha="center",va="center",color="white"); start+=length
ax.set(xlim=(0,12),ylim=(0,1),yticks=[],xlabel="Output sample index",title="Eq. 3.3: selected slices concatenate in declared order"); save("eq-3-3-montage.svg")
# 3.4 envelope
n=np.arange(100); e=np.minimum(np.minimum(1,n/20),(99-n)/25).clip(0,1); x=np.sin(2*np.pi*n/20)
fig,ax=plt.subplots(figsize=(9,4)); ax.plot(n,x,color="#aaa",label="x[n]"); ax.plot(n,e*x,color=RED,label="e[n]x[n]"); ax.plot(n,e,color=TEAL,label="e[n]"); ax.legend(); ax.set(xlabel="Sample n",ylabel="Amplitude",title="Eq. 3.4: 20-sample attack, 25-sample release"); save("eq-3-4-envelope.svg")
# 3.5 FIR impulse
h=np.array([.25,.5,.25]); inp=np.r_[1.,np.zeros(7)]; out=np.convolve(inp,h)[:len(inp)]; fig,ax=plt.subplots(figsize=(9,4)); ax.stem(range(len(out)),out,linefmt=RED,markerfmt="o",basefmt="k-"); ax.set(xlabel="Sample n",ylabel="y[n]",title="Eq. 3.5: impulse through h=[.25,.5,.25]"); save("eq-3-5-fir.svg")
# 3.6 ring modulation
fig,ax=plt.subplots(figsize=(9,4)); ax.stem([330,550],[.5,.5],linefmt=RED,markerfmt="o",basefmt="k-"); ax.set(xlim=(250,630),xlabel="Frequency (Hz)",ylabel="Relative amplitude",title="Eq. 3.6: 440 Hz × 110 Hz gives 330 and 550 Hz"); save("eq-3-6-ring-modulation.svg")
print("Generated Chapter 3 formula visuals.")
