codex/triangular-pulse-clipping-area.py

triangular-pulse-clipping-area.py
"""Generate triangular-pulse-clipping-area.png in cwd (_media).

Tested with Python 3.14.4, NumPy and Matplotlib 3.10.7;
dependencies are declared in the repository pyproject.toml.
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

t=np.linspace(-1.3,1.3,1301)
original=4*np.maximum(1-np.abs(t),0)
clipped=np.minimum(original,2)
fig,ax=plt.subplots(figsize=(7,3.2),dpi=100,layout='constrained')
ax.fill_between(t,0,clipped,color='#c6dbef',label='Recorded area: 3 V ms')
ax.fill_between(t,clipped,original,color='#fdd0a2',label='Lost area: 1 V ms')
ax.plot(t,original,color='#b35806',linewidth=2,label='Unclipped triangle: 4 V peak')
ax.plot(t,clipped,color='#2166ac',linewidth=2,label='Clipped at 2 V')
ax.set(xlim=(-1.3,1.3),ylim=(0,4.5),xlabel='Time (ms)',ylabel='Potential difference (V)',title='Peak halved; waveform area reduced by 25%')
ax.grid(alpha=.18)
ax.legend(loc='upper right',fontsize=8)
fig.savefig('triangular-pulse-clipping-area.png',facecolor='white',dpi=100)
plt.close(fig)