Coverage for planit/plotting.py: 89%
216 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-11 15:42 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-11 15:42 +0000
1"""
2 planit plotting functions
3"""
4from .globaldefs import *
6import numpy as npy
7import scipy
8import matplotlib
9import matplotlib.pyplot as plt
10import matplotlib.ticker as ticker
13# plot type identifiers
14materials_type = ['mat','materials','mats','material']
15phase_type = ['phase',]
16density_type = ['density','rho']
17entropy_type = ['entropy','ent','S']
18pressure_type = ['pressure', 'P']
19temperature_type = ['temperature', 'T', 'temp']
22def get_scale_fac(scale):
23 if scale not in ['Mm', 'km', 'earth', 'Earth'] and type(scale) != int and type(scale) != float:
24 raise TypeError('scale must be a recognized label or a number')
25 if scale == 'Mm':
26 scf = 1e8
27 elif scale == 'km':
28 scf = 1e5
29 elif scale == 'earth' or scale == 'Earth':
30 scf = Rearth
31 else:
32 scf = scale
33 return scf
36def get_axis_units(scale):
37 if scale not in ['Mm', 'km', 'earth', 'Earth'] and type(scale) != int and type(scale) != float:
38 raise TypeError('scale must be a recognized label or a number')
39 if scale == 'Mm':
40 u = ' (Mm)'
41 elif scale == 'km':
42 u = ' (km)'
43 elif scale == 'earth' or scale == 'Earth':
44 u = r' (R$_\oplus$)'
45 else:
46 u = ''
47 return u
50def get_default_colormap(ptype):
51 if ptype in materials_type:
52 cmap = plt.get_cmap('cmr.bubblegum').copy()
53 elif ptype in density_type:
54 cmap = plt.get_cmap('cmr.eclipse').copy()
55 elif ptype in entropy_type:
56 cmap = plt.get_cmap('magma').copy()
57 elif ptype in temperature_type:
58 cmap = plt.get_cmap('cmr.sunburst').copy()
59 elif ptype in pressure_type:
60 cmap = plt.get_cmap('inferno').copy()
61 elif ptype in phase_type:
62 cmap = plt.get_cmap('plasma', 6).copy()
63 else:
64 cmap = plt.get_cmap('plasma').copy()
65 if ptype in density_type:
66 cmap.with_extremes(under='k')
67 else:
68 cmap.with_extremes(under='w')
69 return cmap
72def format_colorbar_axis(cbar, ptype, y=False):
73 if y:
74 axis = cbar.ax.yaxis
75 else:
76 axis = cbar.ax.xaxis
77 if ptype in density_type:
78 axis.set_label_text(r'$\rho$ (g$\,$cm$^{-3}$)')
79 elif ptype in entropy_type:
80 axis.set_label_text(r'$S$ (kJ$\,$K$^{-1}\,$kg$^{-1}$)')
81 elif ptype in pressure_type:
82 axis.set_label_text(r'$P$ (GPa)')
83 elif ptype in temperature_type:
84 locs = [100,300,1000,3000,10000,30000]
85 cbar.set_ticks(locs)
86 axis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: f'{x:g}'))
87 axis.set_label_text(r'$T$ (K)')
88 elif ptype in phase_type:
89 cbar.set_ticks([3.,4.,5.,6.,7.,8.])
90 #cbar.ax.set_xticklabels(['','s','s+l','l','l+v','v','scf'])
91 if y:
92 cbar.ax.set_yticklabels(['s','s+l','l','l+v','v','scf'])
93 else:
94 cbar.ax.set_xticklabels(['s','s+l','l','l+v','v','scf'])
95 axis.set_label_text(r'Phase')
96 if y:
97 axis.set_label_position('right')
98 else:
99 axis.set_label_position('top')
102def plot_snapshot_scatter(snap,ax=None,cmap=plt.get_cmap('plasma').copy(),plotQ=None,ptype='mat',axlim=1.,scale='Earth',zcut=None,tcut=0.,focus='potmin',rhomin=1e-5):
103 #phase flag limits
104 phmin=2.5
105 phmax=8.5
107 if ptype not in [*materials_type,*phase_type]:
108 raise ValueError('Unknown plot type:', ptype)
110 if ax is None:
111 ax = plt.gca()
113 scf = get_scale_fac(scale)
115 ti = (snap.header.time)/3600.
116 if npy.ndim(ti)>0:
117 ti=ti[0]
119 if not zcut:
120 zcut = axlim / 200. * scf
122 if focus=='potmin' and snap.header.time >= tcut:
123 x = snap.x - (snap.x[snap.pot==snap.pot.min()])[0]
124 y = snap.y - (snap.y[snap.pot==snap.pot.min()])[0]
125 z = snap.z - (snap.z[snap.pot==snap.pot.min()])[0]
126 elif focus=='targcore':
127 x = snap.x - npy.median(snap.x[snap.id<PROJ_ID_OFFSET])
128 y = snap.y - npy.median(snap.y[snap.id<PROJ_ID_OFFSET])
129 z = snap.z - npy.median(snap.z[snap.id<PROJ_ID_OFFSET])
130 else:
131 x = snap.x
132 y = snap.y
133 z = snap.z
134 modz = npy.abs(z)
136 # reorder phases for plotting
137 if ptype in phase_type:
138 plotQ = npy.where(plotQ<=6,plotQ-1,plotQ)
139 plotQ = npy.where(plotQ<2,6,plotQ)
140 cmin = phmin
141 cmax = phmax
142 norm = matplotlib.colors.Normalize(vmin=cmin,vmax=cmax,clip=False)
143 elif ptype in materials_type:
144 #cmin = 0
145 #cmax = 1
146 norm = None
147 select = (modz<zcut)*(x<=axlim*scf)*(x>=-axlim*scf)*(y<=axlim*scf)*(y>=-axlim*scf)
148 im = ax.scatter(x[select]/scf,y[select]/scf,s=0.1,c=plotQ[select],alpha=1.,cmap=cmap,norm=norm,rasterized=True) #s=0.8
150 labcolor='k'
151 if ti<1.1:
152 ax.text(0.96,0.96,'{:.2f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
153 elif ti>23.8:
154 ax.text(0.96,0.96,'{:.0f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
155 else:
156 ax.text(0.96,0.96,'{:.1f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
158 ax.set_xlim(-axlim,axlim)
159 ax.set_ylim(-axlim,axlim)
160 ax.set_aspect('equal')
161 ax.minorticks_on()
163 unitstr = get_axis_units(scale)
164 ax.set_ylabel('y' + unitstr)
165 ax.set_xlabel('x' + unitstr)
167 return im
170def plot_snapshot_fluid(snap,X=npy.empty([]),Y=npy.empty([]),Z=npy.empty([]),ax=None,cmap=plt.get_cmap('plasma').copy(),plotQ=None,ptype='rho',axlim=1.,scale='Earth',zcut=None,tcut=0.,vcut=None,rhomin=1e-5,focus='potmin'): # zi=npy.empty([])
171 # density limits
172 # rhomin=1e-5
173 rhomax=10.
174 # entropy limits
175 Smin=1.5
176 Smax=10.
177 # temperature limits
178 Tmin=100.
179 Tmax=30000.
180 # pressure limits
181 Pmin=1.e-5
182 Pmax=1000.
183 vi = vit = None
185 if ptype not in [*density_type,*entropy_type,*pressure_type,*temperature_type]:
186 raise ValueError('Unknown plot type:',ptype)
188 if ax is None:
189 ax = plt.gca()
191 scf = get_scale_fac(scale)
193 if not zcut:
194 zcut = axlim / 200. * scf
196 # number of cells for grid
197 Ng = 1201j
198 #Ngz = 21j
199 #if zi.ndim ==0:
200 # zi=npy.linspace(-axlim/10.,axlim/10.,int(Ngz.imag))
201 if X.ndim==0 or Y.ndim==0 or Z.ndim==0:
202 #X,Y,Z = npy.mgrid[-axlim:axlim:(Ng),-axlim:axlim:(Ng),-axlim/10.:axlim/10.:(Ngz)]
203 X,Y = npy.mgrid[-axlim:axlim:(Ng),-axlim:axlim:(Ng)]
204 Z = npy.full_like(X, 0)
206 ti = (snap.header.time)/3600.
207 if npy.ndim(ti)>0:
208 ti=ti[0]
210 if focus=='potmin' and snap.header.time >= tcut:
211 x = snap.x - (snap.x[snap.pot==snap.pot.min()])[0]
212 y = snap.y - (snap.y[snap.pot==snap.pot.min()])[0]
213 z = snap.z - (snap.z[snap.pot==snap.pot.min()])[0]
214 elif focus=='targcore':
215 x = snap.x - npy.median(snap.x[snap.id<PROJ_ID_OFFSET])
216 y = snap.y - npy.median(snap.y[snap.id<PROJ_ID_OFFSET])
217 z = snap.z - npy.median(snap.z[snap.id<PROJ_ID_OFFSET])
218 else:
219 x = snap.x
220 y = snap.y
221 z = snap.z
222 modz = npy.abs(z)
224 #if snap.header.time >= tcut and focus=='potmin':
225 # coz = (z[snap.pot==snap.pot.min()])[0]/scf #s.z[modz<zcut]
226 #else:
227 coz = 0.0
229 if snap.header.time<tcut and vcut:
230 if ptype not in density_type:
231 vit = scipy.interpolate.griddata((x[(snap.vx>vcut)*(modz<zcut)]/scf,y[(snap.vx>vcut)*(modz<zcut)]/scf,z[(snap.vx>vcut)*(modz<zcut)]/scf),plotQ[(snap.vx>vcut)*(modz<zcut)],(X,Y,Z),method='linear',fill_value=1.e-18)
232 rhoit = scipy.interpolate.griddata((x[(snap.vx>vcut)*(modz<zcut)]/scf,y[(snap.vx>vcut)*(modz<zcut)]/scf,z[(snap.vx>vcut)*(modz<zcut)]/scf),snap.rho[(snap.vx>vcut)*(modz<zcut)],(X,Y,Z),method='linear',fill_value=1.e-18)
233 else:
234 vcut = 2*snap.vel.max()
235 if ptype not in density_type:
236 vi = scipy.interpolate.griddata((x[(snap.vx<vcut)*(modz<zcut)]/scf,y[(snap.vx<vcut)*(modz<zcut)]/scf,z[(snap.vx<vcut)*(modz<zcut)]/scf),plotQ[(snap.vx<vcut)*(modz<zcut)],(X,Y,Z),method='linear',fill_value=1.e-18)
237 rhoi = scipy.interpolate.griddata((x[(snap.vx<vcut)*(modz<zcut)]/scf,y[(snap.vx<vcut)*(modz<zcut)]/scf,z[(snap.vx<vcut)*(modz<zcut)]/scf),snap.rho[(snap.vx<vcut)*(modz<zcut)],(X,Y,Z),method='linear',fill_value=1.e-18)
238 if snap.header.time<tcut and rhoit is not None:
239 if vi is not None:
240 vi = npy.where(vi>vit,vi,vit)
241 rhoi = npy.where(rhoi>rhoit,rhoi,rhoit)
242 #nn = (npy.nonzero(zi==(zi[zi<=coz])[-1])[0])[0]
243 norm = matplotlib.colors.LogNorm(vmin=rhomin,vmax=rhomax,clip=False)
244 if vi is not None:
245 if ptype in pressure_type:
246 cmin = Pmin
247 cmax = Pmax
248 norm = matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=False)
249 #cols = vi[:,:,nn].T #matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=True)(vi[:,:,nn].T)
250 cols = vi[:,:].T #matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=True)(vi[:,:,nn].T)
251 elif ptype in entropy_type:
252 cmin = Smin
253 cmax = Smax
254 norm = matplotlib.colors.Normalize(vmin=cmin,vmax=cmax,clip=False)
255 #cols = matplotlib.colors.Normalize(vmin=cmin,vmax=cmax,clip=True)(vi[:,:,nn].T)
256 #alphas = matplotlib.colors.LogNorm(vmin=0.05*rhomin,vmax=rhomax,clip=True)(rhoi[:,:,nn].T)
257 cols = matplotlib.colors.Normalize(vmin=cmin,vmax=cmax,clip=True)(vi[:,:].T)
258 alphas = matplotlib.colors.LogNorm(vmin=0.05*rhomin,vmax=rhomax,clip=True)(rhoi[:,:].T)
259 cols = cmap(cols)
260 cols[..., -1] = alphas
261 elif ptype in temperature_type:
262 cmin = Tmin
263 cmax = Tmax
264 norm = matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=False)
265 #cols = vi[:,:,nn].T #matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=True)(vi[:,:,nn].T)
266 cols = vi[:,:].T #matplotlib.colors.LogNorm(vmin=cmin,vmax=cmax,clip=True)(vi[:,:,nn].T)
267 else:
268 #cols = rhoi[:,:,nn].T
269 cols = rhoi[:,:].T
271 im = ax.imshow(cols,origin='lower',extent=[-axlim,axlim,-axlim,axlim],cmap=cmap,norm=norm)
273 if ptype in [*density_type,*temperature_type]:
274 ax.tick_params(colors='w',which='both',labelcolor='k')
275 ax.spines['top'].set_color('w')
276 ax.spines['bottom'].set_color('w')
277 ax.spines['left'].set_color('w')
278 ax.spines['right'].set_color('w')
279 labcolor = 'w'
280 else:
281 labcolor='k'
282 if ti<1.1:
283 ax.text(0.96,0.96,'{:.2f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
284 elif ti>23.8:
285 ax.text(0.96,0.96,'{:.0f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
286 else:
287 ax.text(0.96,0.96,'{:.1f}'.format(ti),ha='right',va='top',fontsize=9,fontweight='bold',color=labcolor,transform=plt.gca().transAxes)
289 ax.set_xlim(-axlim,axlim)
290 ax.set_ylim(-axlim,axlim)
291 ax.set_aspect('equal')
292 ax.minorticks_on()
294 unitstr = get_axis_units(scale)
295 ax.set_ylabel('y' + unitstr)
296 ax.set_xlabel('x' + unitstr)
298 return im