summaryrefslogtreecommitdiffstats
path: root/DiskRTZ.py
blob: 2972bbaa8be76d82514b59827d04921cdfaa5a78 (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
"""
Disk Post-Processing Classes for RTZ Coordinates.

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

@todo - Plots.
@todo - F(R,Z) -> F(R) [WIP: Mass Flux Done]

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

from pymses import RamsesOutput
from pymses.analysis import sample_points
from helpers import mkpoints_rtz, 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):
        # Coordinates
        self.przt = None    # Sampling Coords r(0,0.5), z(0,1), theta(0,2pi]
        self.prz = None
        self.pxyz = None    # XZY Corresponding to Sampled Coords (0,1)
        self.rtz = {"r": None, "theta":None, "z": None}
        self.rz = {"r": None, "z": None}
        self.r = {"r": None}
        # Velocities
        self.vcart = {"vx": None, "vy": None, "vz": None}
        self.vcyl = {"vr": None, "vtheta": None, "vz": None}
        # Sampling
        self.nr = 64; self.ntheta = 64; self.nz = 64
        self.center = 0.5; self.radius = 0.4; self.thickness = 0.2
        self.dl = {"dr": None, "dtheta": None, "dz": None}
        # Raw & Reduced Data
        self.dset = None; self.iout = iout; self.info = None
        self.mdotr_rz = None; self.mdotr_r = None
        self.rho_rz = None; self.rho_r = None
        self.mass_r = None
        self.total_mass = None
        # MinMax Holders
        self.rho_rz_min = None; self.rho_rz_max = None
        self.mdotr_rz_g0_min = None; self.mdotr_rz_g0_max = None
        self.mdotr_rz_l0_min = None; self.mdotr_rz_l0_max = None
        self.mdotr_r_g0_min = None; self.mdotr_r_g0_max = None
        self.mdotr_r_l0_min = None; self.mdotr_r_l0_max = None

    def init_cylindrical_coords(self):
        self.rtz["r"] = self.przt[:,0] * self.info["boxlen"]
        self.rtz["z"] = self.przt[:,1] * self.info["boxlen"]
        self.rtz["theta"] = self.przt[:,2]
        self.rz["r"] = self.prz[:,0] * self.info["boxlen"]
        self.rz["z"] = self.prz[:,1] * self.info["boxlen"]
        self.r["r"] = self.rz["r"].reshape(self.nr, self.nz)[:,0]

    def init_velocities(self):
        self.vcart["vx"] = self.dset["vel"][:,0]
        self.vcart["vy"] = self.dset["vel"][:,1]
        self.vcart["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.przt, self.prz, self.pxyz, _, _, _, self.dl = \
            mkpoints_rtz(self.center,
                         self.radius,
                         self.thickness,
                         self.nr, self.ntheta, self.nz)
        # Read Data
        output = RamsesOutput(".", self.iout)
        source = output.amr_source(["rho", "vel"])
        self.dset = sample_points(source, self.pxyz)
        # Populate Object Fields
        self.info = output.info
        self.dl["dr"] = self.dl["dr"] * self.info["boxlen"]
        self.dl["dz"] = self.dl["dz"] * self.info["boxlen"]
        self.init_cylindrical_coords()
        self.init_velocities()
        self.convert_velocities()

    def load_npz(self):
        """Load **Reduced** Data.."""
        npz = np.load("DiskRZ_%05d.npz" % self.iout)
        self.nr = npz["nr"]; self.ntheta = npz["ntheta"]; self.nz = npz["nz"]
        self.rz = npz["rz"][()]; self.r = npz["r"][()]
        self.mdotr_rz = npz["mdotr_rz"]
        self.mdotr_r = npz["mdotr_r"]
        self.rho_rz = npz["rho_rz"]
        self.rho_r = npz["rho_r"]
        self.mass_r = npz["mass_r"]
        self.total_mass = npz["total_mass"]
        self.mdotr_rz_g0_max = npz["mdotr_rz_g0_max"]
        self.mdotr_rz_g0_min = npz["mdotr_rz_g0_min"]
        self.mdotr_rz_l0_max = npz["mdotr_rz_l0_max"]
        self.mdotr_rz_l0_min = npz["mdotr_rz_l0_min"]
        self.mdotr_r_g0_max = npz["mdotr_r_g0_max"]
        self.mdotr_r_g0_min = npz["mdotr_r_g0_min"]
        self.mdotr_r_l0_max = npz["mdotr_r_l0_max"]
        self.mdotr_r_l0_min = npz["mdotr_r_l0_min"]
        self.rho_rz_max = npz["rho_rz_max"]
        self.rho_rz_min = npz["rho_rz_min"]
        self.info = npz["info"][()]

    def load_npz_minmax(self):
        """Load Min/Max on **Reduced** Data."""
        npz = np.load("DiskRZ_%05d.npz" % self.iout)
        self.mdotr_rz_g0_max = npz["mdotr_rz_g0_max"]
        self.mdotr_rz_g0_min = npz["mdotr_rz_g0_min"]
        self.mdotr_rz_l0_max = npz["mdotr_rz_l0_max"]
        self.mdotr_rz_l0_min = npz["mdotr_rz_l0_min"]
        self.mdotr_r_g0_max = npz["mdotr_r_g0_max"]
        self.mdotr_r_g0_min = npz["mdotr_r_g0_min"]
        self.mdotr_r_l0_max = npz["mdotr_r_l0_max"]
        self.mdotr_r_l0_min = npz["mdotr_r_l0_min"]
        self.rho_rz_max = npz["rho_rz_max"]
        self.rho_rz_min = npz["rho_rz_min"]

    def save_npz(self):
        """Save **Reduced** Data."""
        np.savez("DiskRZ_%05d.npz" % self.iout, \
            nr = self.nr, ntheta = self.ntheta, nz = self.nz, \
            rz = self.rz, r = self.r, \
            mdotr_rz = self.mdotr_rz, \
            mdotr_r = self.mdotr_r, \
            rho_rz = self.rho_rz, \
            rho_r = self.rho_rz, \
            mass_r = self.mass_r, \
            total_mass = self.total_mass, \
            mdotr_rz_g0_max = self.mdotr_rz_g0_max, \
            mdotr_rz_g0_min = self.mdotr_rz_g0_min, \
            mdotr_rz_l0_max = self.mdotr_rz_l0_max, \
            mdotr_rz_l0_min = self.mdotr_rz_l0_min, \
            mdotr_r_g0_max = self.mdotr_r_g0_max, \
            mdotr_r_g0_min = self.mdotr_r_g0_min, \
            mdotr_r_l0_max = self.mdotr_r_l0_max, \
            mdotr_r_l0_min = self.mdotr_r_l0_min, \
            rho_rz_max = self.rho_rz_max, rho_rz_min = self.rho_rz_min, \
            info = self.info )

class DiskReduceBase(DiskIo):
    """General Reduction Methods. Overkill. Deleted."""
    pass

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

    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["vr"] = self.vcart["vx"] * cos_theta + \
                          self.vcart["vy"] * sin_theta
        self.vcyl["vtheta"] = - self.vcart["vx"] * sin_theta + \
                                self.vcart["vy"] * cos_theta

    def compute_mdotr_rz(self):
        """Compute Mass Flow Accross Cylindrical Slices."""
        self.mdotr_rz = np.zeros(self.prz.shape[0])
        idx_lo = 0
        for ii in range(self.prz.shape[0]):
            idx_hi = idx_lo + self.ntheta
            # self.mdotr_rz[ii] = np.sum(self.dset["rho"][idx_lo:idx_hi] * \
            #                            vcyl["vr"][idx_lo:idx_hi]) * \
            #                     rz["r"][ii] * dl["dtheta"] * dl["dz"]
            dtheta = self.rz["r"][ii] * self.dl["dtheta"]
            self.mdotr_rz[ii] = simps(self.dset["rho"][idx_lo:idx_hi] * \
                                      self.vcyl["vr"][idx_lo:idx_hi], \
                                      dx=dtheta) * self.dl["dz"]
            idx_lo = idx_hi
        if np.any(self.mdotr_rz>0):
            self.mdotr_rz_g0_max = np.nanmax(self.mdotr_rz[self.mdotr_rz>0])
            self.mdotr_rz_g0_min = np.nanmin(self.mdotr_rz[self.mdotr_rz>0])
        else:
            self.mdotr_rz_g0_max = np.nan
            self.mdotr_rz_g0_min = np.nan
        if np.any(self.mdotr_rz<0):
            self.mdotr_rz_l0_max = np.nanmax(self.mdotr_rz[self.mdotr_rz<0])
            self.mdotr_rz_l0_min = np.nanmin(self.mdotr_rz[self.mdotr_rz<0])
        else:
            self.mdotr_rz_l0_max = np.nan
            self.mdotr_rz_l0_min = np.nan

    def add_mdotr_to_r(self):
        """Sum Mass Flux along Z."""
        self.mdotr_r = np.sum(self.mdotr_rz.reshape(self.nr, self.nz), axis=1)
        if np.any(self.mdotr_r>0):
            self.mdotr_r_g0_max = np.nanmax(self.mdotr_r[self.mdotr_r>0])
            self.mdotr_r_g0_min = np.nanmin(self.mdotr_r[self.mdotr_r>0])
        else:
            self.mdotr_r_g0_max = np.nan
            self.mdotr_r_g0_min = np.nan
        if np.any(self.mdotr_r<0):
            self.mdotr_r_l0_max = np.nanmax(self.mdotr_r[self.mdotr_r<0])
            self.mdotr_r_l0_min = np.nanmin(self.mdotr_r[self.mdotr_r<0])
        else:
            self.mdotr_r_l0_max = np.nan
            self.mdotr_r_l0_min = np.nan

    def integrate_rho_to_rz(self):
        """Integrate Density along Theta."""
        self.rho_rz = np.zeros(self.prz.shape[0])
        idx_lo = 0
        for ii in range(self.prz.shape[0]):
            idx_hi = idx_lo + self.ntheta
            dtheta = self.rz["r"][ii] * self.dl["dtheta"]
            self.rho_rz[ii] = simps(self.dset["rho"][idx_lo:idx_hi], dx=dtheta)
            idx_lo = idx_hi
        self.rho_rz_max = np.nanmax(self.rho_rz)
        self.rho_rz_min = np.nanmin(self.rho_rz)

    def integrate_rho_to_r(self):
        """Integrate RZ Density along Z."""
        self.rho_r = np.zeros(self.r["r"].shape[0])
        idx_lo = 0
        for ii in range(self.r["r"].shape[0]):
            idx_hi = idx_lo + self.nz
            self.rho_r[ii] = simps(self.rho_rz[idx_lo:idx_hi], \
                                   dx=self.dl["dz"])
            idx_lo = idx_hi

    def compute_mass_r(self):
        """Compute Mass in Radial Bins."""
        self.mass_r = self.rho_r * self.dl["dr"]

    def add_to_total_mass(self):
        """Add Mass per Radial To Get Total Mass."""
        self.total_mass = np.sum(self.mass_r)

    def reduce_all(self):
        self.compute_mdotr_rz()
        self.integrate_rho_to_rz()
        self.integrate_rho_to_r()
        self.compute_mass_r()
        self.add_to_total_mass()
        self.add_mdotr_to_r()

class DiskPlots(DiskReduce):
    """Plotting Routines."""
    def plot_mdotr_r(self, ax_in=None, ylim=None, ylog=False):
        # Plot
        if not ax_in:
            fig = plt.figure()
            ax = fig.add_subplot(1,1,1)
        else:
            ax = ax_in
        if ylog:
            ax.set_yscale('log')
        h, = ax.plot(self.r["r"], self.mdotr_r, 'bs-')
        ax.set_xlabel('R [AU]')
        ax.set_ylabel('Radial Mass Flux [Mstar/yr]')
        ax.set_title('Radial Mass Flux [Mstar/yr]')
        ax.grid(True)
        if not (ylim == None):
            ax.set_ylim(ylim)
        if not ax_in:
            plt.show()
        else:
            return h

    def plot_rho_rz(self, ax_in=None, clim=None):
        """Plot Angle Integrated Density."""
        ext = [np.min(self.rz["r"]), np.max(self.rz["r"]), \
               np.min(self.rz["z"]), np.max(self.rz["z"])]
        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_rz.reshape(self.nr, self.ntheta))), \
                       extent=ext, interpolation='none')
        ax.set_xlabel('R [AU]')
        ax.set_ylabel('Z [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()

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