summaryrefslogtreecommitdiffstats
path: root/DiskXYZ.py
blob: a88789dd1dedb597be2ba09783f048d5a84d059c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""
Disk Post-Processing Classes.

Loads Raw Ramses Data. Processes F(X,Y,Z) -> F(X,Y) -> F(R).
Loads/Saves Reduced Data to Numpy File.
Plots Reduced F(X,Y), F(R) Data.

@todo - Plot w/ global figure handle.
@todo - Mass flow.
@todo - Status messages.
@todo - RZ-Integrate (rho)
@todo - Save plots.

Volker Hoffmann <volker@cheleb.net>
14 May 2013
"""

from pymses import RamsesOutput
from pymses.analysis import sample_points
from helpers import mkpoints_xyz, prof1d
from scipy.integrate import simps
import numpy as np
from math import pi
import matplotlib.pyplot as plt

class DiskBase():
    """Declarations and Initialization Methods."""

    def __init__(self, iout=1):
        # Declarations
        self.pxy = None     # Coords for Sampling, (0,1)
        self.pxyz = None
        self.xy = {"x": None, "y": None}                # Wrapped Coords
        self.xyz = {"x": None, "y": None, "z": None}    # (0,boxlen)
        self.xy0 = {"x": None, "y": None}               # (-boxlen/2, boxlen/2)
        self.xyz0 = {"x": None, "y": None}
        self.rtz = {"r": None, "theta": None, "z": None}
        self.rt = {"r": None, "theta": None}
        self.info = None
        self.Q_xy = None
        self.Q_r = None
        self.P_xy = None
        self.P_r = None
        self.rho_xy = None; self.rho_xy_max = None; self.rho_xy_min = None
        self.rho_r = None; self.rho_r_no0_max = None; self.rho_r_no0_min = None
        self.mdot_r = None;
        self.mdot_r_abs_n0_max = None; self.mdot_r_abs_no0_min = None
        self.vcart_xyz = {"vx": None, "vy": None, "vz": None}
        self.vcart_xy = {"vx": None, "vy": None, "vz": None}
        self.vcart_r = {"vx": None, "vy": None, "vz": None}
        self.vcyl_xyz = {"vr": None, "vtheta": None, "vz": None}
        self.vcyl_xy = {"vr": None, "vtheta": None, "vz": None}
        self.vcyl_r = {"vr": None, "vtheta": None, "vz": None}
        self.dset = None
        self.dl = {"dx": None, "dy": None, "dz": None}
        self.rbins_edges = None
        self.rbins_centers = None
        self.mass_total = None      # Current Mass in Box
        self.mass_disk = None       # Current Mass in Disk
        self.mass_halo = None       # Current Mass in Halo
        self.mass_total_lost_to_halo = None     # Accumulated Mass Lost to Halo
        self.mass_total_lost_to_star = None     # Accumulated Mass Lost to Star
        self.infall_rate = None     # Current Infall Rate (Msolar/yr)
        # Output
        self.iout = iout
        # Sampling Volume, Options
        self.nx = 128; self.ny = 128; self.nz = 128; self.nrbins = 64
        self.center = 0.5; self.radius = 0.4; self.thickness = 0.2
        # self.rbin_min = 0; self.rbin_max = 5

    def init_cartesian_coords(self):
        self.xyz["x"] = self.pxyz[:,0] * self.info["boxlen"]
        self.xyz["y"] = self.pxyz[:,1] * self.info["boxlen"]
        self.xyz["z"] = self.pxyz[:,2] * self.info["boxlen"]
        self.xy["x"] = self.pxy[:,0] * self.info["boxlen"]
        self.xy["y"] = self.pxy[:,1] * self.info["boxlen"]
        self.xyz0["x"] = (self.pxyz[:,0] - 0.5) * self.info["boxlen"]
        self.xyz0["y"] = (self.pxyz[:,1] - 0.5) * self.info["boxlen"]
        self.xyz0["z"] = (self.pxyz[:,2] - 0.5) * self.info["boxlen"]
        self.xy0["x"] = (self.pxy[:,0] - 0.5) * self.info["boxlen"]
        self.xy0["y"] = (self.pxy[:,1] - 0.5) * self.info["boxlen"]

    def init_cylindrical_coords(self):
        self.rt["r"] = np.sqrt(self.xy0["x"]**2. + self.xy0["y"]**2.)
        self.rt["theta"] = np.arctan2(self.xy0["y"], self.xy0["x"])
        self.rtz["r"] = np.sqrt(self.xyz0["x"]**2. + self.xyz0["y"]**2.)
        self.rtz["theta"] = np.arctan2(self.xyz0["y"], self.xyz0["x"])
        self.rtz["z"] = self.xyz0["z"]

    def init_velocities(self):
        self.vcart_xyz["vx"] = self.dset["vel"][:,0]
        self.vcart_xyz["vy"] = self.dset["vel"][:,1]
        self.vcart_xyz["vz"] = self.dset["vel"][:,2]

    def init_rbins(self):
        self.rbin_min = 0.
        self.rbin_max = np.max(self.xy0["x"])
        self.rbins_edges = np.linspace(self.rbin_min, self.rbin_max,\
                                       self.nrbins + 1)
        self.rbins_centers = (self.rbins_edges[1:] + self.rbins_edges[:-1])/2.

class DiskIo(DiskBase):
    """Load/Save Methods."""

    def load_ramses(self):
        """Load **Raw** Data."""
        # Sampling Points
        self.pxyz, self.pxy, _, _, _, self.dl = \
            mkpoints_xyz(self.center,
                         self.radius,
                         self.thickness,
                         self.nx, self.ny, self.nz)
        # Read Data
        output = RamsesOutput(".", self.iout)
        source = output.amr_source(["rho", "vel", "P"])
        self.dset = sample_points(source, self.pxyz)
        # Populate Object Fields
        self.info = output.info
        for key in self.dl: self.dl[key] = self.dl[key] * self.info["boxlen"]
        self.init_cartesian_coords()
        self.init_cylindrical_coords()
        self.init_velocities()
        self.init_rbins()
        self.convert_velocities()
        self.load_stats()

    def load_npz(self):
        """Load **Reduced** Data.."""
        npz = np.load("DiskXY_%05d.npz" % self.iout)
        self.nx = npz["nx"]; self.ny = npz["ny"]; self.nz = npz["nz"]
        self.xy = npz["xy"][()]; self.xy0 = npz["xy0"][()];
        self.rt = npz["rt"][()]
        self.rbins_edges = npz["rbins_edges"]
        self.rbins_centers = npz["rbins_centers"]
        self.rbin_min = npz["rbin_min"]; self.rbin_max = npz["rbin_max"]
        self.vcart_xy = npz["vcart_xy"][()]; self.vcyl_xy = npz["vcyl_xy"][()]
        self.vcart_r = npz["vcart_r"][()]; self.vcyl_r = npz["vcyl_r"][()]
        self.rho_xy = npz["rho_xy"]; self.rho_r = npz["rho_r"]
        self.rho_xy_max = npz["rho_xy_max"]
        self.rho_xy_min = npz["rho_xy_min"]
        self.rho_r_no0_max = npz["rho_r_no0_max"]
        self.rho_r_no0_min = npz["rho_r_no0_min"]
        self.Q_xy = npz["Q_xy"]; self.Q_r = npz["Q_r"]
        self.mdot_r = npz["mdot_r"]
        self.mdot_r_abs_no0_max = npz["mdot_r_abs_no0_max"]
        self.mdot_r_abs_no0_min = npz["mdot_r_abs_no0_min"]
        self.mass_total = npz["mass_total"]
        self.mass_disk = npz["mass_disk"]
        self.mass_halo = npz["mass_halo"]
        self.mass_total_lost_to_halo = npz["mass_total_lost_to_halo"]
        self.mass_total_lost_to_star = npz["mass_total_lost_to_star"]
        self.infall_rate = npz["infall_rate"]
        self.info = npz["info"][()]

    def load_stats(self):
        """Load Stats."""
        fpath = "output_%05d" % self.iout
        fmydisk = "mydisk_%05d.txt" % self.iout
        ff = "./%s/%s" % ( fpath, fmydisk )
        fid = open(ff, 'r')
        lines = fid.readlines()
        fid.close()
        l2 = lines[2]
        l3 = lines[3]
        l4 = lines[4]
        l5 = lines[5]
        l6 = lines[6]
        l7 = lines[7]
        self.infall_rate = float(l7[12:20]) * 2. * pi
        self.mass_total = float(l6[12:20])
        self.mass_disk = float(l4[12:20])
        self.mass_halo = float(l5[12:20])
        self.mass_total_lost_to_halo = float(l3[12:20])
        self.mass_total_lost_to_star = float(l2[12:20])

    def load_npz_minmax(self):
        """Load Min/Max on **Reduced** Data."""
        npz = np.load("DiskXY_%05d.npz" % self.iout)
        self.rho_xy_max = npz["rho_xy_max"]
        self.rho_xy_min = npz["rho_xy_min"]
        self.rho_r_no0_max = npz["rho_r_no0_max"]
        self.rho_r_no0_min = npz["rho_r_no0_min"]
        self.mdot_r_abs_no0_max = npz["mdot_r_abs_no0_max"]
        self.mdot_r_abs_no0_min = npz["mdot_r_abs_no0_min"]

    def load_npz_stats(self):
        """Load Mass Stats Only."""
        npz = np.load("DiskXY_%05d.npz" % self.iout)
        self.mass_total = npz["mass_total"]
        self.mass_disk = npz["mass_disk"]
        self.mass_halo = npz["mass_halo"]
        self.mass_total_lost_to_halo = npz["mass_total_lost_to_halo"]
        self.mass_total_lost_to_star = npz["mass_total_lost_to_star"]
        self.infall_rate = npz["infall_rate"]
        self.info = npz["info"][()]

    def save_npz(self):
        """Save **Reduced** Data."""
        np.savez("DiskXY_%05d.npz" % self.iout, \
            nx = self.nx, ny = self.ny, nz = self.nz, \
            xy = self.xy, xy0 = self.xy0, rt = self.rt, \
            rbins_edges = self.rbins_edges, \
            rbins_centers = self.rbins_centers, \
            rbin_min = self.rbin_min, rbin_max = self.rbin_max, \
            vcart_xy = self.vcart_xy, vcyl_xy = self.vcyl_xy, \
            vcart_r = self.vcart_r, vcyl_r = self.vcyl_r, \
            rho_xy = self.rho_xy, rho_r = self.rho_r, \
            rho_xy_max = self.rho_xy_max, rho_xy_min = self.rho_xy_min, \
            rho_r_no0_max = self.rho_r_no0_max, \
            rho_r_no0_min = self.rho_r_no0_min, \
            Q_xy = self.Q_xy, Q_r = self.Q_r, \
            mdot_r = self.mdot_r, \
            mdot_r_abs_no0_max = self.mdot_r_abs_no0_max, \
            mdot_r_abs_no0_min = self.mdot_r_abs_no0_min, \
            mass_total = self.mass_total, \
            mass_disk = self.mass_disk, \
            mass_halo = self.mass_halo, \
            mass_total_lost_to_halo = self.mass_total_lost_to_halo, \
            mass_total_lost_to_star = self.mass_total_lost_to_star, \
            infall_rate = self.infall_rate, \
            info = self.info )

class DiskReduceBase(DiskIo):
    """General Reduction Methods."""

    def integrate(self, data_xyz):
        """Numerical Z-Integrator."""
        """@todo - Weight function support."""
        data_xy = np.zeros(self.nx * self.ny)
        idx_lo = 0
        for ii in range(self.pxy.shape[0]):
            idx_hi = idx_lo + self.nz
            data_xy[ii] = simps(data_xyz[idx_lo:idx_hi], dx=self.dl["dz"])
            idx_lo = idx_hi
        return data_xy

    def average(self, data_xyz, weights_xyz=None):
        """Z-Averaging. Supports Weight Function."""
        if weights_xyz == None:
            weights_xyz = self.weights(np.ones(data_xyz.shape))
        data_xy = np.zeros(self.nx * self.ny)
        idx_lo = 0
        for ii in range(self.pxy.shape[0]):
            idx_hi = idx_lo + self.nz
            data_xy[ii] = np.sum(data_xyz[idx_lo:idx_hi] * \
                                 weights_xyz[idx_lo:idx_hi])
            idx_lo = idx_hi
        return data_xy

    def weights(self, weights_xyz):
        """Create Weight Function."""
        weights_xyz = weights_xyz.reshape(self.nx, self.ny, self.nz)
        weights_sum = np.sum(weights_xyz, axis=2)
        weights_sum = weights_sum[:,:,None]
        weights_sum = weights_sum * np.ones([self.nx, self.ny, self.nz])
        weights_xyz = weights_xyz / weights_sum
        weights_xyz = weights_xyz.reshape(self.nz * self.ny * self.nx)
        return weights_xyz

class DiskReduce(DiskReduceBase):
    """Specific Reduction Methods."""

    def integrate_to_rho_xy(self):
        """Z-Integrate Volume Density. Gives Surface Density."""
        self.rho_xy = self.integrate(self.dset["rho"])
        self.rho_xy_max = np.nanmax(self.rho_xy)
        self.rho_xy_min = np.nanmin(self.rho_xy)

    def average_to_rho_r(self):
        """Theta-Averaged Surface Density."""
        self.rho_r = prof1d(self.rt["r"], self.rho_xy, self.rbins_edges)
        self.rho_r_no0_max = np.nanmax(self.rho_r[self.rho_r!=0])
        self.rho_r_no0_min = np.nanmin(self.rho_r[self.rho_r!=0])

    def integrate_to_P_xy(self):
        """Z-Integrate 3D Pressure Density. Gives 2D Pressure."""
        self.P_xy = self.integrate(self.dset["P"])

    def convert_velocities(self):
        """Cylindrical Coordinate Components of Velocities."""
        cos_theta = np.cos(self.rtz["theta"])
        sin_theta = np.sin(self.rtz["theta"])
        self.vcyl_xyz["vr"] = self.vcart_xyz["vx"] * cos_theta + \
                              self.vcart_xyz["vy"] * sin_theta
        self.vcyl_xyz["vtheta"] = - self.vcart_xyz["vx"] * sin_theta + \
                                    self.vcart_xyz["vy"] * cos_theta
        self.vcyl_xyz["vz"] = self.vcart_xyz["vz"]

    def average_velocities_to_xy(self):
        """Z-Average Velocity Components. Density Weighted."""
        weights_xyz = self.weights(self.dset["rho"])
        self.vcart_xy["vx"] = self.average(self.vcart_xyz["vx"], weights_xyz)
        self.vcart_xy["vy"] = self.average(self.vcart_xyz["vy"], weights_xyz)
        self.vcart_xy["vz"] = self.average(self.vcart_xyz["vz"], weights_xyz)
        self.vcyl_xy["vr"] = self.average(self.vcyl_xyz["vr"], weights_xyz)
        self.vcyl_xy["vtheta"] = self.average(self.vcyl_xyz["vtheta"], weights_xyz)
        self.vcyl_xy["vz"] = self.average(self.vcyl_xyz["vz"], weights_xyz)

    def average_velocities_to_r(self):
        """Theta-Averaged Velocity Components."""
        self.vcart_r["vx"] = \
            prof1d(self.rt["r"], self.vcart_xy["vx"], self.rbins_edges)
        self.vcart_r["vy"] = \
            prof1d(self.rt["r"], self.vcart_xy["vy"], self.rbins_edges)
        self.vcart_r["vz"] = \
            prof1d(self.rt["r"], self.vcart_xy["vz"], self.rbins_edges)
        self.vcyl_r["vr"] = \
            prof1d(self.rt["r"], self.vcyl_xy["vr"], self.rbins_edges)
        self.vcyl_r["vtheta"] = \
            prof1d(self.rt["r"], self.vcyl_xy["vtheta"], self.rbins_edges)
        self.vcyl_r["vz"] = \
            prof1d(self.rt["r"], self.vcyl_xy["vz"], self.rbins_edges)

    def compute_mdot_r(self):
        """Average Mass Flow."""
        """@todo Integrate Properly (rtz->rt->r). See Notes."""
        """Units: Mstar/code_time. 1yr =  code_time/2pi."""
        """So, Mstar*2*pi gives Mstar/yr. Convert in plot."""
        self.mdot_r = \
            2. * pi * self.vcyl_r["vr"] * self.rbins_centers * self.rho_r
        self.mdot_r_abs_no0_max = \
            np.nanmax(np.abs(self.mdot_r[self.mdot_r!=0]))
        self.mdot_r_abs_no0_min = \
            np.nanmin(np.abs(self.mdot_r[self.mdot_r!=0]))
        
    def compute_Q_xy(self):
        """Toomre-Q."""
        G = 1.0
        Omega_xy = self.vcyl_xy["vtheta"] / self.rt["r"]
        cs_xy = np.sqrt(self.P_xy / self.rho_xy)
        self.Q_xy = cs_xy * Omega_xy / pi / G / self.rho_xy

    def average_to_Q_r(self):
        """Theta-Averaged Toomre-Q."""
        self.Q_r = prof1d(self.rt["r"], self.Q_xy, self.rbins_edges)

    def reduce_all(self):
        self.average_velocities_to_xy()
        self.average_velocities_to_r()
        self.integrate_to_P_xy()
        self.integrate_to_rho_xy()
        self.compute_Q_xy()
        self.average_to_rho_r()
        self.average_to_Q_r()
        self.compute_mdot_r()

class DiskPlots(DiskReduce):
    """Plotting Routines."""

    def plot_rho_xy(self, ax_in=None, clim=None):
        ext = [np.min(self.xy0["x"]), np.max(self.xy0["x"]), \
               np.min(self.xy0["y"]), np.max(self.xy0["y"])]
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        im = ax.imshow(np.rot90(np.log10(self.rho_xy.reshape(self.nx, self.ny))), \
                       extent=ext, interpolation='none')
        ax.set_xlabel('X [AU]')
        ax.set_ylabel('Y [AU]')
        ax.set_title('Log10 Surface Density [Mstar/AU^2]')
        ax.grid()
        if clim:
            im.set_clim(clim)
        plt.colorbar(im, ax=ax)
        if not ax_in:
            plt.show()

    def plot_rho_r(self, ax_in=None, ylim=None):
        # Cut Out Empty Bins
        rho_r = self.rho_r
        rbins_centers = self.rbins_centers
        rho_r[rho_r==0.] = np.nan
        rbins_centers = rbins_centers[~np.isnan(rho_r)]
        rho_r = rho_r[~np.isnan(rho_r)]
        # Plot
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        ax.plot(rbins_centers, rho_r, 'bs-')
        ax.set_yscale('log')
        ax.set_xlabel('R [AU]')
        ax.set_ylabel('Log10 Surface Density [Mstar/AU^2]')
        ax.set_title('Log10 Surface Density [Mstar/AU^2]')
        ax.grid()
        ax.set_xlim([self.rbin_min, self.rbin_max])
        if ylim:
            ax.set_ylim(ylim)
        if not ax_in:
            plt.show()

    def plot_Q_xy(self, ax_in=None):
        ext = [np.min(self.xy0["x"]), np.max(self.xy0["x"]), \
               np.min(self.xy0["y"]), np.max(self.xy0["y"])]
        Q_xy = self.Q_xy
        Q_xy[Q_xy>10] = np.nan
        Q_xy[Q_xy<=0] = np.nan
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        im = ax.imshow(np.rot90(Q_xy.reshape(self.nx, self.ny)),\
                       extent=ext, interpolation='none')
        im.set_clim([0, 10])
        ax.set_xlabel('X [AU]')
        ax.set_ylabel('Y [AU]')
        ax.set_title('Toomre-Q')
        ax.grid()
        plt.colorbar(im, ax=ax)
        if not ax_in:
            plt.show()

    def plot_Q_r(self, ax_in=None):
        # Cut Out Empty Bins and Useless Values
        Q_r = self.Q_r
        rbins_centers = self.rbins_centers
        Q_r[Q_r>10] = np.nan
        Q_r[Q_r<=0] = np.nan
        Q_r[Q_r<0.0001] = np.nan
        rbins_centers = rbins_centers[~np.isnan(Q_r)]
        Q_r = Q_r[~np.isnan(Q_r)]
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        # Plot
        ax.hold(True)
        ax.plot(rbins_centers, Q_r, 'bs-')
        ax.plot([self.rbin_min, self.rbin_max], [1.5, 1.5], 'y-', \
                label='Q=1.5')
        ax.plot([self.rbin_min, self.rbin_max], [1.0, 1.0], 'r-', \
                label='Q=1.0')
        ax.hold(False)
        ax.grid()
        ax.set_xlabel('Radius [AU]')
        ax.set_ylabel('Toomre-Q')
        ax.set_title('Toomre-Q')
        ax.set_xlim([self.rbin_min, self.rbin_max])
        ax.set_ylim([0, 10])
        ax.legend(loc='best')
        if not ax_in:
            plt.show()

    def plot_mdot_r(self, ax_in=None, ylim=None):
        # Cut 0.0 and NaN
        mdot_r = self.mdot_r; rbins_centers = self.rbins_centers
        mdot_r[mdot_r==0] = np.nan
        rbins_centers = rbins_centers[~np.isnan(mdot_r)]
        mdot_r = mdot_r[~np.isnan(mdot_r)]
        # Plot
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        ax.plot(rbins_centers, np.abs(mdot_r)*2.*pi, 'bs-')
        ax.grid()
        ax.set_xlabel('Radius [AU]')
        ax.set_ylabel('Mass Flow [Mstar/yr]')
        ax.set_title('Absolute Mass Flow [Mstar/yr]')
        ax.set_yscale('log')
        ax.set_xlim([self.rbin_min, self.rbin_max])
        if ylim:
            ylim = [ylim[0]*2.*pi, ylim[1]*2.*pi]
            ax.set_ylim(ylim)
        if not ax_in:
            plt.show()

class Disk(DiskPlots):
    """Wrapper."""
    pass