plotora 1.0.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- plotora/__init__.py +14 -0
- plotora/__main__.py +2 -0
- plotora/animation.py +13 -0
- plotora/cli.py +19 -0
- plotora/core.py +122 -0
- plotora/datasets.py +42 -0
- plotora/engineering.py +95 -0
- plotora/export.py +26 -0
- plotora/interactive.py +14 -0
- plotora/ltspice.py +113 -0
- plotora/mathematics.py +85 -0
- plotora/plot3d.py +27 -0
- plotora/plots.py +48 -0
- plotora/signals.py +63 -0
- plotora/statistics.py +67 -0
- plotora/units.py +11 -0
- plotora-1.0.0rc1.dist-info/METADATA +555 -0
- plotora-1.0.0rc1.dist-info/RECORD +21 -0
- plotora-1.0.0rc1.dist-info/WHEEL +5 -0
- plotora-1.0.0rc1.dist-info/entry_points.txt +2 -0
- plotora-1.0.0rc1.dist-info/top_level.txt +1 -0
plotora/signals.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Signal statistics respect nonuniform simulation sampling."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import signal, integrate
|
|
4
|
+
from .core import xy,create
|
|
5
|
+
from .plots import plot
|
|
6
|
+
|
|
7
|
+
def _window(t,y,window=None):
|
|
8
|
+
t,y=xy(t,y); t=np.asarray(t,dtype=float)
|
|
9
|
+
if np.iscomplexobj(y): raise ValueError('Signal statistics require real samples')
|
|
10
|
+
y=np.asarray(y,dtype=float)
|
|
11
|
+
if len(t)<2 or not np.all(np.isfinite(t)) or not np.all(np.isfinite(y)) or np.any(np.diff(t)<=0): raise ValueError('Require finite samples and strictly increasing time')
|
|
12
|
+
if window is not None:
|
|
13
|
+
lo,hi=window
|
|
14
|
+
if not t[0]<=lo<hi<=t[-1]: raise ValueError('Window must lie inside sampled range')
|
|
15
|
+
m=(t>lo)&(t<hi); tt=np.r_[lo,t[m],hi]; y=np.interp(tt,t,y); t=tt
|
|
16
|
+
return t,y
|
|
17
|
+
|
|
18
|
+
def metrics(t,y,*,window=None):
|
|
19
|
+
t,y=_window(t,y,window); dur=t[-1]-t[0]
|
|
20
|
+
avg=integrate.trapezoid(y,t)/dur
|
|
21
|
+
# Exact integral of squared piecewise-linear interpolation.
|
|
22
|
+
mean_sq=np.sum(np.diff(t)*(y[:-1]**2+y[:-1]*y[1:]+y[1:]**2)/3)/dur
|
|
23
|
+
return {'minimum':float(y.min()),'maximum':float(y.max()),'peak_to_peak':float(np.ptp(y)),'average':float(avg),'rms':float(np.sqrt(mean_sq)),'ripple_rms':float(np.sqrt(max(0,mean_sq-avg**2)))}
|
|
24
|
+
|
|
25
|
+
def ripple(t,y,*,window=None): return metrics(t,y,window=window)['peak_to_peak']
|
|
26
|
+
def peaks(y,**kwargs): return signal.find_peaks(y,**kwargs)
|
|
27
|
+
def _uniform(t,y):
|
|
28
|
+
t,y=_window(t,y); d=np.diff(t)
|
|
29
|
+
if not np.allclose(d,d[0],rtol=1e-5,atol=abs(d[0])*1e-8): raise ValueError('FFT requires uniform sampling; resample explicitly first')
|
|
30
|
+
return t,y,1/d[0]
|
|
31
|
+
def resample(t,y,*,samples=None):
|
|
32
|
+
t,y=_window(t,y); u=np.linspace(t[0],t[-1],samples or len(t)); return u,np.interp(u,t,y)
|
|
33
|
+
def spectrum(t,y,*,window=None,**kwargs):
|
|
34
|
+
t,y,fs=_uniform(t,y); n=len(y); w=np.ones(n) if window is None else signal.get_window(window,n); scale=w.sum()
|
|
35
|
+
if scale==0: raise ValueError('Window has zero coherent gain')
|
|
36
|
+
f=np.fft.rfftfreq(n,1/fs); a=np.abs(np.fft.rfft(y*w))/abs(scale); a[1: -1 if n%2==0 else None]*=2
|
|
37
|
+
g=plot(f,a,xlabel=kwargs.pop('xlabel','Frequency (Hz)'),ylabel=kwargs.pop('ylabel','Amplitude'),**kwargs); g.metadata.update(frequency=f,amplitude=a); return g
|
|
38
|
+
fft=spectrum
|
|
39
|
+
|
|
40
|
+
def spectrogram(t,y,*,nperseg=256,**kwargs):
|
|
41
|
+
t,y,fs=_uniform(t,y); f,ts,p=signal.spectrogram(y,fs=fs,nperseg=min(nperseg,len(y)))
|
|
42
|
+
def draw(ax):
|
|
43
|
+
im=ax.pcolormesh(ts+t[0],f,10*np.log10(np.maximum(p,np.finfo(float).tiny)),shading='auto'); ax.figure.colorbar(im,ax=ax,label='PSD (dB/Hz)')
|
|
44
|
+
return create(draw,xlabel=kwargs.pop('xlabel','Time (s)'),ylabel=kwargs.pop('ylabel','Frequency (Hz)'),**kwargs)
|
|
45
|
+
def timing(t,channels,**kwargs):
|
|
46
|
+
def draw(ax):
|
|
47
|
+
for i,(name,y) in enumerate(channels.items()):
|
|
48
|
+
_,y=xy(t,y); ax.step(t,np.asarray(y)+i*1.5,where='post',label=name)
|
|
49
|
+
ax.set_yticks(np.arange(len(channels))*1.5+.5,list(channels))
|
|
50
|
+
return create(draw,xlabel=kwargs.pop('xlabel','Time (s)'),**kwargs)
|
|
51
|
+
|
|
52
|
+
def harmonics(t,y,fundamental,*,count=10):
|
|
53
|
+
"""Least-squares sinusoidal amplitude and phase at specified harmonics, relative to t=0."""
|
|
54
|
+
t,y=_window(t,y)
|
|
55
|
+
if fundamental<=0 or count<1 or len(t)<=2*count+1: raise ValueError('Invalid fundamental, count or sample count')
|
|
56
|
+
freqs=fundamental*np.arange(1,count+1); a=2*np.pi*t[:,None]*freqs
|
|
57
|
+
design=np.column_stack([np.ones(len(t)),np.cos(a),np.sin(a)])
|
|
58
|
+
coef,_,rank,_=np.linalg.lstsq(design,y,rcond=None)
|
|
59
|
+
if rank<design.shape[1]: raise ValueError('Harmonics are not independently resolvable')
|
|
60
|
+
c=coef[1:count+1]; s=coef[count+1:]; return {'frequency':freqs,'amplitude':np.hypot(c,s),'phase_deg':np.rad2deg(np.arctan2(-s,c)),'dc':float(coef[0])}
|
|
61
|
+
def phase_difference(t,y1,y2,frequency):
|
|
62
|
+
a=harmonics(t,y1,frequency,count=1); b=harmonics(t,y2,frequency,count=1)
|
|
63
|
+
return float((b['phase_deg'][0]-a['phase_deg'][0]+180)%360-180)
|
plotora/statistics.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Statistical and laboratory analysis with explicit numerical assumptions."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import stats, optimize, integrate, interpolate, signal
|
|
4
|
+
from .core import xy,create
|
|
5
|
+
from .plots import scatter,plot,heatmap
|
|
6
|
+
|
|
7
|
+
def describe(y):
|
|
8
|
+
y=np.asarray(y,dtype=float)
|
|
9
|
+
if y.ndim!=1 or len(y)<2 or not np.all(np.isfinite(y)): raise ValueError('Require at least two finite samples')
|
|
10
|
+
return dict(count=len(y),mean=float(y.mean()),median=float(np.median(y)),variance=float(y.var(ddof=1)),std=float(y.std(ddof=1)),minimum=float(y.min()),maximum=float(y.max()))
|
|
11
|
+
def regression(x,y,*,degree=1,model='polynomial',confidence=.95,interval=None,**kwargs):
|
|
12
|
+
import statsmodels.api as sm
|
|
13
|
+
x,y=xy(x,y); x,y=np.asarray(x,float),np.asarray(y,float)
|
|
14
|
+
if not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)): raise ValueError('Regression requires finite samples')
|
|
15
|
+
if not 0<confidence<1 or interval not in (None,'confidence','prediction'): raise ValueError('Invalid confidence or interval')
|
|
16
|
+
if model=='linear': degree=1; model='polynomial'
|
|
17
|
+
if model=='polynomial':
|
|
18
|
+
if not isinstance(degree,int) or degree<0 or len(x)<=degree+1 or len(np.unique(x))<=degree: raise ValueError('Insufficient independent samples for requested degree')
|
|
19
|
+
center=float(x.mean()); scale=float(np.ptp(x)) or 1
|
|
20
|
+
design=lambda z:np.polynomial.polynomial.polyvander((z-center)/scale,degree)
|
|
21
|
+
elif model=='logarithmic':
|
|
22
|
+
if np.any(x<=0) or len(x)<3 or len(np.unique(x))<2: raise ValueError('Logarithmic fit requires positive, varying x and at least three samples')
|
|
23
|
+
design=lambda z:np.column_stack([np.ones(len(z)),np.log(z)])
|
|
24
|
+
elif model=='exponential':
|
|
25
|
+
if interval is not None: raise ValueError('Intervals are not implemented for nonlinear exponential fit')
|
|
26
|
+
return curve_fit(x,y,lambda x,a,b:a*np.exp(b*x),p0=(max(np.mean(y),1e-9),0),**kwargs)
|
|
27
|
+
else: raise ValueError('Unknown regression model')
|
|
28
|
+
fit=sm.OLS(y,design(x)).fit(); xs=np.linspace(x.min(),x.max(),400); pred=fit.get_prediction(design(xs)).summary_frame(alpha=1-confidence)
|
|
29
|
+
g=scatter(x,y,label='Measurements',**kwargs).add(xs,pred['mean'],label='Fit')
|
|
30
|
+
if interval:
|
|
31
|
+
prefix='mean_ci' if interval=='confidence' else 'obs_ci'; g.shade(xs,pred[prefix+'_lower'].to_numpy(),pred[prefix+'_upper'].to_numpy(),alpha=.18,label=f'{confidence:.0%} {interval} interval'); g.ax.legend()
|
|
32
|
+
coefficients=np.asarray(fit.params)
|
|
33
|
+
if model=='polynomial': coefficients=np.polynomial.Polynomial(coefficients)(np.polynomial.Polynomial([-center/scale,1/scale])).coef
|
|
34
|
+
g.metadata.update(coefficients=coefficients,r_squared=float(fit.rsquared),residuals=np.asarray(fit.resid),fit=fit,model=model); return g
|
|
35
|
+
|
|
36
|
+
def curve_fit(x,y,func,*,p0=None,bounds=(-np.inf,np.inf),**kwargs):
|
|
37
|
+
x,y=xy(x,y); x,y=np.asarray(x,float),np.asarray(y,float); p,cov=optimize.curve_fit(func,x,y,p0=p0,bounds=bounds); xs=np.linspace(x.min(),x.max(),400); residual=y-func(x,*p); ss=np.sum((y-y.mean())**2)
|
|
38
|
+
g=scatter(x,y,label='Measurements',**kwargs).add(xs,func(xs,*p),label='Fit'); g.metadata.update(coefficients=p,covariance=cov,residuals=residual,r_squared=float(1-np.sum(residual**2)/ss) if ss else float('nan')); return g
|
|
39
|
+
|
|
40
|
+
def residuals(x,fit,**kwargs): return scatter(x,fit.metadata['residuals'],**kwargs).hline(0,color='0.5',linestyle='--')
|
|
41
|
+
def distribution(name='norm',*,params=(),domain=None,**kwargs):
|
|
42
|
+
if name not in ('norm','uniform','expon','lognorm','t','chi2','beta','gamma'): raise ValueError('Unsupported continuous distribution')
|
|
43
|
+
d=getattr(stats,name)(*params); domain=domain or (d.ppf(.001),d.ppf(.999)); x=np.linspace(*domain,500); return plot(x,d.pdf(x),ylabel=kwargs.pop('ylabel','Probability density'),**kwargs)
|
|
44
|
+
def correlation(data,**kwargs):
|
|
45
|
+
import pandas as pd
|
|
46
|
+
c=pd.DataFrame(data).corr(numeric_only=True); g=heatmap(c.to_numpy(),vmin=-1,vmax=1,cmap='coolwarm',**kwargs); g.ax.set_xticks(range(len(c)),c.columns,rotation=45,ha='right'); g.ax.set_yticks(range(len(c)),c.columns); g.metadata['correlation']=c; return g
|
|
47
|
+
|
|
48
|
+
def outliers(y,*,threshold=3):
|
|
49
|
+
y=np.asarray(y,float); return np.flatnonzero(np.abs(stats.zscore(y))>threshold)
|
|
50
|
+
def integrate_data(x,y): return float(integrate.trapezoid(y,x))
|
|
51
|
+
def differentiate_data(x,y): return np.gradient(y,x)
|
|
52
|
+
def interpolate_data(x,y,new_x,*,kind='linear'): return interpolate.interp1d(x,y,kind=kind,bounds_error=True)(new_x)
|
|
53
|
+
def smooth(y,*,window=11,degree=2): return signal.savgol_filter(y,window,degree)
|
|
54
|
+
def moving_average(y,window=5):
|
|
55
|
+
y=np.asarray(y,float)
|
|
56
|
+
if not isinstance(window,int) or not 1<=window<=len(y): raise ValueError('Invalid window')
|
|
57
|
+
return np.convolve(y,np.ones(window)/window,mode='valid')
|
|
58
|
+
def propagate(func,values,standard_uncertainties,*,covariance=None):
|
|
59
|
+
"""First-order uncertainty propagation using a central numerical Jacobian."""
|
|
60
|
+
x,u=xy(values,standard_uncertainties); x,u=np.asarray(x,float),np.asarray(u,float)
|
|
61
|
+
if np.any(u<0) or not np.all(np.isfinite(x)) or not np.all(np.isfinite(u)): raise ValueError('Invalid values or uncertainties')
|
|
62
|
+
c=np.diag(u*u) if covariance is None else np.asarray(covariance,float)
|
|
63
|
+
if c.shape!=(len(x),len(x)) or not np.allclose(c,c.T) or np.linalg.eigvalsh(c).min() < -1e-12: raise ValueError('Covariance must be symmetric positive semidefinite')
|
|
64
|
+
jac=[]
|
|
65
|
+
for i in range(len(x)):
|
|
66
|
+
h=np.cbrt(np.finfo(float).eps)*max(abs(x[i]),1); a=x.copy(); b=x.copy(); a[i]+=h;b[i]-=h; jac.append((func(*a)-func(*b))/(2*h))
|
|
67
|
+
j=np.asarray(jac); return float(func(*x)),float(np.sqrt(max(0,j@c@j)))
|
plotora/units.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Physical unit conversions, with optional Pint for arbitrary units."""
|
|
2
|
+
def convert(value,from_unit,to_unit):
|
|
3
|
+
import numpy as np
|
|
4
|
+
scales={'s':('time',1),'ms':('time',1e-3),'us':('time',1e-6),'µs':('time',1e-6),'ns':('time',1e-9),'V':('voltage',1),'mV':('voltage',1e-3),'A':('current',1),'mA':('current',1e-3),'uA':('current',1e-6),'Hz':('frequency',1),'kHz':('frequency',1e3),'MHz':('frequency',1e6),'F':('capacitance',1),'uF':('capacitance',1e-6),'µF':('capacitance',1e-6),'nF':('capacitance',1e-9)}
|
|
5
|
+
if from_unit in scales and to_unit in scales:
|
|
6
|
+
a,b=scales[from_unit],scales[to_unit]
|
|
7
|
+
if a[0]!=b[0]: raise ValueError('Incompatible physical dimensions')
|
|
8
|
+
return np.asarray(value)*a[1]/b[1]
|
|
9
|
+
try: import pint
|
|
10
|
+
except ImportError as e: raise ImportError('Install plotora[engineering] for arbitrary physical units') from e
|
|
11
|
+
u=pint.UnitRegistry(); return u.Quantity(value,from_unit).to(to_unit).magnitude
|