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/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Plotora: scientific visualization, simplified."""
|
|
2
|
+
__version__='1.0.0rc1'
|
|
3
|
+
from .core import Graph,figure,themes,set_theme,register_theme,style
|
|
4
|
+
from .plots import plot,line,scatter,bar,stem,area,errorbar,hist,boxplot,pie,polar,heatmap,contour,vector_field,compare
|
|
5
|
+
from .datasets import load,from_file,clean,normalize,merge,export_data
|
|
6
|
+
from .ltspice import Simulation,read_ltspice,ltspice,compare_ltspice
|
|
7
|
+
from .engineering import transfer_function,bode,poles_zeros,nyquist,step_response,impulse_response,stability_margins,bandwidth,root_locus,phasors,impedance,power_triangle,corner_frequencies,bode_asymptotic
|
|
8
|
+
from .signals import metrics,ripple,peaks,resample,spectrum,fft,spectrogram,timing,harmonics,phase_difference
|
|
9
|
+
from .mathematics import function,parametric,taylor,derivative,tangent,integral,implicit,direction_field,ode,vectors,transform,fourier,sequence
|
|
10
|
+
from .statistics import describe,regression,curve_fit,residuals,distribution,correlation,outliers,integrate_data,differentiate_data,interpolate_data,smooth,moving_average,propagate
|
|
11
|
+
from .plot3d import surface,wireframe,scatter3d,line3d,vector_field3d,contour3d
|
|
12
|
+
from .animation import animate
|
|
13
|
+
from .units import convert
|
|
14
|
+
from .export import latex_figure
|
plotora/__main__.py
ADDED
plotora/animation.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from matplotlib.animation import FuncAnimation
|
|
3
|
+
from .core import create
|
|
4
|
+
|
|
5
|
+
def animate(x,frames,*,interval=67,repeat=True,**kwargs):
|
|
6
|
+
x=np.asarray(x); frames=np.asarray(frames)
|
|
7
|
+
if frames.ndim!=2 or frames.shape[1]!=len(x) or not len(frames): raise ValueError('frames must be a nonempty matrix with one column per x value')
|
|
8
|
+
g=create(lambda a:a.plot(x,frames[0]),**kwargs); line=g.ax.lines[0]
|
|
9
|
+
if 'ylim' not in kwargs:
|
|
10
|
+
lo,hi=np.nanmin(frames),np.nanmax(frames); pad=max((hi-lo)*.05,1e-9); g.ax.set_ylim(lo-pad,hi+pad)
|
|
11
|
+
def update(i): line.set_ydata(frames[i]); return (line,)
|
|
12
|
+
g.animation=FuncAnimation(g.fig,update,frames=len(frames),interval=interval,repeat=repeat,blit=True)
|
|
13
|
+
return g
|
plotora/cli.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Command line plotting without writing a Python script."""
|
|
2
|
+
import argparse
|
|
3
|
+
|
|
4
|
+
def main():
|
|
5
|
+
p=argparse.ArgumentParser(prog='plotora'); p.add_argument('--version',action='store_true'); sub=p.add_subparsers(dest='command')
|
|
6
|
+
for name in ('ltspice','plot'):
|
|
7
|
+
q=sub.add_parser(name); q.add_argument('file'); q.add_argument('-o','--output');q.add_argument('--theme',default='academic');q.add_argument('--show',action='store_true')
|
|
8
|
+
if name=='ltspice': q.add_argument('--trace',action='append');q.add_argument('--time-unit',default='auto');q.add_argument('--component',default='magnitude')
|
|
9
|
+
else: q.add_argument('--x',required=True);q.add_argument('--y',required=True)
|
|
10
|
+
a=p.parse_args()
|
|
11
|
+
if a.version:
|
|
12
|
+
from . import __version__; print(__version__); return
|
|
13
|
+
if not a.command: p.print_help(); return
|
|
14
|
+
if a.command=='ltspice':
|
|
15
|
+
from .ltspice import ltspice; g=ltspice(a.file,traces=a.trace,time_unit=a.time_unit,component=a.component,theme=a.theme)
|
|
16
|
+
else:
|
|
17
|
+
from .datasets import from_file; g=from_file(a.file,a.x,a.y,theme=a.theme)
|
|
18
|
+
if a.output: g.save(a.output)
|
|
19
|
+
if a.show or not a.output: g.show()
|
plotora/core.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Matplotlib-native figures, local styling and publication exports."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
import matplotlib as mpl
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
_THEMES = {}
|
|
11
|
+
_PALETTE = ['#215a91','#b44b29','#18806b','#7955a1','#a47713','#444444']
|
|
12
|
+
_BASE = {'font.family':'serif','font.size':11,'axes.labelsize':11,'axes.titlesize':12,'legend.fontsize':9,'lines.linewidth':1.5,'axes.grid':True,'grid.alpha':.22,'grid.linestyle':'--','figure.dpi':120,'savefig.dpi':300,'pdf.fonttype':42,'ps.fonttype':42,'svg.fonttype':'none','mathtext.fontset':'stix','axes.prop_cycle':mpl.cycler(color=_PALETTE)}
|
|
13
|
+
for name in ('academic','engineering','minimal','midnight','blueprint','monochrome','ieee','latex','presentation','pastel','colorblind'):
|
|
14
|
+
_THEMES[name] = dict(_BASE)
|
|
15
|
+
_THEMES['engineering'].update({'font.family':'sans-serif','axes.facecolor':'#f6f8fb'})
|
|
16
|
+
_THEMES['minimal'].update({'axes.grid':False,'axes.spines.top':False,'axes.spines.right':False})
|
|
17
|
+
for name,bg,fg in [('midnight','#172033','#e5eaf3'),('blueprint','#16385c','#e4f4ff')]:
|
|
18
|
+
_THEMES[name].update({'figure.facecolor':bg,'axes.facecolor':bg,'savefig.facecolor':bg,'text.color':fg,'axes.labelcolor':fg,'axes.edgecolor':fg,'xtick.color':fg,'ytick.color':fg,'grid.color':fg,'axes.prop_cycle':mpl.cycler(color=['#85bafa','#f3b77e','#8ee0cf','#d0b4fa'])})
|
|
19
|
+
_THEMES['monochrome'].update({'axes.prop_cycle':mpl.cycler(color=['black']*4)+mpl.cycler(linestyle=['-','--',':','-.'])})
|
|
20
|
+
_THEMES['ieee'].update({'font.size':9,'axes.labelsize':9,'legend.fontsize':8})
|
|
21
|
+
_THEMES['presentation'].update({'font.size':15,'axes.labelsize':16,'lines.linewidth':2.5})
|
|
22
|
+
_THEMES['pastel'].update({'axes.prop_cycle':mpl.cycler(color=['#5679ad','#b56b86','#458c78','#9369ae'])})
|
|
23
|
+
_THEMES['colorblind'].update({'axes.prop_cycle':mpl.cycler(color=['#0072B2','#D55E00','#009E73','#CC79A7','#E69F00','#000000'])})
|
|
24
|
+
_default_theme = 'academic'
|
|
25
|
+
|
|
26
|
+
def themes() -> tuple[str,...]: return tuple(_THEMES)
|
|
27
|
+
def register_theme(name: str, settings: dict, base: str='academic') -> None:
|
|
28
|
+
merged = {**_THEMES[base], **settings}; mpl.RcParams(merged); _THEMES[name] = merged
|
|
29
|
+
|
|
30
|
+
def set_theme(name: str) -> None:
|
|
31
|
+
global _default_theme
|
|
32
|
+
if name not in _THEMES: raise ValueError(f'Unknown theme {name!r}; choose from {themes()}')
|
|
33
|
+
_default_theme = name
|
|
34
|
+
|
|
35
|
+
def style(theme=None):
|
|
36
|
+
name = theme or _default_theme
|
|
37
|
+
if name not in _THEMES: raise ValueError(f'Unknown theme: {name}')
|
|
38
|
+
return mpl.rc_context(_THEMES[name])
|
|
39
|
+
|
|
40
|
+
def xy(x,y):
|
|
41
|
+
x,y=np.asarray(x),np.asarray(y)
|
|
42
|
+
if x.ndim != 1 or y.ndim != 1 or len(x)!=len(y) or not len(x): raise ValueError('x and y must be nonempty, equally sized one-dimensional arrays')
|
|
43
|
+
return x,y
|
|
44
|
+
|
|
45
|
+
def labels(ax, *, xlabel=None,ylabel=None,title=None,xscale=None,yscale=None,xlim=None,ylim=None,grid=None,legend=True):
|
|
46
|
+
for key,value in locals().copy().items():
|
|
47
|
+
if key in ('xlabel','ylabel','title','xscale','yscale','xlim','ylim') and value is not None: getattr(ax,'set_'+key)(value)
|
|
48
|
+
if grid is not None: ax.grid(grid)
|
|
49
|
+
if legend and ax.get_legend_handles_labels()[0]: ax.legend()
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Graph:
|
|
53
|
+
fig: Any
|
|
54
|
+
axes: Any
|
|
55
|
+
data: Any = None
|
|
56
|
+
metadata: dict = field(default_factory=dict)
|
|
57
|
+
animation: Any = None
|
|
58
|
+
@property
|
|
59
|
+
def ax(self): return np.asarray(self.axes,dtype=object).flat[0]
|
|
60
|
+
@property
|
|
61
|
+
def figure(self): return self.fig
|
|
62
|
+
def show(self, *, block=None):
|
|
63
|
+
plt.show(block=block); return self
|
|
64
|
+
def close(self): plt.close(self.fig); return self
|
|
65
|
+
def save(self, path, *, dpi=300, **kwargs):
|
|
66
|
+
p=Path(path); ext=p.suffix.lower()
|
|
67
|
+
if ext in ('.gif','.mp4'):
|
|
68
|
+
if self.animation is None: raise ValueError('Use animate() to create an animation before exporting GIF or MP4')
|
|
69
|
+
from matplotlib.animation import PillowWriter, FFMpegWriter
|
|
70
|
+
fps=kwargs.pop('fps', 15)
|
|
71
|
+
if ext=='.gif': self.animation.save(p,writer=PillowWriter(fps=fps),dpi=dpi,**kwargs)
|
|
72
|
+
else:
|
|
73
|
+
try:
|
|
74
|
+
import imageio_ffmpeg
|
|
75
|
+
executable=imageio_ffmpeg.get_ffmpeg_exe()
|
|
76
|
+
except ImportError: executable=mpl.rcParams['animation.ffmpeg_path']
|
|
77
|
+
with mpl.rc_context({'animation.ffmpeg_path':executable}): self.animation.save(p,writer=FFMpegWriter(fps=fps),dpi=dpi,**kwargs)
|
|
78
|
+
elif ext=='.html':
|
|
79
|
+
from .interactive import export_html
|
|
80
|
+
export_html(self,p,**kwargs)
|
|
81
|
+
elif ext in ('.csv','.txt','.xlsx','.json'):
|
|
82
|
+
from .datasets import export_data
|
|
83
|
+
if self.data is None: raise ValueError('This graph has no tabular source data')
|
|
84
|
+
export_data(self.data,p,**kwargs)
|
|
85
|
+
elif ext=='.tex': p.write_text(self.latex(**kwargs),encoding='utf-8')
|
|
86
|
+
elif ext=='.py':
|
|
87
|
+
from .export import export_python
|
|
88
|
+
export_python(self,p)
|
|
89
|
+
else: self.fig.savefig(p,dpi=dpi,**kwargs)
|
|
90
|
+
return self
|
|
91
|
+
def save_all(self, stem, *, formats=('pdf','svg','png'), **kwargs):
|
|
92
|
+
for fmt in formats: self.save(f'{stem}.{fmt.lstrip(".")}',**kwargs)
|
|
93
|
+
return self
|
|
94
|
+
def latex(self, caption='Figure', label='fig:plot', filename='figure.pdf',width=r'0.9\linewidth'):
|
|
95
|
+
from .export import latex_figure
|
|
96
|
+
return latex_figure(filename,caption,label,width)
|
|
97
|
+
def add(self,x,y,*,label=None,**kwargs):
|
|
98
|
+
x,y=xy(x,y); self.ax.plot(x,y,label=label,**kwargs)
|
|
99
|
+
if label: self.ax.legend()
|
|
100
|
+
# Track series independently, without requiring identical grids.
|
|
101
|
+
if self.data is None or isinstance(self.data,dict):
|
|
102
|
+
import pandas as pd
|
|
103
|
+
d={} if self.data is None else self.data.copy(); n=len(d)//2+1
|
|
104
|
+
d[f'x_{n}']=pd.Series(x); d[f'y_{n}']=pd.Series(y); self.data=d
|
|
105
|
+
return self
|
|
106
|
+
def annotate(self,text,xy,**kwargs): self.ax.annotate(text,xy,**kwargs); return self
|
|
107
|
+
def hline(self,y,**kwargs): self.ax.axhline(y,**kwargs); return self
|
|
108
|
+
def vline(self,x,**kwargs): self.ax.axvline(x,**kwargs); return self
|
|
109
|
+
def shade(self,x,y1,y2=0,**kwargs): self.ax.fill_between(x,y1,y2,**kwargs); return self
|
|
110
|
+
def secondary_y(self): return self.ax.twinx()
|
|
111
|
+
def secondary_x(self): return self.ax.twiny()
|
|
112
|
+
|
|
113
|
+
def figure(*, rows=1,cols=1,theme=None,figsize=(7,4),**kwargs):
|
|
114
|
+
with style(theme): fig,axes=plt.subplots(rows,cols,figsize=figsize,layout='constrained',**kwargs)
|
|
115
|
+
return Graph(fig,axes)
|
|
116
|
+
|
|
117
|
+
def create(draw,*,theme=None,figsize=(7,4),projection=None,data=None,**opts):
|
|
118
|
+
with style(theme):
|
|
119
|
+
fig=plt.figure(figsize=figsize,layout='constrained'); ax=fig.add_subplot(projection=projection)
|
|
120
|
+
try: draw(ax); labels(ax,**opts)
|
|
121
|
+
except Exception: plt.close(fig); raise
|
|
122
|
+
return Graph(fig,ax,data)
|
plotora/datasets.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Tabular data import, cleanup and export."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from scipy.io import loadmat
|
|
6
|
+
|
|
7
|
+
def load(path,**kwargs):
|
|
8
|
+
p=Path(path); ext=p.suffix.lower()
|
|
9
|
+
if ext in ('.csv','.txt','.tsv','.dat'): return pd.read_csv(p,sep=kwargs.pop('sep',None),engine=kwargs.pop('engine','python'),**kwargs)
|
|
10
|
+
if ext=='.xlsx': return pd.read_excel(p,**kwargs)
|
|
11
|
+
if ext=='.json': return pd.read_json(p,**kwargs)
|
|
12
|
+
if ext=='.mat':
|
|
13
|
+
try: return {k:v for k,v in loadmat(p,**kwargs).items() if not k.startswith('__')}
|
|
14
|
+
except NotImplementedError:
|
|
15
|
+
import h5py
|
|
16
|
+
with h5py.File(p) as f: return {k:v[()] for k,v in f.items() if isinstance(v,h5py.Dataset)}
|
|
17
|
+
raise ValueError(f'Unsupported data format: {ext}')
|
|
18
|
+
def export_data(data,path,**kwargs):
|
|
19
|
+
df=pd.DataFrame(data); p=Path(path); ext=p.suffix.lower()
|
|
20
|
+
if ext=='.xlsx': df.to_excel(p,index=False,**kwargs)
|
|
21
|
+
elif ext=='.json': df.to_json(p,orient='records',**kwargs)
|
|
22
|
+
elif ext in ('.csv','.txt','.tsv'): df.to_csv(p,index=False,sep=kwargs.pop('sep',',' if ext=='.csv' else '\t'),**kwargs)
|
|
23
|
+
else: raise ValueError(f'Unsupported data format: {ext}')
|
|
24
|
+
def from_file(path,x,y,**kwargs):
|
|
25
|
+
from .plots import plot
|
|
26
|
+
df=load(path); return plot(df[x],df[y],xlabel=kwargs.pop('xlabel',str(x)),ylabel=kwargs.pop('ylabel',str(y)),**kwargs)
|
|
27
|
+
def clean(data,*,columns=None,dropna=False,sort=None,fill=None):
|
|
28
|
+
df=pd.DataFrame(data).copy()
|
|
29
|
+
if columns is not None: df=df[columns]
|
|
30
|
+
if fill is not None: df=df.fillna(fill)
|
|
31
|
+
if dropna: df=df.dropna()
|
|
32
|
+
if sort is not None: df=df.sort_values(sort)
|
|
33
|
+
return df
|
|
34
|
+
|
|
35
|
+
def normalize(y):
|
|
36
|
+
y=np.asarray(y,dtype=float); span=np.ptp(y)
|
|
37
|
+
if span==0: return np.zeros_like(y)
|
|
38
|
+
return (y-y.min())/span
|
|
39
|
+
|
|
40
|
+
def merge(*frames,**kwargs):
|
|
41
|
+
from functools import reduce
|
|
42
|
+
return reduce(lambda a,b:pd.merge(a,b,**kwargs),frames)
|
plotora/engineering.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Continuous-time LTI systems. Frequencies are explicitly Hz or rad/s."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import signal
|
|
4
|
+
from .core import create,figure,labels
|
|
5
|
+
from .plots import plot
|
|
6
|
+
|
|
7
|
+
def transfer_function(num,den): return signal.TransferFunction(num,den)
|
|
8
|
+
def _system(num=None,den=None,system=None):
|
|
9
|
+
if system is not None: return system
|
|
10
|
+
if den is None: raise ValueError('Supply num and den, or system=')
|
|
11
|
+
return transfer_function(num,den)
|
|
12
|
+
def _response(num,den,system,w,unit):
|
|
13
|
+
s=_system(num,den,system)
|
|
14
|
+
if unit not in ('Hz','rad/s'): raise ValueError('unit must be Hz or rad/s')
|
|
15
|
+
if w is not None:
|
|
16
|
+
w=np.asarray(w,dtype=float)
|
|
17
|
+
if w.ndim!=1 or not len(w) or np.any(w<=0) or np.any(np.diff(w)<=0): raise ValueError('Frequencies must be positive and increasing')
|
|
18
|
+
wr,h=signal.freqresp(s,w=None if w is None else w*(2*np.pi if unit=='Hz' else 1),n=1000)
|
|
19
|
+
return wr/(2*np.pi if unit=='Hz' else 1),h
|
|
20
|
+
|
|
21
|
+
def bode(num=None,den=None,*,system=None,w=None,unit='rad/s',theme=None,figsize=(7,6),title=None):
|
|
22
|
+
f,h=_response(num,den,system,w,unit); g=figure(rows=2,cols=1,theme=theme,figsize=figsize,sharex=True)
|
|
23
|
+
with np.errstate(divide='ignore'): db=20*np.log10(abs(h))
|
|
24
|
+
phase=np.rad2deg(np.unwrap(np.angle(h))); a,b=g.axes; a.semilogx(f,db); b.semilogx(f,phase); a.set_ylabel('Magnitude (dB)'); b.set_ylabel('Phase (°)'); b.set_xlabel(f'Frequency ({unit})')
|
|
25
|
+
if title: a.set_title(title)
|
|
26
|
+
g.data={'frequency':f,'magnitude_db':db,'phase_deg':phase}; return g
|
|
27
|
+
|
|
28
|
+
def poles_zeros(*,poles=None,zeros=None,num=None,den=None,**kwargs):
|
|
29
|
+
if den is not None: poles=np.roots(den)
|
|
30
|
+
if num is not None: zeros=np.roots(num)
|
|
31
|
+
p=np.asarray([] if poles is None else poles,dtype=complex); z=np.asarray([] if zeros is None else zeros,dtype=complex)
|
|
32
|
+
def draw(ax):
|
|
33
|
+
ax.axhline(0,color='0.6'); ax.axvline(0,color='0.6'); ax.scatter(p.real,p.imag,marker='x',label='Poles'); ax.scatter(z.real,z.imag,facecolors='none',edgecolors='C1',label='Zeros'); ax.set_aspect('equal',adjustable='datalim')
|
|
34
|
+
return create(draw,xlabel=kwargs.pop('xlabel','Real'),ylabel=kwargs.pop('ylabel','Imaginary'),**kwargs)
|
|
35
|
+
def nyquist(num=None,den=None,*,system=None,w=None,unit='rad/s',**kwargs):
|
|
36
|
+
f,h=_response(num,den,system,w,unit)
|
|
37
|
+
def draw(ax): ax.plot(h.real,h.imag,label='Positive frequencies'); ax.plot(h.real,-h.imag,'--',label='Negative frequencies'); ax.plot(-1,0,'x'); ax.axhline(0,color='0.6'); ax.axvline(0,color='0.6')
|
|
38
|
+
return create(draw,xlabel=kwargs.pop('xlabel','Real'),ylabel=kwargs.pop('ylabel','Imaginary'),**kwargs)
|
|
39
|
+
def step_response(num=None,den=None,*,system=None,t=None,**kwargs):
|
|
40
|
+
t,y=signal.step(_system(num,den,system),T=t); return plot(t,y,xlabel=kwargs.pop('xlabel','Time (s)'),ylabel=kwargs.pop('ylabel','Response'),**kwargs)
|
|
41
|
+
def impulse_response(num=None,den=None,*,system=None,t=None,**kwargs):
|
|
42
|
+
t,y=signal.impulse(_system(num,den,system),T=t); return plot(t,y,xlabel=kwargs.pop('xlabel','Time (s)'),ylabel=kwargs.pop('ylabel','Response'),**kwargs)
|
|
43
|
+
def stability_margins(num,den):
|
|
44
|
+
try: import control
|
|
45
|
+
except ImportError as e: raise ImportError('Install plotora[engineering] for exact control-system margins') from e
|
|
46
|
+
gm,pm,wpc,wgc=control.margin(control.tf(num,den)); return dict(gain_margin=gm,phase_margin_deg=pm,phase_crossover_rad_s=wpc,gain_crossover_rad_s=wgc)
|
|
47
|
+
def bandwidth(num,den):
|
|
48
|
+
try: import control
|
|
49
|
+
except ImportError as e: raise ImportError('Install plotora[engineering] for control-system bandwidth') from e
|
|
50
|
+
return float(control.bandwidth(control.tf(num,den)))
|
|
51
|
+
def root_locus(num,den,*,gains=None,**kwargs):
|
|
52
|
+
from scipy.optimize import linear_sum_assignment
|
|
53
|
+
num,den=np.trim_zeros(np.asarray(num,dtype=float),'f'),np.trim_zeros(np.asarray(den,dtype=float),'f')
|
|
54
|
+
if not len(den) or len(num)>len(den): raise ValueError('Require a proper transfer function')
|
|
55
|
+
gains=np.r_[0,np.logspace(-4,4,500)] if gains is None else np.asarray(gains,dtype=float)
|
|
56
|
+
branches=[]
|
|
57
|
+
for k in gains:
|
|
58
|
+
r=np.roots(np.polyadd(den,k*num))
|
|
59
|
+
if len(r)!=len(den)-1: raise ValueError('Polynomial order changes at a requested gain')
|
|
60
|
+
if branches:
|
|
61
|
+
rows,cols=linear_sum_assignment(abs(branches[-1][:,None]-r[None,:])); r=r[cols]
|
|
62
|
+
branches.append(r)
|
|
63
|
+
b=np.asarray(branches)
|
|
64
|
+
def draw(ax):
|
|
65
|
+
for col in b.T: ax.plot(col.real,col.imag)
|
|
66
|
+
ax.axhline(0,color='0.6'); ax.axvline(0,color='0.6')
|
|
67
|
+
g=create(draw,xlabel=kwargs.pop('xlabel','Real'),ylabel=kwargs.pop('ylabel','Imaginary'),**kwargs); g.metadata.update(gains=gains,roots=b); return g
|
|
68
|
+
|
|
69
|
+
def phasors(values,**kwargs):
|
|
70
|
+
def draw(ax):
|
|
71
|
+
for name,z in values.items(): ax.quiver(0,0,complex(z).real,complex(z).imag,angles='xy',scale_units='xy',scale=1,label=name)
|
|
72
|
+
m=max((abs(v) for v in values.values()),default=1) or 1; ax.set_xlim(-1.15*m,1.15*m); ax.set_ylim(-1.15*m,1.15*m); ax.set_aspect('equal'); ax.axhline(0,color='0.6'); ax.axvline(0,color='0.6')
|
|
73
|
+
return create(draw,xlabel=kwargs.pop('xlabel','Real'),ylabel=kwargs.pop('ylabel','Imaginary'),**kwargs)
|
|
74
|
+
def impedance(f,z,**kwargs): return plot(f,abs(np.asarray(z)),xlabel=kwargs.pop('xlabel','Frequency (Hz)'),ylabel=kwargs.pop('ylabel','Impedance (Ω)'),**kwargs)
|
|
75
|
+
def power_triangle(p,q,**kwargs):
|
|
76
|
+
def draw(ax): ax.plot([0,p,p,0],[0,0,q,0],marker='o'); ax.set_aspect('equal',adjustable='datalim')
|
|
77
|
+
g=create(draw,xlabel=kwargs.pop('xlabel','Active power (W)'),ylabel=kwargs.pop('ylabel','Reactive power (var)'),**kwargs); g.metadata['apparent_power_va']=float(np.hypot(p,q)); return g
|
|
78
|
+
|
|
79
|
+
def corner_frequencies(num,den,*,unit='rad/s'):
|
|
80
|
+
if unit not in ('rad/s','Hz'): raise ValueError('unit must be rad/s or Hz')
|
|
81
|
+
factor=2*np.pi if unit=='Hz' else 1
|
|
82
|
+
return {'zeros':np.sort(np.abs(np.roots(num)))/factor,'poles':np.sort(np.abs(np.roots(den)))/factor}
|
|
83
|
+
|
|
84
|
+
def bode_asymptotic(num,den,*,w=None,unit='rad/s',theme=None):
|
|
85
|
+
"""Straight-line magnitude asymptote for rational continuous-time systems."""
|
|
86
|
+
num=np.trim_zeros(np.asarray(num,dtype=float),'f');den=np.trim_zeros(np.asarray(den,dtype=float),'f')
|
|
87
|
+
if not len(num) or not len(den): raise ValueError('Require nonzero polynomials')
|
|
88
|
+
f,h=_response(num,den,None,w,unit); wr=f*(2*np.pi if unit=='Hz' else 1)
|
|
89
|
+
def asym(poly):
|
|
90
|
+
out=np.full(len(wr),20*np.log10(abs(poly[0])))
|
|
91
|
+
for r in np.roots(poly): out+=20*np.log10(np.maximum(wr,abs(r)))
|
|
92
|
+
return out
|
|
93
|
+
from .plots import compare
|
|
94
|
+
with np.errstate(divide='ignore'): actual=20*np.log10(abs(h))
|
|
95
|
+
return compare((f,actual,'Exact'),(f,asym(num)-asym(den),'Asymptote'),theme=theme,xscale='log',xlabel=f'Frequency ({unit})',ylabel='Magnitude (dB)')
|
plotora/export.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""LaTeX figure snippets (requires graphicx in the consuming document)."""
|
|
2
|
+
def latex_figure(filename,caption,label,width=r'0.9\linewidth'):
|
|
3
|
+
# Caption, width and label accept deliberate LaTeX markup.
|
|
4
|
+
return '\n'.join([r'\begin{figure}[htbp]',r' \centering',f' \\includegraphics[width={width}]{{{filename}}}',f' \\caption{{{caption}}}',f' \\label{{{label}}}',r'\end{figure}'])+'\n'
|
|
5
|
+
|
|
6
|
+
def export_python(graph,path):
|
|
7
|
+
"""Reproducible standalone script for supported single-axis line plots."""
|
|
8
|
+
import numpy as np
|
|
9
|
+
ax=graph.ax
|
|
10
|
+
if len(graph.fig.axes)!=1 or ax.name!='rectilinear' or ax.collections or ax.images or ax.patches or not ax.lines or ax.texts:
|
|
11
|
+
raise ValueError('Python script export supports single-axis line plots without extra artists')
|
|
12
|
+
code=['import numpy as np','import matplotlib.pyplot as plt',f'fig, ax = plt.subplots(figsize={tuple(graph.fig.get_size_inches().tolist())!r}, layout="constrained")']
|
|
13
|
+
for line in ax.lines:
|
|
14
|
+
if line.get_transform() != ax.transData: raise ValueError('Python export requires data-coordinate lines')
|
|
15
|
+
x=np.asarray(line.get_xdata());y=np.asarray(line.get_ydata())
|
|
16
|
+
if x.dtype.kind not in 'iuf' or y.dtype.kind not in 'iuf': raise ValueError('Python export requires numeric line data')
|
|
17
|
+
def repr_array(a):
|
|
18
|
+
return '['+', '.join('np.nan' if np.isnan(v) else 'np.inf' if np.isposinf(v) else '-np.inf' if np.isneginf(v) else repr(float(v)) for v in a)+']'
|
|
19
|
+
opts=dict(label=line.get_label(),color=line.get_color(),linestyle=line.get_linestyle(),linewidth=line.get_linewidth(),marker=line.get_marker())
|
|
20
|
+
code.append(f'ax.plot({repr_array(x)}, {repr_array(y)}, **{opts!r})')
|
|
21
|
+
for name in ('xlabel','ylabel','title','xscale','yscale','xlim','ylim'):
|
|
22
|
+
val=getattr(ax,'get_'+name)()
|
|
23
|
+
if name in ('xlim','ylim'): val=tuple(map(float,val))
|
|
24
|
+
code.append(f'ax.set_{name}({val!r})')
|
|
25
|
+
if ax.get_legend() is not None: code.append('ax.legend()')
|
|
26
|
+
code.append('plt.show()'); path.write_text('\n'.join(code)+'\n',encoding='utf-8')
|
plotora/interactive.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Offline interactive HTML for ordinary 2D line/scatter artists."""
|
|
2
|
+
def export_html(graph,path,**kwargs):
|
|
3
|
+
import plotly.graph_objects as go
|
|
4
|
+
from matplotlib.collections import PathCollection
|
|
5
|
+
if len(graph.fig.axes)!=1 or graph.ax.name!='rectilinear' or graph.ax.images or graph.ax.patches or any(not isinstance(c,PathCollection) for c in graph.ax.collections):
|
|
6
|
+
raise ValueError('HTML export currently supports single-axis 2D line/scatter graphs only')
|
|
7
|
+
ax=graph.ax; fig=go.Figure()
|
|
8
|
+
for line in ax.lines:
|
|
9
|
+
fig.add_scatter(x=list(line.get_xdata()),y=list(line.get_ydata()),name=line.get_label(),mode='lines+markers' if line.get_marker() not in (None,'None','', ' ') else 'lines')
|
|
10
|
+
for c in ax.collections:
|
|
11
|
+
xy=c.get_offsets(); fig.add_scatter(x=xy[:,0].tolist(),y=xy[:,1].tolist(),mode='markers',name=c.get_label())
|
|
12
|
+
if not fig.data: raise ValueError('No supported artists for HTML export')
|
|
13
|
+
fig.update_layout(title=ax.get_title(),xaxis_title=ax.get_xlabel(),yaxis_title=ax.get_ylabel(),xaxis_type='log' if ax.get_xscale()=='log' else 'linear',yaxis_type='log' if ax.get_yscale()=='log' else 'linear')
|
|
14
|
+
fig.write_html(str(path),include_plotlyjs=True,**kwargs)
|
plotora/ltspice.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""LTspice exports and native RAW via optional spicelib. No simulator required."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import re
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from .core import create
|
|
8
|
+
|
|
9
|
+
_TIME={'s':1,'ms':1e3,'us':1e6,'µs':1e6,'ns':1e9}
|
|
10
|
+
_COMPLEX=re.compile(r'^\(?\s*([+-]?[\d.eE+-]+)\s*,\s*([+-]?[\d.eE+-]+)\s*\)?$')
|
|
11
|
+
_DB=re.compile(r'^\(?\s*([+-]?[\d.eE+-]+)\s*dB\s*,\s*([+-]?[\d.eE+-]+)\s*(?:°|deg)?\s*\)?$',re.I)
|
|
12
|
+
|
|
13
|
+
def _number(v):
|
|
14
|
+
try: return float(v)
|
|
15
|
+
except (ValueError,TypeError): pass
|
|
16
|
+
m=_DB.fullmatch(str(v).strip())
|
|
17
|
+
if m: return 10**(float(m[1])/20)*np.exp(1j*np.deg2rad(float(m[2])))
|
|
18
|
+
m=_COMPLEX.fullmatch(str(v).strip())
|
|
19
|
+
if m: return complex(float(m[1]),float(m[2]))
|
|
20
|
+
raise ValueError(f'Invalid LTspice numeric value: {v!r}')
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Simulation:
|
|
24
|
+
axis_name: str
|
|
25
|
+
runs: list[pd.DataFrame]
|
|
26
|
+
step_names: list[str]
|
|
27
|
+
@property
|
|
28
|
+
def traces(self): return list(self.runs[0].columns[1:])
|
|
29
|
+
def trace(self,name,step=0): return self.runs[step][name].to_numpy()
|
|
30
|
+
def axis(self,step=0): return self.runs[step].iloc[:,0].to_numpy()
|
|
31
|
+
def metrics(self,name,step=0,window=None):
|
|
32
|
+
from .signals import metrics
|
|
33
|
+
return metrics(self.axis(step),self.trace(name,step),window=window)
|
|
34
|
+
|
|
35
|
+
def read_ltspice(path):
|
|
36
|
+
p=Path(path)
|
|
37
|
+
if p.suffix.lower()=='.raw':
|
|
38
|
+
try: from spicelib import RawRead
|
|
39
|
+
except ImportError as exc: raise ImportError('Native RAW support requires pip install "plotora[engineering]"; alternatively export text from LTspice.') from exc
|
|
40
|
+
raw=RawRead(str(p)); names=raw.get_trace_names(); steps=list(raw.get_steps()); runs=[]
|
|
41
|
+
for step in steps:
|
|
42
|
+
x=raw.get_axis(step); runs.append(pd.DataFrame({names[0]:x,**{n:raw.get_trace(n).get_wave(step) for n in names[1:]}}))
|
|
43
|
+
if not runs: raise ValueError('RAW contains no simulation steps')
|
|
44
|
+
return Simulation(names[0],runs,[f'Step {s+1}' for s in steps])
|
|
45
|
+
b=p.read_bytes(); text=b.decode('utf-16') if b.startswith((b'\xff\xfe',b'\xfe\xff')) else b.decode('utf-8-sig',errors='strict') if b.isascii() or b.startswith(b'\xef\xbb\xbf') else _decode(b)
|
|
46
|
+
lines=[line.strip() for line in text.splitlines() if line.strip()]
|
|
47
|
+
if not lines: raise ValueError('Empty simulation file')
|
|
48
|
+
import csv
|
|
49
|
+
sep='\t' if '\t' in lines[0] else ',' if ',' in lines[0] else None
|
|
50
|
+
def split(s): return next(csv.reader([s],delimiter=sep)) if sep else s.split()
|
|
51
|
+
names=[v.strip() for v in split(lines[0])]; runs=[]; rows=[]; steps=[]; label='Step 1'
|
|
52
|
+
if len(names)<2 or len(set(names))!=len(names): raise ValueError('Expected a unique axis and at least one trace column')
|
|
53
|
+
def flush():
|
|
54
|
+
if rows: runs.append(pd.DataFrame(rows,columns=names)); steps.append(label); rows.clear()
|
|
55
|
+
for line in lines[1:]:
|
|
56
|
+
if line.lower().startswith('step information:'):
|
|
57
|
+
flush(); label=line.split(':',1)[1].strip(); continue
|
|
58
|
+
values=split(line)
|
|
59
|
+
if [v.strip() for v in values]==names: continue
|
|
60
|
+
if len(values)!=len(names): raise ValueError(f'Expected {len(names)} columns; got {len(values)} in {line[:100]!r}')
|
|
61
|
+
rows.append([_number(v) for v in values])
|
|
62
|
+
flush()
|
|
63
|
+
if not runs: raise ValueError('No simulation samples found')
|
|
64
|
+
return Simulation(names[0],runs,steps)
|
|
65
|
+
|
|
66
|
+
def _decode(b):
|
|
67
|
+
try: return b.decode('utf-8')
|
|
68
|
+
except UnicodeDecodeError: return b.decode('cp1252')
|
|
69
|
+
|
|
70
|
+
def ltspice(path,*,traces=None,time_unit='auto',step=None,component='magnitude',window=None,**kwargs):
|
|
71
|
+
sim=path if isinstance(path,Simulation) else read_ltspice(path)
|
|
72
|
+
traces=sim.traces if traces is None else [traces] if isinstance(traces,str) else list(traces)
|
|
73
|
+
if not traces or any(t not in sim.traces for t in traces): raise ValueError(f'Choose traces from {sim.traces}')
|
|
74
|
+
indexes=list(range(len(sim.runs))) if step is None else [step] if isinstance(step,int) else list(step)
|
|
75
|
+
if not indexes: raise ValueError('No steps selected')
|
|
76
|
+
is_time=sim.axis_name.lower()=='time'; is_freq=sim.axis_name.lower()=='frequency'
|
|
77
|
+
if is_time and time_unit=='auto':
|
|
78
|
+
span=max(np.ptp(sim.axis(i)) for i in indexes)
|
|
79
|
+
time_unit='ns' if span<1e-6 else 'us' if span<1e-3 else 'ms' if span<1 else 's'
|
|
80
|
+
if is_time and time_unit not in _TIME: raise ValueError(f'Unsupported time unit {time_unit}')
|
|
81
|
+
factor=_TIME[time_unit] if is_time else 1
|
|
82
|
+
if component not in ('magnitude','db','phase','real','imag'): raise ValueError('Unknown complex component')
|
|
83
|
+
xlab=f'Time ({time_unit})' if is_time else 'Frequency (Hz)' if is_freq else sim.axis_name
|
|
84
|
+
complex_data=any(np.iscomplexobj(sim.trace(t,i)) for t in traces for i in indexes)
|
|
85
|
+
if complex_data: ylab={'magnitude':'Magnitude','db':'Magnitude (dB)','phase':'Phase (°)','real':'Real part','imag':'Imaginary part'}[component]
|
|
86
|
+
elif all(t.lower().startswith('v(') for t in traces): ylab='Voltage (V)'
|
|
87
|
+
elif all(t.lower().startswith('i(') for t in traces): ylab='Current (A)'
|
|
88
|
+
else: ylab='Trace value (mixed units)' if len(traces)>1 else traces[0]
|
|
89
|
+
if is_freq: kwargs.setdefault('xscale','log')
|
|
90
|
+
kwargs.setdefault('xlabel',xlab); kwargs.setdefault('ylabel',ylab)
|
|
91
|
+
d={}
|
|
92
|
+
def draw(ax):
|
|
93
|
+
for i in indexes:
|
|
94
|
+
x=sim.axis(i); mask=np.ones(len(x),bool) if window is None else (x>=window[0])&(x<=window[1]); x=x[mask]*factor
|
|
95
|
+
if not len(x): raise ValueError('Window contains no samples')
|
|
96
|
+
for t in traces:
|
|
97
|
+
y=sim.trace(t,i)[mask]
|
|
98
|
+
if np.iscomplexobj(y):
|
|
99
|
+
with np.errstate(divide='ignore'): y={'magnitude':lambda:abs(y),'db':lambda:20*np.log10(abs(y)),'phase':lambda:np.rad2deg(np.unwrap(np.angle(y))),'real':lambda:y.real,'imag':lambda:y.imag}[component]()
|
|
100
|
+
name=t if len(indexes)==1 else f'{t} [{sim.step_names[i]}]'
|
|
101
|
+
ax.plot(x,y,label=name); d[f'{name} x']=pd.Series(x); d[name]=pd.Series(y)
|
|
102
|
+
g=create(draw,data=d,**kwargs); g.metadata['simulation']=sim; return g
|
|
103
|
+
|
|
104
|
+
def compare_ltspice(*paths,trace,labels=None,time_unit='ms',**kwargs):
|
|
105
|
+
from .plots import compare
|
|
106
|
+
if time_unit not in _TIME: raise ValueError('Choose an explicit time unit')
|
|
107
|
+
series=[]
|
|
108
|
+
for i,p in enumerate(paths):
|
|
109
|
+
s=read_ltspice(p)
|
|
110
|
+
if s.axis_name.lower()!='time' or len(s.runs)!=1: raise ValueError('Comparison requires single-step transient files')
|
|
111
|
+
series.append((s.axis()*_TIME[time_unit],s.trace(trace),labels[i] if labels else Path(p).stem))
|
|
112
|
+
kwargs.setdefault('xlabel',f'Time ({time_unit})'); kwargs.setdefault('ylabel','Voltage (V)' if trace.lower().startswith('v(') else 'Current (A)' if trace.lower().startswith('i(') else trace)
|
|
113
|
+
return compare(*series,**kwargs)
|
plotora/mathematics.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Mathematical visualization with a restricted, non-evaluating expression parser."""
|
|
2
|
+
import ast
|
|
3
|
+
import operator
|
|
4
|
+
import numpy as np
|
|
5
|
+
import sympy as sp
|
|
6
|
+
from scipy.integrate import solve_ivp
|
|
7
|
+
from .plots import plot,compare,contour,vector_field,stem
|
|
8
|
+
from .core import create
|
|
9
|
+
|
|
10
|
+
_FUNCS={name:getattr(sp,name) for name in ('sin','cos','tan','asin','acos','atan','sinh','cosh','tanh','exp','log','sqrt','Abs','sign','floor','ceiling','erf')}
|
|
11
|
+
_FUNCS.update(abs=sp.Abs,ln=sp.log)
|
|
12
|
+
_OPS={ast.Add:operator.add,ast.Sub:operator.sub,ast.Mult:operator.mul,ast.Div:operator.truediv,ast.Pow:operator.pow}
|
|
13
|
+
def expression(text,variables=('x',)):
|
|
14
|
+
symbols=tuple(sp.Symbol(n,real=True) for n in variables)
|
|
15
|
+
if isinstance(text,sp.Expr):
|
|
16
|
+
mapping={s:dict(zip(variables,symbols))[s.name] for s in text.free_symbols if s.name in variables}; result=text.xreplace(mapping)
|
|
17
|
+
if result.free_symbols-set(symbols): raise ValueError('Unexpected symbolic variables')
|
|
18
|
+
return result,symbols
|
|
19
|
+
if not isinstance(text,str): raise TypeError('Expected expression string or SymPy expression')
|
|
20
|
+
if len(text)>2000: raise ValueError('Expression too long')
|
|
21
|
+
tree=ast.parse(text.replace('^','**'),mode='eval'); names={**dict(zip(variables,symbols)),'pi':sp.pi,'e':sp.E,'E':sp.E}
|
|
22
|
+
if sum(1 for _ in ast.walk(tree))>250: raise ValueError('Expression too complex')
|
|
23
|
+
def walk(n):
|
|
24
|
+
if isinstance(n,ast.Constant) and type(n.value) in (int,float): return sp.sympify(n.value)
|
|
25
|
+
if isinstance(n,ast.Name) and n.id in names: return names[n.id]
|
|
26
|
+
if isinstance(n,ast.UnaryOp) and isinstance(n.op,(ast.UAdd,ast.USub)): return walk(n.operand)*(-1 if isinstance(n.op,ast.USub) else 1)
|
|
27
|
+
if isinstance(n,ast.BinOp) and type(n.op) in _OPS:
|
|
28
|
+
a,b=walk(n.left),walk(n.right)
|
|
29
|
+
if isinstance(n.op,ast.Pow) and b.is_number and abs(b)>1000: raise ValueError('Exponent too large')
|
|
30
|
+
return _OPS[type(n.op)](a,b)
|
|
31
|
+
if isinstance(n,ast.Call) and isinstance(n.func,ast.Name) and n.func.id in _FUNCS and not n.keywords: return _FUNCS[n.func.id](*(walk(a) for a in n.args))
|
|
32
|
+
raise ValueError('Unsupported expression syntax; use mathematical functions and declared variables only')
|
|
33
|
+
return walk(tree.body),symbols
|
|
34
|
+
|
|
35
|
+
def evaluate(expr,variables,arrays):
|
|
36
|
+
if callable(expr): f=expr
|
|
37
|
+
else:
|
|
38
|
+
expr,symbols=expression(expr,variables); f=sp.lambdify(symbols,expr,modules='numpy')
|
|
39
|
+
with np.errstate(all='ignore'): out=np.asarray(f(*arrays))
|
|
40
|
+
if np.iscomplexobj(out): raise ValueError('Complex results require an explicit real or imaginary component')
|
|
41
|
+
return np.broadcast_to(out,np.broadcast_shapes(*(np.shape(a) for a in arrays))).astype(float,copy=True)
|
|
42
|
+
def function(expr,domain=(-10,10),*,samples=1000,**kwargs):
|
|
43
|
+
x=np.linspace(*domain,samples); y=evaluate(expr,('x',),(x,)); y[~np.isfinite(y)]=np.nan
|
|
44
|
+
return plot(x,y,xlabel=kwargs.pop('xlabel','x'),ylabel=kwargs.pop('ylabel','f(x)'),**kwargs)
|
|
45
|
+
def parametric(xexpr,yexpr,domain=(0,2*np.pi),*,samples=1000,**kwargs):
|
|
46
|
+
t=np.linspace(*domain,samples); return plot(evaluate(xexpr,('t',),(t,)),evaluate(yexpr,('t',),(t,)),**kwargs)
|
|
47
|
+
def taylor(expr,degree=5,center=0,domain=(-3,3),*,samples=1000,**kwargs):
|
|
48
|
+
if not isinstance(degree,int) or not 0<=degree<=100: raise ValueError('degree must be 0–100')
|
|
49
|
+
ex,(x,)=expression(expr); approx=sp.series(ex,x,center,degree+1).removeO(); v=np.linspace(*domain,samples)
|
|
50
|
+
g=compare((v,evaluate(ex,('x',),(v,)),'Original'),(v,evaluate(approx,('x',),(v,)),f'Taylor degree {degree}'),**kwargs); g.metadata['polynomial']=approx; return g
|
|
51
|
+
|
|
52
|
+
def derivative(expr,domain=(-3,3),**kwargs):
|
|
53
|
+
ex,(x,)=expression(expr); return function(sp.diff(ex,x),domain,ylabel=kwargs.pop('ylabel',"f′(x)"),**kwargs)
|
|
54
|
+
def tangent(expr,at,domain=(-3,3),**kwargs):
|
|
55
|
+
ex,(x,)=expression(expr); y0=float(ex.subs(x,at)); m=float(sp.diff(ex,x).subs(x,at)); v=np.linspace(*domain,1000)
|
|
56
|
+
return compare((v,evaluate(ex,('x',),(v,)),'Function'),(v,y0+m*(v-at),'Tangent'),**kwargs)
|
|
57
|
+
def integral(expr,a,b,*,samples=1000,**kwargs):
|
|
58
|
+
from scipy.integrate import quad
|
|
59
|
+
if a>=b: raise ValueError('Require a < b')
|
|
60
|
+
x=np.linspace(a,b,samples); y=evaluate(expr,('x',),(x,)); g=plot(x,y,**kwargs).shade(x,y,alpha=.2)
|
|
61
|
+
g.metadata['integral'],g.metadata['quadrature_error']=quad(lambda x:float(evaluate(expr,('x',),(np.asarray(x),))),a,b); return g
|
|
62
|
+
|
|
63
|
+
def implicit(expr,xlim=(-3,3),ylim=(-3,3),*,samples=250,**kwargs):
|
|
64
|
+
if isinstance(expr,str) and '=' in expr:
|
|
65
|
+
a,b=expr.split('=',1); expr=expression(a,('x','y'))[0]-expression(b,('x','y'))[0]
|
|
66
|
+
x,y=np.meshgrid(np.linspace(*xlim,samples),np.linspace(*ylim,samples)); z=evaluate(expr,('x','y'),(x,y)); return contour(x,y,z,levels=[0],**kwargs)
|
|
67
|
+
def direction_field(expr,xlim=(-3,3),ylim=(-3,3),*,samples=20,**kwargs):
|
|
68
|
+
x,y=np.meshgrid(np.linspace(*xlim,samples),np.linspace(*ylim,samples)); dy=evaluate(expr,('x','y'),(x,y)); norm=np.hypot(1,dy); return vector_field(x,y,1/norm,dy/norm,**kwargs)
|
|
69
|
+
def ode(rhs,tspan,y0,*,samples=500,rtol=1e-8,atol=1e-10,**kwargs):
|
|
70
|
+
y0=np.atleast_1d(y0).astype(float); t=np.linspace(*tspan,samples)
|
|
71
|
+
f=rhs if callable(rhs) else lambda t,y:[float(evaluate(rhs,('t','y'),(np.asarray(t),np.asarray(y[0]))))]
|
|
72
|
+
sol=solve_ivp(f,tspan,y0,t_eval=t,rtol=rtol,atol=atol)
|
|
73
|
+
if not sol.success: raise RuntimeError(sol.message)
|
|
74
|
+
return compare(*[(sol.t,v,f'y{i+1}') for i,v in enumerate(sol.y)],**kwargs)
|
|
75
|
+
def vectors(vectors,**kwargs):
|
|
76
|
+
from .engineering import phasors
|
|
77
|
+
return phasors({str(k):complex(*v) for k,v in vectors.items()},**kwargs)
|
|
78
|
+
def transform(matrix,vectors,**kwargs):
|
|
79
|
+
m=np.asarray(matrix); v=np.asarray(vectors); out=v@m.T
|
|
80
|
+
return compare((v[:,0],v[:,1],'Original'),(out[:,0],out[:,1],'Transformed'),**kwargs)
|
|
81
|
+
def fourier(expr,terms=10,period=2*np.pi,*,samples=1000,**kwargs):
|
|
82
|
+
if terms<1 or period<=0: raise ValueError('Require positive terms and period')
|
|
83
|
+
ex,(x,)=expression(expr); approx=sp.fourier_series(ex,(x,-period/2,period/2)).truncate(terms); v=np.linspace(-period/2,period/2,samples)
|
|
84
|
+
return compare((v,evaluate(ex,('x',),(v,)),'Original'),(v,evaluate(approx,('x',),(v,)),'Fourier approximation'),**kwargs)
|
|
85
|
+
def sequence(values,**kwargs): return stem(np.arange(1,len(values)+1),values,**kwargs)
|
plotora/plot3d.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Matplotlib-native three-dimensional plotting."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .core import create
|
|
4
|
+
from .plots import _split
|
|
5
|
+
from .mathematics import evaluate
|
|
6
|
+
|
|
7
|
+
def _create(method,x,y,z,*args,zlabel='z',elev=None,azim=None,colorbar=False,**kwargs):
|
|
8
|
+
o,a=_split(kwargs)
|
|
9
|
+
def draw(ax):
|
|
10
|
+
artist=getattr(ax,method)(x,y,z,*args,**a); ax.set_zlabel(zlabel)
|
|
11
|
+
if elev is not None or azim is not None: ax.view_init(elev=elev,azim=azim)
|
|
12
|
+
if colorbar: ax.figure.colorbar(artist,ax=ax,shrink=.7)
|
|
13
|
+
o.setdefault('xlabel','x');o.setdefault('ylabel','y'); return create(draw,projection='3d',**o)
|
|
14
|
+
def _grid(x,y,z,domain,samples):
|
|
15
|
+
if isinstance(x,str) or callable(x):
|
|
16
|
+
xx,yy=np.meshgrid(np.linspace(*domain[0],samples),np.linspace(*domain[1],samples)); return xx,yy,evaluate(x,('x','y'),(xx,yy))
|
|
17
|
+
x,y,z=np.asarray(x),np.asarray(y),np.asarray(z)
|
|
18
|
+
if x.ndim==y.ndim==1: x,y=np.meshgrid(x,y)
|
|
19
|
+
if x.shape!=y.shape or x.shape!=z.shape: raise ValueError('Surface coordinate arrays must have matching shapes')
|
|
20
|
+
return x,y,z
|
|
21
|
+
def surface(x,y=None,z=None,*,domain=((-3,3),(-3,3)),samples=80,**kwargs):
|
|
22
|
+
x,y,z=_grid(x,y,z,domain,samples); kwargs.setdefault('cmap','viridis'); return _create('plot_surface',x,y,z,**kwargs)
|
|
23
|
+
def wireframe(x,y=None,z=None,*,domain=((-3,3),(-3,3)),samples=50,**kwargs): return _create('plot_wireframe',*_grid(x,y,z,domain,samples),**kwargs)
|
|
24
|
+
def scatter3d(x,y,z,**kwargs): return _create('scatter',x,y,z,**kwargs)
|
|
25
|
+
def line3d(x,y,z,**kwargs): return _create('plot',x,y,z,**kwargs)
|
|
26
|
+
def vector_field3d(x,y,z,u,v,w,**kwargs): return _create('quiver',x,y,z,u,v,w,**kwargs)
|
|
27
|
+
def contour3d(x,y,z,**kwargs): return _create('contour3D',x,y,z,**kwargs)
|
plotora/plots.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Simple plotting functions with native Matplotlib artist keyword arguments."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .core import create,xy
|
|
4
|
+
|
|
5
|
+
_OPTION_KEYS={'theme','figsize','xlabel','ylabel','title','xscale','yscale','xlim','ylim','grid','legend'}
|
|
6
|
+
def _split(kwargs): return ({k:v for k,v in kwargs.items() if k in _OPTION_KEYS},{k:v for k,v in kwargs.items() if k not in _OPTION_KEYS})
|
|
7
|
+
def _xyplot(method,x,y,**kwargs):
|
|
8
|
+
x,y=xy(x,y); opts,artist=_split(kwargs)
|
|
9
|
+
return create(lambda a:getattr(a,method)(x,y,**artist),data={'x':x,'y':y},**opts)
|
|
10
|
+
def plot(x,y=None,**kwargs):
|
|
11
|
+
if y is None: y=np.asarray(x); x=np.arange(len(y))
|
|
12
|
+
return _xyplot('plot',x,y,**kwargs)
|
|
13
|
+
line=plot
|
|
14
|
+
def scatter(x,y,**kwargs): return _xyplot('scatter',x,y,**kwargs)
|
|
15
|
+
def bar(x,y,**kwargs): return _xyplot('bar',x,y,**kwargs)
|
|
16
|
+
def stem(x,y,**kwargs): return _xyplot('stem',x,y,**kwargs)
|
|
17
|
+
def area(x,y,**kwargs): return _xyplot('fill_between',x,y,**kwargs)
|
|
18
|
+
def errorbar(x,y,**kwargs): return _xyplot('errorbar',x,y,**kwargs)
|
|
19
|
+
def hist(values,**kwargs):
|
|
20
|
+
o,a=_split(kwargs); v=np.asarray(values); return create(lambda ax:ax.hist(v,**a),data={'values':v},**o)
|
|
21
|
+
def boxplot(values,**kwargs):
|
|
22
|
+
o,a=_split(kwargs); return create(lambda ax:ax.boxplot(values,**a),**o)
|
|
23
|
+
def pie(values,**kwargs):
|
|
24
|
+
o,a=_split(kwargs); return create(lambda ax:ax.pie(values,**a),**o)
|
|
25
|
+
def polar(theta,r,**kwargs):
|
|
26
|
+
theta,r=xy(theta,r); o,a=_split(kwargs); return create(lambda ax:ax.plot(theta,r,**a),projection='polar',data={'theta':theta,'r':r},**o)
|
|
27
|
+
def heatmap(z,*,colorbar=True,**kwargs):
|
|
28
|
+
o,a=_split(kwargs)
|
|
29
|
+
def draw(ax):
|
|
30
|
+
im=ax.imshow(z,**a)
|
|
31
|
+
if colorbar: ax.figure.colorbar(im,ax=ax)
|
|
32
|
+
return create(draw,**o)
|
|
33
|
+
def contour(x,y,z,*,filled=False,colorbar=False,**kwargs):
|
|
34
|
+
o,a=_split(kwargs)
|
|
35
|
+
def draw(ax):
|
|
36
|
+
cs=(ax.contourf if filled else ax.contour)(x,y,z,**a)
|
|
37
|
+
if colorbar: ax.figure.colorbar(cs,ax=ax)
|
|
38
|
+
return create(draw,**o)
|
|
39
|
+
def vector_field(x,y,u,v,**kwargs):
|
|
40
|
+
o,a=_split(kwargs); return create(lambda ax:ax.quiver(x,y,u,v,**a),**o)
|
|
41
|
+
def compare(*series,**kwargs):
|
|
42
|
+
o,a=_split(kwargs); import pandas as pd
|
|
43
|
+
data={}
|
|
44
|
+
def draw(ax):
|
|
45
|
+
for i,s in enumerate(series):
|
|
46
|
+
x,y=xy(s[0],s[1]); name=s[2] if len(s)>2 else f'Series {i+1}'
|
|
47
|
+
ax.plot(x,y,label=name,**a); data[f'x_{i+1}']=pd.Series(x); data[f'y_{i+1}']=pd.Series(y)
|
|
48
|
+
return create(draw,data=data,**o)
|