import astropy.io.fits as fits import astropy.units as u from spectral_cube import SpectralCube from galaxies import Galaxy from pandas import DataFrame, read_csv import pandas as pd import statsmodels.formula.api as smf # Calculate line width, sigma; and surface density, Sigma. alpha = 6.7 sigma = I_mom0 / (np.sqrt(2*np.pi * I_max)) Sigma = alpha*I_mom0 # Importing radius of each data point. gal = Galaxy('NGC1672') hdr = fits.getheader('ngc1672_co21_12m+7m+tp_mom0.fits') rad = gal.radius(header=hdr) rad = (rad * u.Mpc.to(u.kpc)) * u.kpc / u.Mpc # Converts rad from Mpc to kpc. # Calculating width of each pixel, in parsecs. pixsizes_deg = wcs.utils.proj_plane_pixel_scales(wcs.WCS(hdr)) # The size of each pixel, in degrees. Ignore that third dimension; that's pixel size for the speed. pixsizes = pixsizes_deg[0] * np.pi / 180. # Pixel size, in radians. pcperpixel = pixsizes*d # Number of parsecs per pixel. pcperdeg = pcperpixel / pixsizes_deg[0] # Number of parsecs per degree. # Getting beam width, in degrees and parsecs. beam = hdr['BMAJ'] # Beam size, in degrees beam = beam * pcperdeg # Beam size, in pc # Import data from .fits files. I_mom0 = fits.getdata('ngc1672_co21_12m+7m+tp_mom0.fits') # Mass density at each pixel.
'logB': [], 'logC': [], 'logA_std': [], 'ind_std': [], 'logB_std': [], 'logC_std': [] } # for gal in ['M33', 'M31']: for gal in ['M31']: plot_folder = osjoin(data_path, "{}_plots".format(gal)) if not os.path.exists(plot_folder): os.mkdir(plot_folder) gal_obj = Galaxy(gal) gal_obj.distance = fitinfo_dict[gal]['distance'] if gal == 'M31': # Add 180 deg to the PA gal_obj.position_angle += 180 * u.deg filename = osjoin(data_path, gal, fitinfo_dict[gal]['filename']) hdu_coldens = fits.open(filename) proj_coldens = Projection.from_hdu( fits.PrimaryHDU(hdu_coldens[0].data[0].squeeze(), hdu_coldens[0].header)) # Get minimal size
M_vir = 540*np.power(R,2) #Luminous Mass best fit line M_lum = 2000*np.power(np.power(M_vir/39,1.234567901)/130,0.8) #Sigma_0, Mass Density, R_gal sigma0 = mytable['VRMS_EXTRAP_DECONV']/np.sqrt(mytable['RADRMS_EXTRAP_DECONV']) M_den = mytable['MASS_EXTRAP']/(np.pi*np.power(mytable['RADRMS_EXTRAP_DECONV'],2)) #Surface density derived from radarea instead of radrms high_Mden = np.where(M_den > 1000) den_check = mytable['MASS_EXTRAP']/(np.pi*np.power(mytable['RADAREA_DECONV'],2)) test = [40,44,94,104] # Marks the arm cloud that moves to a higher density #galactocentric radii mygalaxy = Galaxy("M100") cpropstable = Table.read('m100.co10.kkms_props_cprops_subsets_improved.fits') x, y = mygalaxy.radius(ra = mytable['XPOS'], dec = mytable['YPOS'], returnXY = True) rgal=mygalaxy.radius(ra = cpropstable['XPOS'], dec = cpropstable['YPOS']) #indexes for low R_gal group index = np.where(rgal.value < 1100) centre_in = np.where(mytable['Nuclear'] == True) arm_in = np.where(mytable['Arms'] == True) interarm_in = np.where(mytable['Interarm'] == True) outliers = np.where(mytable['Outliers'] == True) #Area of each region in kpc2 sr kpc^2 as found by region_areas.py area_arm = 99.0712520445 area_interarm = 106.465208911 area_nuc = 4.20965755925
from cube_analysis.rotation_curves import update_galaxy_params from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path # The models from the peak velocity aren't as biased, based on comparing # the VLA and VLA+GBT velocity curves. Using these as the defaults folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table) # Load in the model from the feathered data as well. folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal_feath = Galaxy("M33") update_galaxy_params(gal_feath, param_table)
from astropy.table import Table from scipy.spatial import Voronoi import matplotlib.path as mplPath import astropy.wcs as wcs from astropy.io import fits import astropy.units as u import numpy as np from galaxies import Galaxy m100 = Galaxy('M100') tbl = Table.read('m100.co10.kkms_props_cprops_withSFR_subsets.fits') hdr = fits.Header.fromtextfile('m100.header') w = wcs.WCS(hdr) ypix, xpix = np.meshgrid(np.linspace(0, 799, 800), np.linspace(0, 799, 800)) ra, dec = w.celestial.wcs_pix2world(xpix, ypix, 0) radius = m100.radius(ra=ra, dec=dec) rclds = m100.radius(ra=tbl[~tbl['Outliers']]['XPOS'], dec=tbl[~tbl['Outliers']]['YPOS']) maxrad = np.max(rclds.value) xcloud, ycloud, zcloud = w.wcs_world2pix(tbl['XPOS'], tbl['YPOS'], tbl['VPOS'], 0) vor = Voronoi(zip(xcloud, ycloud)) label = np.zeros((800, 800), dtype=np.str) keys = ['Nuclear', 'Interarm', 'Arm'] for idx, region in enumerate(vor.regions): verts = vor.vertices[region] path = mplPath.Path(verts) inout = path.contains_points(zip(xcloud, ycloud)) regions = path.contains_points(zip(xpix.ravel(), ypix.ravel()))
# -*- coding: utf-8 -*- #import libraries import astropy import astropy.table import numpy as np from astropy.table import Table import matplotlib.pyplot as plt from galaxies import Galaxy import astropy.units as u mygalaxy = Galaxy("M83") print(mygalaxy) mytable = Table.read('/home/pafreema/Documents/m83.co10.K_props_cprops.fits') idx = np.where(np.isfinite( mytable['VIRMASS_EXTRAP_DECONV'])) #removes values that are infinite/NaN rgal = mygalaxy.radius(ra=(mytable['XPOS'][idx]), dec=(mytable['YPOS'][idx])) #print rgal #get radii in parsecs sigma = (mytable['VRMS_EXTRAP_DECONV'][idx]) / np.sqrt( (mytable['RADRMS_EXTRAP_DECONV'][idx])**2) #sigma naught dens = (mytable['MASS_EXTRAP'][idx]) / (np.pi * ( (mytable['RADRMS_EXTRAP_DECONV'][idx])**2)) #mass density m, b = np.polyfit(np.log(dens), np.log(sigma), 1) x = np.linspace(10, 10e4, 100) figure = plt.figure(figsize=(4.5, 4)) plt.scatter(dens, sigma, c=rgal, marker='s')
def data(galaxyname, data, n_bins=1, r_nuc=0): # Import the libraries. from galaxies import Galaxy from astropy.table import Table from astropy.table import Column import astropy import powerlaw import numpy as np import astropy.table import astropy.units as u import matplotlib.pyplot as plt import matplotlib as mpl # Load its FITS file. t = Table.read(data) # Load the information about the galaxy. gxy = Galaxy(galaxyname) # Calculate the galaxy's properties. distance = np.asarray(gxy.distance) inclination = np.asarray(gxy.inclination) rgal = gxy.radius(ra=(t['XPOS']), dec=(t['YPOS'])) rgal = rgal.to(u.kpc) rpgal = np.asarray(rgal) # Append these to the FITS table. col_rgal = Column(name='RADIUS_KPC', data=(rgal)) t.add_column(col_rgal) # Sort the masses according to galactocentric radius. mass = t['MASS_EXTRAP'].data i_sorted = np.argsort(rgal) rgal_sorted = np.asarray(rgal[i_sorted]) mass_sorted = np.asarray(mass[i_sorted]) # Initiate a loop to calculate the bin boundaries and the indeces of these boundaries in the sorted list. totmass = np.sum(mass) / n_bins edge_f = 1.1 * np.max(rgal_sorted) edges = np.zeros(n_bins - 1) start = 0 mass_equiv = [0] #indeces for the sorted mass bins of equal mass mass_area = [0] #indeces for the sorted mass bins of equal area rgal_equiv = [ 0, 2, 8**0.5, 12**0.5, 4, 20**0.5, 24**0.5, 28**0.5, 32**0.5, 6 ] r = 1 #equal-area radial index e = 0 #edge index f = 0 #loop flag to skip the mass_area loop c = 0 #loop counter for i in range(len(mass_sorted)): #Find the indeces for bins of equal mass (equivalent to totmass) if np.sum(mass_sorted[start:i]) > totmass: edges[e] = 0.5 * (rgal_sorted[i] + rgal_sorted[i - 1]) start = i mass_equiv = np.append(mass_equiv, i) e = e + 1 #Find the indeces for bins of equal area (4pi kpc^2) if rgal_sorted[i] > rgal_equiv[r] and not f: if rgal_sorted[i] < rgal_equiv[3] and not f: mass_area = np.append(mass_area, i) r = r + 1 c = 0 if rgal_sorted[i] > rgal_equiv[3]: f = 1 mass_area = np.append(mass_area, i) mass_equiv = np.append(mass_equiv, i) inneredge = np.concatenate(([0.000000], edges)) outeredge = np.concatenate((edges, [edge_f])) # Create a template for a new table. column_names = [ 'Inner edge (kpc)', 'Outer edge (kpc)', 'GMC index', 'R', 'p', 'Truncation mass ($M_\mathrm{\odot}$)', 'Largest cloud ($M_\mathrm{\odot}$)', '5th largest cloud ($M_\mathrm{\odot}$)' ] column_types = ['f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4', 'f4'] table = Table(names=column_names, dtype=column_types) # Fill the table. for inneredge, outeredge in zip(inneredge, outeredge): idx = np.where((t['RADIUS_KPC'] >= inneredge) & (t['RADIUS_KPC'] < outeredge)) mass = t['MASS_EXTRAP'][idx].data fit = powerlaw.Fit(mass) fit_subset = powerlaw.Fit(mass, xmin=3e5) R, p = fit.distribution_compare('power_law', 'truncated_power_law') table.add_row() table[-1]['R'] = R table[-1]['p'] = p table[-1]['GMC index'] = -fit.alpha table[-1]['Inner edge (kpc)'] = inneredge table[-1]['Outer edge (kpc)'] = outeredge table[-1]['Largest cloud ($M_\mathrm{\odot}$)'] = np.nanmax(mass) table[-1][ 'Truncation mass ($M_\mathrm{\odot}$)'] = 1 / fit.truncated_power_law.parameter2 table[-1]['5th largest cloud ($M_\mathrm{\odot}$)'] = np.sort( t['MASS_EXTRAP'][idx])[-5] # Write the data to a FITS file. table.write('../Data/' + galaxyname + '_data.fits', overwrite=True) # Plot the mass distribution trends for equal-mass bins. t = Table.read('../Data/' + galaxyname + '_data.fits') inneredge = t['Inner edge (kpc)'].data outeredge = t['Outer edge (kpc)'].data subplot_label = ('(a)', '(b)', '(c)', '(d)', '(e)', '(f)') for i in range(len(mass_equiv) - 1): binmass = mass_sorted[mass_equiv[i]:mass_equiv[i + 1]] myfit = powerlaw.Fit(binmass) R, p = myfit.distribution_compare('power_law', 'truncated_power_law') fig = myfit.truncated_power_law.plot_ccdf(label='Truncated\nPower Law') myfit.power_law.plot_ccdf(label='Power Law', ax=fig) myfit.plot_ccdf(drawstyle='steps', label='Data', ax=fig) # Format the plot. plt.legend(loc=0) #plt.title(galaxyname+'Equal-mass Mass Distribution, bin '+repr(i+1)) plt.ylim(ymin=10**-3) plt.xlabel(r'$M_\mathrm{\odot}$', fontsize=20) plt.ylabel('CCDF', fontsize=20) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.text(0.01, 0.5, subplot_label[i], ha='left', va='center', transform=fig.transAxes, fontsize=16) plt.text( 0.35, 0.01, r'$M_{bin}\ =\ %e M_\mathrm{\odot}$' % (totmass) + '\n' + r'$R_{gal}\ =\ %5.4f\ \mathrm{kpc}\ \mathrm{to}\ %5.4f\ \mathrm{kpc}$' % (inneredge[i], outeredge[i]) + '\n' + r'$\mathrm{R}\ =\ %5.4f,\ \mathrm{p}\ =\ %5.4f$' % (R, p) + '\n' + r'$\alpha\ =\ %5.4f,\ M_\mathrm{0}\ =\ %5.4eM_\mathrm{\odot}$' % (-myfit.alpha, 1 / myfit.truncated_power_law.parameter2), ha='left', va='bottom', transform=fig.transAxes, fontsize=16) plt.savefig('../Data/' + galaxyname + '_power_law_equal_mass_' + repr(i + 1) + '.png') plt.close() # Plot the mass distribution trend for equal-area bins. for i in range(len(mass_area) - 1): f = 0 #loop flag if mass_area[i + 1] - mass_area[i] < 3: f = 1 if not f: binmass = mass_sorted[mass_area[i]:mass_area[i + 1]] myfit = powerlaw.Fit(binmass) R, p = myfit.distribution_compare('power_law', 'truncated_power_law') fig = myfit.truncated_power_law.plot_ccdf( label='Truncated\nPower Law') myfit.power_law.plot_ccdf(label='Power Law', ax=fig) myfit.plot_ccdf(drawstyle='steps', label='Data', ax=fig) # Format the plot. plt.legend(loc=0) #plt.title(galaxyname+'Equal-area Mass Distribution, bin '+repr(i+1)) plt.ylim(ymin=10**-3) plt.xlabel(r'$M_\mathrm{\odot}$', fontsize=20) plt.ylabel('CCDF', fontsize=20) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.text(0.01, 0.5, subplot_label[i], ha='left', va='center', transform=fig.transAxes, fontsize=16) plt.text( 0.35, 0.01, r'$R_{gal}\ =\ %5.4f\ \mathrm{kpc}\ \mathrm{to}\ %5.4f\ \mathrm{kpc}$' % (rgal_equiv[i], rgal_equiv[i + 1]) + '\n' + r'$\mathrm{R}\ =\ %5.4f,\ \mathrm{p}\ =\ %5.4f$' % (R, p) + '\n' + r'$\alpha\ =\ %5.4f,\ M_\mathrm{0}\ =\ %5.4eM_\mathrm{\odot}$' % (-myfit.alpha, 1 / myfit.truncated_power_law.parameter2), ha='left', va='bottom', transform=fig.transAxes, fontsize=16) plt.savefig('../Data/' + galaxyname + '_power_law_equal_area_' + repr(i + 1) + '.png') plt.close() return [distance, inclination]
def param(galaxyname, data, r_nuc=0): # This is a module that will plot graphs of the clouds' virial parameter, surface density, # and linewidth on a one-parsec scale to its galactocentric radius. # import the libraries that are needed. from scipy import stats as sps from galaxies import Galaxy from astropy.table import Table import numpy as np import astropy.units as u import matplotlib.pyplot as plt import matplotlib as mpl # Load all of the data. gxy = Galaxy(galaxyname) cpropstable = Table.read(data) # Extract different data set lw = cpropstable['VRMS_EXTRAP'] xval = cpropstable['XPOS'] yval = cpropstable['YPOS'] vmass = cpropstable['VIRMASS_EXTRAP_DECONV'] mass = cpropstable['MASS_EXTRAP'] radrms = cpropstable['RADRMS_EXTRAP_DECONV'] rgal = gxy.radius(ra=xval, dec=yval) rgal = rgal.to(u.kpc) # Sort the masses according to galactocentric radius. i_sorted = np.argsort(rgal) rgal_sorted = np.asarray(rgal[i_sorted]) mass_sorted = np.asarray(mass[i_sorted]) # Calculate the virial parameter, surface density, and linewidth on a one-parsec scale. alpha = vmass / mass sigma = mass / (radrms**2) lwo = lw / ((radrms)**0.5) # Initialize the arrays to extract the glactic disk cloud properties. rad_sorted = radrms[i_sorted] alpha_sorted = np.log10(alpha[i_sorted]) sigma_sorted = np.log10(sigma[i_sorted]) lwo_sorted = np.log10(lwo[i_sorted]) #lwo_sorted = lwo[i_sorted] lw_sorted = lw[i_sorted] mass_disk = [] #mass of each disk GMC rad_disk = [] #radius of each disk GMC alpha_disk = [] #virial parameter of each disk GMC sigma_disk = [] #suface density of each disk GMC lwo_disk = [] #normalized linewidth of each disk GMC lw_disk = [] #linewidth of each disk GMC # Create a loop to extract the galactic disk GMC properties. for i in range(len(mass_sorted)): if rgal_sorted[i] > r_nuc: if not np.isnan(alpha_sorted[i]) and not np.isnan( sigma_sorted[i]) and not np.isnan( lwo_sorted[i]) and not np.isnan(lw_sorted[i]): mass_disk = np.append(mass_disk, mass_sorted[i]) rad_disk = np.append(rad_disk, rad_sorted[i]) alpha_disk = np.append(alpha_disk, alpha_sorted[i]) sigma_disk = np.append(sigma_disk, sigma_sorted[i]) lwo_disk = np.append(lwo_disk, lwo_sorted[i]) lw_disk = np.append(lw_disk, lw_sorted[i]) # Separate the data into bins, then calculate the mean values. binaxis = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5] bin_means, bin_edges, binnumber = sps.binned_statistic( rgal, mass, statistic='mean', bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) bin_medians, bin_edges, binnumber = sps.binned_statistic( rgal, mass, statistic='median', bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) lwo_medians, bin_edges, binnumber = sps.binned_statistic( rgal, lwo, statistic=np.nanmedian, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) alpha_medians, bin_edges, binnumber = sps.binned_statistic( rgal, alpha, statistic=np.nanmedian, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) sigma_medians, bin_edges, binnumber = sps.binned_statistic( rgal, sigma, statistic=np.nanmedian, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # Plot the parameters with respect to the galactocentric radius. figure1 = plt.figure(figsize=(15, 5)) ax = plt.subplot(1, 3, 1) l1 = plt.plot(rgal, alpha) plt.yscale('log') plt.setp(l1, marker='D', markersize=5, linestyle='None', color='b', label='GMC', alpha=0.7) plt.errorbar(binaxis, alpha_medians, xerr=0.5, linestyle='None', marker='o', color='k', lw=5, alpha=0.7, label='Median') plt.legend(loc=0) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.text(0.5, 0.99, '(a)', ha='center', va='top', transform=ax.transAxes, fontsize=16) plt.xlabel(r'$R_g\ (\mathrm{kpc})$', fontsize=20) plt.ylabel(r'$\alpha$', fontsize=20) #plt.title('(a)',fontsize=20) ax = plt.subplot(1, 3, 2) l1 = plt.plot(rgal, sigma) plt.yscale('log') plt.setp(l1, marker='D', markersize=5, linestyle='None', color='b', label='GMC', alpha=0.7) plt.errorbar(binaxis, sigma_medians, xerr=0.5, linestyle='None', marker='o', color='k', lw=5, alpha=0.7, label='Median') plt.legend(loc=0) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.text(0.5, 0.99, '(b)', ha='center', va='top', transform=ax.transAxes, fontsize=16) plt.xlabel(r'$R_g\ (\mathrm{kpc})$', fontsize=20) plt.ylabel(r'$\Sigma\ (\frac{M_\mathrm{\odot}}{\mathrm{pc}^{2}})$', fontsize=20) #plt.title('(b)',fontsize=20) ax = plt.subplot(1, 3, 3) l1 = plt.plot(rgal, lwo) plt.setp(l1, marker='D', markersize=5, linestyle='None', color='b', label='GMC', alpha=0.7) plt.errorbar(binaxis, lwo_medians, xerr=0.5, linestyle='None', marker='o', color='k', lw=5, alpha=0.7, label='Median') plt.legend(loc=0) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.text(0.5, 0.99, '(c)', ha='center', va='top', transform=ax.transAxes, fontsize=16) plt.xlabel(r'$R_g\ (\mathrm{kpc})$', fontsize=20) plt.ylabel(r'$\sigma_{0}\ (\frac{\mathrm{km}}{\mathrm{s}})$', fontsize=20) #plt.title('(c)',fontsize=20) plt.tight_layout() plt.savefig('../Parameters/' + galaxyname + '_param.png') plt.close() # Make a figure of the median mass for a given radius. figure2 = plt.figure(figsize=(8, 8)) plt.errorbar(binaxis, bin_means, xerr=0.5, linestyle='None', marker='D', color='b', label='Mean', alpha=0.7) plt.errorbar(binaxis, bin_medians, xerr=0.5, linestyle='None', marker='D', color='g', label='Median', alpha=0.7) plt.yscale('log') plt.legend(loc=0) mpl.rc('xtick', labelsize=16) mpl.rc('ytick', labelsize=16) plt.xlabel(r'$R\ (\mathrm{kpc})$', fontsize=20) plt.ylabel(r'$M_{\mathrm{lum}}\ (M_{\odot})$', fontsize=20) #plt.title('GMC Mass Distribution in '+galaxyname,fontsize=20) plt.tight_layout() plt.savefig('../Parameters/' + galaxyname + '_dist.png') plt.close() return [mass_disk, rad_disk, alpha_disk, sigma_disk, lwo_disk, lw_disk]