summaryrefslogtreecommitdiffstats
path: root/calc_mass_potential.py
blob: 8122aefa8809c207be01c4e14db22a27910e32f4 (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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
#!/usr/bin/env python3
#
# Aaron LI
# Created: 2016-06-24
# Updated: 2016-07-04
#
# Change logs:
# 2016-07-04:
#   * Remove unnecessary configuration options
#   * Update radii unit to be "kpc", mass unit to be "Msun"
# 2016-06-29:
#   * Update "plot()" to support electron number density profile
# 2016-06-28:
#   * Implement plot function
#   * Adjust integration tolerances and progress report
#   * Fit smoothing splines to profiles using R `mgcv::gam()`
# 2016-06-27:
#   * Implement potential profile calculation:
#     methods 'calc_density_total()' and 'calc_potential()'
# 2016-06-26:
#   * Add document on gravitational potential calculation
# 2016-06-25:
#   * Rename method 'interpolate()' to 'fit_spline()'
#   * Use 'InterpolatedUnivariateSpline' instead of 'interp1d'
#   * Implement 'calc_mass_total()'
#   * Update documentation
# 2016-06-24:
#   * Update method 'gen_radius()'
#

"""
Calculate the (gas and gravitational) mass profile and gravitational
potential profile from the electron number density profile, under the
assumption of hydrostatic equilibrium.

The electron density profile and temperature profile are required.

Assuming that the gas is in hydrostatic equilibrium with the gravitational
potential and a spherically-symmetric distribution of the gas, we can
write the hydrostatic equilibrium equation (HEE) of the ICM as
(ref.[1], eq.(6)):
    derivative(P_gas, r) / rho_gas = - derivative(phi, r)
                                   = - G M_tot(<r) / r^2
where,
    phi: gravitational potential;
    G: gravitational constant;
    rho_gas: gas mass density:
        rho_gas = mu * m_atom * n_gas
    P_gas: gas pressure:
        P_gas = rho_gas * k_B * T_gas / (mu * m_atom) = n_gas * k_B * T_gas
    mu: mean molecular weight in a.m.u (i.e., m_atom) (~ 0.6)
    m_atom: atom mass unit
    n_gas: gas number density; sum of the electron and proton densities
    k_B: Boltzmann constant
    T_gas: gas temperature

Solve the above equation, we can get the total mass of X-ray luminous
galaxy clusters (ref.[1], eq.(7)):
    M_tot(<r) = - (k_B * T_gas(r) * r) / (mu * m_atom * G) *
                (derivative(log(T_gas), log(r)) +
                 derivative(log(n_gas), log(r)))

Note that the second part (i.e., the derivatives) is DIMENSIONLESS, since
    d(log(X)) = d(X) / X
Also note that ('R' is a ratio constant):
    d(log(n_gas)) = d(log(R*n_e)) = d(log(n_e))
And and 'log' derivative can be calculated as:
    derivative(log(X(r)), log(r)) = (r / X(r)) * derivative(X(r), r)

Note that 'kT' has dimension of energy.  Therefore, if the gas temperature
is given in 'keV', then the 'kT' should be substitute as a whole.

For example:
    (1.0 keV) * (1.0 kpc) / (0.6 * m_atom * G) ~= 3.7379e10 [ Msun ]
which is consistent with the formula of (ref.[2], eq.(3))

------------------------------------------------------------
Gravitational potential profile calculation:

Newton's theorems (ref.[3], Sec. 2.2.1):
1. A body that is inside a spherical shell of matter experiences no net
   gravitational force from that shell.
2. The gravitational force on a body that lies outside a spherical shell
   of matter is the same as it would be if all the shell's matter were
   concentrated into a point at its center.

Therefore, the gravitational potential produced by a spherical shell of
mass 'M' is:
    phi = (1) - G * M / R;  (r <= R, i.e., inside the shell)
          (2) - G * M / r;  (r > R, i.e., outside the shell)

The total gravitational potential may be considered to be the sum of the
potentials of spherical shells of mass
    dM(r) = 4 * pi * rho(r) * r^2 dr,
so we may calculate the gravitational potential at 'R' generated by an
arbitrary spherically symmetric density distribution 'rho(r)' by adding
the contributions to the potential produced by shells
    (1) with r < R,
and
    (2) with r > R.
In this way, we obtain
    phi(R) = - (G/R) * \int_0^R dM(r) - G * \int_R^{\inf} dM(r)/r
           = - 4*pi*G * ((1/R) * \int_0^R r^2 * rho(r) dr +
             \int_R^{\inf} r * rho(r) dr)

------------------------------------------------------------
References:
[1] Ettori et al., 2013, Space Science Review, 177, 119-154
[2] Walker et al., 2012, MNRAS, 422, 3503
[3] Tremaine & Binney, Galactic Dynamics, 2nd edition, 2008


Sample configuration file:
------------------------------------------------------------
## Configuration for `calc_mass_potential.py`
## Date: 2016-06-28

# electron density profile
ne_profile = ne_profile.txt

# cooling function profile
cf_profile = coolfunc_profile.txt

# temperature profile
t_profile = t_profile.txt

# number of data points for the output profiles (interpolation)
num_dp = 1000

# output gas mass profile
m_gas_profile = mass_gas_profile.txt
m_gas_profile_image = mass_gas_profile.png

# output total (gravitational) mass profile
m_total_profile = mass_total_profile.txt
m_total_profile_image = mass_total_profile.png

# output total mass density profile
rho_total_profile = rho_total_profile.txt
rho_total_profile_image = rho_total_profile.png

# output gravitational potential profile
potential_profile = potential_profile.txt
potential_profile_image = potential_profile.png
------------------------------------------------------------
"""

import argparse

import numpy as np
import astropy.units as au
import astropy.constants as ac
import scipy.integrate as integrate
from scipy.misc import derivative
from configobj import ConfigObj
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

import rpy2.robjects as ro
from rpy2.robjects.packages import importr

from astro_params import AstroParams, ChandraPixel
from projection import Projection

plt.style.use("ggplot")


class DensityProfile:
    """
    Utilize the 3D (electron number or gas mass) density profile to
    calculate the following quantities:
    * 2D projected surface brightness (requires cooling function profile)
    * gas mass profile (integrated, M_gas(<r))
    * gravitational mass profile (M(<r); requires temperature profile)
    * gravitational potential profile (cut at the largest available radius)

    NOTE:
    * The radii should have unit [ kpc ]
    * The density should have unit [ cm^-3 ] or [ g cm^-3 ]
    """
    # available splines
    SPLINES = ["density", "electron", "rho_gas",
               "cooling_function", "temperature",
               "mass_total", "rho_total"]
    # allowed density profile types
    DENSITY_TYPES = ["electron", "gas"]
    # input density data: [r, r_err, d]
    r = None
    r_err = None
    d = None
    # electron number density
    ne = None
    # gas mass density
    rho_gas = None
    # cooling function profile
    cf_radius = None
    cf_value = None
    # temperature profile
    t_radius = None
    t_value = None
    # generated radial data points for profile calculation
    radius = None
    radius_err = None
    # gas mass profile: M_gas(<r); same length as the above 'radius'
    m_gas = None
    # total (gravitational) mass profile: M_total(<r)
    m_total = None
    # total mass density profile (required by potential calculation)
    rho_total = None
    # potential profile (cut at the largest available radius)
    potential = None
    # fitted spline to the profiles
    d_spline = None
    d_spline_log10 = None
    ne_spline = None
    ne_spline_log10 = None
    rho_gas_spline = None
    rho_gas_spline_log10 = None
    cf_spline = None
    cf_spline_log10 = None
    t_spline = None
    t_spline_log10 = None
    m_total_spline = None
    m_total_spline_log10 = None
    rho_total_spline = None
    rho_total_spline_log10 = None
    # call R through `rpy2`
    mgcv = importr("mgcv")

    def __init__(self, density, density_type="electron"):
        self.load_data(data=density, density_type=density_type)

    def load_data(self, data, density_type="electron"):
        if density_type not in self.DENSITY_TYPES:
            raise ValueError("invalid density_types: %s" % density_type)
        # 3-column density profile: r[kpc], r_err[kpc], density
        self.r = data[:, 0].copy()
        self.r_err = data[:, 1].copy()
        self.d = data[:, 2].copy()
        self.density_type = density_type

    def load_cf_profile(self, data):
        if data.shape[1] == 2:
            # 2-column cooling function profile: r[kpc], cf[flux/EM]
            self.cf_radius = data[:, 0].copy()
            self.cf_value = data[:, 1].copy()
        elif data.shape[1] == 3:
            # 3-column cooling function profile: r[kpc], r_err, cf[flux/EM]
            self.cf_radius = data[:, 0].copy()
            self.cf_value = data[:, 2].copy()
        else:
            raise ValueError("invalid cooling function profile data")

    def load_t_profile(self, data):
        if data.shape[1] == 2:
            # 2-column temperature profile: r[kpc], T[keV]
            self.t_radius = data[:, 0].copy()
            self.t_value = data[:, 1].copy()
        elif data.shape[1] == 3:
            # 3-column temperature profile: r[kpc], r_err[kpc], T[keV]
            self.t_radius = data[:, 0].copy()
            self.t_value = data[:, 2].copy()
        else:
            raise ValueError("invalid temperature profile data")

    def calc_density_electron(self):
        """
        Calculate the electron number density from the gas mass density
        if necessary, and fit a smoothing spline to it.
        """
        if self.density_type == "electron":
            self.ne = self.d.copy()
        elif self.density_type == "gas":
            self.ne = self.d / AstroParams.m_atom / AstroParams.mu_e
        # fit a smoothing spline
        self.fit_spline(spline="electron", log10=True)
        return self.ne

    def calc_density_gas(self):
        """
        Calculate the gas mass density from the electron number density
        if necessary, and fit a smoothing spline to it.
        """
        if self.density_type == "electron":
            self.rho_gas = self.d * AstroParams.mu_e * AstroParams.m_atom
        elif self.density_type == "gas":
            self.rho_gas = self.d.copy()
        # fit a smoothing spline
        self.fit_spline(spline="rho_gas", log10=True)
        return self.rho_gas

    def calc_brightness(self):
        """
        Project the electron number density or gas mass density profile
        to calculate the 2D surface brightness profile.
        """
        if self.cf_radius is None or self.cf_value is None:
            raise ValueError("cooling function profile missing")
        if self.cf_spline is None:
            self.fit_spline(spline="cooling_function", log10=False)
        #
        ne = self.calc_density_electron()
        # flux per unit volume
        cf_new = self.eval_spline(spline="cooling_function", x=self.r)
        flux = cf_new * ne ** 2 / AstroParams.ratio_ne_np
        # project the 3D flux into 2D brightness
        rout = (self.r + self.r_err) * au.kpc.to(au.cm)
        projector = Projection(rout)
        brightness = projector.project(flux)
        return brightness

    def fit_spline(self, spline, log10):
        """
        Fit a smoothing line to the specified spline data,
        by utilizing the R `mgcv::gam()` function.

        If 'log10' is True, the input data are first applied the log-scale
        transform, and then fitted by the smoothing spline.

        The fitted spline allows extrapolation.
        """
        if spline not in self.SPLINES:
            raise ValueError("invalid spline: %s" % spline)
        #
        if spline == "density":
            # given density profile (either electron / gas mass density)
            if log10:
                x = ro.FloatVector(np.log10(self.r))
                y = ro.FloatVector(np.log10(self.d))
                self.d_spline_log10 = True
            else:
                x = ro.FloatVector(self.r)
                y = ro.FloatVector(self.s)
                self.d_spline_log10 = False
            self.d_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "electron":
            # input electron number density profile
            if log10:
                x = ro.FloatVector(np.log10(self.r))
                y = ro.FloatVector(np.log10(self.ne))
                self.ne_spline_log10 = True
            else:
                x = ro.FloatVector(self.r)
                y = ro.FloatVector(self.ne)
                self.ne_spline_log10 = False
            self.ne_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "rho_gas":
            # input gas mass density profile
            if log10:
                x = ro.FloatVector(np.log10(self.r))
                y = ro.FloatVector(np.log10(self.rho_gas))
                self.rho_gas_spline_log10 = True
            else:
                x = ro.FloatVector(self.r)
                y = ro.FloatVector(self.rho_gas)
                self.rho_gas_spline_log10 = False
            self.rho_gas_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "cooling_function":
            # input cooling function profile
            if log10:
                x = ro.FloatVector(np.log10(self.cf_radius))
                y = ro.FloatVector(np.log10(self.cf_value))
                self.cf_spline_log10 = True
            else:
                x = ro.FloatVector(self.cf_radius)
                y = ro.FloatVector(self.cf_value)
                self.cf_spline_log10 = False
            self.cf_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "temperature":
            # input temperature profile
            if log10:
                x = ro.FloatVector(np.log10(self.t_radius))
                y = ro.FloatVector(np.log10(self.t_value))
                self.t_spline_log10 = True
            else:
                x = ro.FloatVector(self.t_radius)
                y = ro.FloatVector(self.t_value)
                self.t_spline_log10 = False
            self.t_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "mass_total":
            # calculated total/gravitational mass profile
            if log10:
                x = ro.FloatVector(np.log10(self.radius))
                y = ro.FloatVector(np.log10(self.m_total))
                self.m_total_spline_log10 = True
            else:
                x = ro.FloatVector(self.radius)
                y = ro.FloatVector(self.m_total)
                self.m_total_spline_log10 = False
            self.m_total_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        elif spline == "rho_total":
            # calculated total mass density profile
            if log10:
                x = ro.FloatVector(np.log10(self.radius))
                y = ro.FloatVector(np.log10(self.rho_total))
                self.rho_total_spline_log10 = True
            else:
                x = ro.FloatVector(self.radius)
                y = ro.FloatVector(self.rho_total)
                self.rho_total_spline_log10 = False
            self.rho_total_spline = self.mgcv.gam(
                ro.Formula("y ~ s(x, bs='ps')"),
                data=ro.DataFrame({"x": x, "y": y}),
                method="REML")
        else:
            raise ValueError("invalid spline: %s" % spline)

    def eval_spline(self, spline, x):
        """
        Evaluate the specified spline at the supplied positions.
        Also check whether the spline was fitted in the log-scale space,
        and transform the evaluated values if necessary.
        """
        x = np.array(x)
        if x.shape == ():
            x = x.reshape((1,))
        if spline == "density":
            spl = self.d_spline
            log10 = self.d_spline_log10
        elif spline == "electron":
            spl = self.ne_spline
            log10 = self.ne_spline_log10
        elif spline == "rho_gas":
            spl = self.rho_gas_spline
            log10 = self.rho_gas_spline_log10
        elif spline == "cooling_function":
            spl = self.cf_spline
            log10 = self.cf_spline_log10
        elif spline == "temperature":
            spl = self.t_spline
            log10 = self.t_spline_log10
        elif spline == "mass_total":
            spl = self.m_total_spline
            log10 = self.m_total_spline_log10
        elif spline == "rho_total":
            spl = self.rho_total_spline
            log10 = self.rho_total_spline_log10
        else:
            raise ValueError("invalid spline: %s" % spline)
        #
        if log10:
            x_new = ro.ListVector({"x": ro.FloatVector(np.log10(x))})
            y_pred = self.mgcv.predict_gam(spl, newdata=x_new)
            y_pred = 10 ** np.array(y_pred)
        else:
            x_new = ro.ListVector({"x": ro.FloatVector(x)})
            y_pred = self.mgcv.predict_gam(spl, newdata=x_new)
            y_pred = np.array(y_pred)
        #
        if len(y_pred) == 1:
            return y_pred[0]
        else:
            return y_pred

    def gen_radius(self, num=1000):
        """
        Generate radial points for following mass and potential calculation.

        The generated radial points are logarithmic-evenly distributed.

        NOTE:
        The radii are first generated to determine the inner-most bin width,
        which is used to further divide the original inner-most bin (i.e.,
        radius 0 - r_out[0]), and then the other radii are generated with
        the constraint of given total number of points.
        """
        rout = self.r + self.r_err
        # first pass to determine the inner-most bin width
        rout_tmp = np.logspace(np.log10(rout[0]), np.log10(rout[-1]),
                               num=num, base=10.0)
        bw = rout_tmp[1] - rout_tmp[0]
        # linear-evenly divide the first original bin (0 - rout[0])
        nbin = int(np.ceil(rout[0] / bw))
        rout_new1 = np.linspace(0.0, rout[0], num=nbin, endpoint=False)[1:]
        # second pass to generate the other radii
        rout_new2 = np.logspace(np.log10(rout[0]), np.log10(rout[-1]),
                                num=(num-nbin+1), base=10.0)
        rout_new = np.concatenate([rout_new1, rout_new2])
        rin_new = np.concatenate([[0.0], rout_new[:-1]])
        self.radius = (rout_new + rin_new) / 2.0
        self.radius_err = (rout_new - rin_new) / 2.0

    def calc_mass_gas(self, verbose=False):
        """
        Calculate the gas mass profile, i.e., the mass of the gas within
        each radius.

        Reference: ref.[1], eq.(9)
        """
        def _f_rho_gas(r):
            return 4*np.pi * r**2 * self.eval_spline(spline="rho_gas", x=r)
        #
        m_gas = np.zeros(self.radius.shape)
        if verbose:
            print("Calculating the gas mass profile (#%d): ..." %
                  len(self.radius), end="", flush=True)
        c = au.kpc.to(au.cm)**3 * au.g.to(au.solMass)
        for i, r in enumerate(self.radius):
            if verbose and (i+1) % 50 == 0:
                print("%d..." % (i+1), end="", flush=True)
            # enclosed gas mass [ Msun ]
            m_gas[i] = c * integrate.quad(_f_rho_gas, a=0.0, b=r,
                                          epsrel=1e-3)[0]
        if verbose:
            print("DONE!", flush=True)
        self.m_gas = m_gas
        return m_gas

    def calc_mass_total(self, verbose=True):
        """
        Calculate the total mass (i.e., gravitational mass) profile,
        under the assumption of hydrostatic equilibrium (HE).

        References: ref.[1], eq.(5,6,7)
        """
        if self.t_radius is None or self.t_value is None:
            raise ValueError("temperature profile required")
        if self.t_spline is None:
            self.fit_spline(spline="temperature", log10=False)
        #
        # calculate the coefficient of the total mass formula
        # M0 = (k_B * T_gas(r) * r) / (mu * m_atom * G)
        M0 = ((1.0*au.keV) * (1.0*au.kpc) /
              (AstroParams.mu * ac.u * ac.G)).to(au.solMass).value
        m_total = np.zeros(self.radius.shape)
        if verbose:
            print("Calculating the total mass profile (#%d): ..." %
                  len(self.radius), end="", flush=True)
        for i, r in enumerate(self.radius):
            if verbose and (i+1) % 100 == 0:
                print("%d..." % (i+1), end="", flush=True)
            T = self.eval_spline(spline="temperature", x=r)
            dT_dr = derivative(lambda r: self.eval_spline("temperature", r),
                               r, dx=0.01)
            ne = self.eval_spline(spline="electron", x=r)
            dne_dr = derivative(lambda r: self.eval_spline("electron", r),
                                r, dx=0.01)
            # enclosed total mass [ Msun ]
            m_total[i] = - M0 * T * r * (((r / T) * dT_dr) +
                                         ((r / ne) * dne_dr))
        if verbose:
            print("DONE!", flush=True)
        self.m_total = m_total
        return m_total

    def calc_density_total(self, verbose=True):
        """
        Calculate the total mass density profile, which is required to
        calculate the following gravitational potential profile.
        """
        if self.m_total_spline is None:
            self.fit_spline(spline="mass_total", log10=True)
        #
        if verbose:
            print("Calculating the total mass density profile ...")
        rho_total = np.zeros(self.radius.shape)
        # unit conversion: Msun/kpc^3 -> g/cm^3
        c = au.solMass.to(au.g) / au.kpc.to(au.cm)**3
        for i, r in enumerate(self.radius):
            dM_dr = derivative(lambda r: self.eval_spline("mass_total", r),
                               r, dx=0.01)
            rho_total[i] = (dM_dr / (4 * np.pi * r**2)) * c
        self.rho_total = rho_total
        return rho_total

    def calc_potential(self, verbose=True):
        """
        Calculate the gravitational potential profile.

        NOTE:
        The integral in the potential formula can only be integrated
        to the largest radius of availability.
        This limitation will affect the absolute values of the calculated
        potentials, but not the shape of the potential profile.
        """
        def _int_inner(x):
            return x**2 * self.eval_spline(spline="rho_total", x=x)

        def _int_outer(x):
            return x * self.eval_spline(spline="rho_total", x=x)

        if self.rho_total is None:
            self.calc_density_total(verbose=verbose)
        if self.rho_total_spline is None:
            self.fit_spline(spline="rho_total", log10=True)
        potential = np.zeros(self.radius.shape)
        if verbose:
            print("Calculating the potential profile (#%d): ..." %
                  len(self.radius), end="", flush=True)
        r_max = max(self.radius)
        c = - 4 * np.pi * au.kpc.to(au.cm)**2
        for i, r in enumerate(self.radius):
            if verbose and (i+1) % 10 == 0:
                print("%d..." % (i+1), end="", flush=True)
            # total gravitational potential [ cm^2/s^2 ]
            potential[i] = c * ac.G.cgs.value * (
                (1/r) * integrate.quad(_int_inner, a=0.0, b=r,
                                       epsrel=1e-2)[0] +
                integrate.quad(_int_outer, a=r, b=r_max,
                               epsrel=1e-2)[0])
        if verbose:
            print("DONE!", flush=True)
        self.potential = potential
        return potential

    def plot(self, profile, with_spline=True, ax=None, fig=None):
        x = self.radius
        xlabel = "3D Radius"
        xunit = "kpc"
        xscale = "log"
        yscale = "log"
        x_spl, y_spl = None, None
        if profile == "electron":
            x = self.r
            y = self.ne
            ylabel = "Electron number density"
            yunit = "cm$^{-3}$"
            if with_spline:
                x_spl = self.radius
                y_spl = self.eval_spline(spline="electron", x=self.radius)
        elif profile == "mass_gas":
            y = self.m_gas
            ylabel = "Gas mass"
            yunit = "M$_{\odot}$"
        elif profile == "mass_total":
            y = self.m_total
            ylabel = "Total mass"
            yunit = "M$_{\odot}$"
        elif profile == "rho_total":
            y = self.rho_total
            ylabel = "Total mass density"
            yunit = "g/cm$^3$"
        elif profile == "potential":
            y = self.potential
            ylabel = "Gravitational potential"
            yunit = "cm$^2$/s$^2$"
            yscale = "linear"
        else:
            raise ValueError("unknown profile name: %s" % profile)
        #
        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.plot(x, y, linewidth=2)
        if with_spline and y_spl is not None:
            ax.plot(x_spl, y_spl, linewidth=2, linestyle="dashed")
        ax.set_xscale(xscale)
        ax.set_yscale(yscale)
        ax.set_xlim(min(x), max(x))
        y_min, y_max = min(y), max(y)
        y_min = y_min/1.2 if y_min > 0 else y_min*1.2
        y_max = y_max*1.2 if y_max > 0 else y_max/1.2
        ax.set_ylim(y_min, y_max)
        ax.set_xlabel(r"%s (%s)" % (xlabel, xunit))
        ax.set_ylabel(r"%s (%s)" % (ylabel, yunit))
        fig.tight_layout()
        return (fig, ax)

    def save(self, profile, outfile):
        if profile == "mass_gas":
            data = np.column_stack([self.radius,
                                    self.radius_err,
                                    self.m_gas])
            header = "radius[kpc]  radius_err[kpc]  mass_gas(<r)[Msun]"
        elif profile == "mass_total":
            data = np.column_stack([self.radius,
                                    self.radius_err,
                                    self.m_total])
            header = "radius[kpc]  radius_err[kpc]  mass_total(<r)[Msun]"
        elif profile == "rho_total":
            data = np.column_stack([self.radius,
                                    self.radius_err,
                                    self.rho_total])
            header = "radius[kpc]  radius_err[kpc]  density_total[g/cm^3]"
        elif profile == "potential":
            data = np.column_stack([self.radius,
                                    self.radius_err,
                                    self.potential])
            header = "radius[kpc]  radius_err[kpc]  potential[???]"
        else:
            raise ValueError("unknown profile name: %s" % profile)
        np.savetxt(outfile, data, header=header)


def main():
    parser = argparse.ArgumentParser(
            description="Calculate the mass and potential profiles")
    parser.add_argument("config", nargs="?", default="mass_potential.conf",
                        help="config for mass and potential profiles " +
                             "calculation (default: mass_potential.conf)")
    args = parser.parse_args()
    config = ConfigObj(args.config)

    ne_profile = np.loadtxt(config["ne_profile"])
    cf_profile = np.loadtxt(config["cf_profile"])
    t_profile = np.loadtxt(config["t_profile"])

    density_profile = DensityProfile(density=ne_profile,
                                     density_type="electron")
    density_profile.load_cf_profile(cf_profile)
    density_profile.load_t_profile(t_profile)
    density_profile.calc_density_electron()
    density_profile.calc_density_gas()
    density_profile.gen_radius(num=config.as_int("num_dp"))

    density_profile.calc_mass_gas(verbose=True)
    density_profile.save(profile="mass_gas",
                         outfile=config["m_gas_profile"])
    fig = Figure(figsize=(10, 8))
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    density_profile.plot(profile="mass_gas", ax=ax, fig=fig)
    fig.savefig(config["m_gas_profile_image"], dpi=150)

    density_profile.calc_mass_total(verbose=True)
    density_profile.save(profile="mass_total",
                         outfile=config["m_total_profile"])
    fig = Figure(figsize=(10, 8))
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    density_profile.plot(profile="mass_total", ax=ax, fig=fig)
    fig.savefig(config["m_total_profile_image"], dpi=150)

    density_profile.calc_density_total(verbose=True)
    density_profile.save(profile="rho_total",
                         outfile=config["rho_total_profile"])
    fig = Figure(figsize=(10, 8))
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    density_profile.plot(profile="rho_total", ax=ax, fig=fig)
    fig.savefig(config["rho_total_profile_image"], dpi=150)

    density_profile.calc_potential(verbose=True)
    density_profile.save(profile="potential",
                         outfile=config["potential_profile"])
    fig = Figure(figsize=(10, 8))
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    density_profile.plot(profile="potential", ax=ax, fig=fig)
    fig.savefig(config["potential_profile_image"], dpi=150)


if __name__ == "__main__":
    main()