Ejemplo n.º 1
0
    def fit_close_background(self, marker='o', markersize='3', color='black'):
        # retrieve background dataframe
        background = self.background.copy()
        # x and y data set as bin locations in alpha, density respectively
        xdata = -background.m31_bin_locs

        ydata = background.bin_densities
        # error also found
        yerr = background.bin_uncs
        # models set with appropriate initial estimates depending on
        # stars and galaxies
        # overcrowded bins skipped for better fit
        # fit carried out
        model = Sersic1D(r_eff=2, n=10.00)

        fit = fitting.LevMarLSQFitter()

        if self.galaxy == 'ngc205' and self.stars == 'c':

            model = Sersic1D(r_eff=10, n=20)
            s = fit(model, xdata[2:], ydata[2:])

        elif self.galaxy == 'm32' and self.stars == 'c':
            model = Sersic1D(r_eff=20, n=10)
            s = fit(model, xdata[3:], ydata[3:])
        elif self.galaxy == 'm32':

            model = Sersic1D(r_eff=20, n=2)
            s = fit(model, xdata[3:], ydata[3:], weights=1/yerr[3:])

        else:

            s = fit(model, xdata[2:], ydata[2:], weights=1/yerr[2:])

        # fit and data plotted with uncertainties
        plt.figure()

        sat_xdata = background.bin_locs

        plt.gca().set_xlabel(r'$\alpha$ (arcmins)')
        plt.gca().set_ylabel('Density (N/arcmin$^2$)')
        plt.gca().invert_xaxis()
        plt.errorbar(sat_xdata, ydata, yerr=yerr, capsize=2,
                     linestyle='none', marker=marker, color=color)

        plt.plot(sat_xdata, s(xdata), label=self.galaxy.upper())

        leg = plt.legend(handlelength=0, handletextpad=0,
                         frameon=False, loc='upper right', markerscale=0.001)
        for item in leg.legendHandles:
            item.set_visible(False)

        plt.savefig(self.galaxy + self.stars + '_background_fit.png')
        plt.savefig(self.galaxy + self.stars + '_background_fit.pdf')

        # sersic fit added to background dataframe
        background['density_fit'] = s(xdata)

        self.background = background
Ejemplo n.º 2
0
    def fit_close_slice_count_profile(self, stars='agb', crowding_num=1):

        distribution = pd.read_parquet('unfit_background_corrected_profiles' +
                                       self.galaxy + stars)

        xdata = distribution.a
        ydata = distribution.density
        yerr = distribution.density_err

        plt.errorbar(xdata,
                     ydata,
                     yerr=yerr,
                     marker='o',
                     linestyle='none',
                     color='black')

        plt.ylabel('Density (N/arcmins$^2$)')
        plt.xlabel('Semi-major axis (arcmins)')

        xdata_orig = xdata

        xdata = xdata[:len(xdata) - (crowding_num)]
        ydata = ydata[:len(ydata) - (crowding_num)]
        yerr = yerr[:len(yerr) - (crowding_num)]

        if self.galaxy == 'ngc205':

            model = Sersic1D(r_eff=2.0, n=1.5)

        elif self.galaxy == 'm32':

            model = Sersic1D(r_eff=1.7, n=1.00)

        fit = fitting.LevMarLSQFitter()

        s = fit(model, xdata, ydata, weights=1 / yerr)

        xdata = np.linspace(min(xdata_orig), max(xdata_orig), num=1000)

        plt.plot(xdata,
                 s(xdata),
                 label='Sersic Fit with a$_{eff}$ = ' +
                 str(round(s.r_eff.value, 3)) + ', n = ' +
                 str(round(s.n.value, 3)))
        plt.legend()
Ejemplo n.º 3
0
    def make_galaxies_astropy(self, image, flux, galsize, x, y, ar, pa, n=4):

        for f, s, xi, yi, pai, ari, in zip(flux, galsize, x, y, pa, ar):

            fluxlim = 0.0001 * f  # 0.1
            scale = 1  # arcsec/pixel
            r_e = s  # effective radius
            ellip = ari  # ellipticity
            theta = numpy.deg2rad(pai)  # position angle
            x_cent = 0  # x centroid
            y_cent = 0  # x centroid
            tot_flux = f  # total flux

            s1 = Sersic1D(amplitude=1, r_eff=r_e, n=n)
            r = numpy.arange(0, 1000, scale)
            s1_n = s1(r) / sum(s1(r))
            extent = numpy.where(s1_n * f > fluxlim)[0].max()

            if extent % 2 > 0:
                extent += 1

            ser_model = Sersic2D(r_eff=r_e,
                                 n=n,
                                 ellip=ellip,
                                 theta=theta,
                                 x_0=x_cent,
                                 y_0=y_cent)

            x = numpy.arange(-extent / 1., extent / 1., scale) + x_cent / scale
            y = numpy.arange(-extent / 1., extent / 1., scale) + y_cent / scale

            X, Y = numpy.meshgrid(x, y)

            img = ser_model(X, Y)
            img /= numpy.sum(img)
            img *= tot_flux

            xi, yi = int(xi), int(yi)
            # COLUMNS FIRST -- because FITS are silly
            image[yi - img.shape[1] // 2:yi + img.shape[1] // 2,
                  xi - img.shape[0] // 2:xi + img.shape[0] // 2] += img

        return image
Ejemplo n.º 4
0
def getLbulge(Amp_eff, R_eff, n, R):  # R en pc
    s2 = Sersic1D(Amp_eff, R_eff, n)
    a = 1
    b = a * sqrt(1 - (0.56**2))
    #I = s2(R)
    Re = R_eff
    Ie = s2(Re)
    bn = 1.9992 * n - 0.3271

    #x = bn *((R/Re)**(1/n))
    #gammaInc = gammainc(2*n,x)*sc.gamma(2*n)

    L = (2 * pi * (b / a) * Ie *
         (R**2) * exp(bn) * n * sc.gamma(2 * n)) / (bn**(2 * n))
    print(L)

    #L = Ie*(Re**2)*2*pi*n*( (exp(bn))/(bn**(2*n)) )*gammaInc

    return (L)
Ejemplo n.º 5
0
def iterativeLuminosity(Amp_eff, R_eff, n):
    s2 = Sersic1D(Amp_eff, R_eff, n)
    a = 1
    b = a * sqrt(1 - (0.56**2))
    #Re = R_eff
    #Ie = s2(Re)
    #bn = 1.9992*n - 0.3271

    r = np.arange(0, (max(rkPC)), 0.001)
    for i in r:
        Ilist.append(s2(i))
    for index in range(len(Ilist) - 1):
        r1 = r[index]
        r2 = r[index + 1]
        #I1 = Ilist[index]
        I2 = Ilist[index + 1]
        L2 = 2 * pi * (b / a) * I2 * (((r2 * 1e3)**2) - ((r1 * 1e3)**2))
        if (index == 0):
            Lr.append(L2)
        else:
            Lr.append(L2 + Lr[index - 1])
Ejemplo n.º 6
0
#!/usr/bin/python

import numpy as np
from astropy.modeling.models import Sersic1D
import matplotlib.pyplot as plt

plt.figure()
plt.subplot(111, xscale='log', yscale='log')
s1 = Sersic1D(amplitude=1, r_eff=5)
r=np.arange(0, 100, .01)

for n in range(1, 10):
     s1.n = n
     plt.plot(r, s1(r), color=str(float(n) / 15))

plt.axis([1e-1, 30, 1e-2, 1e3])
plt.xlabel('log Radius')
plt.ylabel('log Surface Brightness')
plt.text(.25, 1.5, 'n=1')
plt.text(.25, 300, 'n=10')
plt.xticks([])
plt.yticks([])
plt.show()
Ejemplo n.º 7
0
def logSersic1D(x,amplitude,n,r_eff):
    model=Sersic1D(amplitude=amplitude,n=n,r_eff=r_eff)
    return np.log(model(x))
Ejemplo n.º 8
0
    def fit_slice_count_profile(self, background_deg, crowding_num=0):

        slices = self.slices
        areas = self.areas
        outer_rad = self.outer_rad
        a_width = self.a_width
        ellipticity = self.ellipticity
        slice_nums = []

        for i in slices:
            slice_nums.append(len(i.dropna()))

        slice_nums = np.array(slice_nums)

        areas = np.array(areas)

        slice_count_uncs = np.sqrt(slice_nums)

        slice_star_densities = slice_nums / areas
        slice_star_densities_uncs = (np.sqrt((slice_count_uncs / areas)**2 +
                                             background_deg[1]**2))

        slice_star_densities = slice_star_densities - background_deg[0]

        slice_star_densities = slice_star_densities / 3600
        slice_star_densities_uncs = slice_star_densities_uncs / 3600

        xdata = np.linspace(outer_rad - a_width / 2,
                            0 + a_width / 2,
                            num=(outer_rad * 1000) / (a_width * 1000))
        xdata = xdata * 60
        # convert from a to r_eff
        ydata = slice_star_densities
        yerr = slice_star_densities_uncs

        #plt.errorbar(xdata,ydata,yerr=yerr,linestyle='none',marker='o',markersize=5,capsize=2,color='black',label='AGB data')
        #plt.xlabel('Semi-major axis/arcmins')
        # plt.ylabel('Nstars/arcmins$^2$')

        # n147 params

        xdata_orig = xdata
        ydata_orig = ydata
        yerr_orig = yerr

        xdata = xdata[:len(xdata) - (crowding_num)]
        ydata = ydata[:len(ydata) - (crowding_num)]
        yerr = yerr[:len(yerr) - (crowding_num)]

        if self.galaxy == 'ngc147':

            model = Sersic1D(r_eff=5.2, n=1.8)

        elif self.galaxy == 'ngc185':

            model = Sersic1D(r_eff=1.7, n=1.00)

        fit = fitting.LevMarLSQFitter()

        s = fit(model, xdata, ydata, weights=1 / yerr)

        xdata = np.linspace(min(xdata_orig), max(xdata_orig), 1000)

        #plt.plot(xdata,s(xdata),label='Sersic Fit with r$_{eff}$ = ' + str(round(s.r_eff.value,3)) + ', n = ' + str(round(s.n.value,3)))

        # plt.legend()
        print(s)
        self.r_eff = s.r_eff.value
        self.n = s.n.value

        return xdata_orig, ydata_orig, yerr_orig, xdata, s(xdata)
Ejemplo n.º 9
0
Rout_vD = 7.6e3  # in pc
Mtot_vD = 3.4e8  # in Msun
Re_vD = 3.1e3  # in pc
Me_vD = 3.2e8  # in Msun

# Compute Mb(r) and Md(r) for multiple Sersic indices
nlist = [0.6, 1, 2, 3, 4]
rlist = [1e3] * len(nlist)

#nlist = [1]
#rlist = [1e3]

for i in range(len(nlist)):

    # Projected Sersic profile
    s_vD = Sersic1D(amplitude=1., r_eff=1e3,
                    n=nlist[i])  # Van Dokkum et al. 2018
    rhob_Rpy = s_vD(R)
    #Mb_Rpy = 4.*pi * cumtrapz(rhob_Rpy * R**2, x = R, initial=0.)
    Mb_Rpy = 2. * pi * cumtrapz(rhob_Rpy * R, x=R, initial=0.)

    # Adjust the amplitude of rhob and Mb according to Mtot
    #Mb_last = Mb_Rpy[-1]
    #rhob_Rpy = rhob_Rpy * Mb_vD/Mb_last
    #Mb_Rpy = Mb_Rpy * Mb_vD/Mb_last
    """
    # Test stuff
    Mb_an = 4.*pi*Mb_vD/Mb_last * np.log(R) # Test mass
    Md_an = np.sqrt(Cd * 4.*pi*Mb_vD/Mb_last * (np.log(R)+1.)) * R
    Md_an = np.sqrt(Cd * np.gradient(Mb_an * R, R)) * R
    Mtot_an = Mb_an + Md_an
Ejemplo n.º 10
0
M_test = 1.
n_test = 4.
r_test = 1e3

nlist = [0.6, 1., 2., 3., 4.]

for i in range(len(nlist)):

    n_test = nlist[i]

    # Sersic profile density and mass
    rhob_R, rhob_r = Sersic(M_test, n_test, r_test, R)
    Mb_R = 2. * pi * cumtrapz(rhob_R * R, x=R, initial=0.)

    # Projected Sersic profile
    s_vD = Sersic1D(amplitude=M_test, r_eff=r_test,
                    n=n_test)  # Van Dokkum et al. 2018
    rhob_Rpy = s_vD(R)
    Mb_Rpy = 2. * pi * cumtrapz(rhob_Rpy * R, x=R, initial=0.)

    # Adjust the amplitude of rhob and Mb according to Mtot
    #Mb_last = Mb_Rpy[-1]
    #rhob_Rpy = rhob_Rpy * Mb_vD/Mb_last
    #Mb_Rpy = Mb_Rpy * Mb_vD/Mb_last

    # Plot Sersic profile results
    """
    plt.plot(R, rhob_R, ls='-', label=r'$\rho_{\rm b}$(r) for n=%g (projected)'%n_test)
    plt.plot(R, rhob_Rpy, ls='-', label=r'$\rho_{\rm b}$(r) for n=%g (python)'%n_test)
    plt.plot(R, np.abs((rhob_R-rhob_Rpy)/(rhob_R+rhob_Rpy)/2.), ls=':', label=r'Difference')
    """
Ejemplo n.º 11
0
def display_ellipse_sbprofile(ellipsefit, minerr=0.02, sersicfit=None,
                              png=None, verbose=True):
    """Display the multi-band surface brightness profile.

    """
    from legacyhalos.ellipse import ellipse_sbprofile

    band, refband, redshift = ellipsefit['band'], ellipsefit['refband'], ellipsefit['redshift']

    if ellipsefit['success']:
        sbprofile = ellipse_sbprofile(ellipsefit, minerr=minerr)

    colors = iter(sns.color_palette())

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)
    for filt in band:

        if ellipsefit['success']:
            good = (ellipsefit[filt].stop_code < 4)
            bad = ~good

            col = next(colors)
            ax1.fill_between(sbprofile['sma'], 
                sbprofile['mu_{}'.format(filt)] - sbprofile['mu_{}_err'.format(filt)],
                sbprofile['mu_{}'.format(filt)] + sbprofile['mu_{}_err'.format(filt)],
                #sbprofile['{}'.format(filt)] - sbprofile['{}_err'.format(filt)],
                #sbprofile['{}'.format(filt)] + sbprofile['{}_err'.format(filt)],
                label=r'${}$'.format(filt), color=col, alpha=0.75, edgecolor='k', lw=2)
            #if np.count_nonzero(bad) > 0:
            #    ax1.scatter(sbprofile['sma'][bad], sbprofile[filt][bad], marker='s',
            #                s=40, edgecolor='k', lw=2, alpha=0.75)

            #ax1.axhline(y=ellipsefit['mu_{}_sky'.format(filt)], color=col, ls='--')
            if filt == refband:
                ysky = ellipsefit['mu_{}_sky'.format(filt)] - 2.5 * np.log10(0.1) # 10% of sky
                ax1.axhline(y=ysky, color=col, ls='--')

            # Overplot the best-fitting model.
            if sersicfit:
                from astropy.modeling.models import Sersic1D
                rad = np.arange(0, sbprofile['sma'].max(), 0.1)
                sbmodel = -2.5 * np.log10( Sersic1D.evaluate(
                    rad, sersicfit[filt].amplitude, sersicfit[filt].r_eff,
                    sersicfit[filt].n) )
                ax1.plot(rad, sbmodel, lw=2, ls='--', alpha=1, color=col)
            
    ax1.set_ylabel(r'Surface Brightness (mag arcsec$^{-2}$)')
    ax1.set_ylim(30, 17)

    #ax1.set_ylabel(r'$\mu$ (mag arcsec$^{-2}$)')
    #ax1.set_ylim(31.99, 18)

    if ellipsefit['success']:
        ax1.legend(loc='upper right')

        ax2.fill_between(sbprofile['sma'],
                         sbprofile['rz'] - sbprofile['rz_err'],
                         sbprofile['rz'] + sbprofile['rz_err'],
                         label=r'$r - z$', color=next(colors), alpha=0.75,
                         edgecolor='k', lw=2)

        ax2.fill_between(sbprofile['sma'],
                         sbprofile['gr'] - sbprofile['gr_err'],
                         sbprofile['gr'] + sbprofile['gr_err'],
                         label=r'$g - r$', color=next(colors), alpha=0.75,
                         edgecolor='k', lw=2)

        ax2.set_xlabel('Semimajor Axis (arcsec)', alpha=0.75)
        ax2.legend(loc='upper left')
    else:
        ax2.set_xlabel('Semimajor Axis', alpha=0.75)
        
    ax2.set_ylabel('Color (mag)')
    ax2.set_ylim(0, 2.4)

    fig.subplots_adjust(hspace=0.0)

    if png:
        if verbose:
            print('Writing {}'.format(png))
        fig.savefig(png)
        plt.close(fig)
    else:
        plt.show()