summaryrefslogtreecommitdiffstats
path: root/DiskXYZ.py
blob: f9f6134e8653067a3b1556611a52a725ad25141a (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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
"""
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>
16 August 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

# Helpers
twopi = 2.0 * np.pi

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.angular_momentum_total = None
        self.angular_momentum_disk = None
        self.angular_momentum_halo = None
        self.angular_momentum_lost_to_halo = None
        self.angular_momentum_lost_to_star = None
        self.infall_rate = None     # Current Infall Rate (Msolar/yr)
        self.h_xy = None        # Scale Height (AU)
        self.T_mid_xy = None    # Midplane Temperature (T)
        self.Omega_xy = None    # Angular Velocity (1/TU) @todo: sort out units
        self.rho_mid_xy = None  # Midplane Volume Density (Msolar/AU^3)
        self.n_mid_xy = None    # Midplane H2 Number Density (Number/cm^3)
        self.xe_mid_xy = None   # Midplane Electron Fraction (-)
        self.etaB_mid_xy = None # Midplane Magnetic Diffusivity (AU^2/TU)
        self.ua2_mid_xy = None  # Midplane Alfven Velocity (AU/TU)
        self.ReM_mid_xy = None  # Midplane Magnetic Reynolds Number (-)
        # 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_constants(self):
        # Thermodynamic Stuff
        kB  = 1.3806488e-23    # m2 kg s-2 K-1 / Stefan Boltzmann Constant
        amu = 1.66053892e-27   # kg            / Atomic Mass Unit
        Rsp = kB / 2. / amu    # m2 s-2 K-1    / Specific Gas Constant for H2

        # Conversion Constants
        AU = 1.49598e11        # m
        yr = 3.15569e7         # s
        TU = 1./(twopi)        # yr
        Msolar = 1.99e30       # kg

        # Rescale Gas Constant to G=1
        Rsp = Rsp * (yr**2. / AU**2.)   # AU2 yr-2 K-2
        Rsp = Rsp * (TU**2.)            # AU2 TU-2 K-2

        # Hydrogen Mass
        mass_H2 = 2. * amu          # kg
        mass_H2 = mass_H2 / Msolar  # Solar Masses

        # Ratio of Specific Heats
        gamma = 1.4

        # Potassium Abundance (-7 = Solar Abundance)
        KH = -7.

        # Add to Object
        self.AU = AU
        self.yr = yr
        self.TU = TU
        self.Rsp = Rsp
        self.gamma = gamma
        self.mass_H2 = mass_H2
        self.KH = KH

    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, use_C_code=False)
        # Populate Object Fields
        self.info = output.info
        for key in self.dl: self.dl[key] = self.dl[key] * self.info["boxlen"]
        self.init_constants()
        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.angular_momentum_total = npz["angular_momentum_total"]
        self.angular_momentum_disk = npz["angular_momentum_disk"]
        self.angular_momentum_halo = npz["angular_momentum_halo"]
        self.angular_momentum_lost_to_star = npz["angular_momentum_lost_to_star"]
        self.angular_momentum_lost_to_halo = npz["angular_momentum_lost_to_halo"]
        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]
        l8 = lines[8] # L_lost_star
        l9 = lines[9] # L_lost_halo
        l10 = lines[10] # L_disk
        l11 = lines[11] # L_halo
        l12 = lines[12] # L_tot
        self.infall_rate = float(l7[11:33]) * 2. * pi
        self.mass_total = float(l6[11:33])
        self.mass_disk = float(l4[11:33])
        self.mass_halo = float(l5[11:33])
        self.mass_total_lost_to_halo = float(l3[11:33])
        self.mass_total_lost_to_star = float(l2[11:33])
        self.angular_momentum_total = float(l12[11:33])
        self.angular_momentum_disk = float(l10[11:33])
        self.angular_momentum_halo = float(l11[11:33])
        self.angular_momentum_lost_to_star = float(l8[11:33])
        self.angular_momentum_lost_to_halo = float(l9[11:33])

    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.angular_momentum_total = npz["angular_momentum_total"]
        self.angular_momentum_disk = npz["angular_momentum_disk"]
        self.angular_momentum_halo = npz["angular_momentum_halo"]
        self.angular_momentum_lost_to_star = npz["angular_momentum_lost_to_star"]
        self.angular_momentum_lost_to_halo = npz["angular_momentum_lost_to_halo"]
        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, \
            angular_momentum_disk = self.angular_momentum_disk, \
            angular_momentum_halo = self.angular_momentum_halo, \
            angular_momentum_total = self.angular_momentum_total, \
            angular_momentum_lost_to_halo = self.angular_momentum_lost_to_halo, \
            angular_momentum_lost_to_star = self.angular_momentum_lost_to_star, \
            infall_rate = self.infall_rate, \
            info = self.info, \
            h_xy = self.h_xy, \
            T_mid_xy = self.T_mid_xy, \
            Omega_xy = self.Omega_xy, \
            rho_mid_xy = self.rho_mid_xy, \
            n_mid_xy = self.n_mid_xy, \
            xe_mid_xy = self.xe_mid_xy, \
            etaB_mid_xy = self.etaB_mid_xy, \
            ua2_mid_xy = self.ua2_mid_xy, \
            ReM_mid_xy = self.ReM_mid_xy \
            )

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_cs2_xy(self):
        self.cs2_xy = self.P_xy / self.rho_xy
        self.cs2_xy[np.isnan(self.Omega_xy)] = np.nan

    def compute_Omega_xy(self):
        self.Omega_xy = self.vcyl_xy["vtheta"] / self.rt["r"]
        self.Omega_xy[self.Omega_xy == 0.0] = np.nan

    def compute_h_xy(self):
        self.h_xy = np.sqrt(self.cs2_xy) / self.Omega_xy

    def compute_T_mid_xy(self):
        self.T_mid_xy = self.cs2_xy / self.gamma / self.Rsp
        self.T_mid_xy[np.isnan(self.Omega_xy)] = np.nan

    def compute_rho_mid_xy(self):
        self.rho_mid_xy = self.rho_xy / (np.sqrt(twopi) * self.h_xy)

    def compute_n_mid_xy(self):
        """
        Volumetric Midplane Number Density.
        """
        # (Msolar / AU^3) / Msolar = 1/AU^3
        self.n_mid_xy = self.rho_mid_xy / self.mass_H2
        self.n_mid_xy = self.n_mid_xy / self.AU**3.          # 1/m^3
        self.n_mid_xy = self.n_mid_xy / 100.**3.             # 1/cm^3

    def compute_xe_mid_xy(self):
        """
        Midplane Electron Fraction.
        """
        self.xe_mid_xy = 6.47e-13 * np.sqrt(10.0**self.KH) * \
                         (self.T_mid_xy / 1.0e3)**(0.75) * \
                         (2.4e15 / self.n_mid_xy)**(0.5) * \
                         np.exp(-25188. / self.T_mid_xy) / 1.15e-11
        # Prevent Underflows!
        self.xe_mid_xy[self.xe_mid_xy == 0.0]    = 1.0e-30
        self.xe_mid_xy[self.xe_mid_xy < 1.0e-30] = 1.0e-30

    def compute_magnetic_diffusivity(self):
        """
        Magnetic Diffusivity.
        """
        self.etaB_mid_xy = \
            230. / self.xe_mid_xy * np.sqrt(self.T_mid_xy)       # cm^2 / s
        self.etaB_mid_xy = self.etaB_mid_xy / 1000. / 1000       # m^2  / s
        self.etaB_mid_xy = self.etaB_mid_xy / self.AU / self.AU  # AU^2 / s
        self.etaB_mid_xy = self.etaB_mid_xy * self.yr            # AU^2 / yr
        self.etaB_mid_xy = self.etaB_mid_xy * self.TU            # AU^2 / TU

    def compute_alfven_speed_mid_xy(self):
        """
        Midplane Alfven Speed.

        @todo Could depend on field strength, etc.
              For now, just use some fraction of the sound speed.
        """
        factor = 0.5
        self.ua2_mid_xy = factor**2. * self.cs2_xy

    def compute_ReM_xy(self):
        """
        Midplane Magnetic Reynolds Number.
        """
        self.ReM_mid_xy = 2.0 * self.h_xy * \
                          np.sqrt(self.ua2_mid_xy) / self.etaB_mid_xy

    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
        self.Q_xy = np.sqrt(self.cs2_xy) * self.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_Omega_xy()
        self.compute_cs2_xy()
        self.compute_T_mid_xy()
        self.compute_h_xy()
        self.compute_rho_mid_xy()
        self.compute_n_mid_xy()
        self.compute_xe_mid_xy()
        self.compute_magnetic_diffusivity()
        self.compute_alfven_speed_mid_xy()
        self.compute_ReM_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