def main():

    import grid
    import numpy as np
    from os import system,path
    import myclumpfinder as clump_finder
    import mygeometry as myg
    import json

    # define directory locations
    output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/california/figures/cores/'
    av_dir = '/d/bip3/ezbc/california/data/av/'
    hi_dir = '/d/bip3/ezbc/california/data/galfa/'
    region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'
    core_dir = '/d/bip3/ezbc/california/data/python_output/core_properties/'

    # load 2mass Av and GALFA HI images, on same grid
    av_image, h = load_fits(av_dir + 'california_av_planck_5arcmin.fits',
            return_header=True)

    # define core properties
    with open(core_dir + 'california_core_properties.txt', 'r') as f:
        cores = json.load(f)

    cores = convert_core_coordinates(cores, h)

    cores = load_ds9_region(cores,
            filename_base = region_dir + 'california_av_boxes_',
            header = h)

    if True:
        limits = [0, 20, -1, 25] # x-linear limits

        # Initialize fit params
        A_p = []
        pho_c = []
        R_flat = []
        p = []

        # Initialize data lists
        radii_pc_list = []
        profile_list = []
        profile_std_list = []
        profile_fit_params_list = []
        core_names_list = []

        for core in cores:
            print('Calculating for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_image,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

            mask = myg.get_polygon_mask(av_image,
                    cores[core]['box_vertices_rotated'])

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)

            av_image_sub = np.copy(av_image)
            #av_image_sub[mask == 0] = np.NaN
            av_image_sub = np.ma.array(av_image, mask=(mask == 0))

            # to check the positions of the boxes, uncomment the following
            #import matplotlib.pyplot as plt
            #plt.clf()
            #plt.imshow(np.ma.array(av_image_sub, mask=temp_mask))
            #plt.savefig('/usr/users/ezbc/Desktop/map%s.png' % core)
            #plt.clf()

            pix = cores[core]['center_pixel']

            # extract radial profile weighted by SNR
            radii, profile = get_radial_profile(av_image, binsize=3,
                    center=pix,
                    weights=av_image / 0.3,
                    mask=mask
                    )

            # extract std
            radii, profile_std = get_radial_profile(av_image_sub, binsize=3,
                    center=pix,
                    stddev=True,
                    weights=av_image_sub / 0.3,
                    #mask=mask
                    )

            # convert radii from degrees to parsecs
            radii_arcmin = radii * h['CDELT2'] * 60 * 60. # radii in arcminutes
            radii_pc = radii_arcmin * 300 / 206265. # radii in parsecs

            # extract radii from within the limits
            indices = np.where((radii_pc < limits[1]) & \
                               (profile == profile) & \
                               (profile_std == profile_std))
            radii_pc = radii_pc[indices]
            profile = profile[indices]
            profile_std = profile_std[indices]

            # fit profile with power function
            def function(radius, A_p, pho_c, R_flat, p):
                return A_p * pho_c * R_flat / \
                        (1 + (radius / R_flat)**2)**(p/2. - 0.5)
                #return A_p * radius**p

            profile_fit_params = fit_profile(radii_pc, profile, function,
                    sigma=profile / profile_std)[0]

            # plot the radial profile
            figure_types = ['.pdf', '.png']
            for figure_type in figure_types:
                plot_profile(radii_pc, profile,
                        profile_errors = profile_std,
                        limits = limits,
                        profile_fit_params = profile_fit_params,
                        profile_fit_function = function,
                        savedir=figure_dir + 'individual_cores/',
                        filename = 'california_profile_av_' + core + figure_type,
                        title=r'Radial A$_V$ Profile of california Core ' + core,
                        show = False)

            A_p.append(profile_fit_params[0])
            pho_c.append(profile_fit_params[1])
            R_flat.append(profile_fit_params[2])
            p.append(profile_fit_params[3])

            radii_pc_list.append(radii_pc)
            profile_list.append(profile)
            profile_std_list.append(profile_std)
            profile_fit_params_list.append(profile_fit_params)
            core_names_list.append(core)

        for figure_type in figure_types:
            plot_profile_grid(radii_pc_list, profile_list,
                    profile_errors_list = profile_std_list,
                    limits = limits,
                    profile_fit_params_list = profile_fit_params_list,
                    profile_fit_function = function,
                    savedir=figure_dir + 'panel_cores/',
                    filename = 'california_profile_av_cores_planck' + figure_type,
                    title=r'Radial A$_V$ Profiles of california Cores',
                    core_names=core_names_list,
                    show = False)


        print_fit_params(cores, A_p, pho_c, R_flat, p,
                filename=output_dir + 'core_profile_fit_data.txt')

        print_fit_params(cores, A_p, pho_c, R_flat, p)
def main():

    import grid
    import numpy as np
    from myimage_analysis import calculate_nhi
    from mycoords import make_velocity_axis
    import pyfits as pf
    import mygeometry as myg
    import json

    # parameters used in script
    # -------------------------
    # Regions
    # Options are 'ds9' or 'av_gradient'
    box_method = 'av_gradient'

    # define directory locations
    # --------------------------
    output_dir = '/d/bip3/ezbc/perseus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/perseus/figures/dgr/'
    av_dir = '/d/bip3/ezbc/perseus/data/av/'
    hi_dir = '/d/bip3/ezbc/perseus/data/hi/'
    co_dir = '/d/bip3/ezbc/perseus/data/cfa/'
    core_dir = '/d/bip3/ezbc/perseus/data/python_output/core_properties/'
    region_dir = '/d/bip3/ezbc/perseus/data/python_output/ds9_regions/'
    property_dir = '/d/bip3/ezbc/perseus/data/python_output/'

    av_data_planck, planck_header = pf.getdata(av_dir + \
                'perseus_av_planck_5arcmin.fits',
            header=True)
    av_data_error_planck, planck_header = pf.getdata(av_dir + \
                'perseus_av_error_planck_5arcmin.fits',
            header=True)

    # load GALFA HI
    hi_data, hi_header = pf.getdata(hi_dir + \
            'perseus_hi_galfa_cube_regrid_planckres.fits',
            header=True)
    velocity_axis = make_velocity_axis(hi_header)

    noise_cube, noise_header = pf.getdata(hi_dir + \
            'perseus_hi_galfa_cube_regrid_planckres_noise.fits', header=True)

    # define core properties
    with open(core_dir + 'perseus_core_properties.txt', 'r') as f:
        cores = json.load(f)

    cores = convert_core_coordinates(cores, planck_header)

    cores = load_ds9_region(cores,
            filename_base = region_dir + 'perseus_av_boxes_',
            header = planck_header)

    # Initialize lists
    av_images = []
    av_error_images = []
    nhi_images = []
    nhi_error_images = []

    for core in cores:
        print('\nCalculating for core %s' % core)
        if box_method == 'ds9':
            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
                    xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)
        elif box_method == 'av_gradient':
            mask = myg.get_polygon_mask(av_data_planck,
                    cores[core]['box_vertices_rotated'])
        else:
        	raise ValueError('Method for boxes is either ds9 or av_gradient')

        indices = mask == 1

        # Get only the relevant pixels to decrease computation time
        hi_data_sub = np.copy(hi_data[:, indices])
        noise_cube_sub = np.copy(noise_cube[:, indices])
        av_data_planck_sub = np.copy(av_data_planck[indices])
        av_data_error_planck_sub = np.copy(av_data_error_planck[indices])

        # Derive N(HI) image
        nhi_image, nhi_image_error = calculate_nhi(cube=hi_data_sub,
                velocity_axis=velocity_axis,
                noise_cube=noise_cube_sub,
                velocity_range=cores[core]['hi_velocity_range'])

        nhi_images.append(nhi_image)
        nhi_error_images.append(nhi_image_error)
        av_images.append(av_data_planck_sub)
        av_error_images.append(av_data_error_planck_sub)

    plot_av_vs_nhi_grid(nhi_images,
                        av_images,
                        av_error_images=av_error_images,
                        nhi_error_images=nhi_error_images,
                        #limits=[0,14, 0,10],
                        scale=['linear', 'log'],
                        savedir=figure_dir,
                        plot_type='scatter',
                        filename='perseus_av_vs_nhi_panels.png',
                        color_scale='linear')

    # Derive N(HI) image
    nhi_image, nhi_image_error = calculate_nhi(cube=hi_data,
            velocity_axis=velocity_axis,
            noise_cube=noise_cube,
            velocity_range=cores[core]['hi_velocity_range'])

    # Plot correlation, similar to Figure 3 of Paradis et al. (2012)
    plot_av_vs_nhi(nhi_image,
            av_data_planck,
            savedir=figure_dir,
            scale=['log', 'linear'],
            filename='perseus_av_vs_nhi_global.png',
            color_scale='linear')
Esempio n. 3
0
def main():

    import grid
    import numpy as np
    from os import system,path
    import myclumpfinder as clump_finder
    reload(clump_finder)
    import mygeometry as myg
    reload(myg)
    from mycoords import make_velocity_axis
    import mymath
    reload(mymath)

    # define directory locations
    output_dir = '/d/bip3/ezbc/perseus/data/python_output/co_dispersion/'
    figure_dir = '/d/bip3/ezbc/perseus/figures/'
    av_dir = '/d/bip3/ezbc/perseus/data/av/'
    hi_dir = '/d/bip3/ezbc/perseus/data/galfa/'
    cfa_dir = '/d/bip3/ezbc/perseus/data/cfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/taurus/data/python_output/ds9_regions/'

    # load 2mass Av and GALFA HI images, on same grid
    cfa_data, cfa_header = load_fits(cfa_dir + \
                'perseus_cfa_cube_galfa_regrid.fits',
            return_header=True)

    #av_data += - 0.4 # subtracts background of 0.4 mags
    hi_data, hi_header = load_fits(hi_dir + \
                'perseus_galfa_cube_bin_3.7arcmin.fits',
            return_header = True)

    # make the velocity axis
    hi_velocity_axis = make_velocity_axis(hi_header)
    cfa_velocity_axis = make_velocity_axis(cfa_header)

    cfa_mom2 = mymath.calc_moment(cfa_data, moment = 2, spectral_axis = 0)

    # define core properties
    cores = {'L1495':
                {'center_wcs': [(4,14,0), (28, 11, 0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,16,30), (27,44,30), (4,5,20), (28,28,33)]
                 },
             'L1495A':
                {'center_wcs': [(4,18,0), (28,23., 0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,28,23),(28,12,50),(4,16,23),(29,46,5)],
                 },
             'B213':
                {'center_wcs': [(4, 19, 0), (27, 15,0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,22,27), (26,45,47),(4,5,25),(27,18,48)],
                },
             'B220':
                {'center_wcs': [(4, 41, 0.), (26,7,0)],
                 'map': None,
                 'threshold': 7,
                 'box_wcs': [(4,47,49),(25,31,13),(4,40,37),(27,31,17)],
                 },
             'L1527':
                {'center_wcs': [(4, 39, 0.), (25,47, 0)],
                 'map': None,
                 'threshold': 7,
                 'box_wcs': [(4,40,13), (24,46,38), (4,34,35), (25,56,7)],
                 },
             'B215':
                {'center_wcs': [(4, 23, 0), (25, 3, 0)],
                 'map': None,
                 'threshold': 3,
                 'box_wcs': [(4,24,51), (22,36,7), (4,20,54), (25,26,31)],
                 },
             'L1524':
                {'center_wcs': [(4,29,0.), (24,31.,0)],
                 'map': None,
                 'threshold': 3,
                 'box_wcs': [(4,31,0), (22,4,6), (4,25,33), (25,0,55)],
                 }
                }

    cores = convert_core_coordinates(cores, hi_header)

    if True:
        hsd_limits =[0.1,300]
        hisd_limits = [2,20]
        av_limits =[0.01,100]
        nhi_limits = [2,20]

        cores = load_ds9_region(cores,
                filename_base = region_dir + 'taurus_av_boxes_',
                header = hi_header)

        # save cores for later
        if 0:
            mask = np.zeros((cfa_mom2.shape))
            for core in cores:
                print('Calculating for core %s' % core)

                av_limits = [0.01,100]

                # Grab the mask
                xy = cores[core]['box_center_pix']
                box_width = cores[core]['box_width']
                box_height = cores[core]['box_height']
                box_angle = cores[core]['box_angle']
                mask += myg.get_rectangular_mask(cfa_mom2,
                        xy[0], xy[1],
                        width = box_width,
                        height = box_height,
                        angle = box_angle)

                cores[core]['box_vertices'] = myg.get_rect(
                            xy[0], xy[1],
                            width = box_width,
                            height = box_height,
                            angle = box_angle,)

                indices = np.where(mask == 1)

            mask[mask > 1] = 1
            cfa_mom2[mask == 0] = np.nan

        # currently have variance, need dispersion
        cfa_mom2 = cfa_mom2**0.5


        # Plot
        plot_mom2_image(mom2_image = cfa_mom2,
                header = cfa_header,
                boxes = False,
                #limits=[128,37,308,206],
                title = r'Perseus: $\sigma_{\rm CO}$ map with core ' + \
                        'boxed-regions.',
                savedir = figure_dir,
                filename='perseus_co_veldisp_map.png',
                show=True)
def main():
    ''' Executes script.
    '''

    # import external modules
    import pyfits as pf
    import numpy as np
    from mycoords import make_velocity_axis
    import mygeometry as myg
    reload(myg)

    # define directory locations
    output_dir = '/d/bip3/ezbc/perseus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/perseus/figures/'
    av_dir = '/d/bip3/ezbc/perseus/data/av/'
    hi_dir = '/d/bip3/ezbc/perseus/data/galfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/perseus/data/python_output/ds9_regions/'

    # Load hi fits file
    hi_image, hi_header = pf.getdata(hi_dir + \
            'perseus_galfa_cube_bin_3.7arcmin.fits', header=True)
    h = hi_header

    # Load av fits file
    av_image, av_header = \
    pf.getdata('/d/bip3/ezbc/perseus/data/2mass/perseus_av_2mass_galfa_regrid.fits',
            header=True)

    # make velocity axis for hi cube
    velocity_axis = make_velocity_axis(hi_header)

    # create nhi image
    nhi_image = calculate_nhi(hi_cube=hi_image,
            velocity_axis=velocity_axis, velocity_range=[-100,100])

    if False:
        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image, mask=av_image != av_image)

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                contour_image=av_image, contours=[5,10,15],
                savedir=figure_dir, filename='perseus_nhi_cores_map.png',
                show=True)

    cores = {'IC348':
                {'center_wcs': [(3, 44, 0), (32, 8, 0)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': [(3,46,13), (26,3,24), (3,43,4), (32,25,41)],
                 },
             'NGC1333':
                {'center_wcs': [(3, 29, 11), (31, 16, 53)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
             'B4':
                {'center_wcs': [(3, 45, 50), (31, 42, 0)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
             'B5':
                {'center_wcs': [(3, 47, 34), (32, 48, 17)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
             #'':
             #   {'center_wcs': [],
             #    'map': None,
             #    'threshold': None,
             #    'box_wcs': None,
             #    },
            }

    cores = convert_core_coordinates(cores, h)

    if False:
        nhi_image = np.zeros(nhi_image.shape)

        for core in cores:
        	core_image = np.load(core_dir + core + '.npy')
        	core_indices = np.where(core_image == core_image)
        	nhi_image[core_indices] += core_image[core_indices]

        nhi_image_trim =np.ma.array(nhi_image, mask=((av_image != av_image) &\
                (nhi_image == 0)))

        nhi_image_trim[nhi_image_trim == 0] = np.NaN

        read_ds9_region(av_dir + 'perseus_av_boxes.reg')

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
            savedir=figure_dir,
            cores=cores,
            filename='perseus_nhi_core_regions_map.png',
            show=True)

    if True:
        cores = load_ds9_region(cores,
                filename_base = region_dir + 'perseus_av_boxes_',
                header = h)

        # Grab the mask
        mask = np.zeros((nhi_image.shape))
        for core in cores:
        	xy = cores[core]['box_center_pix']
        	box_width = cores[core]['box_width']
        	box_height = cores[core]['box_height']
        	box_angle = cores[core]['box_angle']
        	mask += myg.get_rectangular_mask(nhi_image,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

        	cores[core]['box_vertices'] = myg.get_rect(
                        xy[0], xy[1],
                        width = box_width,
                        height = box_height,
                        angle = box_angle,)

        #print(cores[core]['box_vertices'])
        #print core, xy, box_width, box_height, box_angle

        mask[mask > 1] = 1

        #nhi_image[mask == 0] = np.nan

        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image,
                mask = (av_image != av_image))

        # Plot
        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            plot_nhi_image(nhi_image=nhi_image_trim,
                    header=hi_header,
                    contour_image=av_image,
                    contours=[2.5,5,8],
                    boxes=True,
                    cores = cores,
                    limits=[47,128,231,222,],
                    title='Perseus: N(HI) map with core boxed-regions.',
                    savedir=figure_dir,
                    filename='perseus_nhi_cores_map.%s' % figure_type,
                    show=False)
def main():
    ''' Executes script.
    '''

    # import external modules
    import pyfits as pf
    import numpy as np
    from mycoords import make_velocity_axis
    import mygeometry as myg
    reload(myg)

    # define directory locations
    output_dir = '/d/bip3/ezbc/taurus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/taurus/figures/maps/'
    av_dir = '/d/bip3/ezbc/taurus/data/av/'
    hi_dir = '/d/bip3/ezbc/taurus/data/galfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/taurus/data/python_output/ds9_regions/'

    # Load hi fits file
    hi_image, hi_header = pf.getdata(hi_dir + \
            'taurus_galfa_cube_bin_3.7arcmin.fits', header=True)
    h = hi_header

    # Load av fits file
    av_image, av_header = pf.getdata(av_dir + 'taurus_av_k09_regrid.fits',
                                     header=True)

    # make velocity axis for hi cube
    velocity_axis = make_velocity_axis(hi_header)

    # create nhi image
    nhi_image = calculate_nhi(hi_cube=hi_image,
                              velocity_axis=velocity_axis,
                              velocity_range=[-100, 100])

    if False:
        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image, mask=av_image != av_image)

        plot_nhi_image(nhi_image=nhi_image_trim,
                       header=hi_header,
                       contour_image=av_image,
                       contours=[5, 10, 15],
                       savedir=figure_dir,
                       filename='taurus_nhi_cores_map.png',
                       show=True)

    cores = {
        'L1495': {
            'center_wcs': [(4, 14, 0), (28, 11, 0)],
            'map': None,
            'threshold': 4.75,
            'box_wcs': [(4, 16, 30), (27, 44, 30), (4, 5, 20), (28, 28, 33)]
        },
        'L1495A': {
            'center_wcs': [(4, 18, 0), (28, 23., 0)],
            'map': None,
            'threshold': 4.75,
            'box_wcs': [(4, 28, 23), (28, 12, 50), (4, 16, 23), (29, 46, 5)],
        },
        'B213': {
            'center_wcs': [(4, 19, 0), (27, 15, 0)],
            'map': None,
            'threshold': 4.75,
            'box_wcs': [(4, 22, 27), (26, 45, 47), (4, 5, 25), (27, 18, 48)],
        },
        'B220': {
            'center_wcs': [(4, 41, 0.), (26, 7, 0)],
            'map': None,
            'threshold': 7,
            'box_wcs': [(4, 47, 49), (25, 31, 13), (4, 40, 37), (27, 31, 17)],
        },
        'L1527': {
            'center_wcs': [(4, 39, 0.), (25, 47, 0)],
            'map': None,
            'threshold': 7,
            'box_wcs': [(4, 40, 13), (24, 46, 38), (4, 34, 35), (25, 56, 7)],
        },
        'B215': {
            'center_wcs': [(4, 23, 0), (25, 3, 0)],
            'map': None,
            'threshold': 3,
            'box_wcs': [(4, 24, 51), (22, 36, 7), (4, 20, 54), (25, 26, 31)],
        },
        'L1524': {
            'center_wcs': [(4, 29, 0.), (24, 31., 0)],
            'map': None,
            'threshold': 3,
            'box_wcs': [(4, 31, 0), (22, 4, 6), (4, 25, 33), (25, 0, 55)],
        }
    }

    cores = convert_core_coordinates(cores, h)

    if False:
        nhi_image = np.zeros(nhi_image.shape)

        for core in cores:
            core_image = np.load(core_dir + core + '.npy')
            core_indices = np.where(core_image == core_image)
            nhi_image[core_indices] += core_image[core_indices]

        nhi_image_trim =np.ma.array(nhi_image, mask=((av_image != av_image) &\
                (nhi_image == 0)))

        nhi_image_trim[nhi_image_trim == 0] = np.NaN

        read_ds9_region(av_dir + 'taurus_av_boxes.reg')

        plot_nhi_image(nhi_image=nhi_image_trim,
                       header=hi_header,
                       savedir=figure_dir,
                       cores=cores,
                       filename='taurus_nhi_core_regions_map.png',
                       show=True)

    if True:
        cores = load_ds9_region(cores,
                                filename_base=region_dir + 'taurus_av_boxes_',
                                header=h)

        # Grab the mask
        mask = np.zeros((nhi_image.shape))
        for core in cores:
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask += myg.get_rectangular_mask(nhi_image,
                                             xy[0],
                                             xy[1],
                                             width=box_width,
                                             height=box_height,
                                             angle=box_angle)

            cores[core]['box_vertices'] = myg.get_rect(
                xy[0],
                xy[1],
                width=box_width,
                height=box_height,
                angle=box_angle,
            )

        #print(cores[core]['box_vertices'])
        #print core, xy, box_width, box_height, box_angle

        mask[mask > 1] = 1

        #nhi_image[mask == 0] = np.nan

        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image, mask=(av_image != av_image))

        # Plot
        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                    contour_image=av_image, contours=[5,10,15],
                    boxes=True, cores = cores, limits=[128,37,308,206],
                    title='Taurus: N(HI) map with core boxed-regions.',
                    savedir=figure_dir, filename='taurus_nhi_cores_map.%s' % \
                            figure_type,
                    show=False)
def main():

    import grid
    import numpy as np
    from os import system, path
    import myclumpfinder as clump_finder
    import mygeometry as myg

    # define directory locations
    output_dir = "/d/bip3/ezbc/perseus/data/python_output/nhi_av/"
    figure_dir = "/d/bip3/ezbc/perseus/figures/cores/"
    av_dir = "/d/bip3/ezbc/perseus/data/av/"
    hi_dir = "/d/bip3/ezbc/perseus/data/galfa/"
    region_dir = "/d/bip3/ezbc/perseus/data/python_output/ds9_regions/"
    core_dir = output_dir + "core_arrays/"

    # load 2mass Av and GALFA HI images, on same grid
    av_image, h = load_fits(av_dir + "perseus_planck_av_regrid.fits", return_header=True)

    cores = {
        "IC348": {
            "center_wcs": [(3, 43, 52), (31, 59, 55)],
            "map": None,
            "threshold": None,
            "box_wcs": [(3, 46, 13), (26, 3, 24), (3, 43, 4), (32, 25, 41)],
        },
        "NGC1333": {"center_wcs": [(3, 29, 02), (31, 17, 28)], "map": None, "threshold": None, "box_wcs": None},
        "B4": {"center_wcs": [(3, 45, 14), (31, 40, 57)], "map": None, "threshold": None, "box_wcs": None},
        "B5": {"center_wcs": [(3, 47, 39), (32, 53, 26)], "map": None, "threshold": None, "box_wcs": None},
        #'':
        #   {'center_wcs': [],
        #    'map': None,
        #    'threshold': None,
        #    'box_wcs': None,
        #    },
    }

    cores = convert_core_coordinates(cores, h)

    cores = load_ds9_region(cores, filename_base=region_dir + "perseus_av_boxes_", header=h)

    if True:
        # limits = [0.1, 100, 0.1, 100] # x-log limits
        limits = [0, 20, -1, 30]  # x-linear limits

        A_p = []
        pho_c = []
        R_flat = []
        p = []

        for core in cores:
            print ("Calculating for core %s" % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]["box_center_pix"]
            box_width = cores[core]["box_width"]
            box_height = cores[core]["box_height"]
            box_angle = cores[core]["box_angle"]
            mask = myg.get_rectangular_mask(av_image, xy[0], xy[1], width=box_width, height=box_height, angle=box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)

            # plotting radial profiles only within boxes
            # av_image_sub = get_sub_image(av_image, cores[core]['box_pixel'])
            # change center pixel to correspond to sub image
            # pix = cores[core]['center_pixel']
            # pix = (pix[0] - cores[core]['box_pixel'][0],
            #    pix[1] - cores[core]['box_pixel'][1],)
            # cores[core]['center_pixel'] = pix

            av_image_sub = np.copy(av_image)
            # av_image_sub[mask == 0] = np.NaN

            temp_mask = np.copy(mask)
            temp_mask[mask == 0] = 1
            temp_mask[mask == 1] = 0

            import matplotlib.pyplot as plt

            plt.clf()
            plt.imshow(np.ma.array(av_image_sub, mask=temp_mask))
            plt.savefig("/usr/users/ezbc/Desktop/map%s.png" % core)
            plt.clf()

            pix = cores[core]["center_pixel"]

            # extract radial profile weighted by SNR
            radii, profile = get_radial_profile(
                av_image_sub, binsize=3, center=pix, weights=av_image_sub / 0.3, mask=mask
            )

            # extract std
            radii, profile_std = get_radial_profile(
                av_image_sub,
                binsize=3,
                center=pix,
                stddev=True,
                weights=av_image_sub / 0.3,
                # mask=mask
            )

            # convert radii from degrees to parsecs
            radii_arcmin = radii * h["CDELT2"] * 60 * 60.0  # radii in arcminutes
            radii_pc = radii_arcmin * 300 / 206265.0  # radii in parsecs

            # extract radii from within the limits
            indices = np.where((radii_pc < limits[1]) & (profile == profile) & (profile_std == profile_std))
            radii_pc = radii_pc[indices]
            profile = profile[indices]
            profile_std = profile_std[indices]

            # fit profile with power function
            def function(radius, A_p, pho_c, R_flat, p):
                return A_p * pho_c * R_flat / (1 + (radius / R_flat) ** 2) ** (p / 2.0 - 0.5)
                # return A_p * radius**p

            profile_fit_params = fit_profile(radii_pc, profile, function, sigma=profile / profile_std)[0]

            # plot the radial profile
            figure_types = [".pdf", ".png"]
            for figure_type in figure_types:
                plot_profile(
                    radii_pc,
                    profile,
                    profile_errors=profile_std,
                    limits=limits,
                    profile_fit_params=profile_fit_params,
                    profile_fit_function=function,
                    savedir=figure_dir,
                    filename="perseus_profile_av_" + core + figure_type,
                    title=r"Radial A$_V$ Profile of Perseus Core " + core,
                    show=False,
                )

            A_p.append(profile_fit_params[0])
            pho_c.append(profile_fit_params[1])
            R_flat.append(profile_fit_params[2])
            p.append(profile_fit_params[3])

        print_fit_params(cores, A_p, pho_c, R_flat, p, filename=output_dir + "core_profile_fit_data.txt")

        print_fit_params(cores, A_p, pho_c, R_flat, p)
def main():

    import grid
    import numpy as np
    from os import system, path
    import myclumpfinder as clump_finder
    import mygeometry as myg

    # define directory locations
    output_dir = '/d/bip3/ezbc/perseus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/perseus/figures/cores/'
    av_dir = '/d/bip3/ezbc/perseus/data/av/'
    hi_dir = '/d/bip3/ezbc/perseus/data/galfa/'
    region_dir = '/d/bip3/ezbc/perseus/data/python_output/ds9_regions/'
    core_dir = output_dir + 'core_arrays/'

    # load 2mass Av and GALFA HI images, on same grid
    av_image, h = load_fits(av_dir + 'perseus_planck_av_regrid.fits',
                            return_header=True)

    cores = {
        'IC348': {
            'center_wcs': [(3, 43, 52), (31, 59, 55)],
            'map': None,
            'threshold': None,
            'box_wcs': [(3, 46, 13), (26, 3, 24), (3, 43, 4), (32, 25, 41)],
        },
        'NGC1333': {
            'center_wcs': [(3, 29, 02), (31, 17, 28)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'B4': {
            'center_wcs': [(3, 45, 14), (31, 40, 57)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'B5': {
            'center_wcs': [(3, 47, 39), (32, 53, 26)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        #'':
        #   {'center_wcs': [],
        #    'map': None,
        #    'threshold': None,
        #    'box_wcs': None,
        #    },
    }

    cores = convert_core_coordinates(cores, h)

    cores = load_ds9_region(cores,
                            filename_base=region_dir + 'perseus_av_boxes_',
                            header=h)

    if True:
        #limits = [0.1, 100, 0.1, 100] # x-log limits
        limits = [0, 20, -1, 30]  # x-linear limits

        A_p = []
        pho_c = []
        R_flat = []
        p = []

        for core in cores:
            print('Calculating for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_image,
                                            xy[0],
                                            xy[1],
                                            width=box_width,
                                            height=box_height,
                                            angle=box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)

            # plotting radial profiles only within boxes
            #av_image_sub = get_sub_image(av_image, cores[core]['box_pixel'])
            # change center pixel to correspond to sub image
            #pix = cores[core]['center_pixel']
            #pix = (pix[0] - cores[core]['box_pixel'][0],
            #    pix[1] - cores[core]['box_pixel'][1],)
            #cores[core]['center_pixel'] = pix

            av_image_sub = np.copy(av_image)
            #av_image_sub[mask == 0] = np.NaN

            temp_mask = np.copy(mask)
            temp_mask[mask == 0] = 1
            temp_mask[mask == 1] = 0

            import matplotlib.pyplot as plt

            plt.clf()
            plt.imshow(np.ma.array(av_image_sub, mask=temp_mask))
            plt.savefig('/usr/users/ezbc/Desktop/map%s.png' % core)
            plt.clf()

            pix = cores[core]['center_pixel']

            # extract radial profile weighted by SNR
            radii, profile = get_radial_profile(av_image_sub,
                                                binsize=3,
                                                center=pix,
                                                weights=av_image_sub / 0.3,
                                                mask=mask)

            # extract std
            radii, profile_std = get_radial_profile(
                av_image_sub,
                binsize=3,
                center=pix,
                stddev=True,
                weights=av_image_sub / 0.3,
                #mask=mask
            )

            # convert radii from degrees to parsecs
            radii_arcmin = radii * h['CDELT2'] * 60 * 60.  # radii in arcminutes
            radii_pc = radii_arcmin * 300 / 206265.  # radii in parsecs

            # extract radii from within the limits
            indices = np.where((radii_pc < limits[1]) & \
                               (profile == profile) & \
                               (profile_std == profile_std))
            radii_pc = radii_pc[indices]
            profile = profile[indices]
            profile_std = profile_std[indices]

            # fit profile with power function
            def function(radius, A_p, pho_c, R_flat, p):
                return A_p * pho_c * R_flat / \
                        (1 + (radius / R_flat)**2)**(p/2. - 0.5)
                #return A_p * radius**p

            profile_fit_params = fit_profile(radii_pc,
                                             profile,
                                             function,
                                             sigma=profile / profile_std)[0]

            # plot the radial profile
            figure_types = ['.pdf', '.png']
            for figure_type in figure_types:
                plot_profile(
                    radii_pc,
                    profile,
                    profile_errors=profile_std,
                    limits=limits,
                    profile_fit_params=profile_fit_params,
                    profile_fit_function=function,
                    savedir=figure_dir,
                    filename='perseus_profile_av_' + core + figure_type,
                    title=r'Radial A$_V$ Profile of Perseus Core ' + core,
                    show=False)

            A_p.append(profile_fit_params[0])
            pho_c.append(profile_fit_params[1])
            R_flat.append(profile_fit_params[2])
            p.append(profile_fit_params[3])

        print_fit_params(cores,
                         A_p,
                         pho_c,
                         R_flat,
                         p,
                         filename=output_dir + 'core_profile_fit_data.txt')

        print_fit_params(cores, A_p, pho_c, R_flat, p)
def main():

    import numpy as np
    from os import system,path
    import mygeometry as myg
    reload(myg)


    # define directory locations
    if 1:
        output_dir = '/home/ezbc/Desktop/'
        figure_dir = '/home/ezbc/research/figures/'
        av_dir = '/home/ezbc/research/data/california/'
        hi_dir = '/home/ezbc/research/data/california/'
        core_dir = output_dir + 'core_arrays/'
        region_dir = '/home/ezbc/research/data/california/'
    if 0:
        output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
        figure_dir = '/d/bip3/ezbc/california/figures/'
        av_dir = '/d/bip3/ezbc/california/data/av/'
        hi_dir = '/d/bip3/ezbc/california/data/galfa/'
        core_dir = output_dir + 'core_arrays/'
        region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'

    # load 2mass Av and GALFA HI images, on same grid
    av_data, av_header = load_fits(av_dir + 'california_planck_av_regrid.fits',
            return_header=True)

    #av_data += - 0.4 # subtracts background of 0.4 mags
    hi_data,h = load_fits(hi_dir + 'california_galfa_cube_bin_3.7arcmin.fits',
            return_header=True)

    # make the velocity axis
    velocity_axis = (np.arange(h['NAXIS3']) - h['CRPIX3'] + 1) * h['CDELT3'] + \
            h['CRVAL3']
    velocity_axis /= 1000.

    # Plot NHI vs. Av for a given velocity range
    noise_cube_filename = 'california_galfa_cube_bin_3.7arcmin_noise.fits'
    if not path.isfile(hi_dir + noise_cube_filename):
        noise_cube = calculate_noise_cube(cube=hi_data,
                velocity_axis=velocity_axis,
                velocity_noise_range=[90,110], header=h, Tsys=30.,
                filename=hi_dir + noise_cube_filename)
    else:
        noise_cube, noise_header = load_fits(hi_dir + noise_cube_filename,
            return_header=True)

    # calculate nhi and error maps, write nhi map to fits file
    nhi_image, nhi_image_error = calculate_nhi(cube=hi_data,
        velocity_axis=velocity_axis,
        noise_cube = noise_cube,
        velocity_range=[-100,100],
        return_nhi_error=True,
        fits_filename = hi_dir + 'california_galfa_nhi_3.7arcmin.fits',
        fits_error_filename = hi_dir + 'california_galfa_nhi_error_3.7arcmin.fits',
        header = h)

    # calculate N(H2) maps
    nh2_image = calculate_nh2(nhi_image = nhi_image,
            av_image = av_data, dgr = 5.3e-2)
    nh2_image_error = calculate_nh2(nhi_image = nhi_image_error,
            av_image = 0.1, dgr = 5.3e-2)

    # convert to column density to surface density
    hi_sd_image = calculate_sd(nhi_image, sd_factor=1./1.25,)
    hi_sd_image_error = calculate_sd(nhi_image_error, sd_factor=1./1.25)
    h2_sd_image = calculate_sd(nh2_image, sd_factor=10./6.25,)
    h2_sd_image_error = calculate_sd(nh2_image_error, sd_factor=10./6.25)
    h_sd_image = hi_sd_image + h2_sd_image
    h_sd_image_error = (hi_sd_image_error**2 + h2_sd_image_error**2)**0.5

    # Write ratio between H2 and HI
    rh2_image = h2_sd_image / hi_sd_image
    rh2_image_error = rh2_image * (hi_sd_image_error**2 / hi_sd_image**2 \
                 + h2_sd_image_error**2 / h2_sd_image**2)**0.5

    # define core properties
    cores = {'L1482':
                {'center_wcs': [(4, 29, 41), (35, 48, 41)],
                 'map': None,
                 'threshold': None,
                 },
              'L1483':
                {'center_wcs': [(4, 34, 57), (36, 18, 12)],
                 'map': None,
                 'threshold': None,
                 },
              'L1478':
                {'center_wcs': [(4, 25, 7), (37, 13, 0)],
                 'map': None,
                 'threshold': None,
                 },
              'L1434':
                {'center_wcs': [(3, 50, 51), (35, 15, 10)],
                 'map': None,
                 'threshold': None,
                 },
              'L1503':
                {'center_wcs': [(4, 40, 27), (29, 57, 12)],
                 'map': None,
                 'threshold': None,
                 },
              'L1507':
                {'center_wcs': [(4, 42, 51), (29, 44, 47)],
                 'map': None,
                 'threshold': None,
                 },
                }

    cores = convert_core_coordinates(cores, h)

    if True:
        hsd_limits =[0.1,300]
        hisd_limits = [4,50]
        av_limits =[0.1,50]
        nhi_limits = [2,20]

        cores = load_ds9_region(cores,
                filename_base = region_dir + 'california_av_boxes_',
                header = h)

        print('core\t phi_CNM')

        for core in cores:

            av_limits =[0.01,100]

            # Grab the mask
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(nhi_image,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)
            # apply mask and avoid NaNs
            indices = np.where((mask == 1) &\
                    (hi_sd_image == hi_sd_image) &\
                    (h2_sd_image == h2_sd_image) &\
                    (h_sd_image == h_sd_image))

            # Apply mask to images
            av_data_sub = av_data[indices]
            hi_sd_image_sub = hi_sd_image[indices]
            hi_sd_image_error_sub = hi_sd_image_error[indices]
            h2_sd_image_sub = h2_sd_image[indices]
            h2_sd_image_error_sub = h2_sd_image_error[indices]
            h_sd_image_sub = h_sd_image[indices]
            h_sd_image_error_sub = h_sd_image_error[indices]
            rh2_image_sub = rh2_image[indices]
            rh2_image_error_sub = rh2_image_error[indices]

            # Unravel images to single dimension
            hi_sd_ravel = hi_sd_image_sub.ravel()
            h2_sd_ravel = h2_sd_image_sub.ravel()
            hi_sd_error_ravel = hi_sd_image_error_sub.ravel()
            h2_sd_error_ravel = h2_sd_image_error_sub.ravel()
            h_sd_ravel = h_sd_image_sub.ravel()
            h_sd_error_ravel = h_sd_image_error_sub.ravel()
            rh2_ravel = rh2_image_sub.ravel()
            rh2_error_ravel = rh2_image_error_sub.ravel()

            # write indices for only ratios > 0
            indices = np.where(rh2_ravel > 0)

            # Fit to krumholz model, init guess of phi_CNM = 10
            rh2_fit, h_sd_fit, phi_cnm = fit_krumholz(h_sd_ravel[indices],
                    rh2_ravel[indices],
                    (0.001, 1000, 1e6),
                    p0 = 10,
                    return_params = True)

            print('%s\t %.2f' % (core, phi_cnm))
            # see eq 6 of krumholz+09
            # phi_cnm is the number density of the CNM over the minimum number
            # density required for pressure balance
            # the lower phi_cnm values than for perseus mean that california
            # has a more diffuse CNM

            '''
            rh2 = fh2 / fhi
            rh2 = (2*(1-hi_sd) / (hi_sd+2*h2_sd)) / (hi_sd / (hi_sd+2*h2_sd))
            rh2 = (2*(1-hi_sd) / hi_sd
            rh2 = 2/hi_sd - 2
            rh2 / 2 + 1 = 1 / hi_sd
            hi_sd = 1 / (rh2/2 + 1)

            '''

            hi_sd_fit = h_sd_fit / (rh2_fit/2. + 1)

            if True:
                plot_rh2_vs_h(rh2_ravel, h_sd_ravel,
                        rh2_error = rh2_error_ravel,
                        h_sd_error = h_sd_error_ravel,
                        rh2_fit = rh2_fit,
                        h_sd_fit = h_sd_fit,
                        limits = [0.5, 1000, 10**-3, 10**2],
                        savedir = figure_dir,
                        scale = 'log',
                        filename = 'california_rh2_vs_hsd_' + core + '_box.png',
                        title = r'$R_{\rm H2}$ vs. $\Sigma_{\rm HI}$'\
                                + ' of California Core ' + core,
                        show = False)

                plot_hi_vs_h(hi_sd_ravel, h_sd_ravel,
                        hi_sd_error = hi_sd_error_ravel,
                        h_sd_error = h_sd_error_ravel,
                        hi_sd_fit = hi_sd_fit,
                        h_sd_fit = h_sd_fit,
                        limits = [0.5, 1000, 10**0, 10**2],
                        savedir = figure_dir,
                        scale = 'log',
                        filename = 'california_hisd_vs_hsd_' + core + \
                                '_box.png',
                        title = r'$\Sigma_{\rm HI}$ vs. $\Sigma_{\rm H}$'\
                                + ' of California Core ' + core,
                        show = False)
def main():

    import grid
    import numpy as np
    from os import system,path
    import myclumpfinder as clump_finder
    reload(clump_finder)
    import mygeometry as myg
    reload(myg)
    import json

    # define directory locations
    output_dir = '/d/bip3/ezbc/taurus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/taurus/figures/cores/'
    av_dir = '/d/bip3/ezbc/taurus/data/av/'
    hi_dir = '/d/bip3/ezbc/taurus/data/galfa/'
    core_dir = '/d/bip3/ezbc/taurus/data/python_output/core_properties/'
    region_dir = '/d/bip3/ezbc/taurus/data/python_output/ds9_regions/'

    # load 2mass Av and GALFA HI images, on same grid
    av_data_k09, av_header = load_fits(av_dir + 'taurus_av_k09_regrid_planckres.fits',
            return_header=True)

    av_data_k09_orig, av_header = load_fits(av_dir + \
                                          'taurus_av_kainulainen2009.fits',
                                       return_header=True)

    av_data_k09_orig[av_data_k09_orig == -1] = np.NaN

    # load Planck Av and GALFA HI images, on same grid
    av_data_planck, h = load_fits(av_dir + \
                'taurus_av_planck_5arcmin.fits',
            return_header=True)

    # define core properties
    with open(core_dir + 'taurus_core_properties.txt', 'r') as f:
        cores = json.load(f)

    cores = convert_core_coordinates(cores, h)

    if True:
        print('Calculating PDF for global map')

        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            if 1:
                plot_pdf(av_data_planck,
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        filename='taurus_av_pdf_global_planck.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'Taurus',
                        show=False)

                plot_pdf(av_data_k09,
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        filename='taurus_av_pdf_global_k09.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'Taurus',
                        show=False)
            if 1:
                # Create PDF with original Av image from Jouni
                plot_pdfs((av_data_k09_orig, av_data_k09),
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        core_names=('Original', 'Planck Regrid'),
                        filename='taurus_av_pdf_global_k09_orig_vs_regrid.%s'%\
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of Taurus',
                        show=False)

        cores = load_ds9_region(cores,
                filename_base = region_dir + 'taurus_av_boxes_',
                header = h)

        av_data_list_k09 = []
        av_data_list_planck = []
        core_name_list = []

        for core in cores:
            print('Calculating PDF for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)
            av_data_k09_sub = av_data_k09[indices]
            av_data_planck_sub = av_data_planck[indices]

            if 1:
                figure_types = ['pdf', 'png']
                for figure_type in figure_types:
                    plot_pdf(av_data_planck_sub,
                            limits = [-1,4,1,1000],
                            savedir=figure_dir + 'individual_cores/',
                            scale=(0,1),
                            filename='taurus_av_pdf_' + core + '_planck.%s' % \
                                    figure_type,
                            title=r'A$_{\rm V}$ PDF of ' + \
                                    'Taurus Core ' + core,
                            show=False)

            av_data_list_k09.append(av_data_k09_sub)
            av_data_list_planck.append(av_data_planck_sub)
            core_name_list.append(core)

        if 1:
            for figure_type in figure_types:
                plot_pdfs(av_data_list_k09,
                          limits = [-2,2.9,1,100],
                          savedir=figure_dir + 'panel_cores/',
                          scale=(0,1),
                          filename='taurus_av_pdfs_k09.%s' % figure_type,
                          title=r'A$_{\rm V}$ PDF of Taurus Core ',
                          core_names=core_name_list,
                          show=False)

                plot_pdfs(av_data_list_planck,
                          limits = [-2,2.9,1,100],
                          savedir=figure_dir + 'panel_cores/',
                          scale=(0,1),
                          filename='taurus_av_pdfs_planck.%s' % figure_type,
                          title=r'A$_{\rm V}$ PDF of Taurus Core ',
                          core_names=core_name_list,
                          show=False)
def main():

    import grid
    import numpy as np
    from os import system,path
    import myclumpfinder as clump_finder
    reload(clump_finder)
    import mygeometry as myg
    reload(myg)


    # define directory locations
    output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/california/figures/cores/'
    av_dir = '/d/bip3/ezbc/california/data/av/'
    hi_dir = '/d/bip3/ezbc/california/data/galfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'

    # load Planck Av and GALFA HI images, on same grid
    av_data_planck, h = load_fits(av_dir + \
                'california_planck_av_regrid.fits',
            return_header=True)

    # define core properties
    cores = {'L1482':
                {'center_wcs': [(4, 29, 41), (35, 48, 41)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
              'L1483':
                {'center_wcs': [(4, 34, 57), (36, 18, 12)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
              'L1478':
                {'center_wcs': [(4, 25, 7), (37, 13, 0)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
              'L1434':
                {'center_wcs': [(3, 50, 51), (35, 15, 10)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
              'L1503':
                {'center_wcs': [(4, 40, 27), (29, 57, 12)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
              'L1507':
                {'center_wcs': [(4, 42, 51), (29, 44, 47)],
                 'map': None,
                 'threshold': None,
                 'box_wcs': None,
                 },
                }

    cores = convert_core_coordinates(cores, h)


    if True:
        print('Calculating PDF for global map')

        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            plot_pdf(av_data_planck,
                    limits = [-2, 3.1, 1, 10**5],
                    savedir=figure_dir,
                    scale=(0,1),
                    filename='california_av_pdf_global_planck.%s' % \
                            figure_type,
                    title=r'A$_{\rm V}$ PDF of ' + \
                            'california',
                    show=False)

        cores = load_ds9_region(cores,
                filename_base = region_dir + 'california_av_boxes_',
                header = h)

        for core in cores:
            print('Calculating PDF for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)
            av_data_planck_sub = av_data_planck[indices]

            figure_types = ['pdf', 'png']
            for figure_type in figure_types:
                plot_pdf(av_data_planck_sub,
                        limits = [-1,4,1,1000],
                        savedir=figure_dir,
                        scale=(0,1),
                        filename='california_av_pdf' + core + '_planck.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'california Core ' + core,
                        show=False)
def main():
    ''' Executes script.
    '''

    # import external modules
    import pyfits as pf
    import numpy as np
    from mycoords import make_velocity_axis
    import mygeometry as myg
    reload(myg)

    # define directory locations
    output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/california/figures/'
    av_dir = '/d/bip3/ezbc/california/data/av/'
    hi_dir = '/d/bip3/ezbc/california/data/galfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'

    # Load hi fits file
    hi_image, hi_header = pf.getdata(hi_dir + \
            'california_galfa_cube_bin_3.7arcmin.fits', header=True)
    h = hi_header

    # Load av fits file
    av_image, av_header = pf.getdata(av_dir + \
                'california_planck_av_regrid.fits',
            header=True)

    # make velocity axis for hi cube
    velocity_axis = make_velocity_axis(hi_header)

    # create nhi image
    nhi_image = calculate_nhi(hi_cube=hi_image,
            velocity_axis=velocity_axis, velocity_range=[-100,100])

    if False:
        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image, mask=av_image != av_image)

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                contour_image=av_image, contours=[5,10,15],
                savedir=figure_dir, filename='california_nhi_cores_map.png',
                show=True)

    # define core properties
    cores = {'L1482':
                {'center_wcs': [(4, 29, 41), (35, 48, 41)],
                 'map': None,
                 'threshold': None,
                 },
              'L1483':
                {'center_wcs': [(4, 34, 57), (36, 18, 12)],
                 'map': None,
                 'threshold': None,
                 },
              'L1478':
                {'center_wcs': [(4, 25, 7), (37, 13, 0)],
                 'map': None,
                 'threshold': None,
                 },
              'L1434':
                {'center_wcs': [(3, 50, 51), (35, 15, 10)],
                 'map': None,
                 'threshold': None,
                 },
              'L1503':
                {'center_wcs': [(4, 40, 27), (29, 57, 12)],
                 'map': None,
                 'threshold': None,
                 },
              'L1507':
                {'center_wcs': [(4, 42, 51), (29, 44, 47)],
                 'map': None,
                 'threshold': None,
                 },
                }

    cores = convert_core_coordinates(cores, h)

    if False:
        nhi_image = np.zeros(nhi_image.shape)

        for core in cores:
        	core_image = np.load(core_dir + core + '.npy')
        	core_indices = np.where(core_image == core_image)
        	nhi_image[core_indices] += core_image[core_indices]

        nhi_image_trim =np.ma.array(nhi_image, mask=((av_image != av_image) &\
                (nhi_image == 0)))

        nhi_image_trim[nhi_image_trim == 0] = np.NaN

        read_ds9_region(av_dir + 'california_av_boxes.reg')

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
            savedir=figure_dir,
            cores=cores,
            filename='california_nhi_core_regions_map.png',
            show=True)

    if True:
        cores = load_ds9_region(cores,
                filename_base = region_dir + 'california_av_boxes_',
                header = h)

        # Grab the mask
        mask = np.zeros((nhi_image.shape))
        for core in cores:
        	xy = cores[core]['box_center_pix']
        	box_width = cores[core]['box_width']
        	box_height = cores[core]['box_height']
        	box_angle = cores[core]['box_angle']
        	mask += myg.get_rectangular_mask(nhi_image,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

        	cores[core]['box_vertices'] = myg.get_rect(
                        xy[0], xy[1],
                        width = box_width,
                        height = box_height,
                        angle = box_angle,)

        #print(cores[core]['box_vertices'])
        #print core, xy, box_width, box_height, box_angle

        mask[mask > 1] = 1

        #nhi_image[mask == 0] = np.nan

        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image,
                mask = (av_image != av_image))

        # Plot
        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                contour_image=av_image, contours=[3,6,10],
                boxes=True, cores = cores, #limits=[128,37,308,206],
                title='California: N(HI) map with core boxed-regions.',
                savedir=figure_dir, filename='california_nhi_cores_map.pdf',
                show=True)
def main():
    ''' Executes script.
    '''

    # import external modules
    import pyfits as pf
    import numpy as np
    from mycoords import make_velocity_axis
    import mygeometry as myg
    reload(myg)

    # define directory locations
    output_dir = '/d/bip3/ezbc/taurus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/taurus/figures/maps/'
    av_dir = '/d/bip3/ezbc/taurus/data/av/'
    hi_dir = '/d/bip3/ezbc/taurus/data/hi/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/taurus/data/python_output/ds9_regions/'

    # Load hi fits file
    hi_image, hi_header = pf.getdata(hi_dir + \
            'taurus_hi_galfa_cube_regrid_planckres.fits', header=True)
    h = hi_header

    # Load av fits file
    av_image, av_header = pf.getdata(av_dir + \
                'taurus_av_planck_5arcmin.fits',
            header=True)

    # make velocity axis for hi cube
    velocity_axis = make_velocity_axis(hi_header)

    # create nhi image
    nhi_image = calculate_nhi(hi_cube=hi_image,
            velocity_axis=velocity_axis, velocity_range=[-16.53,28.83])

    if False:
        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image, mask=av_image != av_image)

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                contour_image=av_image, contours=[5,10,15],
                savedir=figure_dir, filename='taurus_nhi_cores_map.png',
                show=True)

    cores = {'L1495':
                {'center_wcs': [(4,14,0), (28, 11, 0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,16,30), (27,44,30), (4,5,20), (28,28,33)]
                 },
             'L1495A':
                {'center_wcs': [(4,18,0), (28,23., 0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,28,23),(28,12,50),(4,16,23),(29,46,5)],
                 },
             'B213':
                {'center_wcs': [(4, 19, 0), (27, 15,0)],
                 'map': None,
                 'threshold': 4.75,
                 'box_wcs': [(4,22,27), (26,45,47),(4,5,25),(27,18,48)],
                },
             'B220':
                {'center_wcs': [(4, 41, 0.), (26,7,0)],
                 'map': None,
                 'threshold': 7,
                 'box_wcs': [(4,47,49),(25,31,13),(4,40,37),(27,31,17)],
                 },
             'L1527':
                {'center_wcs': [(4, 39, 0.), (25,47, 0)],
                 'map': None,
                 'threshold': 7,
                 'box_wcs': [(4,40,13), (24,46,38), (4,34,35), (25,56,7)],
                 },
             'B215':
                {'center_wcs': [(4, 23, 0), (25, 3, 0)],
                 'map': None,
                 'threshold': 3,
                 'box_wcs': [(4,24,51), (22,36,7), (4,20,54), (25,26,31)],
                 },
             'L1524':
                {'center_wcs': [(4,29,0.), (24,31.,0)],
                 'map': None,
                 'threshold': 3,
                 'box_wcs': [(4,31,0), (22,4,6), (4,25,33), (25,0,55)],
                 }
                }

    cores = convert_core_coordinates(cores, h)

    if False:
        nhi_image = np.zeros(nhi_image.shape)

        for core in cores:
        	core_image = np.load(core_dir + core + '.npy')
        	core_indices = np.where(core_image == core_image)
        	nhi_image[core_indices] += core_image[core_indices]

        nhi_image_trim =np.ma.array(nhi_image, mask=((av_image != av_image) &\
                (nhi_image == 0)))

        nhi_image_trim[nhi_image_trim == 0] = np.NaN

        read_ds9_region(av_dir + 'taurus_av_boxes.reg')

        plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
            savedir=figure_dir,
            cores=cores,
            filename='taurus_nhi_core_regions_map.png',
            show=True)

    if True:
        cores = load_ds9_region(cores,
                filename_base = region_dir + 'taurus_av_boxes_',
                header = h)

        # Grab the mask
        mask = np.zeros((nhi_image.shape))
        for core in cores:
        	xy = cores[core]['box_center_pix']
        	box_width = cores[core]['box_width']
        	box_height = cores[core]['box_height']
        	box_angle = cores[core]['box_angle']
        	mask += myg.get_rectangular_mask(nhi_image,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

        	cores[core]['box_vertices'] = myg.get_rect(
                        xy[0], xy[1],
                        width = box_width,
                        height = box_height,
                        angle = box_angle,)

        mask[mask > 1] = 1

        # trim hi_image to av_image size
        nhi_image_trim = np.ma.array(nhi_image,
                mask = ((av_image != av_image) & \
                        (av_image > 1.0)))
        av_image_trim = np.ma.array(av_image,
                mask = ((nhi_image != nhi_image) & \
                        (av_image > 1.0)))

        nhi_image_trim = np.copy(nhi_image)
        nhi_image_trim[av_image > 1.] = np.nan
        av_image_trim = np.copy(av_image)
        av_image_trim[av_image > 1.] = np.nan

        # Plot
        figure_types = ['png',]
        for figure_type in figure_types:
            # N(HI) alone
            plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                    contour_image=av_image, contours=[5,10,15],
                    boxes=True, cores = cores,
                    limits=[50,37,200,160],
                    savedir=figure_dir,
                    filename='taurus_nhi_cores_map.%s' % \
                            figure_type,
                    show=0)

            # N(HI) + Av
            plot_nhi_image(nhi_image=nhi_image_trim, header=hi_header,
                    av_image=av_image_trim,
                    #boxes=True, cores = cores,
                    limits=[50,37,200,160],
                    savedir=figure_dir,
                    filename='taurus_nhi_av_map.%s' % \
                            figure_type,
                    show=0)
Esempio n. 13
0
def main():

    import grid
    import numpy as np
    from os import system, path
    import myclumpfinder as clump_finder
    reload(clump_finder)
    import mygeometry as myg
    reload(myg)
    import json

    # define directory locations
    output_dir = '/d/bip3/ezbc/taurus/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/taurus/figures/cores/'
    av_dir = '/d/bip3/ezbc/taurus/data/av/'
    hi_dir = '/d/bip3/ezbc/taurus/data/galfa/'
    core_dir = '/d/bip3/ezbc/taurus/data/python_output/core_properties/'
    region_dir = '/d/bip3/ezbc/taurus/data/python_output/ds9_regions/'

    # load 2mass Av and GALFA HI images, on same grid
    av_data_k09, av_header = load_fits(av_dir +
                                       'taurus_av_k09_regrid_planckres.fits',
                                       return_header=True)

    av_data_k09_orig, av_header = load_fits(av_dir + \
                                          'taurus_av_kainulainen2009.fits',
                                       return_header=True)

    av_data_k09_orig[av_data_k09_orig == -1] = np.NaN

    # load Planck Av and GALFA HI images, on same grid
    av_data_planck, h = load_fits(av_dir + \
                'taurus_av_planck_5arcmin.fits',
            return_header=True)

    # define core properties
    with open(core_dir + 'taurus_core_properties.txt', 'r') as f:
        cores = json.load(f)

    cores = convert_core_coordinates(cores, h)

    if True:
        print('Calculating PDF for global map')

        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            if 1:
                plot_pdf(av_data_planck,
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        filename='taurus_av_pdf_global_planck.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'Taurus',
                        show=False)

                plot_pdf(av_data_k09,
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        filename='taurus_av_pdf_global_k09.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'Taurus',
                        show=False)
            if 1:
                # Create PDF with original Av image from Jouni
                plot_pdfs((av_data_k09_orig, av_data_k09),
                        limits = [-2, 3.1, 1, 10**5],
                        savedir=figure_dir + 'panel_cores/',
                        scale=(0,1),
                        core_names=('Original', 'Planck Regrid'),
                        filename='taurus_av_pdf_global_k09_orig_vs_regrid.%s'%\
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of Taurus',
                        show=False)

        cores = load_ds9_region(cores,
                                filename_base=region_dir + 'taurus_av_boxes_',
                                header=h)

        av_data_list_k09 = []
        av_data_list_planck = []
        core_name_list = []

        for core in cores:
            print('Calculating PDF for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
                                            xy[0],
                                            xy[1],
                                            width=box_width,
                                            height=box_height,
                                            angle=box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)
            av_data_k09_sub = av_data_k09[indices]
            av_data_planck_sub = av_data_planck[indices]

            if 1:
                figure_types = ['pdf', 'png']
                for figure_type in figure_types:
                    plot_pdf(av_data_planck_sub,
                            limits = [-1,4,1,1000],
                            savedir=figure_dir + 'individual_cores/',
                            scale=(0,1),
                            filename='taurus_av_pdf_' + core + '_planck.%s' % \
                                    figure_type,
                            title=r'A$_{\rm V}$ PDF of ' + \
                                    'Taurus Core ' + core,
                            show=False)

            av_data_list_k09.append(av_data_k09_sub)
            av_data_list_planck.append(av_data_planck_sub)
            core_name_list.append(core)

        if 1:
            for figure_type in figure_types:
                plot_pdfs(av_data_list_k09,
                          limits=[-2, 2.9, 1, 100],
                          savedir=figure_dir + 'panel_cores/',
                          scale=(0, 1),
                          filename='taurus_av_pdfs_k09.%s' % figure_type,
                          title=r'A$_{\rm V}$ PDF of Taurus Core ',
                          core_names=core_name_list,
                          show=False)

                plot_pdfs(av_data_list_planck,
                          limits=[-2, 2.9, 1, 100],
                          savedir=figure_dir + 'panel_cores/',
                          scale=(0, 1),
                          filename='taurus_av_pdfs_planck.%s' % figure_type,
                          title=r'A$_{\rm V}$ PDF of Taurus Core ',
                          core_names=core_name_list,
                          show=False)
def main():

    import grid
    import numpy as np
    from os import system, path
    import myclumpfinder as clump_finder
    reload(clump_finder)
    import mygeometry as myg
    reload(myg)

    # define directory locations
    output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/california/figures/cores/'
    av_dir = '/d/bip3/ezbc/california/data/av/'
    hi_dir = '/d/bip3/ezbc/california/data/galfa/'
    core_dir = output_dir + 'core_arrays/'
    region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'

    # load Planck Av and GALFA HI images, on same grid
    av_data_planck, h = load_fits(av_dir + \
                'california_planck_av_regrid.fits',
            return_header=True)

    # define core properties
    cores = {
        'L1482': {
            'center_wcs': [(4, 29, 41), (35, 48, 41)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'L1483': {
            'center_wcs': [(4, 34, 57), (36, 18, 12)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'L1478': {
            'center_wcs': [(4, 25, 7), (37, 13, 0)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'L1434': {
            'center_wcs': [(3, 50, 51), (35, 15, 10)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'L1503': {
            'center_wcs': [(4, 40, 27), (29, 57, 12)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
        'L1507': {
            'center_wcs': [(4, 42, 51), (29, 44, 47)],
            'map': None,
            'threshold': None,
            'box_wcs': None,
        },
    }

    cores = convert_core_coordinates(cores, h)

    if True:
        print('Calculating PDF for global map')

        figure_types = ['pdf', 'png']
        for figure_type in figure_types:
            plot_pdf(av_data_planck,
                    limits = [-2, 3.1, 1, 10**5],
                    savedir=figure_dir,
                    scale=(0,1),
                    filename='california_av_pdf_global_planck.%s' % \
                            figure_type,
                    title=r'A$_{\rm V}$ PDF of ' + \
                            'california',
                    show=False)

        cores = load_ds9_region(cores,
                                filename_base=region_dir +
                                'california_av_boxes_',
                                header=h)

        for core in cores:
            print('Calculating PDF for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
                                            xy[0],
                                            xy[1],
                                            width=box_width,
                                            height=box_height,
                                            angle=box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)
            av_data_planck_sub = av_data_planck[indices]

            figure_types = ['pdf', 'png']
            for figure_type in figure_types:
                plot_pdf(av_data_planck_sub,
                        limits = [-1,4,1,1000],
                        savedir=figure_dir,
                        scale=(0,1),
                        filename='california_av_pdf' + core + '_planck.%s' % \
                                figure_type,
                        title=r'A$_{\rm V}$ PDF of ' + \
                                'california Core ' + core,
                        show=False)
Esempio n. 15
0
        cores = load_ds9_region(cores,
                filename_base = region_dir + 'perseus_av_boxes_',
                header = h)

        for core in cores:
            print('Calculating PDF for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_data_planck,
        	        xy[0], xy[1],
                    width = box_width,
                    height = box_height,
                    angle = box_angle)

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)
            av_data_planck_sub = av_data_planck[indices]

            figure_types = ['pdf', 'png']
            for figure_type in figure_types:
                plot_pdf(av_data_planck_sub,
                        limits = [-1,4,1,1000],
                        savedir=figure_dir,
                        scale=(0,1),
                        filename='perseus_av_pdf' + core + '_planck.%s' % \
                                figure_type,
def main():

    import grid
    import numpy as np
    from os import system, path
    import myclumpfinder as clump_finder
    import mygeometry as myg
    import json

    # define directory locations
    output_dir = '/d/bip3/ezbc/california/data/python_output/nhi_av/'
    figure_dir = '/d/bip3/ezbc/california/figures/cores/'
    av_dir = '/d/bip3/ezbc/california/data/av/'
    hi_dir = '/d/bip3/ezbc/california/data/galfa/'
    region_dir = '/d/bip3/ezbc/california/data/python_output/ds9_regions/'
    core_dir = '/d/bip3/ezbc/california/data/python_output/core_properties/'

    # load 2mass Av and GALFA HI images, on same grid
    av_image, h = load_fits(av_dir + 'california_av_planck_5arcmin.fits',
                            return_header=True)

    # define core properties
    with open(core_dir + 'california_core_properties.txt', 'r') as f:
        cores = json.load(f)

    cores = convert_core_coordinates(cores, h)

    cores = load_ds9_region(cores,
                            filename_base=region_dir + 'california_av_boxes_',
                            header=h)

    if True:
        limits = [0, 20, -1, 25]  # x-linear limits

        # Initialize fit params
        A_p = []
        pho_c = []
        R_flat = []
        p = []

        # Initialize data lists
        radii_pc_list = []
        profile_list = []
        profile_std_list = []
        profile_fit_params_list = []
        core_names_list = []

        for core in cores:
            print('Calculating for core %s' % core)

            # Grab the mask from the DS9 regions
            xy = cores[core]['box_center_pix']
            box_width = cores[core]['box_width']
            box_height = cores[core]['box_height']
            box_angle = cores[core]['box_angle']
            mask = myg.get_rectangular_mask(av_image,
                                            xy[0],
                                            xy[1],
                                            width=box_width,
                                            height=box_height,
                                            angle=box_angle)

            mask = myg.get_polygon_mask(av_image,
                                        cores[core]['box_vertices_rotated'])

            # Get indices where there is no mask, and extract those pixels
            indices = np.where(mask == 1)

            av_image_sub = np.copy(av_image)
            #av_image_sub[mask == 0] = np.NaN
            av_image_sub = np.ma.array(av_image, mask=(mask == 0))

            # to check the positions of the boxes, uncomment the following
            #import matplotlib.pyplot as plt
            #plt.clf()
            #plt.imshow(np.ma.array(av_image_sub, mask=temp_mask))
            #plt.savefig('/usr/users/ezbc/Desktop/map%s.png' % core)
            #plt.clf()

            pix = cores[core]['center_pixel']

            # extract radial profile weighted by SNR
            radii, profile = get_radial_profile(av_image,
                                                binsize=3,
                                                center=pix,
                                                weights=av_image / 0.3,
                                                mask=mask)

            # extract std
            radii, profile_std = get_radial_profile(
                av_image_sub,
                binsize=3,
                center=pix,
                stddev=True,
                weights=av_image_sub / 0.3,
                #mask=mask
            )

            # convert radii from degrees to parsecs
            radii_arcmin = radii * h['CDELT2'] * 60 * 60.  # radii in arcminutes
            radii_pc = radii_arcmin * 300 / 206265.  # radii in parsecs

            # extract radii from within the limits
            indices = np.where((radii_pc < limits[1]) & \
                               (profile == profile) & \
                               (profile_std == profile_std))
            radii_pc = radii_pc[indices]
            profile = profile[indices]
            profile_std = profile_std[indices]

            # fit profile with power function
            def function(radius, A_p, pho_c, R_flat, p):
                return A_p * pho_c * R_flat / \
                        (1 + (radius / R_flat)**2)**(p/2. - 0.5)
                #return A_p * radius**p

            profile_fit_params = fit_profile(radii_pc,
                                             profile,
                                             function,
                                             sigma=profile / profile_std)[0]

            # plot the radial profile
            figure_types = ['.pdf', '.png']
            for figure_type in figure_types:
                plot_profile(
                    radii_pc,
                    profile,
                    profile_errors=profile_std,
                    limits=limits,
                    profile_fit_params=profile_fit_params,
                    profile_fit_function=function,
                    savedir=figure_dir + 'individual_cores/',
                    filename='california_profile_av_' + core + figure_type,
                    title=r'Radial A$_V$ Profile of california Core ' + core,
                    show=False)

            A_p.append(profile_fit_params[0])
            pho_c.append(profile_fit_params[1])
            R_flat.append(profile_fit_params[2])
            p.append(profile_fit_params[3])

            radii_pc_list.append(radii_pc)
            profile_list.append(profile)
            profile_std_list.append(profile_std)
            profile_fit_params_list.append(profile_fit_params)
            core_names_list.append(core)

        for figure_type in figure_types:
            plot_profile_grid(
                radii_pc_list,
                profile_list,
                profile_errors_list=profile_std_list,
                limits=limits,
                profile_fit_params_list=profile_fit_params_list,
                profile_fit_function=function,
                savedir=figure_dir + 'panel_cores/',
                filename='california_profile_av_cores_planck' + figure_type,
                title=r'Radial A$_V$ Profiles of california Cores',
                core_names=core_names_list,
                show=False)

        print_fit_params(cores,
                         A_p,
                         pho_c,
                         R_flat,
                         p,
                         filename=output_dir + 'core_profile_fit_data.txt')

        print_fit_params(cores, A_p, pho_c, R_flat, p)