Ejemplo n.º 1
0
def compare_spectral_indices(finaliter_prefix_b3, finaliter_prefix_b6,
                             cutoutregion, fignum=1, stdthresh=5,
                             scalebarlength=5,
                             basepath='/home/adam/work/alma-imf/reduction/', ):
    image_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)
    try:
        image_tt1_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt1', format='casa_image').subcube_from_ds9region(cutoutregion)
    except FileNotFoundError:
        image_tt1_b3 = SpectralCube.read(f'{finaliter_prefix_b3.replace("cleanest", "cleanest/extras")}.image.tt1', format='casa_image').subcube_from_ds9region(cutoutregion)
    image_b6 = SpectralCube.read(f'{finaliter_prefix_b6}.image.tt0', format='casa_image').subcube_from_ds9region(cutoutregion)
    try:
        image_tt1_b6 = SpectralCube.read(f'{finaliter_prefix_b6}.image.tt1', format='casa_image').subcube_from_ds9region(cutoutregion)
    except FileNotFoundError:
        image_tt1_b6 = SpectralCube.read(f'{finaliter_prefix_b6.replace("cleanest", "cleanest/extras")}.image.tt1', format='casa_image').subcube_from_ds9region(cutoutregion)

    image_b3 = image_b3 * u.beam / image_b3.beam.sr
    image_b6 = image_b6 * u.beam / image_b6.beam.sr
    image_tt1_b3 = image_tt1_b3 * u.beam / image_tt1_b3.beam.sr
    image_tt1_b6 = image_tt1_b6 * u.beam / image_tt1_b6.beam.sr


    fieldname = os.path.basename(finaliter_prefix_b6).split("_")[0]
    print(fieldname)
    noise_region_b3 = regions.read_ds9(f"{basepath}/reduction/noise_estimation_regions/{fieldname}_B3_noise_sampling.reg")
    noise_region_b6 = regions.read_ds9(f"{basepath}/reduction/noise_estimation_regions/{fieldname}_B6_noise_sampling.reg")

    beams = radio_beam.Beams(major=u.Quantity([image_b3.beam.major, image_b6.beam.major]),
                             minor=u.Quantity([image_b3.beam.minor, image_b6.beam.minor]),
                             pa=u.Quantity([image_b3.beam.pa, image_b6.beam.pa]))
    commonbeam = radio_beam.commonbeam.commonbeam(beams)

    if image_b3.beam.sr < image_b6.beam.sr:
        header = image_b6[0].header
        ww = image_b6.wcs
    else:
        header = image_b3[0].header
        ww = image_b3.wcs

    image_b3_repr = image_b3.convolve_to(commonbeam)[0].reproject(header)
    image_tt1_b3_repr = image_tt1_b3.convolve_to(commonbeam)[0].reproject(header)
    image_b6_repr = image_b6.convolve_to(commonbeam)[0].reproject(header)
    image_tt1_b6_repr = image_tt1_b6.convolve_to(commonbeam)[0].reproject(header)

    alpha_b3 = image_tt1_b3_repr / image_b3_repr
    alpha_b6 = image_tt1_b6_repr / image_b6_repr

    noiseim_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0', format='casa_image', use_dask=True).subcube_from_regions(noise_region_b3)[0].convolve_to(commonbeam)
    noiseim_b6 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0', format='casa_image', use_dask=True).subcube_from_regions(noise_region_b6)[0].convolve_to(commonbeam)
    b3_std = stats.mad_std(noiseim_b3.value, ignore_nan=True)
    b6_std = stats.mad_std(noiseim_b6.value, ignore_nan=True)

    mask = (image_b3_repr.value > stdthresh*b3_std) & (image_b6_repr.value > stdthresh*b6_std)
    alpha_b3_b6 = (np.log(image_b3_repr / image_b6_repr) / np.log(image_b3.wcs.wcs.crval[2] / image_b6.wcs.wcs.crval[2])).value
    alpha_b3_b6[~mask] = np.nan
    alpha_b3[~mask] = np.nan
    alpha_b6[~mask] = np.nan


    fig = pl.figure(num=fignum, figsize=(12,4))
    fig.clf()
    ax = pl.subplot(1,3,1,label='B3')
    ax.imshow(alpha_b3.value, vmax=4, vmin=-2)
    ax.set_xticks([])
    ax.set_yticks([])

    ax.set_title("B3")
    cb=pl.colorbar(mappable=pl.gca().images[0], cax=fig.add_axes([0.91,0.1,0.02,0.8]))
    cb.set_label(r"Spectral Index $\alpha$")

    ax = pl.subplot(1,3,2,label='B6')
    ax.imshow(alpha_b6.value, vmax=4, vmin=-2)
    ax.set_xticks([])
    ax.set_yticks([])

    ax.set_title("B6")
    cb=pl.colorbar(mappable=pl.gca().images[0], cax=fig.add_axes([0.91,0.1,0.02,0.8]))
    cb.set_label(r"Spectral Index $\alpha$")

    # scalebar
    cd = (ww.pixel_scale_matrix[1,1] * 3600)
    ax.plot([10*scalebarlength, 10*scalebarlength+scalebarlength/cd], [5,5], color='k')
    tx = ax.annotate(f'{scalebarlength}"', (10*scalebarlength+scalebarlength/2/cd, 9))
    tx.set_horizontalalignment('center')

    ax = pl.subplot(1,3,3,label='B3/B6')
    ax.imshow(alpha_b3_b6, vmax=4, vmin=-2)
    ax.set_xticks([])
    ax.set_yticks([])

    cb=pl.colorbar(mappable=pl.gca().images[0], cax=fig.add_axes([0.91,0.1,0.02,0.8]))
    cb.set_label(r"Spectral Index $\alpha$")
    ax.set_title("B6/B3")
    pl.subplots_adjust(wspace=0.05)
Ejemplo n.º 2
0
def main():
    """Main function"""

    #===========================
    #==   PARSE ARGS
    #===========================
    logger.info("Get script args ...")
    try:
        args = get_args()
    except Exception as ex:
        logger.error("Failed to get and parse options (err=%s)", str(ex))
        return 1

    filenames = [x.strip() for x in args.filenames.split(',')]
    userbeam = args.userbeam
    bmaj_user = args.bmaj
    bmin_user = args.bmin
    pa_user = args.pa

    print("=== ARGS ===")
    print("filenames")
    print(filenames)
    print("userbeam? %d" % userbeam)
    if userbeam:
        print("Beam (bmaj=%f arcsec,bmin=%f arcsec,pa=%f deg)" %
              (bmaj_user, bmin_user, pa_user))
    print("============")

    #===========================
    #==   READ IMAGES
    #===========================
    filenames_out = []
    data_list = []
    header_list = []
    pixsize_x = []
    pixsize_y = []
    beam_list = []

    for filename in filenames:
        # - Store output filename
        filename_out = Utils.getBaseFileNoExt(filename) + '_conv.fits'
        filenames_out.append(filename_out)

        # - Get image data & header
        #data_alldim, header= Utils.read_fits(filename)
        #nchan = len(data_alldim.shape)

        data, header = Utils.read_fits(filename)
        nchan = len(data.shape)

        logger.info("nchan=%d" % nchan)

        #if nchan==4:
        #	data= data_alldim[0, 0, :, :]
        #else:
        #	data= data_alldim
        data[np.isnan(data)] = 0.0  # replace all NAN pixels with 0
        data_list.append(data)
        header_list.append(header)

        # - Get beam and WCS info
        wcs = WCS(header)
        hasBeamInfo = Utils.hasBeamInfo(header)
        xc = header['CRPIX1']
        yc = header['CRPIX2']
        if nchan == 4:
            ra, dec = wcs.all_pix2world(xc, yc, 0, 0, 0, ra_dec_order=True)
        else:
            ra, dec = wcs.all_pix2world(xc, yc, 0, ra_dec_order=True)
        print("ra=%f, dec=%f" % (ra, dec))
        dx = abs(header['CDELT1'])  # in deg
        dy = abs(header['CDELT2'])  # in deg
        pixsize_x.append(dx)
        pixsize_y.append(dy)

        if hasBeamInfo:
            bmaj = header['BMAJ']  # in deg
            bmin = header['BMIN']  # in deg
            pa = header['BPA'] if 'BPA' in header else 0  # in deg
            beam = radio_beam.Beam(bmaj * u.deg, bmin * u.deg, pa * u.deg)
            beam_list.append(beam)
        else:
            logger.error("No BMAJ/BMIN keyword present in file " + filename +
                         "!")
            return -1

    #===========================
    #==   SET COMMON BEAM
    #===========================
    if userbeam:
        #common_beam_bmaj= bmaj_user.to(u.arcsec).value
        #common_beam_bmin= bmin_user.to(u.arcsec).value
        #common_beam_pa= pa_user.to(u.deg).value
        common_beam_bmaj = bmaj_user
        common_beam_bmin = bmin_user
        common_beam_pa = pa_user
        common_beam = radio_beam.Beam(bmaj_user * u.arcsec,
                                      bmin_user * u.arcsec, pa_user * u.deg)
    else:
        beams = radio_beam.Beams(beams=beam_list)
        common_beam = radio_beam.commonbeam.common_manybeams_mve(beams)
        common_beam_bmaj = common_beam.major.to(u.arcsec).value
        common_beam_bmin = common_beam.minor.to(u.arcsec).value
        common_beam_pa = common_beam.pa.to(u.deg).value

    logger.info(
        "Convolving images to common beam size (bmaj,bmin,pa)=(%s,%s,%s) ..." %
        (str(common_beam_bmaj), str(common_beam_bmin), str(common_beam_pa)))

    #===========================
    #==   CONVOLVE IMAGES
    #===========================
    for index in range(0, len(data_list)):

        # - Find convolving beam for this image
        bmaj, bmin, pa = radio_beam.utils.deconvolve(common_beam,
                                                     beam_list[index])
        bmaj_deg = bmaj.to(u.deg).value
        bmin_deg = bmin.to(u.deg).value
        pa_deg = pa.to(u.deg).value
        conv_beam = radio_beam.Beam(bmaj_deg * u.deg, bmin_deg * u.deg,
                                    pa_deg * u.deg)

        bmaj_arcsec = bmaj.to(u.arcsec).value
        bmin_arcsec = bmin.to(u.arcsec).value
        ny = data_list[index].shape[0]
        nx = data_list[index].shape[1]

        # - Create convolution kernel
        dx = pixsize_x[index]
        dy = pixsize_y[index]
        pixsize = max(dx, dy)
        conv_kernel = conv_beam.as_kernel(pixsize * u.deg)
        conv_kernel.normalize()
        kernel = conv_kernel.array
        logger.info("Convolution kernel size: %d x %d" %
                    (kernel.shape[0], kernel.shape[1]))

        # - Convolve image
        logger.info(
            "Convolving image %d (size=%d,%d) by beam (bmaj,bmin,pa)=(%s,%s,%s) ..."
            % (index + 1, nx, ny, str(bmaj_arcsec), str(bmin_arcsec),
               str(pa_deg)))
        data_conv = cv.filter2D(np.float64(data_list[index]),
                                -1,
                                kernel,
                                borderType=cv.BORDER_CONSTANT)

        # - Write output FITS
        logger.info("Saving convolved image to file %s ..." %
                    filenames_out[index])
        Utils.write_fits(data_conv, filenames_out[index], header_list[index])

    return 0
Ejemplo n.º 3
0
def alpha_hist(finaliter_prefix_b3, finaliter_prefix_b6, threshold=5,
               basepath='/home/adam/work/alma-imf/reduction/', las=None):
    image_b3 = SpectralCube.read(f'{finaliter_prefix_b3}.image.tt0.fits', use_dask=False, format='fits').minimal_subcube()
    image_b6 = SpectralCube.read(f'{finaliter_prefix_b6}.image.tt0.fits', use_dask=False, format='fits').minimal_subcube()
    image_b3 = image_b3 * u.beam / image_b3.beam.sr
    image_b6 = image_b6 * u.beam / image_b6.beam.sr

    fieldname = os.path.basename(finaliter_prefix_b6).split("_")[0]
    print()
    print(fieldname)
    print(image_b3)
    print(image_b6)

    if las:
        print(f"LAS {las} unsharp masking")
        t0 = time.time()
        smb3 = image_b3[0].convolve_to(radio_beam.Beam(las), allow_huge=True)
        print(f"Convolution of b3: {time.time() - t0} seconds")
        image_b3 = image_b3 - smb3
        print(f"Subtraction of convolved slice: {time.time()-t0}")
        smb6 = image_b6[0].convolve_to(radio_beam.Beam(las), allow_huge=True)
        image_b6 = image_b6 - smb6
        dt = time.time() - t0
        print(f"LAS subtraction took {dt} seconds")


    noise_region_b3 = regions.read_ds9(f"{basepath}/reduction/noise_estimation_regions/{fieldname}_B3_noise_sampling.reg")
    noise_region_b6 = regions.read_ds9(f"{basepath}/reduction/noise_estimation_regions/{fieldname}_B6_noise_sampling.reg")

    beams = radio_beam.Beams(major=u.Quantity([image_b3.beam.major, image_b6.beam.major]),
                             minor=u.Quantity([image_b3.beam.minor, image_b6.beam.minor]),
                             pa=u.Quantity([image_b3.beam.pa, image_b6.beam.pa]))
    commonbeam = radio_beam.commonbeam.commonbeam(beams)
    print(commonbeam)

    if image_b3.beam.sr < image_b6.beam.sr:
        header = image_b6[0].header
    else:
        header = image_b3[0].header

    print("Convolution and Reprojection")
    t0 = time.time()
    image_b3_repr = image_b3[0].convolve_to(commonbeam, allow_huge=True).reproject(header)
    print(f"B3 reprojection took {time.time()-t0} seconds")
    t0 = time.time()
    image_b6_repr = image_b6[0].convolve_to(commonbeam, allow_huge=True).reproject(header)
    print(f"B6 reprojection took {time.time()-t0} seconds")

    t0 = time.time()
    noiseim_b3 = image_b3.subcube_from_regions(noise_region_b3)[0].convolve_to(commonbeam, allow_huge=True)
    noiseim_b6 = image_b6.subcube_from_regions(noise_region_b6)[0].convolve_to(commonbeam, allow_huge=True)
    print(f"Shape of noiseims; b3={noiseim_b3.shape}, b6={noiseim_b6.shape}.  Subcubes took {time.time()-t0} seconds.")

    t0 = time.time()
    b3_std = stats.mad_std(noiseim_b3, ignore_nan=True)
    b6_std = stats.mad_std(noiseim_b6, ignore_nan=True)
    print(f"mad_std took {time.time()-t0} seconds")

    t0 = time.time()
    mask = (image_b3_repr > threshold*b3_std) & (image_b6_repr > threshold*b6_std)
    alpha_b3_b6 = (np.log(image_b3_repr / image_b6_repr) / np.log(image_b3.wcs.wcs.crval[2] / image_b6.wcs.wcs.crval[2])).value
    alpha_b3_b6[~mask] = np.nan
    print(f"mask & alpha calc took {time.time()-t0} seconds")

    pl.figure(2, figsize=(8,8)).clf()
    ax = pl.gca()
    ax.hist(alpha_b3_b6[mask], bins=np.linspace(-2,5), density=True)
    ax.set_xlabel("Spectral Index $\\alpha$")
    ax.set_ylabel("Fraction of Pixels")

    return mask, alpha_b3_b6, image_b3_repr, image_b6_repr
Ejemplo n.º 4
0
    'OrionSourceI_Unknown_2_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_3_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_4_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_5_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_8_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_9_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_Unknown_10_robust0.5maskedclarkclean10000_medsub_K.fits',
    'OrionSourceI_U229.682_robust0.5maskedclarkclean10000_medsub_K.fits',
]

allbeamlist = [
    SpectralCube.read(paths.dpath('cubes/' + fn)).beams.common_beam()
    for fn in files
]
allbeams = radio_beam.Beams(major=u.Quantity([x.major for x in allbeamlist]),
                            minor=u.Quantity([x.minor for x in allbeamlist]),
                            pa=u.Quantity([x.pa for x in allbeamlist]))
refbeam = allbeams.common_beam()

refcube = SpectralCube.read(paths.dpath('cubes/' + files[0]))
refcube = refcube.convolve_to(refbeam)

stackcube = [refcube]

for cubefn in files[1:]:
    reproj_cube = (SpectralCube.read(
        paths.dpath('cubes/' +
                    cubefn)).convolve_to(refbeam).spectral_interpolate(
                        refcube.spectral_axis))

    stackcube.append(reproj_cube)