def rms_logprob(p,surf_lum, sigobs_lum, qobs_lum, surf_pot, sigobs_pot, qobs_pot, \ Mbh, dist, xbin, ybin, Vrmsbin, dVrmsbin, qmin, sigmapsf, pixsize,ideg_in): beta_scalar = p[0] ml = p[1] ideg_lim = np.arccos(qmin) * 180. / np.pi # defining the distribution of the priors priors = ss.uniform.logpdf(beta_scalar,loc=-1.0,scale=2.0)+\ ss.uniform.logpdf(ml,loc=0.0,scale=10.0) #condition related to the limitations of the priors if np.isfinite(priors) == False: return -np.inf #...Call JAM code _, _, chi2,_ = \ jam_axi_rms(surf_lum, sigobs_lum, qobs_lum, surf_pot, sigobs_pot, qobs_pot, ideg_in, Mbh, dist, xbin, ybin, plot=False, quiet=True, rms=Vrmsbin,ml=ml, erms=dVrmsbin, sigmapsf=sigmapsf, beta=beta_scalar+(surf_lum*0), pixsize=pixsize) #calculating the log-probability throght the chi2 of the Vrms_model fit lp = -chi2 * len(Vrmsbin) + priors if np.isnan(lp): return -np.inf return lp
def test_jam_axi_vel(): """ Usage example for jam_axi_vel(). It takes about 5s on a 2.5 GHz computer """ np.random.seed(123) xbin, ybin = np.random.uniform(low=[-55, -40], high=[55, 40], size=[1000, 2]).T inc = 60. # assumed galaxy inclination r = np.sqrt(xbin**2 + (ybin/np.cos(np.radians(inc)))**2) # Radius in the plane of the disk a = 40 # Scale length in arcsec vr = 2000*np.sqrt(r)/(r+a) # Assumed velocity profile vel = vr * np.sin(np.radians(inc))*xbin/r # Projected velocity field sig = 8700/(r+a) # Assumed velocity dispersion profile rms = np.sqrt(vel**2 + sig**2) # Vrms field in km/s surf = np.array([39483., 37158., 30646., 17759., 5955.1, 1203.5, 174.36, 21.105, 2.3599, 0.25493]) sigma = np.array([0.153, 0.515, 1.58, 4.22, 10, 22.4, 48.8, 105, 227, 525]) qObs = np.full_like(sigma, 0.57) distance = 16.5 # Assume Virgo distance in Mpc (Mei et al. 2007) mbh = 1e8 # Black hole mass in solar masses beta = np.full_like(surf, 0.3) surf_lum = surf # Assume self-consistency sigma_lum = sigma qobs_lum = qObs surf_pot = surf sigma_pot = sigma qobs_pot = qObs sigmapsf = 0.6 pixsize = 0.8 goodbins = r > 10 # Arbitrarily exclude the center to illustrate how to use goodbins # First the M/L is determined by fitting the Vrms. # In general beta_z and the inclination will also be # fitted at this stage as described in Cappellari (2008) rmsModel, ml, chi2, flux = jam_axi_rms( surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin, ybin, plot=True, rms=rms, goodbins=goodbins, sigmapsf=sigmapsf, beta=beta, pixsize=pixsize, tensor='zz') plt.pause(0.01) # The velocity is fitted at the best fitting M/L, beta_z and # inclination determined at the previous stage surf_pot *= ml # Scale the density by the best fitting M/L velModel, kappa, chi2, flux = jam_axi_vel( surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin, ybin, plot=True, vel=vel, goodbins=goodbins, sigmapsf=sigmapsf, beta=beta, pixsize=pixsize, component='z') plt.pause(0.01)
def lnlike(theta, ParameterNames, Data, model, mbh, distance, FixedStellarMass, logStellarMass, reff, filename, surf_lum, sigma_lum, qobs_lum): ParameterNames = np.array(ParameterNames) if 'Inclination' in ParameterNames: inc = np.array(theta)[np.where(ParameterNames == 'Inclination')] else: raise ValueError('Inclination not set as a free parameter. ') if 'Beta' in ParameterNames: beta = np.array(theta)[np.where(ParameterNames == 'Beta')] else: raise ValueError('Beta not set as a free parameter. ') if 'ScaleDensity' in ParameterNames: log_rho_s = np.array(theta)[np.where(ParameterNames == 'ScaleDensity')] else: raise ValueError('Scale density not set as a free parameter. ') if 'Gamma' in ParameterNames: gamma = np.array(theta)[np.where(ParameterNames == 'Gamma')] else: raise ValueError('Gamma not set as a free parameter. ') if 'ML' in ParameterNames: ml = np.array(theta)[np.where(ParameterNames == 'ML')] elif FixedStellarMass: # calculate here what the M/L should be in order for the total luminous MGE to account for # all measured stellar mass. sigma_lum_pc = sigma_lum * ( distance * 1e6) / 206265 # since the input sigma_lum is in arcseconds. StellarMassMGE = MGE_mass_total(surf_lum, sigma_lum_pc, qobs_lum, 1000 * reff, radian(inc), 1) ml = 10**logStellarMass / StellarMassMGE else: ml = 1 if 'ScaleRadius' in ParameterNames: R_S = np.array(theta)[np.where(ParameterNames == 'ScaleRadius')] else: R_S = 20000 if len(Data) == 4: if 'AtlasWeight' in ParameterNames: raise ValueError( "ATLAS^3D hyperparameter set, but ATLAS^3D data not provided.") else: xbin1, ybin1, rms1, erms1 = Data DatasetNumber = 1 elif len(Data) == 8: if not 'AtlasWeight' in ParameterNames: raise ValueError("ATLAS^3D hyperparameter not not provided.") if not 'SluggsWeight' in ParameterNames: raise ValueError("SLUGGS hyperparameter not not provided.") sluggsWeight = np.array(theta)[np.where( ParameterNames == 'SluggsWeight')] atlasWeight = np.array(theta)[np.where( ParameterNames == 'AtlasWeight')] xbin1, ybin1, rms1, erms1, xbin2, ybin2, rms2, erms2 = Data DatasetNumber = 2 elif len(Data) == 12: if not 'AtlasWeight' in ParameterNames: raise ValueError("ATLAS^3D hyperparameter not not provided.") if not 'SluggsWeight' in ParameterNames: raise ValueError("SLUGGS hyperparameter not not provided.") if not 'GCWeight' in ParameterNames: raise ValueError("GC hyperparameter not not provided.") sluggsWeight = np.array(theta)[np.where( ParameterNames == 'SluggsWeight')] atlasWeight = np.array(theta)[np.where( ParameterNames == 'AtlasWeight')] gcWeight = np.array(theta)[np.where(ParameterNames == 'GCWeight')] xbin1, ybin1, rms1, erms1, xbin2, ybin2, rms2, erms2, xbin3, ybin3, rms3, erms3 = Data DatasetNumber = 3 beta_array = np.ones(len(surf_lum)) * beta n_MGE = 300. # logarithmically spaced radii in parsec x_MGE = np.logspace(np.log10(1), np.log10(30000), n_MGE) # the units of the density are now mass/pc^2 if model == 'gNFW': y_MGE = gNFW_RelocatedDensity(1000, x_MGE, 10.**log_rho_s, R_S, gamma) # measured at 1 kpc (1000 pc) p = mge.mge_fit_1d(x_MGE, y_MGE, ngauss=10, quiet=True) surf_dm = p.sol[0] # here implementing a potential sigma_dm = p.sol[1] * 206265 / (distance * 1e6 ) # configuration which includes the qobs_dm = np.ones(len(surf_dm)) # stellar mass and also a dark matter # halo in the form of a gNFW distribution. surf_pot = np.append( ml * surf_lum, surf_dm ) # I'm going to need to be careful here to account for the stellar M/L, sigma_pot = np.append( sigma_lum, sigma_dm ) # since the scaling between the two mass distributions needs to be right. qobs_pot = np.append(qobs_lum, qobs_dm) # if DatasetNumber == 1: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2 = np.sum( np.log(2 * np.pi * erms1**2) + ((rms1 - rmsModel) / erms1)**2.) except: realChi2 = np.inf elif DatasetNumber == 2: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_sluggs = np.sum( np.log(2 * np.pi * erms1**2 / sluggsWeight) + (sluggsWeight * (rms1 - rmsModel) / erms1)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin2, ybin2, filename, rms=rms2, erms=erms2, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_atlas = np.sum( np.log(2 * np.pi * erms2**2 / atlasWeight) + (atlasWeight * (rms2 - rmsModel) / erms2)**2.) realChi2 = realChi2_sluggs + realChi2_atlas except: realChi2 = np.inf elif DatasetNumber == 3: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_sluggs = np.sum( np.log(2 * np.pi * erms1**2 / sluggsWeight) + (sluggsWeight * (rms1 - rmsModel) / erms1)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin2, ybin2, filename, rms=rms2, erms=erms2, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_atlas = np.sum( np.log(2 * np.pi * erms2**2 / atlasWeight) + (atlasWeight * (rms2 - rmsModel) / erms2)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin3, ybin3, filename, rms=rms3, erms=erms3, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_gc = np.sum( np.log(2 * np.pi * erms3**2 / gcWeight) + (gcWeight * (rms3 - rmsModel) / erms3)**2.) realChi2 = realChi2_sluggs + realChi2_atlas + realChi2_gc except: realChi2 = np.inf elif model == 'powerLaw': y_MGE = powerLaw(x_MGE, 10.**log_rho_s, R_S, gamma, -3) p = mge.mge_fit_1d(x_MGE, y_MGE, ngauss=10, quiet=True) surf_pot = p.sol[0] sigma_pot = p.sol[1] * 206265 / ( distance * 1e6 ) # converting the dispersions into arcseconds because it wants only qobs_pot = np.ones( len(surf_pot)) # the radial dimension in these units. if DatasetNumber == 1: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, ml, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2 = np.sum( np.log(2 * np.pi * erms1**2) + ((rms1 - rmsModel) / erms1)**2.) except: realChi2 = np.inf elif DatasetNumber == 2: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, ml, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_sluggs = np.sum( np.log(2 * np.pi * erms1**2 / sluggsWeight) + (sluggsWeight * (rms1 - rmsModel) / erms1)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin2, ybin2, filename, ml, rms=rms2, erms=erms2, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_atlas = np.sum( np.log(2 * np.pi * erms2**2 / atlasWeight) + (atlasWeight * (rms2 - rmsModel) / erms2)**2.) realChi2 = realChi2_sluggs + realChi2_atlas except: realChi2 = np.inf elif DatasetNumber == 3: try: rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin1, ybin1, filename, ml, rms=rms1, erms=erms1, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_sluggs = np.sum( np.log(2 * np.pi * erms1**2 / sluggsWeight) + (sluggsWeight * (rms1 - rmsModel) / erms1)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin2, ybin2, filename, ml, rms=rms2, erms=erms2, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_atlas = np.sum( np.log(2 * np.pi * erms2**2 / atlasWeight) + (atlasWeight * (rms2 - rmsModel) / erms2)**2.) rmsModel, ml, chi2, flux = Jrms.jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin3, ybin3, filename, ml, rms=rms3, erms=erms3, plot=False, beta=beta_array, tensor='zz', quiet=True) realChi2_gc = np.sum( np.log(2 * np.pi * erms3**2 / gcWeight) + (gcWeight * (rms3 - rmsModel) / erms3)**2.) realChi2 = realChi2_sluggs + realChi2_atlas + realChi2_gc except: realChi2 = np.inf else: raise ValueError( 'Model is unrecognisable. Should be either "gNFW" or "powerLaw"') return -realChi2 / 2
def test_jam_axi_vel(): """ Usage example for jam_axi_vel(). It takes about 5s on a 2.5 GHz computer """ np.random.seed(123) xbin, ybin = np.random.uniform(low=[-55, -40], high=[55, 40], size=[1000, 2]).T inc = 60. # assumed galaxy inclination r = np.sqrt( xbin**2 + (ybin / np.cos(np.radians(inc)))**2) # Radius in the plane of the disk a = 40 # Scale length in arcsec vr = 2000 * np.sqrt(r) / (r + a) # Assumed velocity profile vel = vr * np.sin(np.radians(inc)) * xbin / r # Projected velocity field sig = 8700 / (r + a) # Assumed velocity dispersion profile rms = np.sqrt(vel**2 + sig**2) # Vrms field in km/s surf = np.array([ 39483., 37158., 30646., 17759., 5955.1, 1203.5, 174.36, 21.105, 2.3599, 0.25493 ]) sigma = np.array([0.153, 0.515, 1.58, 4.22, 10, 22.4, 48.8, 105, 227, 525]) qObs = np.full_like(sigma, 0.57) distance = 16.5 # Assume Virgo distance in Mpc (Mei et al. 2007) mbh = 1e8 # Black hole mass in solar masses beta = np.full_like(surf, 0.3) surf_lum = surf # Assume self-consistency sigma_lum = sigma qobs_lum = qObs surf_pot = surf sigma_pot = sigma qobs_pot = qObs sigmapsf = 0.6 pixsize = 0.8 goodbins = r > 10 # Arbitrarily exclude the center to illustrate how to use goodbins # First the M/L is determined by fitting the Vrms. # In general beta_z and the inclination will also be # fitted at this stage as described in Cappellari (2008) rmsModel, ml, chi2, flux = jam_axi_rms(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin, ybin, plot=True, rms=rms, goodbins=goodbins, sigmapsf=sigmapsf, beta=beta, pixsize=pixsize, tensor='zz') plt.pause(0.01) # The velocity is fitted at the best fitting M/L, beta_z and # inclination determined at the previous stage surf_pot *= ml # Scale the density by the best fitting M/L velModel, kappa, chi2, flux = jam_axi_vel(surf_lum, sigma_lum, qobs_lum, surf_pot, sigma_pot, qobs_pot, inc, mbh, distance, xbin, ybin, plot=True, vel=vel, goodbins=goodbins, sigmapsf=sigmapsf, beta=beta, pixsize=pixsize, component='z') plt.pause(0.01)
qobs_tot = np.append(qobs_lum, qobs_dm) # jamFigureFilename = JAM_path + '/' + str( GalName) + '/' + suffix + '/' + str( GalName) + '_' + suffix + '_Fig' rmsModel, ml_JAM, chi2, flux = Jrms.jam_axi_rms( surf_lum, sigma_lum, qobs_lum, surf_tot, sigma_tot_arcsec, qobs_tot, inc, mbh, distance, xbin, ybin, jamFigureFilename, rms=rms, erms=erms, plot=True, beta=beta_array, tensor='zz', quiet=False) plt.close() Radius_MassProfile = np.logspace( np.log10(10), np.log10(30000), 100) dataRadiusMaximum = np.sqrt(
def tests_jam_hernquist_model(): M = 1e11 # Total mass in Solar Masses a = 1e3 # Break radius in pc distance = 16.5 # Assume Virgo distance in Mpc (Mei et al. 2007) pc = distance*np.pi/0.648 # Constant factor to convert arcsec --> pc G = 0.00430237 # (km/s)**2 pc/Msun [6.674e-11 SI units] mbh = 0 n = 300 # Number of values to sample the H90 profile for the fit r = np.logspace(-2.5, 2, n)*a # logarithmically spaced radii in pc rho = M*a/(2*np.pi*r*(r+a)**3) # Density in Msun/pc**3 (H90 equation 2) m = mge_fit_1d(r, rho, ngauss=16, plot=True) plt.pause(0.01) surf = m.sol[0,:] # Surface density in Msun/pc**2 sigma = m.sol[1,:]/pc # Gaussian dispersion in arcsec qObs = np.full_like(surf, 1) # Assume spherical model inc = 90 # Edge-on view npix = 100 rad = np.linspace(0.01, 50, npix) # desired output radii in arcsec (avoid R=0) r = rad*pc ################## Circular Velocity ################# vcirc = mge_vcirc(surf, sigma, qObs, inc, mbh, distance, rad) plt.clf() plt.subplot(211) plt.plot(rad, vcirc, 'b', linewidth=8) plt.xlabel('R (arcsec)') plt.ylabel(r'$V_{circ}$, $V_{rms}$ (km/s)') plt.title('Reproduces the analytic results by Hernquist (1990)') # Compare with analytic result # vc = np.sqrt(G*M*r)/(r+a) # H90 equation (16) plt.plot(rad, vc, 'LimeGreen', linewidth=3) plt.text(30, 310, '$V_{circ}$ (mge_vcirc, H90)') #################### Isotropic Vrms ################### # Spherical isotropic H90 model # sigp = jam_sph_rms(surf, sigma, surf, sigma, mbh, distance, rad)[0] plt.plot(rad, sigp, 'b', linewidth=8) # Axisymmetric isotropic model in the spherical limit. # This is plotted on the major axis, but the Vrms has circular symmetry # vrms = jam_axi_rms(surf, sigma, qObs, surf, sigma, qObs, inc, mbh, distance, rad, rad*0)[0] plt.plot(rad, vrms, 'r', linewidth=5) # Analytic surface brightness from H90 # s = r/a xs = np.where(s < 1, np.arccosh(1/s) / np.sqrt(1 - s**2), # H90 equation (33) np.arccos(1/s) / np.sqrt(s**2 - 1)) # H90 equation (34) IR = M*((2 + s**2)*xs - 3) / (2*np.pi*a**2*(1 - s**2)**2) # H90 equation (32) # Projected second moments of isotropic model from H90 # sigp = np.sqrt( G*M**2/(12*np.pi*a**3*IR) # H90 equation (41) * ( 0.5/(1 - s**2)**3 * ( -3*s**2*xs* (8*s**6 - 28*s**4 + 35*s**2 - 20) - 24*s**6 + 68*s**4 - 65*s**2 + 6) - 6*np.pi*s) ) plt.plot(rad, sigp, 'LimeGreen', linewidth=2) plt.text(20, 90, 'Isotropic $V_{rms}$ (jam_sph, jam_axi, H90)') ################### Anisotropic Vrms ################## # Projected second moments for a H90 model with sigma_R=0. # This implies beta=-Infinity but I adopt as an approximation # below a large negative beta. This explains why te curves do not # overlap perfectly. # beta = np.full_like(surf, -20) sigp = jam_sph_rms(surf, sigma, surf, sigma, mbh, distance, rad, beta=beta)[0] plt.plot(rad, sigp, linewidth=8) # Axisymmetric anisotropic model in the spherical limit. # The spherical Vrms is the quadratic average of major # and minor axes of the axisymmetric model. # vrms_maj = jam_axi_rms(surf, sigma, qObs, surf, sigma, qObs, inc, mbh, distance, rad, rad*0, beta=beta)[0] vrms_min = jam_axi_rms(surf, sigma, qObs, surf, sigma, qObs, inc, mbh, distance, rad*0, rad, beta=beta)[0] plt.plot(rad, np.sqrt((vrms_maj**2 + vrms_min**2)/2), 'r', linewidth=5) # Projected second moments of fully tangential model from H90 # sigp = np.sqrt( G*M**2*r**2/(2*np.pi*a**5*IR) # H90 equation (42) * ( 1./(24*(1 - s**2)**4) * ( -xs*(24*s**8 - 108*s**6 + 189*s**4 - 120*s**2 + 120) - 24*s**6 + 92*s**4 - 117*s**2 + 154) + 0.5*np.pi/s) ) plt.plot(rad, sigp, 'LimeGreen', linewidth=2) plt.text(20, 200, 'Tangential $V_{rms}$ (jam_sph, jam_axi, H90)') ############### Anisotropic models with Black Hole ############### # Reproduces Fig.4.20 of Binney J., & Tremaine S.D., 2008, # Galactic Dynamics, 2nd ed., Princeton University Press plt.subplot(212) plt.xlabel('R/a') plt.ylabel('$V_{rms}\\, (G M / a)^{-1/2}$') plt.title('Reproduces Fig.4.20 of Binney & Tremaine (2008)') cost = np.sqrt(G*M/a) rad = np.logspace(-2.3, 1, 50)*a/pc # desired output radii in arcsec bhs = np.array([0., 0.002, 0.004])*M betas = np.array([-0.51, 0, 0.51]) # Avoids singularity at beta=+/-0.5 colors = ['r', 'b', 'LimeGreen'] for color, beta in zip(colors, betas): betaj = np.full_like(surf, beta) for bh in bhs: sigp = jam_sph_rms(surf, sigma, surf, sigma, bh, distance, rad, beta=betaj)[0] plt.semilogx(rad/a*pc, sigp/cost, linewidth=5, color=color) # Test the jam_axi_rms with Black Hole in the spherical isotropic limit # for bh in bhs: vrms = jam_axi_rms(surf, sigma, qObs, surf, sigma, qObs, inc, bh, distance, rad, rad*0)[0] plt.semilogx(rad/a*pc, vrms/cost, linewidth=2, color=colors[2]) plt.axis([0.006, 10, 0, 0.6]) # x0, x1, y0, y1 plt.tight_layout() plt.text(0.03, 0.15,'$\\beta$=-0.5 (tangential: jam_sph)', color=colors[0]) plt.text(.03, 0.35,'$\\beta$=0 (isotropic: jam_sph, jam_axi)', color=colors[1]) plt.text(0.03, 0.5,'$\\beta$=0.5 (radial: jam_sph)', color=colors[2]) plt.pause(0.01) # allow the plot to appear in certain situations
def runjam(gal, qmin, dist, surf_lum, sigobs_lum, qobs_lum, surf_pot, sigobs_pot, qobs_pot, xbin, ybin, Vrmsbin, dVrmsbin, Mbh, sigmapsf, pixscale, nwalks, burn_steps, steps, threads, ideg_in): ideg_lim = np.arccos(qmin) * 180. / np.pi #print 'ideg_enter=',ideg_lim # Set the number of the free parameters and the walkers ndim, nwalkers = 2, nwalks p0 = np.zeros((nwalkers, ndim)) # set the start position of the walkers p0[:, 0] = np.random.uniform(-1, 1.0, nwalkers) p0[:, 1] = np.random.uniform(0, 10, nwalkers) #stop() # Call EMCEE code sampler = emcee.EnsembleSampler(nwalkers, ndim, rms_logprob, args=[surf_lum, sigobs_lum, qobs_lum, surf_pot, sigobs_pot, qobs_pot, \ Mbh, dist, xbin, ybin, Vrmsbin, dVrmsbin, qmin, sigmapsf, pixscale,ideg_in], \ threads=threads) print "%&%&%&%&%&%&%&%&%&%&%&%&%&" print "Run MCMC analysis" print "%&%&%&%&%&%&%&%&%&%&%&%&%&" # result from the EMCEE code print("Burn-in...") #pos, prob, state = sampler.run_mcmc(p0, burn_steps) peixe = fish.ProgressFish(total=burn_steps) for j, results in enumerate(sampler.sample(p0, iterations=burn_steps)): peixe.animate(amount=j + 1) pos = results[0] burn_chains = sampler.chain.copy() burn_lns = sampler.lnprobability.copy() burn_flatchains = sampler.flatchain.copy() burn_flatlns = sampler.flatlnprobability.copy() #################################################### #... save the data in a file np.savez('data_output/Burn_in/' + gal + '_burn_lnP', chain_JAM=sampler.chain, lnprobability_JAM=sampler.lnprobability) #... save the data in a file np.savez('data_output/Burn_in/' + gal + '_burn_flatlnP', flatchain_JAM=sampler.flatchain, flatlnprobability_JAM=sampler.flatlnprobability) ################################################## # RUN again MCMC after burn-in print("Running MCMC...") sampler.reset() #pos,prob,state = sampler.run_mcmc(pos, 10) peixe = fish.ProgressFish(total=steps) for j, results in enumerate(sampler.sample(pos, iterations=steps)): peixe.animate(amount=j + 1) final_chains = sampler.chain final_lns = sampler.lnprobability final_flatchains = sampler.flatchain final_flatlns = sampler.flatlnprobability #################################################### #... save the data in a file np.savez('data_output/Chains/' + gal + '_final_lnP', chain_JAM=sampler.chain, lnprobability_JAM=sampler.lnprobability) #... save the data in a file np.savez('data_output/Chains/' + gal + '_final_flatlnP', flatchain_JAM=sampler.flatchain, flatlnprobability_JAM=sampler.flatlnprobability) #################################################### # make distributions of the parameters beta_dist = final_flatchains[:, 0] beta_md = np.median(beta_dist) beta_plus = np.percentile(final_flatchains[:, 0], 75) - np.median( final_flatchains[:, 0]) beta_minus = np.median(final_flatchains[:, 0]) - np.percentile( final_flatchains[:, 0], 25) ml_dist = final_flatchains[:, 1] ml_md = np.median(ml_dist) ml_plus = np.percentile(final_flatchains[:, 1], 75) - np.median( final_flatchains[:, 1]) ml_minus = np.median(final_flatchains[:, 1]) - np.percentile( final_flatchains[:, 1], 25) #----------------------------------------------- medians = [beta_md, ml_md, ideg_in] # Array for the upper 75th percentiles ups = [beta_plus, ml_plus, 0.0] # Array for the lower 25th percentiles lws = [beta_minus, ml_minus, 0.0] # make table table = Table([medians, ups, lws], names=['#medians(Bz, M/L, ideg_in)', 'ups', 'lws ']) table.write("data_output/Tables/" + gal + "_bestfit.txt", format="ascii.tab", delimiter=",") #------------------------------------------------- print "%&%&%&%&%&%&%&%&%&%&%&%&%&" print "Final best fit values" print "%&%&%&%&%&%&%&%&%&%&%&%&%&" print 'Beta_z:' , np.median(final_flatchains[:,0]), \ '+', np.percentile(final_flatchains[:,0], 75) - np.median(final_flatchains[:,0]),\ '-', np.median(final_flatchains[:,0]) - np.percentile(final_flatchains[:,0], 25) print 'M/L: ', np.median(final_flatchains[:,1]), \ '+', np.percentile(final_flatchains[:,1], 75) - np.median(final_flatchains[:,1]),\ '-', np.median(final_flatchains[:,1]) - np.percentile(final_flatchains[:,1], 25) #--------------------------------------------------------------- print "%&%&%&%&%&%&%&%&%&%&%&%&%&" print "Final Vrms model" print 'ideg_in=', ideg_in print "%&%&%&%&%&%&%&%&%&%&%&%&%&" rmsmodel, _, chi2, flux = \ jam_axi_rms(surf_lum, sigobs_lum, qobs_lum, surf_pot, sigobs_pot, qobs_pot, ideg_in, Mbh, dist, xbin, ybin, plot=False, rms=Vrmsbin,ml=ml_md, erms=dVrmsbin, sigmapsf=sigmapsf, beta=beta_md+(surf_lum*0), pixsize=pixscale) chi2 = chi2 * len(Vrmsbin) / (len(Vrmsbin) - 2) return table, burn_chains, burn_lns, burn_flatchains, burn_flatlns, \ final_chains, final_lns, final_flatchains, final_flatlns, rmsmodel, chi2, flux