Coverage for planit/snaptools/snaptools.py: 88%
381 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 snapshot and header classes
3"""
5from ..globaldefs import *
6from .. import utils, eos, plotting
7from . import io
10import os
11import numpy as npy
12import scipy
13import h5py
14import matplotlib
15import matplotlib.pyplot as plt
16#import struct
19class SnapHeader:
20 """
21 Class for Gadget/Swift snapshot header
22 """
23 def __init__(self, t=0.0, nfiles=1, ent=1):
24 """
25 Creates SnapHeader object
26 """
27 self.npart = npy.zeros(6).astype(int)
28 self.mass = npy.zeros(6)
29 self.time = t
30 self.redshift = 0.0
31 self.flag_sfr = 0
32 self.flag_feedbacktp = 0
33 self.npartTotal = npy.zeros(6).astype(int)
34 self.flag_cooling = 0
35 self.num_files = nfiles
36 self.BoxSize = 0.0 #npy.zeros(3)
37 self.Omega0 = 0.0
38 self.OmegaLambda = 0.0
39 self.HubbleParam = 1.0
40 self.flag_stellarage = 0
41 self.flag_metals = 0
42 self.nallhw = npy.zeros(6).astype(int)
43 self.flag_entr_ics = ent
46class SnapDark:
47 """
48 Class for holding dark matter particles
49 """
50 def __init__(self):
51 self.id = npy.empty(0)
52 self.m = npy.empty(0)
53 self.pos = npy.empty((0,3))
54 self.x = npy.empty(0)
55 self.y = npy.empty(0)
56 self.z = npy.empty(0)
57 self.vel = npy.empty((0,3))
58 self.vx = npy.empty(0)
59 self.vy = npy.empty(0)
60 self.vz = npy.empty(0)
61 self.soft = npy.empty(0)
62 self.pot = npy.empty(0)
65 def add_obj(self, m=Msun, pos=(0,0,0), vel=(0,0,0), soft_l=1e5):
66 self.id = npy.append(self.id, len(self.id))
67 self.m = npy.append(self.m, m)
68 self.x = npy.append(self.x, pos[0])
69 self.y = npy.append(self.y, pos[1])
70 self.z = npy.append(self.z, pos[2])
71 self.pos = npy.append(self.pos, [pos], axis=0)
72 self.vx = npy.append(self.vx, vel[0])
73 self.vy = npy.append(self.vy, vel[1])
74 self.vz = npy.append(self.vz, vel[2])
75 self.vel = npy.append(self.vel, [vel], axis=0)
76 self.soft = npy.append(self.soft, soft_l)
77 self.pot = npy.append(self.pot, 0)
80class Snapshot:
81 """
82 Gadget/Swift snapshot class
84 Includes header and gas particle data, with functions for
85 reading and writing snapshots.
87 load() -- load Gadget snapshot data
88 remove() -- remove particle from snapshot
89 write() -- save snapshot
90 ic_from_seagen() -- create snapshot from seagen particle planet
91 combine() -- create snapshot from two other snapshots
92 G2_to_swift() -- output Gadget2 format snapshot in swift hdf5 format
93 identify() -- determine material types
94 summary() -- print basic info
95 eq_test() -- test for equilibration (rms v below threshold multiple of escape v)
96 bound_mass() -- calculate remnant mass(es)
97 calc_phase() -- calculate material phases
98 calc_vap_frac() -- calculate vapour fractions of particles
99 correct_entropy() -- correct thermal profile of body to give correct entropies
100 plot() -- quick plot of the snapshot
101 """
103 def __init__(self):
104 """
105 Creates Snapshot object
106 """
107 self.header = SnapHeader() # header
108 self.N = 0 # number of SPH particles
109 self.initarrays() # initialise particle arrays
110 # extras
111 self.file = None # name of file read from
112 self.inclthermo = False # read/calculate extra thermodynamic variables
113 self.dark = None # generally don't need dark matter
116 def initarrays(self):
117 """
118 Initialises particle attributes
119 """
120 self.pos = npy.empty((0,3)) # position vector
121 self.x = npy.empty(0)
122 self.y = npy.empty(0)
123 self.z = npy.empty(0)
124 self.vel = npy.empty((0,3)) # velocity vector
125 self.vx = npy.empty(0)
126 self.vy = npy.empty(0)
127 self.vz = npy.empty(0)
128 self.id = npy.empty(0) # particle ID
129 self.m = npy.empty(0) # mass
130 self.S = npy.empty(0) # entropy
131 self.rho = npy.empty(0) # density
132 self.hsml = npy.empty(0) # smoothing length
133 self.pot = npy.empty(0) # potential
134 # Thermo extension
135 self.P = npy.empty(0) # pressure
136 self.T = npy.empty(0) # temperature
137 self.U = npy.empty(0) # internal energy
138 self.cs = npy.empty(0) # sound speed
139 # extras
140 self.materialIDs = None # particle material ID
141 self.r = None # radial distance from center
142 self.rem = self.bnd = None # ID of remnant particle belongs to
143 self.vapfrac = None # vapour fraction
144 self.meltfrac = None # particle melt fraction
145 self.phase = None # particle phase number
146 # not used:
147 #self.accel = npy.empty(0) # acceleration
148 #self.dt = npy.empty(0) # time step
151 def __getattribute__(self, attr):
152 """
153 Automatically attempts read from file if attribute is accessed but not already loaded
154 """
155 if attr in ['x','y','z','vx','vy','vz','pos','vel','id','m','S','rho','hsml','pot','P','T','U','cs'] and self.file:
156 if len(super().__getattribute__(attr))==0 and self.file:
157 self.load(self.file, headonly=False, compress=False, thermo=self.inclthermo, loadprops=[attr,])
158 elif attr in ['materialIDs', 'dark']:
159 if super().__getattribute__(attr) is None and self.file:
160 self.load(self.file, headonly=False, compress=False, thermo=self.inclthermo, loadprops=[attr,])
161 elif attr in ['rem', 'bnd']:
162 if super().__getattribute__(attr) is None and self.file:
163 if h5py.is_hdf5(self.file):
164 with h5py.File(self.file,'r') as f:
165 if 'RemnantIDs' in f['PartType0'].keys():
166 self.load(self.file, headonly=False, compress=False, thermo=self.inclthermo, loadprops=[attr,])
167 #else:
168 # #self.bound_mass()
169 # print('run bound_mass()')
170 else:
171 if os.path.exists(str(self.file)+'_rem.txt'):
172 self.load(self.file, headonly=False, compress=False, thermo=self.inclthermo, loadprops=[attr,])
173 #else:
174 # #self.bound_mass()
175 # print('run bound_mass()')
176 elif attr in ['vapfrac','meltfrac','phase']:
177 if super().__getattribute__(attr) is None and len(self.S) > 0:
178 self.calc_phase()
179 elif attr in ['r']:
180 if super().__getattribute__(attr) is None:
181 self.calc_rad()
182 return super().__getattribute__(attr)
185 def freedata(self):
186 """
187 Clear all loaded data
188 """
189 self.initarrays()
192 def _add_dark(self):
193 self.dark = SnapDark()
196 def ensure_matIDs(self,mats):
197 """
198 If materialIDs missing, add correct material IDs
199 """
200 eosIDs = [eos.select(mat).womaID for mat in mats]
201 if npy.ndim(self.materialIDs) < 1:
202 self.materialIDs = npy.choose( (self.id/GADGET_EOS_OFFSET).astype(int), eosIDs )
205 def load(self, fname, headonly = False, thermo=False, compress=False, mats=[402,400], loadprops=['all',]):
206 """
207 Loads snapshot data from file
208 """
209 io.load_snapshot(self, fname, headonly=headonly, thermo=thermo, compress=compress, mats=mats, loadprops=loadprops)
212 def ic_from_seagen(self, partplanet, thermo=False, init_h=100e5):
213 io.load_seagen(self, partplanet, thermo, init_h)
216 def combine(self, body1, body2, bidoffset=PROJ_ID_OFFSET, thermo=False, box=0.0):
217 """
218 Assign snapshot particle data by combining two other Snapshots
219 """
220 #HEADER
221 self.header.npart = body1.header.npart + body2.header.npart
222 self.header.mass = npy.array([0., 0., 0., 0., 0., 0.])
223 self.header.time = 0.
224 self.header.redshift= 0.
225 self.header.flag_sfr = self.header.flag_feedbacktp = self.header.flag_cooling = 0
226 self.header.npartTotal = self.header.npart
227 self.header.num_files = 1
228 if box>0.0:
229 self.header.BoxSize = box
230 else:
231 self.header.BoxSize = body1.header.BoxSize
232 self.header.Omega0 = self.header.OmegaLambda = 0.0
233 self.header.HubbleParam = 1.0
234 self.header.flag_stellarage = self.header.flag_metals = 0
235 self.header.nallhw = npy.array([0, 0, 0, 0, 0, 0])
236 #if body1.header.flag_entr_ics[0] != body2.header.flag_entr_ics[0]:
237 if body1.header.flag_entr_ics != body2.header.flag_entr_ics:
238 raise ValueError("Entropy IC flags must match!", body1.header.flag_entr_ics, body2.header.flag_entr_ics)
240 self.header.flag_entr_ics = body1.header.flag_entr_ics
242 self.N = self.header.npart[0]
244 if self.N/2.2 > bidoffset:
245 print('WARNING: low body ID offset, N =', self.N, ' body ID offset =', bidoffset)
247 #PARTICLE DATA
248 self.x = npy.append(body1.x, body2.x)
249 self.y = npy.append(body1.y, body2.y)
250 self.z = npy.append(body1.z, body2.z)
251 self.pos = npy.array((self.x, self.y, self.z))
252 self.pos = self.pos.T
254 self.vx = npy.append(body1.vx, body2.vx)
255 self.vy = npy.append(body1.vy, body2.vy)
256 self.vz = npy.append(body1.vz, body2.vz)
257 self.vel = npy.array((self.vx, self.vy, self.vz))
258 self.vel = self.vel.T
260 self.id = npy.append(body1.id, body2.id+bidoffset)
261 self.m = npy.append(body1.m, body2.m)
262 self.S = npy.append(body1.S, body2.S)
263 self.rho = npy.append(body1.rho, body2.rho)
264 self.pot = npy.append(body1.pot, body2.pot)
265 self.hsml = npy.append(body1.hsml, body2.hsml)
266 if npy.ndim(body1.materialIDs) > 0 and npy.ndim(body2.materialIDs) > 0:
267 self.materialIDs = npy.append(body1.materialIDs, body2.materialIDs)
268 if len(body1.U)>0 and len(body2.U)>0:
269 self.U = npy.append(body1.U, body2.U)
270 if len(body1.T)>0 and len(body2.T)>0:
271 self.T = npy.append(body1.T, body2.T)
272 if len(body1.P)>0 and len(body2.P)>0:
273 self.P = npy.append(body1.P, body2.P)
276 def remove(self, pid):
277 """
278 Remove particle from Snapshot
279 """
280 if pid not in self.id:
281 raise ValueError('Particle:', pid, 'not found in Snapshot')
282 self.header.npart[0] = self.header.npart[0]-1
283 self.N = self.header.npart[0]
285 select = self.id != pid
287 self.x = self.x[select]
288 self.y = self.y[select]
289 self.z = self.z[select]
290 self.pos = self.pos[select]
291 self.vx = self.vx[select]
292 self.vy = self.vy[select]
293 self.vz = self.vz[select]
294 self.vel = self.vel[select]
295 if super().__getattribute__('r') is not None:
296 self.r = self.r[select]
297 self.m = self.m[select]
298 if len(self.S) > 0:
299 self.S = self.S[select]
300 if self.materialIDs is not None:
301 self.materialIDs = self.materialIDs[select]
302 self.rho = self.rho[select]
303 self.hsml = self.hsml[select]
304 self.pot = self.pot[select]
305 if len(self.P) > 0:
306 self.P = self.P[select]
307 if len(self.T) > 0:
308 self.T = self.T[select]
309 if len(self.U) > 0:
310 self.U = self.U[select]
311 if len(self.cs) > 0:
312 self.cs = self.cs[select]
313# if type(self.accel) != int:
314# self.ax = npy.delete(self.ax, npy.where(self.id == pid))
315# self.ay = npy.delete(self.ay, npy.where(self.id == pid))
316# self.az = npy.delete(self.az, npy.where(self.id == pid))
317# self.dt = npy.delete(self.dt, npy.where(self.id == pid))
318 if self.rem is not None:
319 self.rem = self.rem[select]
320 if super().__getattribute__('vapfrac') is not None:
321 # calc_phase would be triggered by a normal lookup and requires id to already be shortened,
322 # but id needs to be last attribute in order for particle ID matching. Also don't really want
323 # to calculate in this case anyway
324 self.vapfrac = self.vapfrac[select]
325 self.meltfrac = self.meltfrac[select]
326 self.phase = self.phase[select]
328 self.id = self.id[select]
331 def write(self, fname):
332 """
333 Write snapshot to file
334 """
335 io.write_snapshot(self, fname)
338 def G2_to_swift(self, mats=[401,400], box=5000.*6.371e8, fname=None, write=False):
339 """
340 Convert Gadget2 format to Swift format
341 """
342 self.ensure_matIDs(mats)
343 #define U
344 if len(self.U) == 0:
345 self.U = eos.calcprop('U','rho','S',self.rho,self.S,self.materialIDs)
346 #define P
347 if len(self.P) == 0:
348 self.P = eos.calcprop('P','rho','S',self.rho,self.S,self.materialIDs)
349 #set BoxSize
350 if npy.ndim(self.header.BoxSize) == 0:
351 if self.header.BoxSize < self.x.max():
352 self.header.BoxSize = box
353 if not fname:
354 fname = self.file+'.hdf5'
355 self.header.flag_entr_ics = 0
356 if write:
357 io.write_hdf5(self,fname,units='cgs',mats=mats)
360### edit
361# def identify(self, crust=False):
362# self.core = self.iron = npy.where(self.id <= IDOFF, 1, 0)
363# self.mant = self.fors = npy.where(self.id > IDOFF, 1, 0)
364### edit end
367 def summary(self):
368 print('N SPH:', self.N)
369 print('Total mass:', self.m.sum()/5.972e27, 'Earth masses')
370 print('Time:', self.header.time/3600., 'hrs')
371 if self.file:
372 print('File:', self.file)
375 def calc_rad(self):
376 """
377 Calculate radial distances from com
378 """
379 cx, cy, cz = utils.com(self.m, self.x, self.y, self.z)
380 self.r = utils.rad(self.x-cx, self.y-cy, self.z-cz)
383 def eq_test(self, threshold=0.01, verbose=False):
384 """
385 Test for succesful equilibration
386 """
387 #r = npy.sqrt( (self.x-npy.average(self.x,weights=self.m))**2 + (self.y-npy.average(self.y,weights=self.m))**2 + (self.z-npy.average(self.z,weights=self.m))**2 )
388 vesc = npy.sqrt( 2*G*self.m.sum()/self.r.max() )
389 vrms = ( npy.sqrt( ( (self.vx-npy.average(self.vx,weights=self.m))**2 + (self.vy-npy.average(self.vy,weights=self.m))**2 + (self.vz-npy.average(self.vz,weights=self.m))**2 ).mean() ) )
390 if verbose:
391 print('rms velocity:', vrms/1e5, 'km/s')
392 print('escape velocity:', vesc/1e5, 'km/s')
393 if vrms <= threshold*vesc:
394 return True
395 else:
396 return False
399 def bound_mass(self, nrem=1, minbnd=500, maxiter=2000, tol=0.001, reorder=True, discardsmall=False, calc_pot_all=True, save=True):
400 """
401 Calculate bound remnants
402 """
403 self.rem = npy.zeros(len(self.id)).astype(int)
405 for r in range(1,nrem+1):
406 prevmass = 0
407 icount = 0
408 if r==1:
409 seed = self.id[self.pot==self.pot.min()][0]
410 else:
411 if len(self.id[self.rem==0]) < minbnd:
412 # if fewer particles than classed as a remnant remain to be tested we are done
413 break
414 pid = self.id[self.rem==0]
415 px = self.x[self.rem==0]
416 py = self.y[self.rem==0]
417 pz = self.z[self.rem==0]
418 pm = self.m[self.rem==0]
419 if calc_pot_all:
420 pot = utils.calc_potential(pm,px,py,pz)
421 else:
422 pot = self.pot[self.rem==0]
423 seed = pid[(pot==pot.min())][0]
425 self.rem[self.id==seed] = r
427 while (icount==0 or abs((self.m[self.rem==r].sum()-prevmass)/prevmass) > tol) and icount < maxiter:
428 sm = prevmass = self.m[self.rem==r].astype('float64',copy=False).sum()
429 #sx = (self.x[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
430 #sy = (self.y[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
431 #sz = (self.z[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
432 #svx = (self.vx[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
433 #svy = (self.vy[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
434 #svz = (self.vz[self.rem==r].astype('float64',copy=False)*self.m[self.rem==r].astype('float64',copy=False)).sum()/sm
436 sx,sy,sz = utils.com(self.m[self.rem==r].astype('float64',copy=False), self.x[self.rem==r].astype('float64',copy=False), self.y[self.rem==r].astype('float64',copy=False), self.z[self.rem==r].astype('float64',copy=False))
437 svx,svy,svz = utils.com_v(self.m[self.rem==r].astype('float64',copy=False), self.vx[self.rem==r].astype('float64',copy=False), self.vy[self.rem==r].astype('float64',copy=False), self.vz[self.rem==r].astype('float64',copy=False))
439 ke = 0.5 * self.m.astype('float64',copy=False) * ( (self.vx-svx)**2 + (self.vy-svy)**2 + (self.vz-svz)**2 ).astype('float64',copy=False)
440 pe = - G * self.m.astype('float64',copy=False) * sm / npy.sqrt( (self.x-sx)**2 + (self.y-sy)**2 + (self.z-sz)**2 ).astype('float64',copy=False)
442 self.rem[self.rem==0] = npy.where((ke+pe)[self.rem==0] < 0, r, self.rem[self.rem==0])
444 icount += 1
446 if discardsmall:
447 for r in range(1,self.rem.max()+1):
448 if len(self.m[self.rem==r]) < minbnd:
449 self.rem[self.rem==r] = -r
451 if reorder:
452 sm = [self.m[self.rem==r].sum() for r in range(1, self.rem.max()+1)]
453 order = npy.argsort(sm)
454 sbnd = self.rem.copy()
455 rr = 1
456 for r in order[::-1]:
457 self.rem[sbnd==r+1] = rr
458 rr+=1
460 if save:
461 io.save_remnant_ids(self)
463 self.bnd = self.rem
466### edit
467 def calc_phase(self,release=False,plot=False):
468 """
469 Calculate phase and melt/vapor fractions
470 """
471 ### currently only works for forsterite mantle and iron or alloy core!
472 if npy.unique(self.materialIDs)[-1] == 402:
473 CoreEOS = eos.select('alloy')
474 else:
475 CoreEOS = eos.select('iron')
476 MantleEOS = eos.select('forsterite')
478 if release:
479 release*=10
481 self.vapfrac = npy.zeros(len(self.materialIDs))
482 self.meltfrac = npy.zeros(len(self.materialIDs))
483 self.phase = npy.zeros(len(self.materialIDs))
485 FoSsol=scipy.interpolate.interp1d(MantleEOS.mc.Ps*1e10,MantleEOS.mc.Ss*1e3*1e7, bounds_error=False)
486 FoSmelt=scipy.interpolate.interp1d(MantleEOS.mc.Pl*1e10,MantleEOS.mc.Sl*1e3*1e7, bounds_error=False)
487 CSsol=scipy.interpolate.interp1d(CoreEOS.mc.Ps*1e10,CoreEOS.mc.Ss*1e3*1e7, bounds_error=False)
488 CSmelt=scipy.interpolate.interp1d(CoreEOS.mc.Pl*1e10,CoreEOS.mc.Sl*1e3*1e7, bounds_error=False)
490 if release:
491 self.meltfrac[self.materialIDs >= 300] = (self.S[self.materialIDs >= 300] - FoSsol(release)) / (FoSmelt(release) - FoSsol(release))
492 self.meltfrac[self.id < GADGET_EOS_OFFSET] = (self.S[self.id < GADGET_EOS_OFFSET] - CSsol(release)) / (CSmelt(release) - CSsol(release))
493 else:
494 self.meltfrac[self.materialIDs >= 300] = (self.S[self.materialIDs >= 300] - FoSsol(self.P[self.materialIDs >= 300])) / (FoSmelt(self.P[self.materialIDs >= 300]) - FoSsol(self.P[self.materialIDs >= 300]))
495 self.meltfrac[self.id < GADGET_EOS_OFFSET] = (self.S[self.id < GADGET_EOS_OFFSET] - CSsol(self.P[self.id < GADGET_EOS_OFFSET])) / (CSmelt(self.P[self.id < GADGET_EOS_OFFSET]) - CSsol(self.P[self.id < GADGET_EOS_OFFSET]))
496 self.meltfrac = npy.where(self.meltfrac < 0, 0., self.meltfrac)
497 self.meltfrac = npy.where(self.meltfrac > 1, 1., self.meltfrac)
498 self.meltfrac = npy.where(npy.isnan(self.meltfrac), 0., self.meltfrac)
500 FoSliq=scipy.interpolate.interp1d(MantleEOS.vc.Pl*1e10,MantleEOS.vc.Sl*1e3*1e7, bounds_error=False)
501 FoSvap=scipy.interpolate.interp1d(MantleEOS.vc.Pv*1e10,MantleEOS.vc.Sv*1e3*1e7, bounds_error=False)
502 CSliq=scipy.interpolate.interp1d(CoreEOS.vc.Pl*1e10,CoreEOS.vc.Sl*1e3*1e7, bounds_error=False)
503 CSvap=scipy.interpolate.interp1d(CoreEOS.vc.Pv*1e10,CoreEOS.vc.Sv*1e3*1e7, bounds_error=False)
505 if release:
506 self.vapfrac[self.materialIDs >= 300] = (self.S[self.materialIDs >= 300] - FoSliq(release)) / (FoSvap(release) - FoSliq(release))
507 self.vapfrac[self.id < GADGET_EOS_OFFSET] = (self.S[self.id < GADGET_EOS_OFFSET] - CSliq(release)) / (CSvap(release) - CSliq(release))
508 else:
509 self.vapfrac[self.materialIDs >= 300] = (self.S[self.materialIDs >= 300] - FoSliq(self.P[self.materialIDs >= 300])) / (FoSvap(self.P[self.materialIDs >= 300]) - FoSliq(self.P[self.materialIDs >= 300]))
510 self.vapfrac[self.id < GADGET_EOS_OFFSET] = (self.S[self.id < GADGET_EOS_OFFSET] - CSliq(self.P[self.id < GADGET_EOS_OFFSET])) / (CSvap(self.P[self.id < GADGET_EOS_OFFSET]) - CSliq(self.P[self.id < GADGET_EOS_OFFSET]))
511 self.vapfrac = npy.where(self.vapfrac < 0, 0., self.vapfrac)
512 self.vapfrac = npy.where(self.vapfrac > 1, 1., self.vapfrac)
513 self.vapfrac = npy.where(npy.isnan(self.vapfrac),0.,self.vapfrac)
515 self.phase[self.materialIDs >= 300] = npy.where(self.S[self.materialIDs >= 300]<FoSsol(self.P[self.materialIDs>=300]),4,5)
516 self.phase[self.id >= GADGET_EOS_OFFSET] = npy.where(self.S > FoSmelt(self.P), 6, self.phase)[self.id >= GADGET_EOS_OFFSET]
517 self.phase[self.id >= GADGET_EOS_OFFSET] = npy.where(self.S > FoSliq(self.P), 2, self.phase)[self.id >= GADGET_EOS_OFFSET]
518 self.phase[self.id >= GADGET_EOS_OFFSET] = npy.where(self.S > FoSvap(self.P), 7, self.phase)[self.id >= GADGET_EOS_OFFSET]
519 # should be P,T!
520 self.phase[self.id >= GADGET_EOS_OFFSET] = npy.where((self.P > MantleEOS.cp.P*1e10)*(self.S > MantleEOS.cp.S*1e3*1e7), 8, self.phase)[self.id >= GADGET_EOS_OFFSET]
522 self.phase[self.id < GADGET_EOS_OFFSET] = npy.where(self.S < CSsol(self.P), 4, 5)[self.id < GADGET_EOS_OFFSET]
523 self.phase[self.id < GADGET_EOS_OFFSET] = npy.where(self.S > CSmelt(self.P), 6, self.phase)[self.id < GADGET_EOS_OFFSET]
524 self.phase[self.id < GADGET_EOS_OFFSET] = npy.where(self.S > CSliq(self.P), 2, self.phase)[self.id < GADGET_EOS_OFFSET]
525 self.phase[self.id < GADGET_EOS_OFFSET] = npy.where(self.S > CSvap(self.P), 7, self.phase)[self.id < GADGET_EOS_OFFSET]
526 # should be P,T!
527 self.phase[self.id < GADGET_EOS_OFFSET] = npy.where((self.P > CoreEOS.cp.P*1e10)*(self.S > CoreEOS.cp.S*1e3*1e7), 8, self.phase)[self.id < GADGET_EOS_OFFSET]
528### edit end
531 def calc_vap_frac(self, plot=False):
532 self.calc_phase(plot=False)
535 def correct_entropy(self,reference):
536 """
537 Correct entropy (and T, U) to expected values either from
538 reference snapshot (e.g. ICs) or dict of materials and isentrope entropies
539 (one per material in J/kg/K).
540 """
541 if isinstance(reference, Snapshot):
542 entropy = reference.S
543 elif isinstance(reference, dict):
544 #mats,idx,choice = npy.unique(self.materialIDs,return_index=True,return_inverse=True)
545 mats = npy.unique(self.materialIDs)
546 if len(mats) != len(reference):
547 raise ValueError('list of entropies must match number of materials')
548 #choice = choice[npy.argsort(idx)]
549 #entropy = npy.array(reference)[npy.argsort(idx)][choice] * 1e7
550 entropy = npy.zeros_like(self.materialIDs)
551 for key, val in reference.items():
552 entropy = npy.where(self.materialIDs == eos.select(key).womaID, val, entropy)
553 entropy = entropy * 1e7
554 else:
555 raise TypeError('entropy reference must be a Snapshot or dictionary')
556 self.T = eos.calcprop('T', 'rho', 'S', self.rho, entropy, self.materialIDs)
557 self.U = eos.calcprop('U', 'rho', 'S', self.rho, entropy, self.materialIDs)
558 self.S = entropy
561 def add_DarkM_obj(self, m=Msun, pos=(0,0,0), vel=(0,0,0), soft_l=1e5):
562 if self.dark is None:
563 self._add_dark()
564 nDark = len(self.dark.id)
565 if nDark > 0:
566 print('WARNING: Snapshot already contains ', nDark, ' dark matter particle(s)!')
567 self.dark.add_obj(m=m, pos=pos, vel=vel, soft_l=soft_l)
568 self.header.npart[1] = self.header.npart[1] + 1
571 def plot(self, ptype='materials', scale='Mm', tcut = 3600., zoom=1., focus='potmin', cmap=None):
572 """
573 tcut -- time cut for pre-contact treatment
574 """
575 scf = plotting.get_scale_fac(scale)
576 axlim = 4*int(npy.ceil((self.x.max()-self.x.min())/scf/4.))
577 zcut = axlim/180.*scf
578 axlim /= zoom
580 if not cmap:
581 cmap = plotting.get_default_colormap(ptype)
582 if ptype in plotting.phase_type:
583 cmap = matplotlib.colors.ListedColormap(cmap.colors[[0,1,2,3,4,5],:])
585 fig = plt.figure(figsize=(3.5,2.8))
587 if ptype in plotting.materials_type:
588 im = plotting.plot_snapshot_scatter(self,cmap=cmap,plotQ=-(self.id/PROJ_ID_OFFSET).astype(int),ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,focus=focus)
589 elif ptype in plotting.density_type:
590 im = plotting.plot_snapshot_fluid(self,ax=plt.gca(),cmap=cmap,ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,vcut=0.5*self.vel.min(),focus=focus)
591 elif ptype in plotting.entropy_type:
592 im = plotting.plot_snapshot_fluid(self,plotQ=self.S/1e7,ax=plt.gca(),cmap=cmap,ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,vcut=0.5*self.vel.min(),focus=focus)
593 elif ptype in plotting.temperature_type:
594 im = plotting.plot_snapshot_fluid(self,plotQ=self.T,ax=plt.gca(),cmap=cmap,ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,vcut=0.5*self.vel.min(),focus=focus)
595 elif ptype in plotting.pressure_type:
596 im = plotting.plot_snapshot_fluid(self,plotQ=self.P/1e9,ax=plt.gca(),cmap=cmap,ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,vcut=0.5*self.vel.min(),focus=focus)
597 elif ptype in plotting.phase_type:
598 im = plotting.plot_snapshot_scatter(self,cmap=cmap,plotQ=self.phase,ptype=ptype,axlim=axlim,scale=scale,zcut=zcut,tcut=tcut,focus=focus)
600 tlab = plt.gca().texts[0]
601 tlab.set_text(tlab.get_text()+' hrs')
603 if ptype not in plotting.materials_type:
604 pbox=plt.gca().get_position()
605 cbar_ax = fig.add_axes([pbox.x1*1.02, pbox.y0, 0.035, 1.0*(pbox.y1-pbox.y0)])
606 cbar = fig.colorbar(im, cax=cbar_ax, orientation='vertical')
607 plotting.format_colorbar_axis(cbar, ptype, y=True)
609 return fig