Coverage for planit/makeplanet.py: 47%

799 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-11 15:42 +0000

1""" 

2 planit SPH planet generation functions 

3""" 

4 

5from .main import * 

6from .globaldefs import * 

7from .snaptools import Snapshot 

8from . import eos 

9#from . import utils 

10 

11import numpy as npy 

12from scipy import interpolate 

13import matplotlib 

14import matplotlib.pyplot as plt 

15import seagen 

16 

17 

18G_mks = 6.67E-11 # Gravitational constant m3/kg/s2 

19Rcmb = 348000000. # CMB radius in cm (from PREM) 

20 

21 

22class planet_profile: 

23 """ 

24 1D planet profile class 

25  

26 load() 

27 write() 

28 add_isentropic_layer() 

29 add_adiabatic_layer() 

30 """ 

31 def __init__(self): 

32 self.M = 0. 

33 self.cf = 0. 

34 self.rarr = npy.array([]) 

35 self.density = npy.array([]) 

36 self.pressure = npy.array([]) 

37 self.temperature = npy.array([]) 

38 self.entropy = npy.array([]) 

39 self.mat = npy.array([]) 

40 

41 def write(self, file='profile.dat'): 

42 npy.savetxt(file,npy.transpose([self.rarr, self.mat, self.entropy, self.density, self.pressure, self.temperature])) 

43 

44 def load(self, file='profile.dat'): 

45 (self.rarr, self.mat, self.entropy, self.density, self.pressure, self.temperature) = npy.loadtxt(file,unpack=True) 

46 

47 

48 def reset(self): 

49 self.__init__() 

50 

51 

52 def add_isentropic_layer(self,mass=0,Pmin=0,iendprevlayer=0,isentrope=None,dR=Rearth/3000.,maxiter=2000, firstlayer=False, masstolerance=1e-3): 

53 if isentrope is None: 

54 raise ValueError('isentrope must be defined') 

55 if not len(self.rarr) == len(self.density) == len(self.temperature) == len(self.pressure): 

56 raise ValueError('Arrays rarr, darr, parr, tarr must have same length') 

57 if len(self.rarr)<1: 

58 raise ValueError('Central values must be provided!') 

59 

60 #if self.M == 0: 

61 # firstlayer = True 

62 menclosed = self.M 

63 

64 j = 0 

65 ii = len(self.rarr) 

66 ri = self.rarr[-1] 

67 if len(self.mat) == 0: 

68 matN = 0 

69 self.entropy = npy.append(self.entropy, isentrope.entropy*1e7) 

70 self.mat = npy.append(self.mat, matN) 

71 else: 

72 matN = self.mat[-1] + 1 

73 

74 while (self.M-menclosed) < (mass)*(1.-masstolerance) and self.pressure[-1] > Pmin and j < maxiter: 

75 ri +=dR # m 

76 self.rarr = npy.append(self.rarr,ri) 

77 mlayer = 4.*npy.pi*self.rarr[ii]*self.rarr[ii]*dR*self.density[ii-1] # g 

78 if ii == iendprevlayer+1: 

79 density0 = npy.interp(self.pressure[ii-1]/1.E10,isentrope.pressure,isentrope.density) 

80 if self.M > 0: 

81 dp = G*self.M*density0*dR/self.rarr[ii]/self.rarr[ii] 

82 else: 

83 dp = G*density0*dR/self.rarr[ii]/self.rarr[ii] # Pa 

84 else: 

85 dp = G*self.M*self.density[ii-1]*dR/self.rarr[ii]/self.rarr[ii] # Pa 

86 self.pressure = npy.append(self.pressure, self.pressure[ii-1]-dp) #  

87 if firstlayer: 

88 di = npy.interp(self.pressure[ii]/1.E10,isentrope.pressure,isentrope.density) # g/cm3 

89 else: 

90 di = npy.interp(self.pressure[ii-1]/1.E10,isentrope.pressure,isentrope.density) # g/cm3 

91 self.density = npy.append(self.density,di) # g/cm3 

92 if firstlayer: 

93 ti = npy.interp(self.pressure[ii]/1.E10,isentrope.pressure,isentrope.temperature) # K 

94 else: 

95 ti = npy.interp(self.pressure[ii-1]/1.E10,isentrope.pressure,isentrope.temperature) # K 

96 self.temperature = npy.append(self.temperature,ti) # K 

97 self.M += mlayer 

98 self.entropy = npy.append(self.entropy, isentrope.entropy*1e7) 

99 self.mat = npy.append(self.mat, matN) 

100 ii += 1 

101 j += 1 

102 

103 

104 def add_adiabatic_layer(self,mass=0,Pmin=0,iendprevlayer=0,EOS=None,dR=Rearth/3000.,maxiter=2000, firstlayer=False, masstolerance=1e-3): 

105 if EOS is None: 

106 raise ValueError('EOS must be defined') 

107 if not len(self.rarr) == len(self.density) == len(self.temperature) == len(self.pressure): 

108 raise ValueError('Arrays rarr, darr, parr, tarr must have same length') 

109 if len(self.rarr) < 1: 

110 raise ValueError('Central values must be provided!') 

111 

112 if EOS.TYPE != 'HM80': 

113 S = eos.tabinterp.from_rhoT('S',self.density[-1],self.temperature[-1],EOS.make_passer_class()) * eos.uconversion_S_inv / 1.e7 

114 print(S) 

115 isentrope = eos.isentrope_class(S,EOS.MODELNAME) 

116 self.add_isentropic_layer(mass=mass,Pmin=Pmin,iendprevlayer=iendprevlayer,isentrope=isentrope,dR=dR,maxiter=maxiter,masstolerance=masstolerance) 

117 else: # HM80 only 

118 menclosed = self.M 

119 

120 j = 0 

121 ii = len(self.rarr) 

122 ri = self.rarr[-1] 

123 if len(self.mat) == 0: 

124 matN = 0 

125 self.entropy = npy.append(self.entropy, 0) 

126 self.mat = npy.append(self.mat, matN) 

127 else: 

128 matN = self.mat[-1] + 1 

129 

130 while (self.M-menclosed) < (mass)*(1.-masstolerance) and self.pressure[-1] > Pmin and j < maxiter: 

131 ri +=dR # m 

132 self.rarr = npy.append(self.rarr,ri) 

133 mlayer = 4.*npy.pi*self.rarr[ii]*self.rarr[ii]*dR*self.density[ii-1] # g 

134 if ii == iendprevlayer+1: 

135 density0 = eos.HM80_rho_P_T(self.pressure[ii-1],self.temperature[ii-1],rho_est=0.9*self.density[ii-1]) 

136 if self.M > 0: 

137 dp = G*self.M*density0*dR/self.rarr[ii]/self.rarr[ii] 

138 else: 

139 dp = G*density0*dR/self.rarr[ii]/self.rarr[ii] # Pa 

140 else: 

141 dp = G*self.M*self.density[ii-1]*dR/self.rarr[ii]/self.rarr[ii] # Pa 

142 self.pressure = npy.append(self.pressure, self.pressure[ii-1]-dp) #  

143 #U = HM80_U_rho_T(self.density[ii-1],self.temperature[ii-1]) 

144 #P = HM80_P_rho_T(rho,T) #tabinterp.from_rhoU1D('P',rho,U,EOS) 

145 newrho = eos.HM80_rho_P_T(self.pressure[ii-1],self.temperature[ii-1],rho_est=0.9*self.density[ii-1]) 

146 self.density = npy.append(self.density,newrho) 

147 if ii == iendprevlayer+1: 

148 newT = eos.HM80_adiabat_T(density0,self.density[ii],self.temperature[ii-1]) 

149 else: 

150 newT = eos.HM80_adiabat_T(self.density[ii-1],self.density[ii],self.temperature[ii-1]) 

151 self.temperature = npy.append(self.temperature,newT) 

152 self.M += mlayer 

153 self.entropy = npy.append(self.entropy, 0) 

154 self.mat = npy.append(self.mat, matN) 

155 ii+=1 

156 j+=1 

157 if j%500 == 0: 

158 print(newrho,newT,self.pressure[-1]) 

159 

160 

161 

162def planet_density(m): 

163 """ 

164 Estimate density from planet mass. 

165 Based on Müller et al., A&A 686, A296 (2024). 

166 """ 

167 if m < 3.8: 

168 d = 5.12 * m**0.12 

169 elif m < 183: 

170 d = 16.6 * m**-0.76 

171 else: 

172 d = 4.39e-4 * m**1.26 

173 return d 

174 

175 

176 

177def make_1D_planet(mass=Mearth, corefraction=0.325, Pmin=1.e6, Score=1.81, Smantle=3.02, 

178 mtolerance=1e-3, layer1='iron', layer2='forsterite', layers=[], S=[], mantlepotT=False, 

179 plot=False, fixcoreT=False, rhocent=None, verbose=False): 

180 """ 

181 Create a 1D planet profile 

182  

183 mass - list of layer masses (inside to out) or total mass of 2 layer planet 

184 corefraction - core mass fraction for 2 layer planet 

185 Pmin - surface pressure (Pa) 

186 Score - core entropy for 2 layer planet 

187 Smantle - 2nd layer entropy for 2 layer planet 

188 mtolerance - tolerance for total mass of planet 

189 layer1 - 1st layer material for 2 layer planet 

190 layer 2 - 2nd layer material for 2 layer planet 

191 layers - list of materials for layers (inside to out) 

192 S - list of layer entropies (inside to out) 

193 mantlepotT - mantle potential temperature for 2 layer planet 

194 plot - plot pressure-temperature profile? 

195 fixcoreT - ensure outer core is at least as hot as inner mantle (2nd layer)? 

196 rhocent - initial central density to use (optional, use for troublesome cases) 

197 verbose - print extra information 

198  

199 """ 

200 

201 if layers or S: 

202 if not len(layers) == len(S) == len(mass): 

203 raise ValueError('number of layers must match. layers, S, mass:', len(layers), len(S), len(mass) if npy.ndim(mass) > 0 else 0) 

204 if (not layers or len(layers) == 2) and not any(x in [*layers,layer1,layer2] for x in [*eos.hm80HHenames]): 

205 if layers: 

206 layer1 = layers[0] 

207 layer2 = layers[1] 

208 Score = S[0] 

209 Smantle = S[1] 

210 totmass = sum(mass) 

211 corefraction = mass[0]/totmass 

212 mass = totmass 

213 return make_1D_2L_planet(mass=mass,corefraction=corefraction,Pmin=Pmin,Score=Score,Smantle=Smantle,mtolerance=mtolerance,layer1=layer1,layer2=layer2,mantlepotT=mantlepotT,plot=plot,fixcoreT=fixcoreT,verbose=verbose,rhocent=rhocent) 

214 else: 

215 return make_1D_NL_planet(mass=mass, Pmin=Pmin, S=S, mtolerance=mtolerance, layers=layers, 

216 plot=plot, fixcoreT=fixcoreT, verbose=verbose, rhocent=rhocent, mantlepotT=mantlepotT) 

217 

218 

219 

220def make_1D_2L_planet(mass=Mearth, corefraction=0.325, Pmin=1.e6, Score=1.81, Smantle=3.02, 

221 mtolerance=1e-3, layer1='iron', layer2='forsterite', mantlepotT=False, plot=False, 

222 fixcoreT=False, verbose=False, rhocent=None): 

223 

224 mcore = corefraction * mass 

225 mmantle = (1-corefraction) * mass 

226 

227 mtotal = mcore + mmantle 

228 

229 Pcenter = 0 

230 

231 ly1EOS = eos.select(layer1) 

232 #if ly1EOS is None: 

233 # print('Unknown core EOS') 

234 # return 

235 

236 ly2EOS = eos.select(layer2) 

237 #if ly2EOS is None: 

238 # print('Unknown mantle EOS') 

239 # return 

240 

241 if mantlepotT: 

242 refP = Pmin 

243 refP_T = npy.zeros(ly2EOS.NT) 

244 refP_S = npy.zeros(ly2EOS.NT) 

245 refP_rho = npy.zeros(ly2EOS.NT) 

246 #it0 = npy.where(ly2EOS.T >= ly2EOS.T0REF)[0] 

247 id0 = npy.arange(ly2EOS.ND) 

248 for iit in range(0,ly2EOS.NT): 

249 refP_T[iit] = ly2EOS.T[iit] 

250 refP_S[iit] = npy.interp(refP/1.E10,ly2EOS.P[iit,id0],ly2EOS.S[iit,id0]) 

251 refP_rho[iit] = npy.interp(refP/1.E10,ly2EOS.P[iit,id0],ly2EOS.rho[id0]) 

252 Smantle = npy.interp(mantlepotT,refP_T,refP_S)*1e3 

253 

254 # first extract the isentropes for the planet from the EOS tables 

255 mantle = eos.isentrope_class(Smantle,layer2) 

256 

257 Tcmb_accept = False 

258 

259 # overall loop to allow core temperature adjustment (no max iterations!) 

260 while not Tcmb_accept: 

261 

262 core = eos.isentrope_class(Score,layer1) 

263 

264 if plot: 

265 PREM = PREMclass() 

266 #print(PREM.temperature,PREM.pressure) 

267 fig = plt.figure(figsize=(7,5)) 

268 plt.plot(PREM.pressure,PREM.temperature,'-.',color='xkcd:deep blue',label='PREM profile') 

269 plt.plot(mantle.pressure,mantle.temperature,'-',color='xkcd:purple',label='mantle isentrope',markersize=10) 

270 plt.plot(core.pressure,core.temperature,'-',color='xkcd:tangerine',label='core isentrope',markersize=10) 

271 

272 plt.plot(ly2EOS.mc.Pl,ly2EOS.mc.T,'-',color='black',label='forsterite MC',markersize=10) 

273 plt.plot(ly1EOS.mc.Pl,ly1EOS.mc.T,'--',color='black',label='iron MC',markersize=10) 

274 

275 plt.ylim(0.,max(PREM.temperature)) 

276 plt.xlim(0,max(PREM.pressure)) 

277 plt.xlabel('Pressure (GPa)') 

278 plt.ylabel('Temperature (K)') 

279 plt.legend() 

280 plt.show() 

281 

282 if rhocent: 

283 rhocenter = rhocent 

284 else: 

285 rhocenter = 2*planet_density(mtotal/Mearth) 

286 changefac = 0.00003*rhocenter**4.2 

287 

288 if verbose: 

289 print('m:',mtotal/Mearth,'fac:',changefac,' rho:',rhocenter ) 

290 

291 r_est = (mtotal/(4./3.*npy.pi*rhocenter/2.))**(1./3.) 

292 dR = npy.floor(r_est/1e5)*1e5 / 3000 

293 # ensure dR is not too small 

294 if dR < 0.025e5: 

295 dR = 0.025e5 

296 

297 Pi = 0. 

298 rhoi = rhocenter 

299 

300 darr = npy.full(1,rhoi) 

301 parr = npy.full(1,Pi) 

302 rarr = npy.zeros(1) 

303 

304 planet = planet_profile() 

305 #planet.rarr = rarr 

306 #planet.density = darr 

307 #planet.pressure = parr 

308 

309 itercount = 0 

310 maxiter = 5000 

311 maxiterm = 5000 

312 

313 if mtolerance < 5e-4: 

314 changefac *= 0.2 

315 maxiterm *= 3 

316 dR *= 0.3 

317 elif mtolerance < 1e-3: 

318 changefac *= 0.4 

319 maxiterm *= 1.2 

320 dR *= 0.8 

321 

322 if verbose: 

323 print('dR: ', dR/1e5, 'km') 

324 

325 

326 # outer loop to find the correct total mass 

327 while npy.abs(mtotal-planet.M)/mtotal > mtolerance and itercount < maxiter: 

328 if (itercount%100 == 0 and itercount!=0 and verbose) or (itercount%10000 == 0 and itercount!=0): 

329 print(planet.pressure[0],planet.density[0],planet.M/mtotal) 

330 

331 rarr = npy.zeros(1) 

332 darr = npy.full(1,rhoi) # Pa 

333 parr = npy.full(1,npy.interp(rhoi,core.density,core.pressure)*1.E10) #  

334 tarr = npy.full(1,npy.interp(rhoi,core.density,core.temperature)) # K 

335 

336 #ri = rarr[0] 

337 #ii=1 

338 #coreiter=0 

339 

340 planet.reset() 

341 planet.M = 0. 

342 planet.rarr = rarr 

343 planet.density = darr 

344 planet.pressure = parr 

345 planet.temperature = tarr 

346 

347 # inner loop 1 to make core of required mass 

348 planet.add_isentropic_layer(mass=mcore,Pmin=Pmin,iendprevlayer=0,isentrope=core,dR=dR,maxiter=maxiterm,masstolerance=mtolerance) 

349 

350 iendcore = len(planet.rarr)-1 

351 

352 # inner loop 2 to add mantle up to surface pressure 

353 planet.add_isentropic_layer(mass=mtotal-mcore,Pmin=Pmin,iendprevlayer=iendcore,isentrope=mantle,dR=dR,maxiter=maxiterm,masstolerance=mtolerance) 

354 

355 # adjust initial density if total mass wrong 

356 if planet.M < mtotal: 

357 #rhoi *= 1.0+2*mtolerance*changefac 

358 #Pi *= 1.0+2*mtolerance*changefac 

359 rhoi *= 1.0 + (0.04*(mtotal-planet.M)/mtotal + 1.8*mtolerance)*changefac 

360 #Pi *= 1.0+2*mtolerance*changefac 

361 elif planet.M > mtotal: 

362 #rhoi *= 1.0-1*mtolerance*changefac 

363 #Pi *= 1.0-1*mtolerance*changefac 

364 rhoi *= 1.0 - (0.02*(planet.M-mtotal)/mtotal + 0.5*mtolerance)*changefac 

365 #Pi *= 1.0-1*mtolerance*changefac 

366 

367 itercount += 1 

368 

369 if not fixcoreT: 

370 Tcmb_accept = True 

371 

372 if planet.temperature[iendcore] < npy.interp(planet.pressure[iendcore]/1.E10,mantle.pressure,mantle.temperature): 

373 print('WARNING! Core colder than mantle! {:10.3f} {:10.3f} | S: {:.3f}'.format(planet.temperature[iendcore],npy.interp(planet.pressure[iendcore]/1.E10,mantle.pressure,mantle.temperature),Score)) 

374 if fixcoreT: 

375 Score += 0.01 

376 else: 

377 Tcmb_accept = True 

378 

379 print('Iterations: ',itercount,'\n') 

380 

381 planet.cf = mcore/planet.M 

382 #planet.mat = npy.where(npy.arange(len(planet.rarr))<=iendcore,0,1) 

383 #planet.entropy = npy.where(npy.arange(len(planet.rarr))<=iendcore,Score,Smantle)*1e7 

384 

385 print('MODEL PLANET:') 

386 print('Score (kJ/K/kg) = {:10.3f}'.format(Score)) 

387 print('Smantle (kJ/K/kg) = {:10.3f}'.format(Smantle)) 

388 print('Tcmb (K) = {:10.3f} [{:10.3f}]'.format(planet.temperature[iendcore],npy.interp(planet.pressure[iendcore]/1.E10,mantle.pressure,mantle.temperature))) 

389 print('Mantle Tp (K) = {:10.3f}'.format(planet.temperature[-1])) #min(tarr) 

390 print('Pcenter (GPa) = {:10.3f}'.format(planet.pressure[0]/1.E10)) 

391 print('Tcenter (K) = {:10.3f}'.format(planet.temperature[0])) 

392 print('rho center (g/cm3) = {:10.3f}'.format(planet.density[0])) 

393 print('Core radius (km, Rcmb) = {:10.3f}{:10.3f}'.format(planet.rarr[iendcore]/1.e5, planet.rarr[iendcore]/Rcmb)) 

394 print('CMB pressure (GPa) = {:10.3f}'.format(planet.pressure[iendcore]/1.E10)) 

395 print('Radius (km, Rearth) = {:10.3f}{:10.3f}'.format(planet.rarr[-1]/1.e5, planet.rarr[-1]/Rearth)) 

396 print('Surface pressure (GPa) = {:10.3f}'.format(planet.pressure[-1]/1.E10)) 

397 print('Surface gravity (m/s2) = {:10.3f}'.format(G*planet.M/planet.rarr[-1]/planet.rarr[-1]/100.)) 

398 print('Vesc (km/s) = {:10.3f}'.format(npy.sqrt(2*G*planet.M/planet.rarr[-1])/1.E5)) 

399 print('Mass/Mearth, Mcore/Mass = {:10.5f}{:10.4f}'.format(planet.M/Mearth, mcore/planet.M)) 

400 

401 return planet,core,mantle 

402 

403 

404def make_1D_NL_planet(mass=[0.3*Mearth,0.7*Mearth], Pmin=1.e6, S=[1.81,3.02], 

405 mtolerance=1e-3, layers=['iron','forsterite'], mantlepotT=False, plot=False, 

406 fixcoreT=False, verbose=False, rhocent=None): 

407 

408 mtotal = sum(mass) 

409 

410 Pcenter = 0 

411 

412 layerEOS = [] 

413 isentropes = [] 

414 for layer,layerS in zip(layers,S): 

415 EOS = eos.select(layer) 

416 if EOS is None: 

417 raise ValueError('Unknown EOS:',layer) 

418 layerEOS.append(EOS) 

419 if EOS.TYPE == 'HM80' or layerS == 'adiabat' or layerS == 'adiabatic': 

420 isentropes.append('adiabat') 

421 else: 

422 isentropes.append(eos.isentrope_class(layerS,layer)) 

423 

424 Tcmb_accept = False 

425 

426 # overall loop to allow core temperature adjustment (no max iterations!) 

427 while not Tcmb_accept: 

428 

429 isentropes[0] = eos.isentrope_class(S[0],layers[0]) 

430 

431 if plot: 

432 PREM = PREMclass() 

433 fig = plt.figure(figsize=(7,5)) 

434 plt.plot(PREM.pressure,PREM.temperature,'-.',color='xkcd:deep blue',label='PREM profile') 

435 for isentrope in isentropes: 

436 if isentrope == 'adiabat': 

437 continue 

438 plt.plot(isentrope.pressure,isentrope.temperature,label=str(isentrope.material)+' isentrope',markersize=10) 

439 

440 for EOS in layerEOS: 

441 if EOS.TYPE == 'ANEOS': 

442 plt.plot(EOS.mc.Pl,EOS.mc.T,'--',color='black',label=EOS.MODELNAME+' MC',markersize=10) 

443 

444 plt.ylim(0.,max(PREM.temperature)) 

445 plt.xlim(0,max(PREM.pressure)) 

446 plt.xlabel('Pressure (GPa)') 

447 plt.ylabel('Temperature (K)') 

448 plt.legend() 

449 plt.show() 

450 

451 if rhocent: 

452 rhocenter = rhocent 

453 else: 

454 rhocenter = 2*planet_density(mtotal/Mearth) 

455 changefac = 0.00003*rhocenter**4.2 

456 

457 if verbose: 

458 print('m:',mtotal/Mearth,'fac:',changefac,' rho:',rhocenter ) 

459 

460 r_est = (mtotal/(4./3.*npy.pi*rhocenter/2.))**(1./3.) 

461 dR = npy.floor(r_est/1e5)*1e5 / 3000 

462 # ensure dR is not too small 

463 if dR < 0.025e5: 

464 dR = 0.025e5 

465 

466 Pi = 0. 

467 rhoi = rhocenter 

468 

469 darr = npy.full(1,rhoi) 

470 parr = npy.full(1,Pi) 

471 rarr = npy.zeros(1) 

472 

473 planet = planet_profile() 

474 #planet.rarr = rarr 

475 #planet.density = darr 

476 #planet.pressure = parr 

477 

478 itercount = 0 

479 maxiter = 1000 

480 maxiterm = 5000 

481 

482 if mtolerance < 5e-4: 

483 changefac *= 0.2 

484 maxiterm *= 3 

485 dR *= 0.3 

486 elif mtolerance < 1e-3: 

487 changefac *= 0.4 

488 maxiterm *= 1.2 

489 dR *= 0.8 

490 

491 if verbose: 

492 print('dR: ', dR/1e5, 'km') 

493 

494 

495 # outer loop to find the correct total mass 

496 while npy.abs(mtotal-planet.M)/mtotal > mtolerance and itercount < maxiter: 

497 if (itercount%100 == 0 and verbose) or (itercount%10000 == 0 and itercount!=0): 

498 print(planet.pressure[0],planet.density[0],planet.M/mtotal) 

499 

500 rarr = npy.zeros(1) 

501 darr = npy.full(1,rhoi) # Pa 

502 parr = npy.full(1,npy.interp(rhoi,isentropes[0].density,isentropes[0].pressure)*1.E10) #  

503 tarr = npy.full(1,npy.interp(rhoi,isentropes[0].density,isentropes[0].temperature)) # K 

504 

505 planet.reset() 

506 planet.M = 0. 

507 planet.rarr = rarr 

508 planet.density = darr 

509 planet.pressure = parr 

510 planet.temperature = tarr 

511 

512 layerfinalindices = [] 

513 layermasses = [] 

514 # make layers of required masses 

515 for layermass, layerisentrope, EOS in zip(mass, isentropes, layerEOS): 

516 if layerisentrope == 'adiabat': 

517 planet.add_adiabatic_layer(mass=layermass,Pmin=Pmin,iendprevlayer=len(planet.rarr)-1,EOS=EOS,dR=dR,maxiter=maxiterm,masstolerance=mtolerance) 

518 else: 

519 planet.add_isentropic_layer(mass=layermass,Pmin=Pmin,iendprevlayer=len(planet.rarr)-1,isentrope=layerisentrope,dR=dR,maxiter=maxiterm,masstolerance=mtolerance) 

520 layerfinalindices.append(len(planet.rarr)-1) 

521 layermasses.append(planet.M-sum(layermasses)) 

522 

523 # adjust initial density if total mass wrong 

524 if planet.M < mtotal: 

525 #rhoi *= 1.0+2*mtolerance*changefac 

526 #Pi *= 1.0+2*mtolerance*changefac 

527 rhoi *= 1.0 + (0.04*(mtotal-planet.M)/mtotal + 1.8*mtolerance)*changefac 

528 #Pi *= 1.0+2*mtolerance*changefac 

529 elif planet.M > mtotal: 

530 #rhoi *= 1.0-1*mtolerance*changefac 

531 #Pi *= 1.0-1*mtolerance*changefac 

532 rhoi *= 1.0 - (0.02*(planet.M-mtotal)/mtotal + 0.5*mtolerance)*changefac 

533 #Pi *= 1.0-1*mtolerance*changefac 

534 

535 itercount += 1 

536 

537 if not fixcoreT: 

538 Tcmb_accept = True 

539 

540 if planet.temperature[layerfinalindices[0]] < npy.interp(planet.pressure[layerfinalindices[0]]/1.E10,isentropes[1].pressure,isentropes[1].temperature): 

541 print('WARNING! Core colder than mantle! {:10.3f} {:10.3f} | S: {:.3f}'.format(planet.temperature[layerfinalindices[0]],npy.interp(planet.pressure[layerfinalindices[0]]/1.E10,isentropes[1].pressure,isentropes[1].temperature),S[0])) 

542 if fixcoreT: 

543 S[0] += 0.01 

544 else: 

545 Tcmb_accept = True 

546 

547 print('Iterations: ',itercount,'\n') 

548 

549 planet.cf = layermasses[0]/planet.M 

550# planet.mat = npy.digitize(range(len(planet.rarr)),layerfinalindices,right=True) 

551## planet.entropy = npy.where(npy.arange(len(planet.rarr))<=iendcore,Score,Smantle)*1e7 

552 

553 print('MODEL PLANET:') 

554 print('Score (kJ/K/kg) = {:10.3f}'.format(S[0])) 

555 print('Smantle (kJ/K/kg) = {:10.3f}'.format(S[1])) 

556 print('Tcmb (K) = {:10.3f} [{:10.3f}]'.format(planet.temperature[layerfinalindices[0]],npy.interp(planet.pressure[layerfinalindices[0]]/1.E10,isentropes[1].pressure,isentropes[1].temperature))) 

557 print('Mantle Tp (K) = {:10.3f}'.format(planet.temperature[-1])) #min(tarr) 

558 print('Pcenter (GPa) = {:10.3f}'.format(planet.pressure[0]/1.E10)) 

559 print('Tcenter (K) = {:10.3f}'.format(planet.temperature[0])) 

560 print('rho center (g/cm3) = {:10.3f}'.format(planet.density[0])) 

561 print('Core radius (km, Rcmb) = {:10.3f}{:10.3f}'.format(planet.rarr[layerfinalindices[0]]/1.e5, planet.rarr[layerfinalindices[0]]/Rcmb)) 

562 print('CMB pressure (GPa) = {:10.3f}'.format(planet.pressure[layerfinalindices[0]]/1.E10)) 

563 print('Radius (km, Rearth) = {:10.3f}{:10.3f}'.format(planet.rarr[-1]/1.e5, planet.rarr[-1]/Rearth)) 

564 print('Surface pressure (GPa) = {:10.3f}'.format(planet.pressure[-1]/1.E10)) 

565 print('Surface gravity (m/s2) = {:10.3f}'.format(G*planet.M/planet.rarr[-1]/planet.rarr[-1]/100.)) 

566 print('Vesc (km/s) = {:10.3f}'.format(npy.sqrt(2*G*planet.M/planet.rarr[-1])/1.E5)) 

567 print('Mass/Mearth, Mcore/Mass = {:10.5f}{:10.4f}'.format(planet.M/Mearth, layermasses[0]/planet.M)) 

568 

569 return planet,isentropes 

570 

571 

572 

573def make_SPH_planet(mass=Mearth, corefraction=0.3, Pmin=1.e6, Score=1.81, Smantle=3.03, 

574 mtolerance=1e-3, layer1='alloy', layer2='forsterite', layers=[], S=[], mantlepotT=False, 

575 plot=False, resolution=5e5, fixcoreT=False, rhocent=None, verbose=False, profile=None): 

576 """ 

577 mass - list of layer masses (inside to out) or total mass of 2 layer planet 

578 corefraction - core mass fraction for 2 layer planet 

579 resolution - number of particles per Earth mass 

580 Pmin - surface pressure (Pa) 

581 Score - core entropy for 2 layer planet 

582 Smantle - 2nd layer entropy for 2 layer planet 

583 mtolerance - tolerance for total mass of planet 

584 layer1 - 1st layer material for 2 layer planet 

585 layer2 - 2nd layer material for 2 layer planet 

586 layers - list of materials for layers (inside to out) 

587 S - list of layer entropies (inside to out) 

588 mantlepotT - mantle potential temperature for 2 layer planet 

589 plot - plot pressure-temperature profile and x-y slice? 

590 fixcoreT - ensure outer core is at least as hot as inner mantle (2nd layer)? 

591 rhocent - initial central density to use (optional, use for troublesome cases) 

592 verbose - print extra information 

593 profile - 1D profile from which to make planet (if not supplied 1D prof will be generated) 

594 """ 

595 

596 if profile: 

597 planet = profile 

598 else: 

599 if len(layers) != len(S): 

600 raise ValueError('Number of layers must match number of entropies:', len(layers), len(S)) 

601 if not layers or len(layers) == 2: 

602 planet,core,mantle = make_1D_planet(plot=plot, mantlepotT=mantlepotT, layer1=layer1, layer2=layer2, mass=mass, corefraction=corefraction, Pmin=Pmin, Score=Score, Smantle=Smantle, mtolerance=mtolerance, fixcoreT=fixcoreT, verbose=verbose, layers=layers, S=S, rhocent=rhocent) 

603 isentropes = [core, mantle] 

604 else: 

605 planet,isentropes = make_1D_planet(plot=plot, mantlepotT=mantlepotT, layer1=layer1, layer2=layer2, mass=mass, corefraction=corefraction, Pmin=Pmin, Score=Score, Smantle=Smantle, mtolerance=mtolerance, fixcoreT=fixcoreT, verbose=verbose, layers=layers, S=S, rhocent=rhocent) 

606 

607 partmass = Mearth / resolution # mass per particle 

608 Np = int(planet.M / partmass) # desired total number of particles 

609 

610 if verbose: 

611 print(partmass,Np) 

612 print(planet.rarr) 

613 

614 # use seagen to generate spherical planet particles 

615 particleplanet = seagen.GenSphere(Np,planet.rarr[1:],planet.density[1:],A1_T_prof=planet.temperature[1:],A1_P_prof=planet.pressure[1:],A1_mat_prof=planet.mat[1:],verbosity=0, A1_m_rel_prof=1.0*npy.ones(len(planet.mat[1:])))#, A1_force_more_shells=[False,True]) 

616 #if len(layers) == 0: 

617 # ents = [Score,Smantle] 

618 if profile: 

619 if len(profile.entropy) > 0: 

620 u, ind = npy.unique(profile.entropy, return_index=True) 

621 ents = u[ind.argsort()] 

622 else: 

623 ents = npy.zeros(len(npy.unique(profile.mat))) 

624 else: 

625 ents = npy.zeros(len(isentropes)) 

626 for i in range(len(isentropes)): 

627 if isentropes[i] == 'adiabat': 

628 ents[i] = 0 

629 else: 

630 ents[i] = isentropes[i].entropy 

631 

632 setattr(particleplanet, "S", npy.array(ents)[particleplanet.mat]*1e7) 

633 

634 if verbose: 

635 print(npy.unique(particleplanet.A1_m)) 

636 print( (particleplanet.A1_m.max()-npy.mean(particleplanet.A1_m))/npy.mean(particleplanet.A1_m), (particleplanet.A1_m.min()-npy.mean(particleplanet.A1_m))/npy.mean(particleplanet.A1_m) ) 

637 

638 if plot: 

639 zcut = 100e5 

640 plt.scatter(particleplanet.A1_x[npy.abs(particleplanet.z)<zcut]/1e5,particleplanet.A1_y[npy.abs(particleplanet.z)<zcut]/1e5,c=particleplanet.rho[npy.abs(particleplanet.z)<zcut],s=5) 

641 plt.axis('equal') 

642 plt.colorbar(label='density') 

643 plt.show() 

644 

645 print('N:', particleplanet.N_picle) 

646 massresid = partmass-npy.unique(particleplanet.A1_m) 

647 if verbose: 

648 print('pm:', massresid.min()/partmass, massresid.max()/partmass) 

649 

650 # load particle planet into planit snapshot 

651 sn = Snapshot() 

652 sn.ic_from_seagen(particleplanet) 

653 if len(layers) == 0: 

654 sn.ensure_matIDs((layer1,layer2)) 

655 else: 

656 sn.ensure_matIDs(layers) 

657 

658 if verbose: 

659 print(sn.m.sum()/Mearth, sn.m.std()/Mearth) 

660 

661 sn.m = npy.ones(len(sn.m))*partmass # set all particle masses to calculated value 

662 

663 if verbose: 

664 print(sn.m.sum()/Mearth, sn.m.std()/Mearth) 

665 

666 if not profile: 

667 if len(layers) == 0: 

668 return planet, core, mantle, sn, particleplanet 

669 else: 

670 return planet, isentropes, sn, particleplanet 

671 else: 

672 return sn, particleplanet 

673 

674 

675 

676# <b>PREM</b> 

677# PREM is a one-dimensional average structure model for the Earth developed from seismic data. The original reference is:<br> 

678# <b>Dziewonski, A. M., and D. L. Anderson. 1981. "Preliminary reference Earth model." Phys. Earth Plan. Int. 25:297-356.</b> 

679#  

680# The 1D model has been updated by Panning and Romanowicz (2006). Download the Modified PREM model from the <a href="http://ds.iris.edu/spud/earthmodel/9785674">IRIS web site</a>. 

681#Durek, J. J., and G. Ekstrom (1996) Modified PREM (Preliminary Reference Earth Model), doi:10.17611/DP/9785674, http://ds.iris.edu/spud/earthmodel/9785674. 

682 

683class PREMclass: 

684 """Class to hold PREM data and other 1-D Earth variables.""" # this is a documentation string for this class 

685 def __init__(self): # self is the default name of the object for internal referencing of the variables in the class 

686 """A function to initialize the class object.""" # this is a documentation string for this function 

687 self.NR = 0 # number of radius points 

688 self.radius = npy.zeros(self.NR) 

689 self.density = npy.zeros(self.NR) 

690 #self.pwavevel = npy.zeros(self.NR)  

691 #self.swavevel = npy.zeros(self.NR) 

692 self.pressure = npy.zeros(self.NR) 

693 self.temperature = npy.zeros(self.NR) 

694 # not going to use all the variables in the file 

695 self.units = '' # I like to keep a text note in a structure about the units 

696 

697 self.load() 

698 

699 

700 def load(self,PREM_filename=datadir+'PREM500_IDV.csv'): 

701 # Read in PREM: Preliminary Earth Reference Model 

702 

703 self.radius, self.density = npy.loadtxt(PREM_filename, delimiter=',', skiprows=2, usecols=[0,1], unpack=True) # radius in m 

704 #self.density = npy.loadtxt(PREM_filename,delimiter=',',skiprows=2, usecols=[1]) # density in kg/m3 

705 ##self.pwavevel = npy.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[2]) # p-wave velocity m/s 

706 ##self.swavevel = npy.loadtxt(PREM_filename,delimiter=',',skiprows=2,usecols=[3]) # s-wave velocity m/s 

707 self.NR = len(self.radius) # number of radius points 

708 self.units = 'radius (m), density (kg/m3)'#, pwavevel (m/s), swavevel (m/s)' 

709 

710 # start at the surface and integrate via a for loop to the center of the planet 

711 

712 # calculate the thickness of each layer in the PREM model using the roll function 

713 PREM_dr = npy.roll(self.radius,-1)-self.radius 

714 PREM_dr[self.NR-1] = 0. # we are not using the last entry in the list because there are NR-1 layers 

715 #print(PREM_dr) 

716 

717 # calculate the mass of each layer 

718 # density x area x thickness of each layer 

719 PREM_mass_rad = self.density*(4.*npy.pi*self.radius*self.radius*PREM_dr) 

720 

721 # core radius 

722 ir0 = npy.where(self.density < 6000.)[0] 

723 PREM_rcore = self.radius[ir0[0]] 

724 

725 self.pressure = npy.zeros(self.NR) # make array of zeros for pressure of the same length as the arrays in the PREM model 

726 # The first entry is the middle of the planet, so start at the surface and integrate inwards 

727 for i in range(self.NR-2,0,-1): 

728 self.pressure[i] = self.pressure[i+1]+G_mks*npy.sum(PREM_mass_rad[0:i-1])*self.density[i]*PREM_dr[i]/self.radius[i]/self.radius[i] 

729 

730 PREM_mass_enclosed = npy.zeros(self.NR) # make a new array 

731 for i in range(1,self.NR): 

732 PREM_mass_enclosed[i] = npy.sum(PREM_mass_rad[0:i]) 

733 

734 # use SESAME units 

735 self.pressure = self.pressure/1.E9 # GPa 

736 

737 Anzellini_filename = datadir+'Anzellini-2013-Science-coretemp.csv' 

738 Anzellini_pressure, Anzellini_temperature = npy.loadtxt(Anzellini_filename, delimiter=',',skiprows=0, unpack=True) # GPa, K 

739 Anzellini_pressure[0] = 0. 

740 #Anzellini_temperature = npy.loadtxt(Anzellini_filename,delimiter=',',skiprows=0,usecols=[1]) # K 

741 # we want to use this data with PREM but it doesn't have the same number of points 

742 # interpolate the Anzellini profile to match the PREM profile 

743 # the following defines a function = y(x) 

744 interp_func = interpolate.interp1d(Anzellini_pressure,Anzellini_temperature,fill_value="extrapolate") 

745 self.temperature = interp_func(self.pressure) 

746 

747 self.pressure = self.pressure[1:] 

748 self.temperature = self.temperature[1:] 

749 

750 

751 

752def plot_planet_prof(planet,particleplanet=None,show=False,path=False,coreEOS='iron',mantleEOS='Forsterite',logaxes=False): 

753 if particleplanet: 

754 inclpart = True 

755 if not hasattr(particleplanet, 'r'): 

756 particleplanet.r = npy.sqrt(particleplanet.x**2 + particleplanet.y**2 + particleplanet.z**2) 

757 

758 if planet.M >= 0.1*Mearth: 

759 showPREM = True 

760 PREM = PREMclass() 

761 else: 

762 showPREM = False 

763 

764 cEOS = eos.select(coreEOS) 

765 if cEOS is None: 

766 print('Unknown core EOS') 

767 return 

768 mEOS = eos.select(mantleEOS) 

769 if mEOS is None: 

770 print('Unknown core EOS') 

771 return 

772 

773 fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(8,12)) 

774 plt.subplots_adjust(wspace=0.25) 

775 #------------------------------ 

776 ai=0 

777 aj=0 

778 axes[ai,aj].set_xlabel('Radius (km)') 

779 axes[ai,aj].set_ylabel('Density (g/cm$^3$)') 

780 if inclpart: 

781 axes[ai,aj].scatter(particleplanet.r/1e5,particleplanet.rho,s=6,c=particleplanet.S/1e7,vmax=4.) 

782 axes[ai,aj].plot(planet.rarr/1.e5,planet.density,'-',color='xkcd:purple',label='Planet model') 

783 if showPREM: 

784 axes[ai,aj].plot(PREM.radius/1.e3,PREM.density/1.e3,'-.',color='xkcd:deep blue',label='PREM (Earth)') 

785 axes[ai,aj].set_title(str(planet.M/Mearth)[0:6]+" (Mearth) Total Mass") 

786 if logaxes: 

787 axes[ai,aj].semilogy() 

788 

789 #------------------------------ 

790 ai=0 

791 aj=1 

792 axes[ai,aj].set_xlabel('Radius (km)') 

793 axes[ai,aj].set_ylabel('Pressure (GPa)') 

794 

795 if inclpart: 

796 axes[ai,aj].scatter(particleplanet.r/1e5,particleplanet.P/1e10,s=6,c=particleplanet.S/1e7,vmax=4.) 

797 axes[ai,aj].plot(planet.rarr/1.e5,planet.pressure/1.e10,'-',color='xkcd:purple',label='Planet model') 

798 if showPREM: 

799 axes[ai,aj].plot(PREM.radius[1:]/1.e3,PREM.pressure,'-.',color='xkcd:deep blue',label='PREM (Earth)') 

800 axes[ai,aj].set_title(str(planet.cf)[0:6]+" Core Mass Fraction") 

801 

802 if logaxes: 

803 axes[ai,aj].semilogy() 

804 

805 #------------------------------ 

806 ai=1 

807 aj=0 

808 axes[ai,aj].set_xlabel('Radius (km)') 

809 axes[ai,aj].set_ylabel('Temperature (K)') 

810 

811 if inclpart: 

812 axes[ai,aj].scatter(particleplanet.r/1e5,particleplanet.T,s=6,c=particleplanet.S/1e7,vmax=4.) 

813 axes[ai,aj].plot(planet.rarr/1.e5,planet.temperature,'-',color='xkcd:purple',label='Planet model') 

814 if showPREM: 

815 axes[ai,aj].plot(PREM.radius[1:]/1.e3,PREM.temperature,'-.',color='xkcd:deep blue',label='Anzellini et al. 2013 (Earth)') 

816 

817 #------------------------------ 

818 ai=1 

819 aj=1 

820 

821 axes[ai,aj].set_xlabel('Pressure (GPa)') 

822 axes[ai,aj].set_ylabel('Temperature (K)') 

823 if mEOS.mc.NT > 0: 

824 axes[ai,aj].plot(mEOS.mc.Pl,mEOS.mc.T,'-',color='black',label='Forsterite melt curve',markersize=10) 

825 if cEOS.mc.NT > 0: 

826 axes[ai,aj].plot(cEOS.mc.Pl,cEOS.mc.T,'--',color='black',label=coreEOS+' melt curve') 

827 

828 if inclpart: 

829 axes[ai,aj].scatter(particleplanet.P/1e10,particleplanet.T,s=6,c=particleplanet.S/1e7,vmax=4.) 

830 axes[ai,aj].plot(planet.pressure/1.e10,planet.temperature,'-',color='xkcd:purple',label='Planet model') 

831 if showPREM: 

832 axes[ai,aj].plot(PREM.pressure,PREM.temperature,'-.',color='xkcd:deep blue',label='Anzellini et al. 2013 (Earth)') 

833 

834 

835 axes[ai,aj].set_ylim(0,1.2*max(planet.temperature)) 

836 axes[ai,aj].set_xlim(0,1.2*max(planet.pressure/1.e10)) 

837 

838 #------------------------------ 

839 ai=2 

840 aj=0 

841 

842 axes[ai,aj].set_ylabel('Pressure (GPa)') 

843 axes[ai,aj].set_xlabel('Entropy (kJ K$^{-1}$ kg$^{-1}$)') 

844 

845 if mEOS.mc.NT > 0: 

846 axes[ai,aj].plot(mEOS.mc.Sl*1e3,mEOS.mc.Pl,'-',color='black',label=mantleEOS+' PB') 

847 axes[ai,aj].plot(mEOS.mc.Ss*1e3,mEOS.mc.Ps,'-',color='black',markersize=10) 

848 if cEOS.mc.NT > 0: 

849 axes[ai,aj].plot(cEOS.mc.Sl*1e3,cEOS.mc.Pl,'--',color='black',label=coreEOS+' PB') 

850 axes[ai,aj].plot(cEOS.mc.Ss*1e3,cEOS.mc.Ps,'--',color='black') 

851 

852 axes[ai,aj].plot(mEOS.vc.Sl*1e3,mEOS.vc.Pl,'-',color='black',markersize=10) 

853 axes[ai,aj].plot(cEOS.vc.Sl*1e3,cEOS.vc.Pl,'--',color='black',markersize=10) 

854 axes[ai,aj].plot(mEOS.vc.Sv*1e3,mEOS.vc.Pv,'-',color='black',markersize=10) #label='forsterite VD' 

855 axes[ai,aj].plot(cEOS.vc.Sv*1e3,cEOS.vc.Pv,'--',color='black',markersize=10) #label='iron VD' 

856 

857 if inclpart: 

858 axes[ai,aj].scatter(particleplanet.S/1e7,particleplanet.P/1e10,s=6,c=particleplanet.S/1e7,vmax=4.) 

859 axes[ai,aj].plot(planet.entropy/1e7,planet.pressure/1.e10,'-',color='xkcd:purple',label='Planet model') 

860 

861 axes[ai,aj].set_xlim(1,10.) 

862 axes[ai,aj].set_ylim(0,max(planet.pressure/1.e10)) 

863 

864 #------------------------------ 

865 ai=2 

866 aj=1 

867 

868 axes[ai,aj].set_ylabel('Pressure (GPa)') 

869 axes[ai,aj].set_xlabel('Entropy (kJ K$^{-1}$ kg$^{-1}$)') 

870 

871 if mEOS.mc.NT > 0: 

872 axes[ai,aj].plot(mEOS.mc.Sl*1e3,mEOS.mc.Pl,'-',color='black',label=mantleEOS + ' PB') 

873 axes[ai,aj].plot(mEOS.mc.Ss*1e3,mEOS.mc.Ps,'-',color='black',markersize=10) 

874 axes[ai,aj].plot(mEOS.vc.Sl*1e3,mEOS.vc.Pl,'-',color='black',markersize=10) 

875 axes[ai,aj].plot(mEOS.vc.Sv*1e3,mEOS.vc.Pv,'-',color='black',markersize=10) #label='forsterite VD' 

876 if cEOS.mc.NT > 0: 

877 axes[ai,aj].plot(cEOS.mc.Sl*1e3,cEOS.mc.Pl,'--',color='black',label=coreEOS+' PB') 

878 axes[ai,aj].plot(cEOS.mc.Ss*1e3,cEOS.mc.Ps,'--',color='black') 

879 

880 axes[ai,aj].plot(cEOS.vc.Sl*1e3,cEOS.vc.Pl,'--',color='black',markersize=10) 

881 axes[ai,aj].plot(cEOS.vc.Sv*1e3,cEOS.vc.Pv,'--',color='black',markersize=10) #label='iron VD' 

882 

883 if inclpart: 

884 axes[ai,aj].scatter(particleplanet.S/1e7,particleplanet.P/1e10,s=6,c=particleplanet.S/1e7,vmax=4.) 

885 axes[ai,aj].plot(planet.entropy/1e7,planet.pressure/1.e10,'-',color='xkcd:purple',label='Planet model') 

886 

887 axes[ai,aj].set_xlim(1,10.) 

888 axes[ai,aj].set_ylim(1e-5,max(planet.pressure/1.e10)) 

889 axes[ai,aj].semilogy() 

890 

891 # don't show a plot in lower right 

892 #axes[2,1].axis("off") 

893 

894 axes[0,0].legend() 

895 axes[0,1].legend() 

896 axes[1,0].legend() 

897 axes[1,1].legend() 

898 axes[2,0].legend() 

899 axes[2,1].legend() 

900 

901 if path: 

902 plt.savefig(path, format='pdf', dpi=300,transparent=True) 

903 

904 if show: 

905 plt.show() 

906 

907 

908 

909### in progress... 

910class EquilRun: 

911 def __init__(self): 

912 self.M = 0 

913 self.N = 0 

914 self.nsnaps = 0 

915 self.data = None 

916 self.prof1D = planet_profile() 

917 self.radp = npy.empty(0) 

918 self.radp1 = npy.empty(0) 

919 self.radmax = npy.empty(0) 

920 self.times = npy.empty(0) 

921 self.Sc = npy.empty(0) 

922 self.Sm = npy.empty(0) 

923 #P = npy.empty(0) 

924 #T = npy.empty(0) 

925 self.rhoc = npy.empty(0) 

926 self.rhom = npy.empty(0) 

927 self.ke = npy.empty(0) 

928 #ie = npy.empty(0) 

929 self.pe = npy.empty(0) 

930 self.v = npy.empty(0) 

931 

932 

933 def load(self, loc, thermo=False, inter=1, fname1D='planetprofile.dat',names1='equil_',names2='equilB_', icfile='planetIC.sw.hdf5'): 

934 """for gadget standard set names1 to 'snapshot_' and names2 to None""" 

935 N1 = N2 = 0 

936 f1 = f2 = [] 

937 

938 if names1: 

939 f1 = sorted(glob.glob(loc+names1+'*[!yml]')) 

940 N = [(f1[x].split('/')[-1]).split('_')[1].split('.')[0] for x in range(len(f1))] 

941 print(N) 

942 N1 = int(sorted(npy.array(N).astype(int))[-1]) 

943 if names2: 

944 f2 = sorted(glob.glob(loc+names2+'*[!yml]')) 

945 N = [(f2[x].split('/')[-1]).split('_')[1].split('.')[0] for x in range(len(f2))] 

946 N2 = int(sorted(npy.array(N).astype(int))[-1]) 

947 

948 print(N1,N2) 

949 

950 fnums = npy.arange(0,N1+N2,1) 

951 print(loc,fnums[::5]) 

952 

953 files = npy.array(f1+f2)[::inter] 

954 files = npy.append(npy.array(loc+icfile),files) 

955 self.nsnaps = len(files) 

956 self.data = npy.ndarray((self.nsnaps,),dtype=object) 

957 

958 self.prof1D.load(loc+fname1D) 

959 

960 radp = [] 

961 radp1 = [] 

962 radmax = [] 

963 times = [] 

964 Sc = [] 

965 Sm = [] 

966 P = [] 

967 T = [] 

968 rhoc = [] 

969 rhom = [] 

970 ke = [] 

971 pe = [] 

972 ie = [] 

973 v = [] 

974 

975 for i in range(self.nsnaps): 

976 honly = True #False #True 

977 if i==0 or i==1 or i==self.nsnaps: 

978 honly = False 

979 self.data[i] = Snapshot() 

980 print(files[i]) 

981 self.data[i].load(files[i],headonly=honly,thermo=thermo) 

982 

983 #rr = npy.sqrt( (s.x - (s.x[s.pot==s.pot.min()])[0])**2 + (s.y - (s.y[s.pot==s.pot.min()])[0])**2 + (s.z - (s.z[s.pot==s.pot.min()])[0])**2) 

984 #rr = npy.sqrt( (s.x-s.x.mean())**2 + (s.y-s.y.mean())**2 + (s.z-s.z.mean())**2 ) 

985 rr = npy.sqrt( (self.data[i].x-npy.average(self.data[i].x,weights=self.data[i].m))**2 + (self.data[i].y-npy.average(self.data[i].y,weights=self.data[i].m))**2 + (self.data[i].z-npy.average(self.data[i].z,weights=self.data[i].m))**2 ) 

986 radp.append(npy.median(npy.sort(rr)[-int(0.02*self.data[i].N):-1])) 

987 radp1.append(npy.median(npy.sort(rr)[-int(0.01*self.data[i].N):-1])) 

988 radmax.append(rr.max()) 

989 #if npy.ndim(self.data[i].header.time)==0: 

990 # times.append(self.data[i].header.time/3600.) 

991 #else: 

992 # times.append(self.data[i].header.time[0]/3600.) 

993 Sc.append((self.data[i].S[self.data[i].id<GADGET_EOS_OFFSET]).mean()) 

994 Sm.append((self.data[i].S[self.data[i].id>=GADGET_EOS_OFFSET]).mean()) 

995 #P.append(s.P.mean()) 

996 #T.append(s.T.mean()) 

997 rhoc.append(self.data[i].rho[self.data[i].id<GADGET_EOS_OFFSET].mean()) 

998 rhom.append(self.data[i].rho[self.data[i].id>=GADGET_EOS_OFFSET].mean()) 

999 ke.append( (self.data[i].m*0.5*(self.data[i].vx**2 + self.data[i].vy**2 + self.data[i].vz**2)).sum() ) 

1000 #ie.append( (self.data[i].m*self.data[i].U).sum() ) 

1001 pe.append( (self.data[i].m * 0.5*self.data[i].pot).sum() ) 

1002 v.append( npy.sqrt( (self.data[i].vx**2 + self.data[i].vy**2 + self.data[i].vz**2).mean() ) ) #+s.vy**2+s.vz**2 

1003 

1004 #print(times) 

1005 self.radp = npy.array(radp) 

1006 self.radp1 = npy.array(radp1) 

1007 self.radmax = npy.array(radmax) 

1008 self.times = npy.array(times) 

1009 self.Sc = npy.array(Sc) 

1010 self.Sm = npy.array(Sm) 

1011 #P = npy.array(P) 

1012 #T = npy.array(T) 

1013 self.rhoc = npy.array(rhoc) 

1014 self.rhom = npy.array(rhom) 

1015 self.ke = npy.array(ke) 

1016 #ie = npy.array(ie) 

1017 self.pe = npy.array(pe) 

1018 self.v = npy.array(v) 

1019 

1020 self.vesc = npy.sqrt( 2*G*self.data[i].m.sum()/radmax[0] ) 

1021 #minpe = self.pe.min() 

1022 #pe = pe - minpe 

1023 

1024 #energy = ke+ie+pe 

1025 

1026 

1027 def equil_mov_plot(n,scale='Mm'): 

1028 recenter = True 

1029 thermo=False 

1030 ncol=4 

1031 tmax = 24 #24. #12 

1032 if times[-1]<tmax: 

1033 tmax=times[-1]*1.01 

1034 

1035 rhomin=5e-2 #5e5 

1036 rhomax=10. 

1037 Smin = 1.5 

1038 Smax = 4. #10. 

1039 

1040 zcutl = -0.2 #2.5 

1041 zcuth = 0.2 #2.5 

1042 vcut = 1e18 

1043 

1044 lpos=16.6 

1045 

1046 Ng=401j 

1047 Ngz=61j 

1048 #xmin=-8 

1049 #xmax=8 

1050 #ymin=-8 

1051 #ymax=8 

1052 #zmin=-8 

1053 #zmax=8 

1054 cmap = plt.get_cmap('plasma').copy() 

1055 cmap.set_under('k') 

1056 

1057 if scale=='Mm': 

1058 scf = 1e8 

1059 elif scale=='km': 

1060 scf = 1e5 

1061 elif scale=='earth' or scale=='Earth': 

1062 scf = 6.371e8 

1063 else: 

1064 scf = scale 

1065 axlim = 4*int(npy.ceil((self.data[0].x.max()-self.data[0].x.min())/scf/8.)) 

1066 zcut = axlim/200.*scf 

1067 

1068 zmin=-axlim/10. 

1069 zmax=axlim/10. 

1070 zi=npy.linspace(zmin,zmax,int(Ngz.imag)) 

1071 X,Y,Z = npy.mgrid[-axlim:axlim:(Ng),-axlim:axlim:(Ng),zmin:zmax:(Ngz)] 

1072 

1073 

1074 print(n) 

1075 #ke[n] i = ( (self.data[i].m*0.5*(self.data[i].vx**2 + s.vy**2 + s.vz**2)).sum() ) 

1076 ##iei = ( (s.m*s.U).sum() ) 

1077 #pei = ( (s.m * 0.5*s.pot).sum() ) - minpe 

1078 #if code=='gadget': 

1079 # ti = ( s.header.time )/3600. 

1080 #elif code=='swift': 

1081 # ti = ( s.header.time )[0]/3600. 

1082 #rr = npy.sqrt( (s.x-s.x.mean())**2 + (s.y-s.y.mean())**2 + (s.z-s.z.mean())**2 ) 

1083 #rr = npy.sqrt( (s.x-npy.average(s.x,weights=s.m))**2 + (s.y-npy.average(s.y,weights=s.m))**2 + (s.z-npy.average(s.z,weights=s.m))**2 ) 

1084 #rr = npy.sqrt( (s.x - (s.x[s.pot==s.pot.min()])[0])**2 + (s.y - (s.y[s.pot==s.pot.min()])[0])**2 + (s.z - (s.z[s.pot==s.pot.min()])[0])**2) 

1085 #radpi = (npy.median(npy.sort(rr)[-int(0.02*s.N):-1])) 

1086 #radp1i = (npy.median(npy.sort(rr)[-int(0.01*s.N):-1])) 

1087 #radmaxi = (rr.max()) 

1088 #Sci = ((s.S[s.id<GADGET_EOS_OFFSET]).mean()) 

1089 #Smi = ((s.S[s.id>=GADGET_EOS_OFFSET]).mean()) 

1090 #rhoci = (s.rho[s.id<GADGET_EOS_OFFSET].mean()) 

1091 #rhomi = (s.rho[s.id>=GADGET_EOS_OFFSET].mean()) 

1092 #veli = ( npy.sqrt( (s.vx**2 + s.vy**2 + s.vz**2).mean() ) ) 

1093 #print(ti) 

1094 

1095 

1096 #if recenter: 

1097 x = self.data[i].x - (self.data[i].x[self.data[i].pot==self.data[i].pot.min()])[0] 

1098 y = self.data[i].y - (self.data[i].y[self.data[i].pot==self.data[i].pot.min()])[0] 

1099 z = self.data[i].z - (self.data[i].z[self.data[i].pot==self.data[i].pot.min()])[0] 

1100 rr = npy.sqrt(x**2+y**2+z**2) 

1101 

1102 vi = interpolate.griddata((x[self.data[i].vx<vcut]/scf,y[self.data[i].vx<vcut]/scf,z[self.data[i].vx<vcut]/scf),self.data[i].rho[self.data[i].vx<vcut],(X,Y,Z),method='linear',fill_value=1.e-18) 

1103 

1104 coz = (z[self.data[i].pot==self.data[i].pot.min()])[0] 

1105 nn=(npy.nonzero(zi==(zi[zi<=coz])[-1])[0])[0] 

1106 

1107 

1108 plt.clf() 

1109 

1110 # density plot (fluid) 

1111 gs = gridspec.GridSpec(2, ncol) 

1112 plt.subplot(gs[0, 0]) 

1113 #plt.subplot2grid((2, ncol), (0, 0)) 

1114 plt.minorticks_on() 

1115 

1116 im = plt.imshow(vi[:,:,nn].T,origin='lower',extent=[-axlim,axlim,-axlim,axlim],cmap=cmap,norm=matplotlib.colors.LogNorm(vmin=rhomin,vmax=rhomax,clip=False)) 

1117 plt.ylabel('$y$ (Mm)') 

1118 ax=plt.gca() 

1119 ax.tick_params(colors='w',which='both',labelcolor='k') 

1120 ax.spines['top'].set_color('w') 

1121 ax.spines['bottom'].set_color('w') 

1122 ax.spines['left'].set_color('w') 

1123 ax.spines['right'].set_color('w') 

1124 ax.xaxis.set_major_locator(ticker.MultipleLocator(10.00)) 

1125 ax.xaxis.set_minor_locator(ticker.MultipleLocator(2.00)) 

1126 ax.yaxis.set_major_locator(ticker.MultipleLocator(10.00)) 

1127 ax.yaxis.set_minor_locator(ticker.MultipleLocator(2.00)) 

1128 ax.xaxis.set_ticklabels('') 

1129 

1130 cbar_ax = fig.add_axes([0.240, 0.58, 0.008, 0.41]) 

1131 cbar = fig.colorbar(im, cax=cbar_ax,label=r'$\rho$ (g$\,$cm$^{-3}$)') 

1132 cbar_ax.yaxis.set_label_coords(5.,0.5) 

1133 #plt.colorbar(fraction=0.0466,pad=0.01,label=r'$\rho$ (g$\,$cm$^{-3}$)') 

1134 

1135 # entropy plot (particle) 

1136 plt.subplot(gs[1,0]) 

1137 #plt.subplot2grid((2, ncol), (1, 0)) 

1138 plt.minorticks_on() 

1139 

1140 Splt = plt.scatter( (x)[(z>-zcut)*(z<zcut)]/scf, (y)[(z>-zcut)*(z<zcut)]/scf,s=0.5,marker='o',c=self.data[i].S[(z>-zcut)*(s.z<zcut)]/1e7,edgecolor='none',vmin=Smin,vmax=Smax) 

1141 #plt.scatter( (s.x)[(s.z>zcutl)*(s.z<zcuth)*(s.id<GADGET_EOS_OFFSET)], (s.y)[(s.z>zcutl)*(s.z<zcuth)*(s.id<GADGET_EOS_OFFSET)],s=0.5,marker='o',c=s.S[(s.z>zcutl)*(s.z<zcuth)*(s.id<GADGET_EOS_OFFSET)]/1e7,edgecolor='none') 

1142 plt.axis([-axlim,axlim,-axlim,axlim]) 

1143 plt.text(0.94,0.94,'{:.1f}'.format(ti),ha='right',va='top',fontsize=8,color='k',transform=plt.gca().transAxes) 

1144 plt.ylabel('$y$ (Mm)') 

1145 plt.xlabel('$x$ (Mm)') 

1146 ax=plt.gca() 

1147 ax.set_aspect(aspect=1.) 

1148 ax.xaxis.set_major_locator(ticker.MultipleLocator(10.00)) 

1149 ax.xaxis.set_minor_locator(ticker.MultipleLocator(2.00)) 

1150 ax.yaxis.set_major_locator(ticker.MultipleLocator(10.00)) 

1151 ax.yaxis.set_minor_locator(ticker.MultipleLocator(2.00)) 

1152 cbar_ax = fig.add_axes([0.240, 0.1, 0.008, 0.41]) 

1153 cbar = fig.colorbar(Splt, cax=cbar_ax,label=r'$S$ (J$\,$K$^{-1}\,$g$^{-1}$)') 

1154 cbar_ax.yaxis.set_label_coords(5.,0.5) 

1155 

1156 gs.update(top=0.99,bottom=0.1,left=0.065,right=0.98,hspace=0.16,wspace=0.4) 

1157 

1158 

1159 #radius plot 

1160 gs2 = gridspec.GridSpec(2, ncol) 

1161 plt.subplot(gs2[0, 1]) 

1162 #plt.subplot2grid((2, ncol), (0, 1))#, rowspan=2,colspan=2) 

1163 plt.minorticks_on() 

1164 

1165 plt.axvline(ti,c='0.5') 

1166 plt.plot(self.data[:].header.time,(radp/(radp1[0]))[times<tmax],color='xkcd:deep rose',lw=1.,label='outer 2%') #,marker='+' 

1167 plt.plot(times[times<tmax],(radp1/(radp1[0]))[times<tmax],color='xkcd:purple',lw=1.,label='outer 1%') 

1168 plt.plot(times[times<tmax],(radmax/(radp1[0]))[times<tmax],color='xkcd:tangerine',lw=1.,label='max') 

1169 

1170 plt.plot(ti,(radp[n]/(radp1[0])),ms=2,marker='o', color='xkcd:deep rose') 

1171 plt.plot(ti,(radp1[n]/(radp1[0])),ms=2,marker='o', color='xkcd:purple') 

1172 plt.plot(ti,(radmax[n]/(radp1[0])),ms=2,marker='o', color='xkcd:tangerine') 

1173 

1174 #plt.ylim([0.,1.02]) 

1175 plt.xlim(xmin=0) 

1176 plt.xlim(xmax=tmax) 

1177 #plt.xlabel('Time (hrs)') 

1178 plt.ylabel(u'R/R$_\mathrm{init}$') 

1179 plt.legend() 

1180 ax=plt.gca() 

1181 ax.xaxis.set_major_locator(ticker.MultipleLocator(5.)) 

1182 ax.xaxis.set_minor_locator(ticker.MultipleLocator(1.)) 

1183 

1184 

1185 #density profile plot 

1186 plt.subplot(gs2[0, 2]) 

1187 plt.minorticks_on() 

1188 

1189 plt.plot(planet1D.rarr/Rearth,planet1D.density,color='xkcd:purple',lw=1.) #,marker='+' 

1190 plt.scatter(rr/Rearth,self.data[i].rho,s=1,marker='o', c=s.id, vmax=400000000) 

1191 

1192 plt.ylim([0.,1.1*planet1D.density.max()]) 

1193 plt.xlim([0.,1.05*planet1D.rarr.max()/Rearth]) 

1194 #plt.xlabel('Radius (R$_\oplus$)') 

1195 plt.ylabel(u'Density (g$\,$cm$^{-3}$)') 

1196 

1197 

1198 #entropy profile plot 

1199 plt.subplot(gs2[1, 2]) 

1200 plt.minorticks_on() 

1201 

1202 plt.plot(planet1D.rarr/Rearth,planet1D.entropy/1e7,color='xkcd:purple',lw=1.) #,marker='+' 

1203 plt.scatter(rr/Rearth,self.data[i].S/1e7,s=1,marker='o', c=s.id, vmax=400000000) 

1204 

1205 plt.ylim([0.,1.2*planet1D.entropy.max()/1e7]) 

1206 plt.xlim([0.,1.05*planet1D.rarr.max()/Rearth]) 

1207 plt.xlabel('Radius (R$_\oplus$)') 

1208 plt.ylabel(u'Entropy (J$\,$K$^{-1}\,$g$^{-1}$)') 

1209 

1210 

1211 #velocity plot 

1212 plt.subplot(gs2[0, 3]) 

1213 #plt.subplot2grid((2, ncol), (0, 2))#, rowspan=2,colspan=2) 

1214 plt.minorticks_on() 

1215 

1216 plt.axvline(ti,c='0.5') 

1217 plt.plot(times[times<tmax],(v/vesc)[times<tmax],color='xkcd:purple',lw=1.) #,marker='+' 

1218 

1219 plt.plot(ti,(veli/vesc),ms=2,marker='o', color='xkcd:purple') 

1220 

1221 #plt.ylim([0.,1.02]) 

1222 plt.xlim(xmin=0) 

1223 plt.xlim(xmax=tmax) 

1224 plt.xlabel('Time (hrs)') 

1225 plt.ylabel(u'v$_\mathrm{rms}$/v$_\mathrm{esc}$') 

1226 plt.legend() 

1227 ax=plt.gca() 

1228 ax.xaxis.set_major_locator(ticker.MultipleLocator(5.)) 

1229 ax.xaxis.set_minor_locator(ticker.MultipleLocator(1.)) 

1230 

1231 

1232 #mean entropy plot 

1233 plt.subplot(gs2[1, 1]) 

1234 #plt.subplot2grid((2, ncol), (1, 1))#, rowspan=2,colspan=2) 

1235 plt.minorticks_on() 

1236 

1237 plt.axvline(ti,c='0.5') 

1238 plt.plot(times[times<tmax],(Sm/Sm[0])[times<tmax],color='xkcd:purple',lw=1.,label='mantle') #,marker='+' 

1239 plt.plot(times[times<tmax],(Sc/Sc[0])[times<tmax],color='xkcd:tangerine',lw=1.,label='core') #,marker='+' 

1240 

1241 plt.plot(ti,(Smi/Sm[0]),ms=2,marker='o', color='xkcd:purple') 

1242 plt.plot(ti,(Sci/Sc[0]),ms=2,marker='o', color='xkcd:tangerine') 

1243 

1244 #plt.ylim([0.,1.02]) 

1245 plt.xlim(xmin=0) 

1246 plt.xlim(xmax=tmax) 

1247 plt.xlabel('Time (hrs)') 

1248 plt.ylabel(u'S/S$_\mathrm{init}$') 

1249 plt.legend() 

1250 ax=plt.gca() 

1251 ax.xaxis.set_major_locator(ticker.MultipleLocator(5.)) 

1252 ax.xaxis.set_minor_locator(ticker.MultipleLocator(1.)) 

1253 

1254 

1255 #energy plot 

1256 if thermo: 

1257 plt.subplot(gs2[1, 3]) 

1258 #plt.subplot2grid((2, ncol), (1, 2))#, rowspan=2,colspan=2) 

1259 plt.minorticks_on() 

1260 

1261 plt.plot(times[times<23.97],(energy/(energy[0]))[times<23.97],color='k',lw=1.) #,marker='+' 

1262 plt.plot(times[times<23.97],(pe/(energy[0]))[times<23.97],color='xkcd:purple',lw=1.) 

1263 plt.plot(times[times<23.97],((ke+pe)/(energy[0]))[times<23.97],color='xkcd:tangerine',lw=1.) 

1264 

1265 plt.fill_between(times[times<=ti],0./(energy[0]),(pe[times<=ti])/(energy[0]), color=cmap(0.15),alpha=0.65) 

1266 plt.fill_between(times[times<=ti],pe[times<=ti]/(energy[0]),(ke+pe)[times<=ti]/(energy[0]), color=cmap(0.73),alpha=0.94) 

1267 plt.fill_between(times[times<=ti],(ke+pe)[times<=ti]/(energy[0]),energy[times<=ti]/(energy[0]), color=cmap(0.43),alpha=0.82) 

1268 

1269 plt.plot(ti,pei/(energy[0]),ms=2,marker='o', color='xkcd:purple') 

1270 plt.plot(ti,(pei+kei)/(energy[0]),ms=2,marker='o', color='xkcd:tangerine') 

1271 plt.plot(ti,(pei+kei+iei)/(energy[0]),ms=2,marker='o', color='xkcd:deep rose') 

1272 

1273 #plt.text(lpos,(0.5*penergy[times>lpos])[0]/(energy[0]),'Potential',color='purple',size=8,ha='right',va='center') 

1274 #plt.text(lpos,((0.5*kenergy+penergy)[times>lpos])[0]/(energy[0]),'Kinetic',color='orangered',size=8,ha='right',va='center') 

1275 #plt.text(lpos,((0.5*ienergy+kenergy+penergy)[times>lpos])[0]/(energy[0]),'Internal',color='mediumvioletred',size=8,ha='right',va='center') 

1276 

1277 #plt.ylim([0.,1.02]) 

1278 plt.xlim(xmin=0) 

1279 plt.xlim(xmax=tmax) 

1280 plt.xlabel('Time (hrs)') 

1281 plt.ylabel('Fraction of event energy') 

1282 ax=plt.gca() 

1283 ax.xaxis.set_major_locator(ticker.MultipleLocator(5.)) #2.5 

1284 ax.xaxis.set_minor_locator(ticker.MultipleLocator(1.)) 

1285 

1286 gs2.update(top=0.99,bottom=0.1,right=0.98,hspace=0.14,wspace=0.38)