示例#1
0
def rotate_image_wcs(ima_name,
                     ima_folder="",
                     outwcs_folder=None,
                     rotangle=0.,
                     **kwargs):
    """Routine to remove potential Nan around an image and reconstruct
    an optimal WCS reference image. The rotation angle is provided as a way
    to optimise the extent of the output image, removing Nan along X and Y
    at that angle.

    Args:
        ima_name (str): input image name. No default.
        ima_folder (str): input image folder ['']
        outwcs_folder (str): folder where to write the output frame. Default is
            None which means that it will use the folder of the input image.
        rotangle (float): rotation angle in degrees [0]
        **kwargs:
            in_suffix (str): in suffix to remove from name ['prealign']
            out_suffix (str): out suffix to add to name ['rotwcs']
            margin_factor (float): factor to extend the image [1.1]

    Returns:

    """

    # Reading the input names and setting output folder
    fullname = joinpath(ima_folder, ima_name)
    ima_folder, ima_name = os.path.split(fullname)
    if outwcs_folder is None:
        outwcs_folder = ima_folder

    # Suffix
    in_suffix = kwargs.pop("in_suffix", "prealign")
    out_suffix = kwargs.pop("out_suffix", "rotwcs")

    # Get margin if needed
    margin_factor = kwargs.pop("margin_factor", 1.1)
    extend_fraction = np.maximum(0., (margin_factor - 1.))
    upipe.print_info("Will use a {:5.2f}% extra margin".format(
        extend_fraction * 100.))

    # Opening the image via mpdaf
    imawcs = Image(fullname)
    extra_pixels = (np.array(imawcs.shape) * extend_fraction).astype(np.int)

    # New dimensions and extend current image
    new_dim = tuple(np.array(imawcs.shape).astype(np.int) + extra_pixels)
    ima_ext = imawcs.regrid(newdim=new_dim,
                            refpos=imawcs.get_start(),
                            refpix=tuple(extra_pixels / 2.),
                            newinc=imawcs.get_step()[0] * 3600.)

    # Copy and rotate WCS
    new_wcs = copy.deepcopy(ima_ext.wcs)
    upipe.print_info("Rotating WCS by {} degrees".format(rotangle))
    new_wcs.rotate(rotangle)

    # New rotated image
    ima_rot = Image(data=np.nan_to_num(ima_ext.data), wcs=new_wcs)

    # Then resample the image using the initial one as your reference
    ima_rot_resampled = ima_rot.align_with_image(ima_ext, flux=True)

    # Crop NaN
    ima_rot_resampled.crop()

    # get the new header with wcs and rotate back
    finalwcs = ima_rot_resampled.wcs
    finalwcs.rotate(-rotangle)

    # create the final image
    final_rot_image = Image(data=ima_rot_resampled.data, wcs=finalwcs)

    # Save image
    if isinstance(in_suffix,
                  str) and in_suffix != "" and in_suffix in ima_name:
        out_name = ima_name.replace(in_suffix, out_suffix)
    else:
        name, extension = os.path.splitext(ima_name)
        out_suffix = add_string(out_suffix)
        out_name = "{0}{1}{2}".format(name, out_suffix, extension)

    # write output
    final_rot_image.write(joinpath(outwcs_folder, out_name))
    return outwcs_folder, out_name
示例#2
0
    def write(self, path=None, erase=False):
        """Save the current session in a folder that will have the name of the
        ORIGIN object (self.name).

        The ORIGIN.load(folder, newname=None) method will be used to load a
        session. The parameter newname will let the user to load a session but
        continue in a new one.

        Parameters
        ----------
        path : str
            Path where the folder (self.name) will be stored.
        erase : bool
            Remove the folder if it exists.

        """
        self._loginfo("Writing...")

        # adapt session if path changes
        if path is not None and path != self.path:
            if not os.path.exists(path):
                raise ValueError(f"path does not exist: {path}")
            self.path = path
            outpath = os.path.join(path, self.name)
            # copy outpath to the new path
            shutil.copytree(self.outpath, outpath)
            self.outpath = outpath
            self._setup_logfile(self.logger)

        if erase:
            shutil.rmtree(self.outpath)
        os.makedirs(self.outpath, exist_ok=True)

        # PSF
        if isinstance(self.PSF, list):
            for i, psf in enumerate(self.PSF):
                cube = Cube(data=psf, mask=np.ma.nomask, copy=False)
                cube.write(os.path.join(self.outpath,
                                        "cube_psf_%02d.fits" % i))
        else:
            cube = Cube(data=self.PSF, mask=np.ma.nomask, copy=False)
            cube.write(os.path.join(self.outpath, "cube_psf.fits"))

        if self.wfields is not None:
            for i, wfield in enumerate(self.wfields):
                im = Image(data=wfield, mask=np.ma.nomask)
                im.write(os.path.join(self.outpath, "wfield_%02d.fits" % i))

        if self.ima_white is not None:
            self.ima_white.write("%s/ima_white.fits" % self.outpath)

        for step in self.steps.values():
            step.dump(self.outpath)

        # parameters in .yaml
        with open(f"{self.outpath}/{self.name}.yaml", "w") as stream:
            dump_yaml(self.param, stream)

        # step3 - saving this manually for now
        if self.nbAreas is not None:
            if self.testO2 is not None:
                for area in range(1, self.nbAreas + 1):
                    np.savetxt("%s/testO2_%d.txt" % (self.outpath, area),
                               self.testO2[area - 1])
            if self.histO2 is not None:
                for area in range(1, self.nbAreas + 1):
                    np.savetxt("%s/histO2_%d.txt" % (self.outpath, area),
                               self.histO2[area - 1])
            if self.binO2 is not None:
                for area in range(1, self.nbAreas + 1):
                    np.savetxt("%s/binO2_%d.txt" % (self.outpath, area),
                               self.binO2[area - 1])

        self._loginfo("Current session saved in %s", self.outpath)
示例#3
0
def xav_explorer(ima, ima_err, name, plot=False):
    F_min = flux_min(ima, name)
    IP2, JP2, gauss_im, I2, J2, pcont2, IPd, JPd, IPs, JPs = HIIrecover_loop(
        ima, ima_err, name=name, plot=False, F_min=0, p=0)
    gfitim, cont2, param = HIIplot2(IPs, JPs, gauss_im, ima, param=False)
    JP3, IP3, tcont = background_interpolation(ima, name)
    grid = interpolate_continuum(ima=ima,
                                 JP=JP2,
                                 IP=IP2,
                                 I=I2,
                                 J=J2,
                                 pcont=pcont2,
                                 cont=cont2,
                                 JP3=JP3,
                                 IP3=IP3,
                                 tcont=tcont,
                                 plot=False)
    gfitim2 = HIIplot_cont(gfitim, grid, ima)
    #res = Image(data=(ima.data - gfitim.data), wcs=ima.wcs)
    p = 0
    print(p)
    gfitim, gfitim2, IP2, JP2, IPd, JPd, grid, param = loop2(IP2,
                                                             JP2,
                                                             I2,
                                                             J2,
                                                             pcont2,
                                                             cont2,
                                                             gfitim,
                                                             gfitim2,
                                                             ima,
                                                             ima_err,
                                                             IPd,
                                                             JPd,
                                                             param,
                                                             JP3,
                                                             IP3,
                                                             tcont,
                                                             name,
                                                             plot=False)
    res2 = Image(data=(ima.data - gfitim2.data), wcs=ima.wcs)

    catal = cat(param, name)
    I_list = chi_histogram(param, plot=True)
    b = 0
    for k in range(0, len(I_list)):
        catal.remove_row(I_list[k] - b)
        b += 1
    #param2 = read(cat=catal)
    #gftim = HIIplot(ima, param2)
    gfitim2 = HIIplot_cont(gfitim, grid, ima)

    #ima = Image(filename=DATA_PATH + '{}_flux_drz.fits'.format(name))
    ima2 = ima[:, :]
    #if name == 'ASASSN14jg':
    #    ima2=ima2[40:290, 20:260]
    chi2_global = chi_square(subima=ima2,
                             subima_err=ima_err,
                             gfitim=gfitim2,
                             parameter=1)
    alpha = catal['alpha']

    #Table with important data for plotting HII regions
    data = [len(alpha), chi2_global, F_min]
    CreateTable(name, OUTPUT_TABLES_PATH, data)
    print(IPd, JPd)

    if plot == True:
        #        fig, ax = plt.subplots(2, 3, constrained_layout=True)
        fig, ax = plt.subplots(2, 3, figsize=(12, 8))
        fig.suptitle('# {} HII regions - Chi2 {}'.format(
            len(alpha), np.round(chi2_global, 2)),
                     fontsize=16)
        ima.plot(scale='log',
                 colorbar='v',
                 ax=ax[0, 0],
                 vmin=0,
                 vmax=0.9 * np.amax(ima.data),
                 zscale=False,
                 title=r'flux = %s [10$^{-16}$ cgs]' %
                 (np.round(np.sum(ima.data), 2)))
        ax[0, 1].scatter(IPd, JPd, color='red', marker='.', linewidth=0.01)
        #res = Image(data=(ima.data - gfitim.data), wcs=ima.wcs)
        gfitim.plot(scale='log',
                    vmin=0,
                    vmax=0.9 * np.amax(ima.data),
                    colorbar='v',
                    ax=ax[0, 1],
                    zscale=False,
                    title=r'flux = %s [10$^{-16}$ cgs]' %
                    (np.round(np.sum(gfitim.data), 2)))
        gfitim2.plot(scale='log',
                     vmin=0,
                     vmax=0.9 * np.amax(ima.data),
                     colorbar='v',
                     ax=ax[0, 2],
                     zscale=False,
                     title=r'flux = %s [10$^{-16}$ cgs]' %
                     (np.round(np.sum(gfitim2.data), 2)))
        grid.plot(scale='log',
                  vmin=0,
                  vmax=0.9 * np.amax(ima.data),
                  colorbar='v',
                  ax=ax[1, 0],
                  zscale=False,
                  title=r'flux = %s [10$^{-16}$ cgs]' %
                  (np.round(np.sum(grid.data), 2)))
        res2 = Image(data=(ima.data - gfitim2.data), wcs=ima.wcs)
        print('RESIDUALS: mean = {}, median = {}, std = {}'.format(
            np.round(np.mean(np.ravel(res2.data)), 2),
            np.round(np.median(np.ravel(res2.data)), 2),
            np.round(np.std(np.ravel(res2.data)), 2)))  #
        #F_min
        #        res2.plot(vmin=np.amin(res2.data), vmax=np.amax(res2.data), colorbar='v', ax=ax[1,1],   zscale=False, title=r'flux = %s [10$^{-20}$ cgs]'%( np.round(np.sum(res2.data),2)))
        print("F_min" + str(F_min))
        res2.plot(vmin=-3 * F_min,
                  vmax=3 * F_min,
                  colorbar='v',
                  ax=ax[1, 1],
                  zscale=False,
                  title=r'flux = %s [10$^{-16}$ cgs]' %
                  (np.round(np.sum(res2.data), 2)))
        res2.plot(scale='log',
                  vmin=0,
                  vmax=0.9 * np.amax(ima.data),
                  colorbar='v',
                  ax=ax[1, 2],
                  zscale=False,
                  title='mean = {}, median = {}, std = {}'.format(
                      np.round(np.mean(np.ravel(res2.data)), 3),
                      np.round(np.median(np.ravel(res2.data)), 3),
                      np.round(np.std(np.ravel(res2.data)), 3)))
        fig.tight_layout()
        fig.savefig(OUTPUT_IMAGES_PATH + 'HII_recover_{}.pdf'.format(name),
                    bbox_inches='tight',
                    transparent=True)
        fig.savefig(OUTPUT_IMAGES_PATH + 'HII_recover_{}.png'.format(name),
                    bbox_inches='tight',
                    transparent=True)
        plt.close()

    #res.write('res')
    gfitim.write(name + '_gfitim_xav_fm.fits')
    gfitim2.write(name + '_gfitim2_xav_fm.fits')
    grid.write(name + '_grid_xav_fm.fits')
    res2.write(name + '_res2_xav_fm.fits')

    return catal, grid, res2, gfitim, gfitim2, chi2_global