示例#1
0
def rebinpix(imagename, output, blc_ra, blc_dec):
    """
    change pixel size to bmaj/4.53
    """
    # get native grid information
    num_x_pix = imhead(imagename, mode="list")["shape"][0]
    num_y_pix = imhead(imagename, mode="list")["shape"][1]
    pix_radian = imhead(imagename, mode="list")["cdelt2"]
    pix_arcsec = round(pix_radian * 3600 * 180 / np.pi, 2)

    # create tempalte image
    beamsize = round(imhead(imagename, "list")["beammajor"]["value"], 2)
    pix_size = round(beamsize / 4.53, 2)
    size_x = max(
        int(num_x_pix * pix_arcsec / pix_size) + 4,
        int(num_y_pix * pix_arcsec / pix_size) + 4)
    size_y = size_x
    c = SkyCoord(blc_ra, blc_dec)
    ra_dgr = str(c.ra.degree)
    dec_dgr = str(c.dec.degree)
    direction_ra = str(ra_dgr) + "deg"
    direction_dec = str(dec_dgr) + "deg"
    direction = "J2000 " + direction_ra + " " + direction_dec
    mycl.done()
    mycl.addcomponent(dir=direction,
                      flux=1.0,
                      fluxunit="Jy",
                      freq="230.0GHz",
                      shape="Gaussian",
                      majoraxis="0.1arcmin",
                      minoraxis="0.05arcmin",
                      positionangle="45.0deg")

    myia.fromshape(output + "_tmp_", [size_x, size_y, 1, 1], overwrite=True)
    mycs = myia.coordsys()
    mycs.setunits(["rad", "rad", "", "Hz"])
    cell_rad = myqa.convert(myqa.quantity(str(pix_size) + "arcsec"),
                            "rad")["value"]
    mycs.setincrement([-cell_rad, cell_rad], "direction")
    mycs.setreferencevalue([
        myqa.convert(direction_ra, "rad")["value"],
        myqa.convert(direction_dec, "rad")["value"]
    ],
                           type="direction")
    mycs.setreferencevalue("230GHz", "spectral")
    mycs.setincrement("1GHz", "spectral")
    myia.setcoordsys(mycs.torecord())
    myia.setbrightnessunit("Jy/pixel")
    myia.modify(mycl.torecord(), subtract=False)
    exportfits(imagename=output + "_tmp_",
               fitsimage=output + "_tmp_.fits",
               overwrite=True)

    importfits(fitsimage=output + "_tmp_.fits", imagename=output)

    myia.close()
    mycl.close()
    os.system("rm -rf " + output + "_tmp_")
    os.system("rm -rf " + output + "_tmp_.fits")
def gridtemplate(imagename10, image_length, direction_ra, direction_dec):
    """
    myim02
    """
    # get native grid information
    num_x_pix = imhead(imagename10, mode="list")["shape"][0]
    num_y_pix = imhead(imagename10, mode="list")["shape"][1]
    pix_radian = imhead(imagename10, mode="list")["cdelt2"]
    obsfreq = 115.27120  # imhead(imagename10,mode="list")["restfreq"][0]/1e9
    pix_arcsec = round(pix_radian * 3600 * 180 / np.pi, 3)

    # create tempalte image
    blc_ra_tmp = imstat(imagename10)["blcf"].split(", ")[0]
    blc_dec_tmp = imstat(imagename10)["blcf"].split(", ")[1]
    blc_ra = blc_ra_tmp.replace(":", "h", 1).replace(":", "m", 1) + "s"
    blc_dec = blc_dec_tmp.replace(".", "d", 1).replace(".", "m", 1) + "s"
    beamsize = round(imhead(imagename10, "list")["beammajor"]["value"], 2)
    pix_size = round(beamsize / 4.53, 2)
    size_x = int(image_length / pix_size)
    size_y = size_x
    c = SkyCoord(blc_ra, blc_dec)
    ra_dgr = str(c.ra.degree)
    dec_dgr = str(c.dec.degree)
    direction = "J2000 " + direction_ra + " " + direction_dec
    mycl.done()
    mycl.addcomponent(dir=direction,
                      flux=1.0,
                      fluxunit="Jy",
                      freq="230.0GHz",
                      shape="Gaussian",
                      majoraxis="0.1arcmin",
                      minoraxis="0.05arcmin",
                      positionangle="45.0deg")

    myia.fromshape("template.im", [size_x, size_y, 1, 1], overwrite=True)
    mycs = myia.coordsys()
    mycs.setunits(["rad", "rad", "", "Hz"])
    cell_rad = myqa.convert(myqa.quantity(str(pix_size) + "arcsec"),
                            "rad")["value"]
    mycs.setincrement([-cell_rad, cell_rad], "direction")
    mycs.setreferencevalue([
        myqa.convert(direction_ra, "rad")["value"],
        myqa.convert(direction_dec, "rad")["value"]
    ],
                           type="direction")
    mycs.setreferencevalue(str(obsfreq) + "GHz", "spectral")
    mycs.setincrement("1GHz", "spectral")
    myia.setcoordsys(mycs.torecord())
    myia.setbrightnessunit("Jy/pixel")
    myia.modify(mycl.torecord(), subtract=False)
    exportfits(imagename="template.im",
               fitsimage="template.fits",
               overwrite=True)

    os.system("rm -rf template.image")
    importfits(fitsimage="template.fits", imagename="template.image")

    myia.close()
    mycl.close()
    def _restore(self, model_fits="", residual_ms="", restored_image="restored"):
        qa = casacore.casac.quanta
        ia = casacore.casac.image

        residual_image = "residual"
        os.system("rm -rf *.log *.last " + residual_image +
                  ".* mod_out convolved_mod_out convolved_mod_out.fits " + restored_image + " " + restored_image + ".fits")

        importfits(imagename="model_out", fitsimage=self.model_fits)
        shape = imhead(imagename="model_out", mode="get", hdkey="shape")
        pix_num = shape[0]
        cdelt = imhead(imagename="model_out", mode="get", hdkey="cdelt2")
        cdelta = qa.convert(v=cdelt, outunit="arcsec")
        cdeltd = qa.convert(v=cdelt, outunit="deg")
        pix_size = str(cdelta['value']) + "arcsec"

        tclean(vis=residual_ms, imagename=residual_image, specmode='mfs', deconvolver='hogbom', niter=0,
               stokes=self.stokes, weighting='briggs', nterms=1, robust=self.robust, imsize=[self.M, self.N], cell=self.cell, datacolumn='RESIDUAL')

        exportfits(imagename=residual_image + ".image",
                   fitsimage=residual_image + ".image.fits", overwrite=True, history=False)

        ia.open(infile=residual_image + ".image")
        rbeam = ia.restoringbeam()
        ia.done()
        ia.close()

        bmaj = imhead(imagename=residual_image + ".image",
                      mode="get", hdkey="beammajor")
        bmin = imhead(imagename=residual_image + ".image",
                      mode="get", hdkey="beamminor")
        bpa = imhead(imagename=residual_image + ".image",
                     mode="get", hdkey="beampa")

        minor = qa.convert(v=bmin, outunit="deg")
        pa = qa.convert(v=bpa, outunit="deg")

        ia.open(infile="model_out")
        ia.convolve2d(outfile="convolved_model_out", axes=[
                      0, 1], type='gauss', major=bmaj, minor=bmin, pa=bpa)
        ia.done()
        ia.close()

        exportfits(imagename="convolved_model_out",
                   fitsimage="convolved_model_out.fits", overwrite=True, history=False)
        ia.open(infile="convolved_model_out.fits")
        ia.setrestoringbeam(beam=rbeam)
        ia.done()
        ia.close()

        imagearr = ["convolved_model_out.fits", residual_image + ".image.fits"]

        immath(imagename=imagearr, expr=" (IM0   + IM1) ", outfile=restored_image)

        exportfits(imagename=restored_image, fitsimage=restored_image +
                   ".fits", overwrite=True, history=False)

        return residual_image + ".image.fits", restored_image + ".fits"
def tscreatemask(imagename, thres, outmask):
    """
    myim03
    """
    os.system("rm -rf " + outmask)
    immath(imagename=imagename,
           mode="evalexpr",
           expr="iif(IM0 >= " + str(thres) + ", 1.0, 0.0)",
           outfile=outmask)
    imhead(imagename=outmask, mode="del", hdkey="beammajor")
def moment_maps(imagename, chans, mask, thres, output_mom=[0, 1, 2, 8]):
    """
    - 8
    """
    # modify the header of the mask
    bmaj = imhead(imagename, "list")["beammajor"]["value"]
    bmin = imhead(imagename, "list")["beamminor"]["value"]
    bpa = imhead(imagename, "list")["beampa"]["value"]
    imhead(mask, "put", "beammajor", str(bmaj) + "arcsec")
    imhead(mask, "put", "beamminor", str(bmin) + "arcsec")
    imhead(mask, "put", "beampa", str(bpa) + "deg")

    # create masked cube
    outfile = imagename + ".masked"
    os.system("rm -rf " + outfile)
    immath(imagename=[imagename, mask],
           mode="evalexpr",
           expr="iif(IM1 >= 1.0, IM0, 0.0)",
           outfile=outfile)

    #create moment maps using the masked cube
    for i in range(len(output_mom)):
        outfile = imagename + ".moment" + str(output_mom[i])
        os.system("rm -rf " + outfile)
        immoments(imagename=imagename + ".masked",
                  moments=[output_mom[i]],
                  chans=chans,
                  includepix=[thres, 100000.],
                  outfile=outfile)
def tsbeam_area(imagename):
    """
    myim01, myim03
    """
    major = imhead(imagename=imagename, mode="get", hdkey="beammajor")["value"]
    minor = imhead(imagename=imagename, mode="get", hdkey="beamminor")["value"]
    pix = abs(imhead(imagename=imagename, mode="list")["cdelt1"])
    pixelsize = pix * 3600 * 180 / np.pi
    beamarea_arcsec = major * minor * np.pi / (4 * np.log(2))
    beamarea_pix = beamarea_arcsec / (pixelsize**2)

    return beamarea_pix
def easy_K2Jy(imagename, synsbeam, freq):
    """
    - 2
    """
    imhead(imagename=imagename, mode="put", hdkey="bunit", hdvalue="Jy/beam")
    expr_coeff = synsbeam * synsbeam * freq * freq / 1.222e6

    os.system("rm -rf " + imagename + ".jy")
    immath(imagename=imagename,
           mode="evalexpr",
           expr="IM0*" + str(expr_coeff),
           outfile=imagename + ".jy")
    os.system("rm -rf " + imagename)
def beam_area(imagename, increment_mask):
    """
    - 6
    """
    major = imhead(imagename=imagename, mode="get", hdkey="beammajor")["value"]
    minor = imhead(imagename=imagename, mode="get", hdkey="beamminor")["value"]
    pix = abs(imhead(imagename=imagename, mode="list")["cdelt1"])

    pixelsize = pix * 3600 * 180 / np.pi
    beamarea = (major * minor * np.pi/(4 * np.log(2))) \
               / (pixelsize ** 2) * increment_mask * increment_mask

    return beamarea
def moment_maps(dir_data, imagename, chans, mask, thres):
    #modify the header of the mask
    maskname = dir_data + "mask2.image"
    os.system("rm -rf " + maskname)
    os.system("cp -r " + dir_data + mask + " " + maskname)
    bmaj = imhead(imagename=imagename, mode="list")["beammajor"]["value"]
    bmin = imhead(imagename=imagename, mode="list")["beamminor"]["value"]
    bpa = imhead(imagename=imagename, mode="list")["beampa"]["value"]
    imhead(imagename=maskname,
           mode="put",
           hdkey="beammajor",
           hdvalue=str(bmaj) + "arcsec")
    imhead(imagename=maskname,
           mode="put",
           hdkey="beamminor",
           hdvalue=str(bmin) + "arcsec")
    imhead(imagename=maskname,
           mode="put",
           hdkey="beampa",
           hdvalue=str(bpa) + "deg")
    #create masked cube
    outfile = imagename + ".masked"
    os.system("rm -rf " + outfile)
    immath(imagename=[imagename, maskname],
           mode="evalexpr",
           expr="iif(IM1 >= 1.0, IM0, 0.0)",
           outfile=outfile)
    #create moment maps using the masked cube
    outfile = imagename + ".moment0"
    os.system("rm -rf " + outfile)
    immoments(imagename=imagename + ".masked",
              moments=[0],
              chans=chans,
              includepix=[thres, 100000.],
              outfile=outfile)
    outfile = imagename + ".moment1"
    os.system("rm -rf " + outfile)
    immoments(imagename=imagename + ".masked",
              moments=[1],
              chans=chans,
              includepix=[thres, 100000.],
              outfile=outfile)
    outfile = imagename + ".moment2"
    os.system("rm -rf " + outfile)
    immoments(imagename=imagename + ".masked",
              moments=[2],
              chans=chans,
              includepix=[thres, 100000.],
              outfile=outfile)
    outfile = imagename + ".moment8"
    os.system("rm -rf " + outfile)
    immoments(imagename=imagename + ".masked",
              moments=[8],
              chans=chans,
              includepix=[thres, 100000.],
              outfile=outfile)
def createmask(dir_data, imagename, thres, outmask="mask1.image", pixelmin=5.):
    #create mask with thres
    outfile = dir_data + outmask
    os.system("rm -rf " + outfile)
    immath(imagename=dir_data + imagename,
           mode="evalexpr",
           expr="iif(IM0 >= " + str(thres) + ", 1.0, 0.0)",
           outfile=outfile)
    imhead(imagename=outfile, mode="del", hdkey="beammajor")
    makemask(mode="copy",
             inpimage=outfile,
             inpmask=outfile,
             output=outfile + ":mask0",
             overwrite=True)
def tsJy2Kelvin(imagename, outfile):
    """
    myim01
    """
    myunit = imhead(imagename, mode="list")["bunit"]
    if myunit == "Jy/beam":
        os.system("mv " + imagename + " " + outfile)
    else:
        headlist = imhead(imagename, mode="list")
        beamsize = headlist["beammajor"]["value"]
        restfreq = headlist["restfreq"][0] / 1e9
        factor = 1.222e6 / beamsize / beamsize / restfreq / restfreq
        os.system("rm -rf " + outfile)
        immath(imagename=imagename, expr="IM0/" + str(factor), outfile=outfile)
        imhead(outfile, mode="put", hdkey="bunit", hdvalue="Jy/beam")
        os.system("rm -rf " + imagename)
def beam_area(imagename):
    """
    for moment map creation
    """
    major = imhead(imagename = imagename,
                   mode = "get",
                   hdkey = "beammajor")["value"]
    minor = imhead(imagename = imagename,
                   mode = "get",
                   hdkey = "beamminor")["value"]
    pix = abs(imhead(imagename = imagename,
                     mode = "list")["cdelt1"])

    pixelsize = pix * 3600 * 180 / np.pi
    beamarea = (major * minor * np.pi/(4 * np.log(2))) \
               / (pixelsize ** 2)

    return beamarea
def def_area(imagename, aperture, beam):
    """
    - 4
    """
    pixsize_tmp = imhead(imagename, mode="list")["cdelt1"]
    pixsize = round(abs(pixsize_tmp) * 3600 * 180 / np.pi, 2)
    S_ap = (aperture / 2.)**2 * np.pi / pixsize**2  # aperture area
    S_bm = (beam / 2.)**2 * np.pi / pixsize**2  # beam area

    return S_ap, S_bm
def import_data(
    imagename,
    mode,
    index=0,
):
    """
    myim10
    """
    image_r = imhead(imagename, mode="list")["shape"][0] - 1
    image_t = imhead(imagename, mode="list")["shape"][1] - 1
    value = imval(imagename, box="0,0," + str(image_r) + "," + str(image_t))

    if mode == "coords":
        value_masked = value[mode][:, :, index] * 180 / np.pi
    else:
        value_masked = value[mode]

    value_masked_1d = value_masked.flatten()

    return value_masked_1d
示例#15
0
def line_ratio(dir_data, im1, im2, outfile, diff, mask=[]):
    """
    """
    os.system("rm -rf " + dir_data + outfile)
    os.system("rm -rf " + dir_data + outfile + ".beforemask")
    if not mask:
        immath(imagename=[dir_data + im1, dir_data + im2],
               mode="evalexpr",
               expr="IM0/IM1/" + diff,
               outfile=dir_data + outfile)
    else:
        #modify the header of the mask
        maskname = dir_data + mask
        bmaj = imhead(imagename=dir_data + im1,
                      mode="list")["beammajor"]["value"]
        bmin = imhead(imagename=dir_data + im1,
                      mode="list")["beamminor"]["value"]
        bpa = imhead(imagename=dir_data + im1, mode="list")["beampa"]["value"]
        imhead(imagename=maskname,
               mode="put",
               hdkey="beammajor",
               hdvalue=str(bmaj) + "arcsec")
        imhead(imagename=maskname,
               mode="put",
               hdkey="beamminor",
               hdvalue=str(bmin) + "arcsec")
        imhead(imagename=maskname,
               mode="put",
               hdkey="beampa",
               hdvalue=str(bpa) + "deg")
        immath(imagename=[dir_data + im1, dir_data + im2],
               mode="evalexpr",
               expr="IM0/IM1/" + diff,
               outfile=dir_data + outfile + ".beforemask")
        immath(imagename=[dir_data + outfile + ".beforemask", maskname],
               mode="evalexpr",
               expr="iif(IM1 >= 1.0, IM0, 0.0)",
               outfile=dir_data + outfile)
        os.system("rm -rf " + dir_data + outfile + ".beforemask")
示例#16
0
def convert_str_to_beam(infile, beam):
    """
    round beam diameter in arcsec
    """
    ### import casa images
    if ".fits" in infile:
        done = glob.glob(infile.replace(".fits", ".image"))
        if not done:
            eazy_importfits(infile, defaultaxes=False)

        imagename = infile.replace(".fits", ".image")
    else:
        imagename = infile.replace(".fits", ".image")

    ### str to beam
    beam = beam * u.arcsec  # arcsec
    beamarea = (2 * np.pi / (8 * np.log(2))) * (beam**2).to(u.sr)  # str

    os.system("rm -rf " + imagename + ".beam")
    immath(imagename=imagename,
           outfile=imagename + ".beam",
           expr="IM0*1e6*" + str(beamarea.value))

    imhead(imagename=imagename + ".beam",
           mode="put",
           hdkey="beammajor",
           hdvalue=str(beam.value) + "arcsec")

    imhead(imagename=imagename + ".beam",
           mode="put",
           hdkey="beamminor",
           hdvalue=str(beam.value) + "arcsec")

    imhead(imagename=imagename + ".beam",
           mode="put",
           hdkey="beampa",
           hdvalue="0.0deg")

    imhead(imagename=imagename + ".beam",
           mode="put",
           hdkey="bunit",
           hdvalue="Jy/beam")
def ch_noise(image_cube,chans):
    ch_line_start = int(chans.split("~")[0])
    ch_line_end = int(chans.split("~")[1])
    size_cube = imhead(image_cube)["shape"][3]

    if int(ch_line_start)-1 > 0:
        ch_noise_1 = "0~"+str(ch_line_start-1)
    else:
        ch_noise_1 = ""

    if ch_line_end+1 < size_cube-1:
        ch_noise_2 = str(ch_line_end+1)+"~"+str(size_cube-1)
    else:
        ch_noise_2 = ""

    ch_noise = ",".join([ch_noise_1, ch_noise_2]).rstrip(",")

    return ch_noise
easy_imregrid(image_cube_sm,temp_rebinpix,axes=[0,1],delete_original=True)
easy_imregrid(image_cube_depb_sm,temp_rebinpix,axes=[0,1],delete_original=True)

image_cube2 = dir_gal+galnames[i]+"_co21_"+suffix+".cube"
os.system("rm -rf "+image_cube2)
os.system("cp -r "+image_cube_sm+".regrid "+image_cube2)
os.system("cp -r "+image_cube_depb_sm+".regrid "+image_cube2+".depb")

# immoments
chnoise = ch_noise(image_cube2,chanss[i])
rms = imstat(image_cube2,chans=chnoise)["rms"][0]
moment_maps(image_cube2,chanss[i],outmask,rms*snr_moms[i],beams[i])

# pb masking
mask_pb = dir_gal+galnames[i]+"_pb_"+suffix+".mask"
peak = imhead(pb_map,mode="list")["datamax"]
createmask(pb_map,peak*pbcuts[i],mask_pb)

images_moment = glob.glob(image_cube2 + ".moment*")
for k in range(len(images_moment)):
    outfile = images_moment[k].replace(".cube","")
    if galnames[i] == "ngc3110":
        os.system("mv " + images_moment[k] + " " \
                  + images_moment[k].replace(".cube",""))
    else:
        os.system("rm -rf " + outfile)
        immath(imagename = [images_moment[k],mask_pb],
               mode = "evalexpr",
               expr = "IM0*IM1",
               outfile = outfile)
        os.system("rm -rf " + images_moment[k])
def fits2eps_phangs(dir_data,
                    imagename_color,
                    imagename_contour,
                    ra_center,
                    dec_center,
                    title,
                    colorbar_label,
                    output,
                    colorscale,
                    colorlog=False,
                    value=None,
                    colorbar=False,
                    contour=[0.1],
                    color_contour="k",
                    color_beam="b",
                    xlim=([-30, 30]),
                    ylim=([30, -30]),
                    clim=None,
                    nucleus=None,
                    showbeam=True):
    """
    test
    """
    ra_center_define = (float(ra_center.split(":")[0]) \
                       + float(ra_center.split(":")[1]) / 60. \
                       + float(ra_center.split(":")[2]) / 3600. ) \
                       * 15.
    if dec_center.split(".")[0][0] == "-":
        dec_center_define = float(dec_center.split(".")[0]) \
                            - float(dec_center.split(".")[1]) / 60. \
                            - float(dec_center.split(".")[2] + "." + dec_center.split(".")[3]) / 3600.
    else:
        dec_center_define = float(dec_center.split(".")[0]) \
                            + float(dec_center.split(".")[1]) / 60. \
                            + float(dec_center.split(".")[2] + "." + dec_center.split(".")[3]) / 3600.
    image_file = dir_data + imagename_color
    datamax = imhead(image_file, "list")["datamax"]
    hdu_list = fits.open(image_file)
    ra_imagecenter = hdu_list[0].header["CRVAL1"]
    dec_imagecenter = hdu_list[0].header["CRVAL2"]
    ra_pixsize = abs(hdu_list[0].header["CDELT1"]) * 3600
    dec_pixsize = abs(hdu_list[0].header["CDELT2"]) * 3600
    print(ra_pixsize, dec_pixsize)
    ra_pixcenter = hdu_list[0].header["CRPIX1"]
    dec_pixcenter = hdu_list[0].header["CRPIX2"]
    dec_newcenter_offset = (dec_imagecenter - dec_center_define) \
                           * 3600 / dec_pixsize
    ra_newcenter_offset = (ra_imagecenter - ra_center_define) \
                           * 3600 / ra_pixsize
    ra_newcenter = ra_pixcenter - ra_newcenter_offset
    dec_newcenter = dec_pixcenter - dec_newcenter_offset
    ra_size = hdu_list[0].header["NAXIS1"]
    dec_size = hdu_list[0].header["NAXIS2"]
    image_data = hdu_list[0].data[:, :]  # .data[0,0,:,:] # .data[:,:]
    xmin_col = (+0.5 - ra_newcenter) * ra_pixsize
    xmax_col = (ra_size + 0.5 - ra_newcenter) * ra_pixsize
    ymin_col = (+1.5 - dec_newcenter) * dec_pixsize
    ymax_col = (dec_size + 1.5 - dec_newcenter) * dec_pixsize
    xmin_cnt = (+1.0 - ra_newcenter) * ra_pixsize
    xmax_cnt = (ra_size + 1.0 - ra_newcenter) * ra_pixsize
    ymin_cnt = (+1.0 - dec_newcenter) * dec_pixsize
    ymax_cnt = (dec_size + 1.0 - dec_newcenter) * dec_pixsize
    plt.figure()
    plt.rcParams["font.size"] = 14
    if colorlog == True:
        plt.imshow(image_data,
                   norm=LogNorm(vmin=0.02 * datamax, vmax=datamax),
                   cmap=colorscale,
                   extent=[xmin_col, xmax_col, ymin_col, ymax_col])
    else:
        plt.imshow(image_data,
                   cmap=colorscale,
                   extent=[xmin_col, xmax_col, ymin_col, ymax_col])
    plt.xlim(xlim)
    plt.ylim(ylim)
    if clim != None:
        plt.clim(clim)
    plt.title(title)
    plt.xlabel("x-offset (arcsec)")
    plt.ylabel("y-offset (arcsec)")
    if colorbar == True:
        cbar = plt.colorbar()
        cbar.set_label(colorbar_label)
    contour_file = dir_data + imagename_contour
    hdu_contour = fits.open(contour_file)
    contour_data = hdu_contour[0].data[:, :]  # .data[0,0,:,:] # .data[:,:]
    if value != None:
        value_contour = value
    else:
        value_contour = imhead(contour_file, "list")["datamax"]
    contour2 = map(lambda x: x * value_contour, contour)
    plt.contour(contour_data,
                levels=contour2,
                extent=[xmin_cnt, xmax_cnt, ymax_cnt, ymin_cnt],
                colors=color_contour,
                linewidths=[0.5])
    if showbeam == True:
        bmaj = imhead(image_file, "list")["beammajor"]["value"]
        bmin = imhead(image_file, "list")["beamminor"]["value"]
        bpa = imhead(image_file, "list")["beampa"]["value"]
        ax = plt.axes()
        e = patches.Ellipse(xy=(min(xlim) * 0.8, max(ylim) * 0.8),
                            width=bmin,
                            height=bmaj,
                            angle=bpa * -1,
                            fc=color_beam)
        ax.add_patch(e)
    if nucleus != None:
        e2 = patches.Ellipse(
            xy=(0, 0),
            width=nucleus,
            height=nucleus,
            angle=0,
            fill=False,
            edgecolor="black",
            alpha=0.5,
            #ls = ":",
            lw=5)
        ax.add_patch(e2)
    #plt.grid()
    plt.savefig(dir_data + output, dpi=100)
def eazy_immoments(dir_proj,
                   imagename,
                   galname,
                   noise,
                   beamp,
                   snr_mom,
                   percent,
                   nchan,
                   maskname=None,
                   myim="03"):
    """
    myim03, myim05
    use co10 mask for co10, co21 mask for co21
    This is be replace by eazy_immoments_r21.
    """
    if myim == "03":
        # prepare workinf directory e.g., ngc0628_co10
        name_line = imagename.split(galname + "_")[1].split("_")[0]
        dir_image = dir_proj + "../" + galname + "_" + name_line + "/"
        cubeimage = dir_image + name_line + "_cube.image"
        os.system("mkdir " + dir_image)
        os.system("cp -r " + imagename + " " + cubeimage)
    elif myim == "05":
        name_line = imagename.split(galname + "_")[1].split("/")[0]
        dir_image = dir_proj
        cubeimage = imagename

    print("### woking on " + galname + " " + name_line + " " + beamp)

    if maskname == None:
        os.system("rm -rf " + cubeimage + ".masked")
        #os.system("rm -rf " + dir_image+"*.noise")
        os.system("rm -rf " + dir_image + "*.mask*")

        # imsmooth
        cubesmooth1 = cubeimage.replace(".image", ".smooth1")  # 4.0 mJy
        bmaj = imhead(cubeimage, "list")["beammajor"]["value"]
        imsmooth(
            imagename=cubeimage,
            targetres=True,
            major=str(bmaj * 3.0) + "arcsec",  #1.2) + "arcsec",
            minor=str(bmaj * 3.0) + "arcsec",  #1.2) + "arcsec",
            pa="0deg",
            outfile=cubesmooth1)
        cubesmooth2 = cubeimage.replace(".image", ".smooth2")  # 10 mJy
        imsmooth(imagename=cubeimage,
                 targetres=True,
                 major=str(bmaj * 5.0) + "arcsec",
                 minor=str(bmaj * 5.0) + "arcsec",
                 pa="0deg",
                 outfile=cubesmooth2)
        cubesmooth3 = cubeimage.replace(".image", ".smooth3")  # 10 mJy
        imsmooth(imagename=cubeimage,
                 targetres=True,
                 major=str(bmaj * 7.0) + "arcsec",
                 minor=str(bmaj * 7.0) + "arcsec",
                 pa="0deg",
                 outfile=cubesmooth3)
        # noise
        noisesmooth1 = noisehist(cubesmooth1,
                                 0.02,
                                 "test",
                                 3.0,
                                 bins=200,
                                 thres=0.0001,
                                 plotter=False)
        noisesmooth2 = noisehist(cubesmooth2,
                                 0.02,
                                 "test",
                                 3.0,
                                 bins=200,
                                 thres=0.0001,
                                 plotter=False)
        noisesmooth3 = noisehist(cubesmooth3,
                                 0.02,
                                 "test",
                                 3.0,
                                 bins=200,
                                 thres=0.0001,
                                 plotter=False)
        # create mask
        #tscreatemask(cubeimage,noise*1.*2.,dir_image+name_line+"_mask0.image")
        tscreatemask(cubesmooth1, noisesmooth1 * 0.0,
                     dir_image + name_line + "_mask1.image")
        tscreatemask(cubesmooth2, noisesmooth2 * 0.0,
                     dir_image + name_line + "_mask2.image")
        tscreatemask(cubesmooth3, noisesmooth3 * 0.0,
                     dir_image + name_line + "_mask3.image")

        immath(imagename=[
            dir_image + name_line + "_mask1.image",
            dir_image + name_line + "_mask2.image",
            dir_image + name_line + "_mask3.image"
        ],
               expr="iif(IM0+IM1 >= 2.0, 1.0, 0.0)",
               outfile=dir_image + name_line + "_" + beamp + "_mask.image")

        os.system("rm -rf " + cubesmooth1)
        os.system("rm -rf " + cubesmooth2)
        os.system("rm -rf " + cubesmooth3)
        os.system("rm -rf " + dir_image + name_line + "_mask0.image")
        os.system("rm -rf " + dir_image + name_line + "_mask1.image")
        os.system("rm -rf " + dir_image + name_line + "_mask2.image")

        mask_use_here = dir_image + name_line + "_" + beamp + "_mask.image"

    else:
        mask_use_here = dir_image + name_line + "_" + beamp + "_mask.image"
        os.system("cp -r " + maskname + " " + mask_use_here)

    immath(imagename=[cubeimage, mask_use_here],
           expr="iif( IM0>=" + str(noise * snr_mom) + ", IM0*IM1, 0.0)",
           outfile=cubeimage + ".masked")
    #os.system("rm -rf " + mask_use_here)

    vch = abs(imhead(cubeimage,
                     mode="list")["cdelt4"]) / 115.27120e9 * 299792.458

    immath(imagename=cubeimage + ".masked",
           expr="iif( IM0>0, 1.0/" + str(vch) + ", 0.0)",
           outfile=cubeimage + ".maskedTF")

    immoments(imagename=cubeimage + ".maskedTF",
              moments=[0],
              outfile=dir_image + name_line + ".moment0.noise_tmp")  # Nch

    beamarea_pix = tsbeam_area(dir_image + name_line + ".moment0.noise_tmp")
    immath(
        dir_image + name_line + ".moment0.noise_tmp",
        expr=str(vch) + "*sqrt(IM0)*" +
        str(noise),  #+"/"+str(np.sqrt(beamarea_pix)),
        outfile=dir_image + name_line + "_" + beamp + ".moment0.noise")

    immoments(
        imagename=cubeimage + ".masked",
        moments=[0],
        #includepix = [noises[i]*3.0,10000.],
        outfile=dir_image + name_line + ".moment0_tmp")

    immoments(
        imagename=cubeimage + ".masked",
        moments=[1],
        #includepix = [noises[i]*3.0,10000.],
        outfile=dir_image + name_line + ".moment1_tmp")

    immoments(
        imagename=cubeimage + ".masked",
        moments=[8],
        #includepix = [noises[i]*3.0,10000.],
        outfile=dir_image + name_line + ".moment8_tmp")

    # masking
    peak = imstat(dir_image + name_line + ".moment0_tmp")["max"][0]

    #
    immath(imagename=[
        dir_image + name_line + ".moment0_tmp",
        dir_image + name_line + ".moment0_tmp"
    ],
           expr="iif( IM0>=" + str(peak * percent) + ", IM1, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment0_tmp2")

    immath(imagename=[
        dir_image + name_line + "_" + beamp + ".moment0_tmp2",
        dir_image + name_line + ".moment0.noise_tmp"
    ],
           expr="iif( IM1>=" + str(nchan) + ", IM0, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment0")

    #
    immath(imagename=[
        dir_image + name_line + ".moment0_tmp",
        dir_image + name_line + ".moment1_tmp"
    ],
           expr="iif( IM0>=" + str(peak * percent) + ", IM1, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment1_tmp2")

    immath(imagename=[
        dir_image + name_line + "_" + beamp + ".moment1_tmp2",
        dir_image + name_line + ".moment0.noise_tmp"
    ],
           expr="iif( IM1>=" + str(nchan) + ", IM0, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment1")

    #
    immath(imagename=[
        dir_image + name_line + ".moment0_tmp",
        dir_image + name_line + ".moment8_tmp"
    ],
           expr="iif( IM0>=" + str(peak * percent) + ", IM1, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment8_tmp2")

    immath(imagename=[
        dir_image + name_line + "_" + beamp + ".moment8_tmp2",
        dir_image + name_line + ".moment0.noise_tmp"
    ],
           expr="iif( IM1>=" + str(nchan) + ", IM0, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment8")

    #
    immath(imagename=[
        dir_image + name_line + "_" + beamp + ".moment0",
        dir_image + name_line + "_" + beamp + ".moment0.noise"
    ],
           expr="IM0/IM1",
           outfile=dir_image + name_line + "_" + beamp +
           ".moment0.snratio_tmp")

    immath(imagename=[
        dir_image + name_line + "_" + beamp + ".moment0.snratio_tmp",
        dir_image + name_line + ".moment0.noise_tmp"
    ],
           expr="iif( IM1>=" + str(nchan) + ", IM0, 0.0)",
           outfile=dir_image + name_line + "_" + beamp + ".moment0.snratio")

    os.system("rm -rf " + cubeimage + ".maskedTF")
    os.system("rm -rf " + dir_image + name_line + ".moment0.noise_tmp")
    os.system("rm -rf " + dir_image + name_line + "_" + beamp +
              ".moment0.snratio_tmp")
    os.system("rm -rf " + dir_image + name_line + ".moment0_tmp")
    os.system("rm -rf " + dir_image + name_line + ".moment1_tmp")
    os.system("rm -rf " + dir_image + name_line + ".moment8_tmp")
    os.system("rm -rf " + dir_image + name_line + "_" + beamp +
              ".moment0_tmp2")
    os.system("rm -rf " + dir_image + name_line + "_" + beamp +
              ".moment1_tmp2")
    os.system("rm -rf " + dir_image + name_line + "_" + beamp +
              ".moment8_tmp2")

    return mask_use_here
def noisehist_kelvin(imagename,
                     jy2k,
                     noises_byeye,
                     output,
                     snr,
                     bins=200,
                     thres=0.0000,
                     logscale=True,
                     plotter=True,
                     title="test"):
    """
    myim03
    """
    shape = imhead(imagename, mode="list")["shape"]
    box = "0,0," + str(shape[0] - 1) + "," + str(shape[1] - 1)
    data = imval(imagename, box=box)
    pixvalues = data["data"].flatten() * jy2k
    pixvalues = pixvalues[abs(pixvalues) > thres]

    # plot
    histrange = [pixvalues.min() - 0.02, -pixvalues.min() + 0.02]
    plt.figure(figsize=(10, 10))
    plt.rcParams["font.size"] = 22
    plt.subplots_adjust(bottom=0.10, left=0.19, right=0.99, top=0.90)
    histdata = plt.hist(pixvalues,
                        bins=bins,
                        range=histrange,
                        lw=0,
                        log=logscale,
                        color="blue",
                        alpha=0.3,
                        label="positive pixels")
    plt.hist(pixvalues * -1,
             bins=bins,
             range=histrange,
             lw=0,
             log=logscale,
             color="red",
             alpha=0.3,
             label="negative pixels (reversed)")

    popt, pcov = curve_fit(
        func1,
        histdata[1][2:][histdata[1][2:] < noises_byeye],
        histdata[0][1:][histdata[1][2:] < noises_byeye],
        p0=[
            np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]),
            noises_byeye
        ],
        maxfev=10000)

    x = np.linspace(histdata[1][1], histdata[1][-1], 200)
    plt.plot(x, func1(x, popt[0], popt[1]), '-', c="black", lw=5)
    plt.plot(
        [0, 0],
        [2e1,
         np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 3.0],
        '-',
        color='black',
        lw=2)
    plt.plot(
        [popt[1], popt[1]],
        [2e1,
         np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 3.0],
        '--',
        color='black',
        lw=2,
        label="1 sigma = " + str(np.round(popt[1], 3)) + " K")
    plt.plot(
        [popt[1] * snr, popt[1] * snr],
        [2e1,
         np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 3.0],
        '--',
        color='black',
        lw=5,
        label=str(snr) + " sigma = " + str(np.round(popt[1] * snr, 3)) + " K")
    plt.plot(
        [-popt[1], -popt[1]],
        [2e1,
         np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 3.0],
        '--',
        color='black',
        lw=2)
    #
    # percentile
    percentile = (0.5 - scipy.special.erf(snr / np.sqrt(2)) / 2.) * 100.
    sigma_percentile = np.percentile(pixvalues, percentile) * -1

    plt.plot(
        [sigma_percentile, sigma_percentile],
        [2e1,
         np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 3.0],
        '-',
        color='black',
        lw=5,
        label=str(np.round(sigma_percentile, 3)) + " K")

    #plt.title(imagename.split("/")[-1])
    plt.xlim(0, histrange[1])
    plt.ylim([
        2e1,
        np.max(histdata[0][1:][histdata[1][2:] < noises_byeye]) * 1.2
    ])  #3.0])
    plt.xlabel("Pixel absolute value (K)")
    plt.ylabel("Number of pixels")
    plt.legend(loc="upper right")
    plt.title(title)
    if plotter == True:
        plt.savefig(output, dpi=300)
示例#22
0
def cube_to_moments(pixelmin, increment_mask, thres_masking, thres_mom, pbcut,
                    dir_data, galname, chans, suffix, beam_size, rms_co10,
                    rms_co21, ra, decl):
    """
    """
    print("###########################")
    print("### running cube_to_moments")
    print("###########################")

    os.system("rm -rf " + dir_data + galname + "/*" + suffix + "*.moment*")
    os.system("rm -rf " + dir_data + galname + "/*" + suffix + "*.mask")
    os.system("rm -rf " + dir_data + galname + "/*" + suffix + "*.cube")

    ### step 1/10: importfits
    print("### momentmaps 1/10: importfits")
    fitsimages = glob.glob(dir_data + "data/" + galname + "*.fits")
    for i in range(len(fitsimages)):
        eazy_importfits(fitsimages[i])

    # find imported images
    image_co10 = glob.glob(dir_data + "data/" + galname + "*co10*image*")[0]
    image_co21 = glob.glob(dir_data + "data/" + galname + "*co21*image*")[0]

    ### step 2/10: Kelvin to Jansky conversion
    print("### momentmaps 2/10: Kelvin to Jansky conversion")

    bunit = imhead(image_co10, "list")["bunit"]
    synsbeam10 = imhead(image_co10, "list")["beammajor"]["value"]
    if bunit == "K":  # CO(1-0) conversion if bunit = K
        easy_K2Jy(image_co10, synsbeam10, 115.27120)
        image_co10 = image_co10 + ".jy"
    else:
        print("# skip K2Jy for the CO(1-0) data")

    bunit = imhead(image_co21, "list")["bunit"]
    synsbeam21 = imhead(image_co21, "list")["beammajor"]["value"]
    if bunit == "K":  # CO(2-1) conversion if bunit = K
        easy_K2Jy(image_co21, synsbeam21, 230.53800)
        image_co21 = image_co21 + ".jy"
    else:
        print("# skip K2Jy for the CO(2-1) data")

    ### step 3/10: imregrid
    print("### momentmaps 3/10: imregrid")

    ###  step new: make template for imregrid
    easy_imsmooth(image_co21, beam_size, False)  # co21
    image2smooth21 = glob.glob(dir_data + "data/" + galname + "*21*smooth")[0]
    os.system("rm -rf " + image_co21 + ".template")
    rebinpix(image2smooth21, image_co21 + ".template", ra, decl)

    pbimage = glob.glob(dir_data + "data/" + galname + "*.pb")[0]
    easy_imregrid(pbimage,
                  image_co21 + ".template",
                  axes=[0, 1],
                  delete_original=False)
    pbimage = pbimage + ".regrid"

    ### step 4/10: imsmooth
    print("### momentmaps 4/10: imsmooth")

    beam_mask = beam_size * increment_mask  # beam size for the masking
    easy_imsmooth(image_co10, beam_mask, False)  # co10
    easy_imsmooth(image_co21, beam_mask, False)  # co21

    image2smooth21 = glob.glob(dir_data + "data/" + galname + "*21*smooth")[0]
    easy_imregrid(image2smooth21,
                  image_co21 + ".template",
                  axes=[0, 1],
                  delete_original=True)
    image2smooth21 = image2smooth21 + ".regrid"

    image2smooth10 = glob.glob(dir_data + "data/" + galname + "*10*smooth")[0]
    easy_imregrid(image2smooth10, image2smooth21, delete_original=True)
    image2smooth10 = image2smooth10 + ".regrid"

    ### mv the cubes to the working directory
    os.system("mkdir " + dir_data + galname)
    os.system("mv "+image2smooth10+" "\
              +dir_data+galname+"/"+galname+"_co10_"+suffix+".cube")
    os.system("mv "+image2smooth21+" "\
              +dir_data+galname+"/"+galname+"_co21_"+suffix+".cube")

    ### step 5/10: create CO(1-0) cube mask
    print("### momentmaps 5/10: create CO(1-0) cube mask")

    cube_co10 = glob.glob(dir_data+galname+"/"\
                          +galname+"*_co10_"+suffix+".cube")[0]
    thres_co10 = rms_co10 * increment_mask * thres_masking
    outmask_co10 = cube_co10.replace(".cube", ".mask")
    createmask(cube_co10, thres_co10, outmask_co10)

    ### step 6/10: create CO(2-1) cube mask
    print("### momentmaps 6/10: create CO(2-1) cube mask")

    cube_co21 = glob.glob(dir_data+galname+"/"\
                          +galname+"*_co21_"+suffix+".cube")[0]
    thres_co21 = rms_co21 * increment_mask * thres_masking
    outmask_co21 = cube_co21.replace(".cube", ".mask")
    createmask(cube_co21, thres_co21, outmask_co21)

    ### step 7/10: combine masks
    print("### momentmaps 7/10: combine masks")

    mask_combine = dir_data + galname + "/" + galname + "_combine_" + suffix + ".mask"
    os.system("rm -rf " + mask_combine)
    immath(imagename=[outmask_co10, outmask_co21],
           mode="evalexpr",
           expr="IM0*IM1",
           outfile=mask_combine)

    beamarea = beam_area(image_co21, increment_mask)
    remove_smallmask(mask_combine, beamarea, pixelmin)

    ### step 8/10: imsmooth
    print("### step 8/10: imsmooth")

    easy_imsmooth(image_co10, beam_size, False)  # co10
    easy_imsmooth(image_co21, beam_size, False)  # co21

    image2smooth21 = glob.glob(dir_data + "data/" + galname + "*21*smooth")[0]
    #os.system("rm -rf "+image_co21+".template")
    #rebinpix(image2smooth21,image_co21+".template",ra,decl)
    easy_imregrid(image2smooth21,
                  image_co21 + ".template",
                  axes=[0, 1],
                  delete_original=True)
    image2smooth21 = image2smooth21 + ".regrid"

    image2smooth10 = glob.glob(dir_data + "data/" + galname + "*10*smooth")[0]
    easy_imregrid(image2smooth10, image2smooth21, delete_original=True)
    image2smooth10 = image2smooth10 + ".regrid"

    # mv to working directory
    os.system("rm -rf " + cube_co10)
    os.system("rm -rf " + cube_co21)
    os.system("mv " + image2smooth10 + " " + cube_co10)
    os.system("mv " + image2smooth21 + " " + cube_co21)

    print("### step 9/10: immoments")
    moment_maps(cube_co10, chans, mask_combine, rms_co10 * thres_mom)
    moment_maps(cube_co21, chans, mask_combine, rms_co21 * thres_mom)

    ### pbmask
    print("### step 10/10: pb mask at " + str(pbcut))

    mask_pb = dir_data + galname + "/" + galname + "_pb_" + suffix + ".mask"
    peak = imhead(pbimage, mode="list")["datamax"]
    createmask(pbimage, peak * pbcut, mask_pb)

    images_moment = glob.glob(cube_co10 + ".moment*")
    images_moment.extend(glob.glob(cube_co21 + ".moment*"))
    for i in range(len(images_moment)):
        outfile = images_moment[i].replace(".cube", "")
        if galname == "ngc3110":
            os.system("mv " + images_moment[i] + " " \
                      + images_moment[i].replace(".cube",""))
        else:
            os.system("rm -rf " + outfile)
            immath(imagename=[images_moment[i], mask_pb],
                   mode="evalexpr",
                   expr="IM0*IM1",
                   outfile=outfile)
            os.system("rm -rf " + images_moment[i])
        """