예제 #1
0
    def _convert_dobs_to_obs(self, dobs):
        """
        convert a Survey object dobs to an ngmix Observation
        """
        j = ngmix.DiagonalJacobian(
            row=0,
            col=0,
            scale=dobs.pixel_scale,
        )

        im=dobs.image.array

        #print('mean sky level:',dobs.mean_sky_level )
        #print('sqrt(mean sky level):',np.sqrt(dobs.mean_sky_level ))
        noise = np.sqrt( dobs.mean_sky_level )
        weight = im*0 + 1.0/noise**2

        #psf_im=dobs.psf_image.array.copy()
        psf_im = dobs.psf_model.drawImage(
            nx=48,
            ny=48,
            scale=dobs.pixel_scale,
        ).array
        psf_im *= 1.0/psf_im.sum()

        pnoise = psf_im.max()/400.0
        psf_s2n = np.sqrt( (psf_im**2).sum())/pnoise
        logger.debug('    psf s2n: %f' % psf_s2n)

        psf_im += self.rng.normal(scale=pnoise, size=psf_im.shape)

        psf_weight = psf_im*0 + 1.0/pnoise**2

        #import images
        #images.multiview(psf_im,title='psf')
        #stop

        psf_cen = (np.array(psf_im.shape)-1.0)/2.0
        psf_j = ngmix.DiagonalJacobian(
            row=psf_cen[0],
            col=psf_cen[1],
            scale=dobs.pixel_scale,
        )

        psf_obs=ngmix.Observation(
            psf_im,
            weight=psf_weight,
            jacobian=psf_j,
        )

        return ngmix.Observation(
            im,
            weight=weight,
            jacobian=j,
            psf=psf_obs,
        )
예제 #2
0
def make_coadd_obs(mbobs, ignore_zero_weight=True):
    """
    perform a simple coadd assuming the images all already align

    This is used for combining the coadds from multiple bands

    Parameters
    ----------
    mbobs: ngmix.MultiBandObsList
        An ngmix multi band observation list to be coadded.  The
        images must align perfectly and have the same wcs
    """

    weights = np.array([obslist[0].weight.max() for obslist in mbobs])
    wsum = weights.sum()

    nweights = weights / wsum

    coadd_image = mbobs[0][0].image.copy()
    coadd_image[:, :] = 0.0

    coadd_weight = coadd_image.copy()
    coadd_weight[:, :] = wsum

    coadd_psf = mbobs[0][0].psf.image.copy()
    coadd_psf[:, :] = 0
    coadd_psf_weight = mbobs[0][0].psf.weight.copy() * 3  # not quite right

    for i, obslist in enumerate(mbobs):
        obs = obslist[0]

        wbad = np.where(obs.weight <= 0.0)
        if wbad[0].size > 0:
            coadd_weight[wbad] = 0.0

        coadd_image += obs.image * nweights[i]
        coadd_psf += obs.psf.image * nweights[i]

    psf_obs = ngmix.Observation(
        coadd_psf,
        weight=coadd_psf_weight,
        jacobian=mbobs[0][0].psf.jacobian,
    )

    obs = ngmix.Observation(
        coadd_image,
        weight=coadd_weight,
        jacobian=mbobs[0][0].jacobian,
        psf=psf_obs,
        ignore_zero_weight=ignore_zero_weight,
    )

    # import images
    # images.view(coadd_weight, title='weight')
    return obs
예제 #3
0
def _get_obs(rng, set_noise_image=False, noise=1.0e-6):

    psf_noise = 1.0e-6

    scale = 0.263

    psf_fwhm = 0.9
    gal_fwhm = 0.7

    psf = galsim.Gaussian(fwhm=psf_fwhm)
    obj0 = galsim.Gaussian(fwhm=gal_fwhm)

    obj = galsim.Convolve(psf, obj0)

    psf_im = psf.drawImage(scale=scale).array
    im = obj.drawImage(scale=scale).array

    psf_im += rng.normal(scale=psf_noise, size=psf_im.shape)
    im += rng.normal(scale=noise, size=im.shape)

    cen = (np.array(im.shape)-1.0)/2.0
    psf_cen = (np.array(psf_im.shape)-1.0)/2.0

    j = ngmix.DiagonalJacobian(row=cen[0], col=cen[1], scale=scale)
    pj = ngmix.DiagonalJacobian(row=psf_cen[0], col=psf_cen[1], scale=scale)

    wt = im*0 + 1.0/noise**2
    psf_wt = psf_im*0 + 1.0/psf_noise**2

    psf_obs = ngmix.Observation(
        psf_im,
        weight=psf_wt,
        jacobian=pj,
    )

    if set_noise_image:
        nim = rng.normal(scale=noise, size=im.shape)
    else:
        nim = None

    bmask = np.zeros(im.shape, dtype='i2')
    obs = ngmix.Observation(
        im,
        weight=wt,
        bmask=bmask,
        noise=nim,
        jacobian=j,
        psf=psf_obs,
    )

    return obs
예제 #4
0
    def _get_mof_obs(self):
        im, psf_im, coords, dims, dx1, dy1, noises = self.sim()

        bg_rms = self.sim['Image']['Bgrms'] / np.sqrt(len(im))
        bg_rms_psf = self.sim['Psf']['Bgrms_psf']

        psf_ccen = (np.array(psf_im.shape) - 1.0) / 2.0
        psf_jacob = ngmix.UnitJacobian(
            row=psf_ccen[0],
            col=psf_ccen[1],
        )
        psf_weight = psf_im * 0 + 1.0 / bg_rms_psf**2
        psf_obs = ngmix.Observation(
            psf_im,
            weight=psf_weight,
            jacobian=psf_jacob,
        )

        psf_gmix = self._fit_psf_admom(psf_obs)
        psf_obs.set_gmix(psf_gmix)

        mb = MultiBandObsList()
        for i in range(len(im)):
            if self.show:
                import images
                tim = im[i] / im[i].max()
                tim = np.log10(tim - tim.min() + 1.0)

                images.view(tim)
                if 'q' == input('hit a key: (q to quit) '):
                    stop

            weight = im[i] * 0 + 1.0 / bg_rms**2
            jacobian = ngmix.UnitJacobian(
                row=0,
                col=0,
            )

            obs = ngmix.Observation(
                im[i],
                weight=weight,
                jacobian=jacobian,
                psf=psf_obs,
            )
            obs.noise = noises[i]
            olist = ObsList()
            olist.append(obs)
            mb.append(olist)

        return mb, coords
def observation(image,sigma,row,col,psf_sigma,psf_im):
    # sigma is the standard deviation of the noise
    weight = image*0 + 1.0/sigma**2
    # row,col are the center of the object in the model
    # image, so we need to figure that out somehow
    jacob = ngmix.UnitJacobian(row=row, col=col)
    psf_weight = psf_im*0 + 1.0/psf_sigma**2
    # psf should be centered
    cen = [(np.array(psf_im.shape[0]) - 1.0)/2.0,(np.array(psf_im.shape[1]) - 1.0)/2.0]
    psf_jacob = ngmix.UnitJacobian(row=cen[0], col=cen[1])
    psf_obs = ngmix.Observation(psf_im, weight=psf_weight, jacobian=psf_jacob)
    obs = ngmix.Observation(image,weight=weight,jacobian=jacob,psf=psf_obs)

    return obs
예제 #6
0
    def _get_ngmix_obs(self, gal_img, psf_img, psf_pars=[0.0, 0.0, -0.01, 0.01, 0.15, 1.0], fit_psf=True):
        """
        """

        eps=0.01
        lm_pars={'maxfev': 2000,
                 'xtol': 5.0e-5,
                 'ftol': 5.0e-5}

        img_shape = gal_img.shape

        # Jacobian
        gal_jacob=ngmix.DiagonalJacobian(scale=self._pixel_scale, x=int((img_shape[0]-1)/2.), y=int((img_shape[1]-1)/2.))
        psf_jacob=ngmix.DiagonalJacobian(scale=self._pixel_scale, x=int((img_shape[0]-1)/2.), y=int((img_shape[1]-1)/2.))

        # PSF fittitng
        psf_noise = np.sqrt(np.sum(psf_img**2)) / 500
        psf_weight = np.ones_like(psf_img) / psf_noise**2
        psf_obs=ngmix.Observation(psf_img, weight=psf_weight, jacobian=psf_jacob)

        if fit_psf:
            pfitter=ngmix.fitting.LMSimple(psf_obs,'gauss',lm_pars=lm_pars)

            guess=np.array(psf_pars)
            guess[0] += urand(low=-eps,high=eps)
            guess[1] += urand(low=-eps,high=eps)
            guess[2] += urand(low=-eps, high=eps)
            guess[3] += urand(low=-eps, high=eps)
            guess[4] *= (1.0 + urand(low=-eps, high=eps))
            guess[5] *= (1.0 + urand(low=-eps, high=eps))

            pfitter.go(guess)

            # print(np.abs((pfitter.get_result()['g']-np.array([-0.01, 0.01]))/np.array([-0.01, 0.01])))

            psf_gmix_fit = pfitter.get_gmix()

            psf_obs.set_gmix(psf_gmix_fit)

        # Gal fitting
        # Get noise level direclty from the image
        sigma_noise = self.mad(gal_img)
        noise = np.random.normal(size=img_shape) * sigma_noise
        weight = np.ones_like(gal_img) * 1/sigma_noise**2.

        obs = ngmix.Observation(gal_img, weight=weight, noise=noise, jacobian=gal_jacob, psf=psf_obs)

        return obs
예제 #7
0
    def _get_mini_model(self):
        im, psf_im, coords, dims, dx1, dy1, noise = Simulation.__call__(self)
        bg_rms = self['Image']['Bgrms']
        mode = self['Mode']
        allobs = []
        bg_rms_psf = self['Psf']['Bgrms_psf']
        allconf = yaml.load(
            open('/astro/u/esheldon/git/nsim/config/run-nbr01-mcal-02.yaml'))
        config = allconf['mof']
        config['psf_pars'] = {'model': 'gauss', 'ntry': 2}
        for coord in coords:
            row, col = coord
            obs = observation(im, bg_rms, row, col, bg_rms_psf, psf_im)
            this_jacob = obs.jacobian.copy()
            this_jacob.set_cen(row=row, col=col)
            this_obs = ngmix.Observation(
                obs.image.copy(),
                weight=obs.weight.copy(),
                jacobian=this_jacob,
                psf=obs.psf,
            )
            allobs.append(this_obs)
        mm = minimof.MiniMOF(config, allobs, rng=rng)
        mm.go()
        res = mm.get_result()
        if not res['converged']:
            output['flags'][j] = 2
        else:
            obs = mm.get_corrected_obs(0)

        return obs, noise
예제 #8
0
    def _make_obs(self):

        mbobs = ngmix.MultiBandObsList()

        for im in self.imlist:
            jacobian = ngmix.DiagonalJacobian(row=0,
                                              col=0,
                                              scale=self['pixel_scale'])

            if self['coadd']:
                wt = np.zeros(im.shape) + 1.0 / self['coadd_noise_sigma']**2
            else:
                wt = np.zeros(im.shape) + 1.0 / self['noise_sigma']**2

            obs = ngmix.Observation(
                im,
                weight=wt,
                jacobian=jacobian,
                psf=self.get_psf_obs(),
            )
            olist = ngmix.ObsList()
            olist.append(obs)
            mbobs.append(olist)

        self.obs = mbobs
예제 #9
0
    def get_psf_obs(self):
        kw = {'scale': self['pixel_scale']}
        dims = self.get('psf_dims', None)
        if dims is not None:
            kw['nx'], kw['ny'] = dims[1], dims[0]

        psf_im = self.psf.drawImage(**kw).array

        dims = np.array(psf_im.shape)
        pcen = (dims - 1.0) / 2.0
        pjac = ngmix.DiagonalJacobian(row=pcen[0],
                                      col=pcen[1],
                                      scale=self['pixel_scale'])

        psf_im += self.rng.normal(
            scale=self['psf']['noise_sigma'],
            size=dims,
        )
        psf_wt = np.zeros(dims) + 1.0 / self['psf']['noise_sigma']**2

        return ngmix.Observation(
            psf_im,
            weight=psf_wt,
            jacobian=pjac,
        )
예제 #10
0
파일: moftest.py 프로젝트: esheldon/mof
    def _set_psf(self):
        import galsim

        self.psf = galsim.Gaussian(fwhm=0.9)

        kw = {'scale': self['pixel_scale']}
        dims = self.get('psf_dims', None)
        if dims is not None:
            kw['nx'], kw['ny'] = dims[1], dims[0]

        self.psf_im = self.psf.drawImage(**kw).array

        dims = np.array(self.psf_im.shape)
        pcen = (dims - 1.0) / 2.0
        pjac = ngmix.DiagonalJacobian(row=pcen[0],
                                      col=pcen[1],
                                      scale=self['pixel_scale'])

        self.psf_im += self.rng.normal(
            scale=self['psf_noise_sigma'],
            size=dims,
        )
        psf_wt = np.zeros(dims) + 1.0 / self['psf_noise_sigma']**2

        self.psf_obs = ngmix.Observation(
            self.psf_im,
            weight=psf_wt,
            jacobian=pjac,
        )

        psf_gmix = self._fit_psf_admom(self.psf_obs)
        self.psf_obs.set_gmix(psf_gmix)
    def get_psf_obs(self, *, x, y, band):
        """Get an ngmix Observation of the PSF at a position.

        Parameters
        ----------
        x : float
            The column of the PSF.
        y : float
            The row of the PSF.
        band : int
            The index of the desired band.

        Returns
        -------
        psf_obs : ngmix.Observation
            An Observation of the PSF.
        """
        psf_images, psf_wcs, noises, _, _ = self._render_psf_image(
            x=x, y=y)

        weight = np.zeros_like(psf_images[band]) + 1.0/noises[band]**2

        cen = (np.array(psf_images[band].shape) - 1.0)/2.0
        j = ngmix.jacobian.Jacobian(
            row=cen[0], col=cen[1], wcs=psf_wcs)
        psf_obs = ngmix.Observation(
            psf_images[band],
            weight=weight,
            jacobian=j)

        return psf_obs
예제 #12
0
    def __call__(self):
        """
        get a simulated ngmix.MultiBandObsList
        """
        iconf = self['image']

        band_images, band_weights, obj_data = self._get_noisy_images()

        jacobian = ngmix.DiagonalJacobian(
            row=0,
            col=0,
            scale=iconf['pixel_scale'],
        )

        mbobs = ngmix.MultiBandObsList()

        for image, weight in zip(band_images, band_weights):
            obs = ngmix.Observation(
                image,
                weight=weight,
                jacobian=jacobian,
                psf=self.get_psf_obs(),
                ignore_zero_weight=False,
            )
            obslist = ngmix.ObsList()
            obslist.append(obs)
            mbobs.append(obslist)

        obj_data_with_cen = self._set_centers(obs, obj_data)
        mbobs.meta['obj_data'] = obj_data_with_cen
        return mbobs
예제 #13
0
    def _do_coadd_fit(self, gmix_guess):
        """
        run the fixed-center em fitter on the coadd image
        """

        coadd_obs = self.coadd_obs

        imsky, sky = ngmix.em.prep_image(coadd_obs.image)

        emobs = ngmix.Observation(
            imsky,
            weight=coadd_obs.weight,
            jacobian=coadd_obs.jacobian,
            psf=coadd_obs.psf,
            ignore_zero_weight=self._ignore_zero_weight,
        )

        em = GMixEMFixCen(
            emobs,
            miniter=self.miniter,
            maxiter=self.maxiter,
            tol=self.tol,
            vary_sky=self.vary_sky,
        )

        em.go(gmix_guess, sky)

        return em
예제 #14
0
    def _get_band_fit(self, obs):
        """
        get the flux-only fit for a band
        """

        imsky, sky = ngmix.em.prep_image(obs.image)

        emobs = ngmix.Observation(
            imsky,
            weight=obs.weight,
            jacobian=obs.jacobian,
            psf=obs.psf,
            ignore_zero_weight=self._ignore_zero_weight,
        )
        em = GMixEMPOnly(
            emobs,
            miniter=self.flux_miniter,
            maxiter=self.flux_maxiter,
            tol=self.tol,
            vary_sky=self.vary_sky,
        )

        gm_guess = self._get_band_guess()

        em.go(gm_guess, sky)

        return em
예제 #15
0
    def _get_psf_obs(self, band, midrow, midcol):
        """
        get the image and wieght for the specified box

        Parameters
        ----------
        band: int
            band to load
        ranges: tuple
            (minrow, maxrow, mincol, maxcol)

        Returns
        -------
        image, weight
        """

        psf = self.psf_list[band]

        rrow = round(midrow)
        rcol = round(midcol)

        image = psf.get_rec(rrow, rcol)
        cen = psf.get_center(rrow, rcol)

        weight = image*0 + 1.0/0.001**2

        jacob = self._get_jacobian(band, midrow, midcol)

        jacob.set_cen(row=cen[0], col=cen[1])

        return ngmix.Observation(
            image,
            weight=weight,
            jacobian=jacob,
        )
예제 #16
0
    def _extract_mbobs(self, ranges, wout):
        """
        extract an ngmix.MultiBandObsList for the given region, filling noise
        in the regions not assigned to the requested objects

        Parameters
        ----------
        ranges: tuple
            (minrow, maxrow, mincol, maxcol)
        wout: tuple of arrays
            (wrows, wcols) indices for areas not assigned to
            the objects of interest

        Returns
        -------
        mbobs: ngmix.MultiBandObsList
        """

        minrow, maxrow, mincol, maxcol = ranges

        midrow = (minrow + maxrow)/2
        midcol = (mincol + maxcol)/2

        mbobs = ngmix.MultiBandObsList()

        for band in range(self.nband):
            image, weight, mask = self._get_image_data(band, ranges)
            jacob = self._get_jacobian(band, midrow, midcol)
            psf_obs = self._get_psf_obs(band, midrow, midcol)

            _replace_with_noise(image, weight, wout, self.rng)

            if self._rescale:
                scale = jacob.scale
                image *= 1.0/scale**2
                weight *= scale**4

            # zero the weight map for bad pixels.  Note we are doing this after
            # replacing non-member objects pixels with noise, in case the
            # weight map ends up all zero

            if self._zero_weight_badpix is not None:
                _zero_weight_map_for_badpix(
                    mask, weight, self._zero_weight_badpix,
                )

            obs = ngmix.Observation(
                image,
                weight=weight,
                jacobian=jacob,
                psf=psf_obs,
                ignore_zero_weight=self._ignore_zero_weight,
            )

            obslist = ngmix.ObsList()
            obslist.append(obs)
            mbobs.append(obslist)

        return mbobs
예제 #17
0
def _get_obs(rng):
    """
    obs with noise image included
    """
    noise = 0.1
    psf_noise = 1.0e-6
    scale = 0.263

    psf_fwhm = 0.9
    gal_fwhm = 0.7

    psf = galsim.Gaussian(fwhm=psf_fwhm)
    obj0 = galsim.Gaussian(fwhm=gal_fwhm)

    obj = galsim.Convolve(psf, obj0)

    psf_im = psf.drawImage(scale=scale).array
    im = obj.drawImage(scale=scale).array

    cen = (np.array(im.shape) - 1.0) / 2.0
    psf_cen = (np.array(psf_im.shape) - 1.0) / 2.0

    j = ngmix.DiagonalJacobian(row=cen[0], col=cen[1], scale=scale)
    pj = ngmix.DiagonalJacobian(row=psf_cen[0], col=psf_cen[1], scale=scale)

    wt = im * 0 + 1.0 / noise**2
    psf_wt = psf_im * 0 + 1.0 / psf_noise**2

    psf_obs = ngmix.Observation(
        psf_im,
        weight=psf_wt,
        jacobian=pj,
    )
    im += rng.normal(scale=noise, size=im.shape)
    psf_im += rng.normal(scale=psf_noise, size=psf_im.shape)
    nim = rng.normal(scale=noise, size=im.shape)

    obs = ngmix.Observation(
        im,
        weight=wt,
        noise=nim,
        jacobian=j,
        psf=psf_obs,
    )

    return obs
예제 #18
0
    def _set_obs(self):
        import ngmix

        self.obs = ngmix.Observation(
            image=self.image,
            weight=self.weight_image,
            jacobian=self.jacobian,
        )
예제 #19
0
def test_gmix_s2n_smoke():
    pars = [0, 0, 0, 0, 5, 1]
    gm = ngmix.GMixModel(pars, "gauss")
    im = gm.make_image([10, 10])

    obs = ngmix.Observation(im)

    gm.get_model_s2n(obs)
예제 #20
0
파일: util.py 프로젝트: esheldon/desclass
def trim_obs(*, obs):
    """
    trim the images to the default radius, returning a new Observation

    Parameters
    ----------
    obs: ngmix.Observation
        Observation to trim

    Returns
    ----------
    new_obs: ngmix.Observation
        Trimmed Observation
    """
    j = obs.jacobian
    row, col = j.cen
    irow, icol = int(row), int(col)

    row_start = irow - RADIUS
    row_end = irow + RADIUS + 1
    col_start = icol - RADIUS
    col_end = icol + RADIUS + 1

    new_image = obs.image[
        row_start:row_end,
        col_start:col_end,
    ]
    new_weight = obs.weight[
        row_start:row_end,
        col_start:col_end,
    ]
    if obs.has_bmask():
        new_bmask = obs.bmask[
            row_start:row_end,
            col_start:col_end,
        ]
    else:
        new_bmask = None

    new_rowcen = RADIUS + row-irow
    new_colcen = RADIUS + col-icol

    new_jac = j.copy()
    new_jac.set_cen(row=new_rowcen, col=new_colcen)

    if obs.has_psf():
        new_psf = trim_obs(obs=obs.psf)
    else:
        new_psf = None

    return ngmix.Observation(
        image=new_image,
        weight=new_weight,
        bmask=new_bmask,
        jacobian=new_jac,
        psf=new_psf,
        meta=obs.meta,
    )
예제 #21
0
파일: metadetect.py 프로젝트: aguinot/ngmix
def make_stamp_obs(obj_data, obs, stamp_dim):
    """
    extract a postage stamp and make an Observation

    Parameters
    ----------
    obj_data: array
        Scalar array representing an object's data from sep
    obs: Observation
        The observation from which to extract postage stamp data
    stamp_dim: int
        Dims of the stamp to extract

    Returns
    -------
    Observation
    """
    half_box_size = stamp_dim//2

    maxrow, maxcol = obs.image.shape

    row = obj_data['y'].astype('i4')
    col = obj_data['x'].astype('i4')

    start_row = row - half_box_size + 1
    end_row = row + half_box_size + 1  # plus one for slices

    start_col = col - half_box_size + 1
    end_col = col + half_box_size + 1

    if start_row < 0:
        return 1, None
        # start_row = 0
    if start_col < 0:
        return 1, None
        # start_col = 0
    if end_row > maxrow:
        return 1, None
        # end_row = maxrow
    if end_col > maxcol:
        return 1, None
        # end_col = maxcol

    image = obs.image[start_row:end_row, start_col:end_col].copy()
    weight = obs.weight[start_row:end_row, start_col:end_col].copy()

    stamp_row = obj_data['y'] - start_row
    stamp_col = obj_data['x'] - start_col
    jacobian = obs.jacobian.copy()
    jacobian.set_cen(row=stamp_row, col=stamp_col)

    stamp_obs = ngmix.Observation(
        image=image,
        weight=weight,
        jacobian=jacobian,
    )

    return 0, stamp_obs
예제 #22
0
def make_mbobs(*, band_data, rng):
    mbobs = ngmix.MultiBandObsList()
    for band, bdata in band_data.items():
        obslist = ngmix.ObsList()

        for epoch_ind, se_obs in enumerate(bdata):
            ny, nx = se_obs.image.array.shape
            cenx = (nx - 1) / 2
            ceny = (ny - 1) / 2
            jacobian = get_jac(wcs=se_obs.wcs, cenx=cenx, ceny=ceny)

            psf_gsimage = se_obs.get_psf(
                cenx,
                ceny,
                center_psf=False,
            )
            psf_image = psf_gsimage.array

            psf_cen = (np.array(psf_image.shape) - 1) / 2
            psf_jac = jacobian.copy()
            psf_jac.set_cen(row=psf_cen[0], col=psf_cen[1])

            psf_noise_fake = psf_image.max() / 50000
            psf_image += rng.normal(scale=psf_noise_fake, size=psf_image.shape)
            psf_weight = psf_image * 0 + 1.0 / psf_noise_fake**2

            psf_obs = ngmix.Observation(
                image=psf_image,
                weight=psf_weight,
                jacobian=psf_jac,
            )

            obs = ngmix.Observation(
                image=se_obs.image.array,
                weight=se_obs.weight.array,
                jacobian=jacobian,
                psf=psf_obs,
            )
            obslist.append(obs)
        mbobs.append(obslist)

    return mbobs
예제 #23
0
def make_data(
    rng,
    counts=100.0,
    g1=0.0,
    g2=0.0,
    noise=0.0,
):

    pixel_scale = 0.263

    dims = [32] * 2
    cen = (np.array(dims) - 1) / 2

    dvdrow, dvdcol, dudrow, dudcol = pixel_scale, -0.02, 0.01, pixel_scale
    jacobian = ngmix.Jacobian(
        row=cen[0],
        col=cen[1],
        dvdrow=dvdrow,
        dvdcol=dvdcol,
        dudrow=dudrow,
        dudcol=dudcol,
    )

    pars1 = [
        -3.25 * pixel_scale,
        -3.25 * pixel_scale,
        0.05,
        0.025,
        0.55,
        0.4 * counts,
    ]
    pars2 = [
        3.0 * pixel_scale,
        0.5 * pixel_scale,
        -0.1,
        -0.05,
        0.27,
        0.6 * counts,
    ]

    gm1 = ngmix.GMixModel(pars1, "gauss")
    gm2 = ngmix.GMixModel(pars2, "gauss")

    full_pars = np.hstack([gm1.get_full_pars(), gm2.get_full_pars()])

    gm = ngmix.GMix(pars=full_pars)

    im0 = gm.make_image(dims, jacobian=jacobian)

    im = im0 + rng.normal(size=im0.shape, scale=noise)

    obs = ngmix.Observation(image=im, jacobian=jacobian)

    return obs, gm
예제 #24
0
def test_gmix_errors():
    with pytest.raises(ValueError):
        ngmix.GMix()

    with pytest.raises(ValueError):
        ngmix.GMixModel([1] * 6, "blah")

    with pytest.raises(ValueError):
        ngmix.GMix(pars=[1] * 10)

    with pytest.raises(ValueError):
        ngmix.GMix(ngauss=-1)

    with pytest.raises(ValueError):
        ngmix.GMixModel([1] * 10, "gauss")

    pars = [0, 0, 0, 0, 10, 1]
    gm = ngmix.GMixModel(pars, "gauss")
    with pytest.raises(ValueError):
        gm.get_sheared(0.1)

    with pytest.raises(TypeError):
        gm.convolve(3)

    with pytest.raises(ValueError):
        gm.make_image([1])

    obs = ngmix.Observation(np.zeros((10, 10)))
    with pytest.raises(ValueError):
        gm.fill_fdiff(obs, np.zeros((10, 10)), start=100000)

    with pytest.raises(TypeError):
        gm.make_galsim_object(gsparams=3)

    with pytest.raises(ValueError):
        gm = ngmix.GMixCoellip([1] * 3)

    with pytest.raises(ValueError):
        ngmix.gmix.get_model_name(-1)

    with pytest.raises(ValueError):
        ngmix.gmix.get_model_num('asdfsa')

    with pytest.raises(ValueError):
        ngmix.gmix.get_model_ngauss('asdfsa')

    with pytest.raises(ValueError):
        ngmix.gmix.get_model_npars('asdfsa')

    with pytest.raises(ValueError):
        tgm = gm.copy()
        tgm._model_name = 'sdfasd'
        tgm._set_fill_func()
예제 #25
0
    def _get_mof_obs(self):
        im, psf_im, coords, dims, dx1, dy1, noise, sep_coords = self.sim()
        #import images
        #images.view(im)
        #if 'q'==input('hit a key'):
        #    stop

        bg_rms = self.sim['Image']['Bgrms']
        bg_rms_psf = self.sim['Psf']['Bgrms_psf']

        psf_ccen = (np.array(psf_im.shape) - 1.0) / 2.0
        psf_jacob = ngmix.UnitJacobian(
            row=psf_ccen[0],
            col=psf_ccen[1],
        )
        psf_weight = psf_im * 0 + 1.0 / bg_rms_psf**2
        psf_obs = ngmix.Observation(
            psf_im,
            weight=psf_weight,
            jacobian=psf_jacob,
        )

        psf_gmix = self._fit_psf_admom(psf_obs)
        psf_obs.set_gmix(psf_gmix)

        weight = im * 0 + 1.0 / bg_rms**2
        jacobian = ngmix.UnitJacobian(
            row=0,
            col=0,
        )

        obs = ngmix.Observation(
            im,
            weight=weight,
            jacobian=jacobian,
            psf=psf_obs,
        )
        obs.noise = noise

        return obs, sep_coords, dims
예제 #26
0
    def _one_gal_obs(self, source_id=None, psf_noise=1e-6):

        index = source_id
        jaclist = self._get_jacobians(source_id)

        psf_cutout = self.medsObj.get_cutout(index, 0, type='psf')
        image_cutout = self.medsObj.get_cutout(index, 0)
        weight_cutout = self.medsObj.get_cutout(index, 0, type='weight')

        # to help Bootstrapper distinguish between object and background
        image_cutout[~np.isfinite(image_cutout)] = 0.
        image_cutout[image_cutout <= 0] = 1E-2
        psf_noise = 1e-6
        this_psf = psf_cutout + 1e-6 * np.random.randn(psf_cutout.shape[0],
                                                       psf_cutout.shape[1])
        psf_weight_image = np.zeros_like(this_psf) + 1. / psf_noise**2

        sky_sigma = (0.0557 *
                     300)**2  # exp_time = 300, sky_var = 0.0957 ADU/pix/s
        weight_image = np.zeros_like(image_cutout) + 1. / sky_sigma

        jj_im = ngmix.jacobian.DiagonalJacobian(scale=0.206,
                                                x=(image_cutout.shape[0]) / 2,
                                                y=(image_cutout.shape[1]) / 2)
        jj_psf = ngmix.jacobian.DiagonalJacobian(scale=0.206,
                                                 x=psf_cutout.shape[0] / 2,
                                                 y=psf_cutout.shape[1] / 2)

        psf_obs = ngmix.Observation(psf_cutout,
                                    weight=psf_weight_image,
                                    jacobian=jj_psf)
        gal_obs = ngmix.Observation(image_cutout,
                                    weight=weight_image,
                                    jacobian=jj_im,
                                    psf=psf_obs)
        return gal_obs
예제 #27
0
def get_psf_obs(psfim, jacobian):
    cen = (np.array(psfim.shape)-1.0)/2.0
    j = jacobian.copy()
    j.set_cen(row=cen[0], col=cen[1])

    psf_obs = ngmix.Observation(
        psfim,
        weight=psfim*0+1,
        jacobian=j
    )

    gmix = fitpsf(psf_obs)
    psf_obs.set_gmix(gmix)

    return psf_obs
예제 #28
0
def test_ml_fitting_galsim_moffat_smoke():

    rng = np.random.RandomState(seed=2312)

    scale = 0.263
    fwhm = 0.9
    beta = 2.5
    image_size = 33
    flux = 1.0

    noise = 1.0e-5

    moff = galsim.Moffat(fwhm=fwhm, beta=beta, flux=flux)
    im = moff.drawImage(
        nx=image_size,
        ny=image_size,
        scale=scale,
    ).array
    im += rng.normal(scale=noise, size=im.shape)
    weight = im * 0 + 1.0 / noise**2

    cen = (image_size - 1.0) / 2.0
    jac = ngmix.DiagonalJacobian(
        y=cen,
        x=cen,
        scale=scale,
    )

    obs = ngmix.Observation(
        image=im,
        weight=weight,
        jacobian=jac,
    )

    fitter = ngmix.fitting.GalsimMoffatFitter()

    guess = np.zeros(7)

    guess[0] = rng.uniform(low=-0.1, high=0.1)
    guess[1] = rng.uniform(low=-0.1, high=0.1)
    guess[2] = rng.uniform(low=-0.1, high=0.1)
    guess[3] = rng.uniform(low=-0.1, high=0.1)
    guess[4] = moff.half_light_radius * rng.uniform(low=0.9, high=1.1)
    guess[5] = rng.uniform(low=1.5, high=3)
    guess[6] = flux * rng.uniform(low=0.9, high=1.1)

    res = fitter.go(obs=obs, guess=guess)
    assert res['flags'] == 0
예제 #29
0
파일: measure.py 프로젝트: esheldon/deconv
    def _measure_moments(self, gs_kimage, weight):
        import ngmix

        if self._deweight:
            raise NotImplementedError("no dweight yet for gauss moms")

        dk = gs_kimage.scale
        dk2 = dk**2
        dk4 = dk**4

        kwt, cen, dims = self._get_weight_object(gs_kimage)

        jacob = ngmix.UnitJacobian(
            row=cen[0],
            col=cen[1],
        )

        medwt = numpy.median(weight)
        dim = weight.shape[0]
        #noise_factor=self._get_noise_factor(dim)
        noise_factor = dim
        weight_factor = 1.0 / noise_factor**2

        kivar = zeros(gs_kimage.array.shape) + medwt * weight_factor

        kobs = ngmix.Observation(
            gs_kimage.array,
            weight=kivar,
            jacobian=jacob,
        )

        res = kwt.get_weighted_moments(kobs)

        # put onto a common scale
        if res['flags'] == 0:
            res['pars'][0:0 + 2] *= dk
            res['pars'][2:2 + 3] *= dk2

            res['pars_cov'][0:0 + 2, 0:0 + 2] *= dk2
            res['pars_cov'][2:2 + 2, 2:2 + 2] *= dk4

        return res
예제 #30
0
    def _get_coadd_psf_obs(self):
        """
        get the psf observation
        """

        psf_obj = self.coadd_exp.getPsf()
        psf_image = psf_obj.computeKernelImage(self.coadd_cen).array

        psf_cen = (np.array(psf_image.shape)-1.0)/2.0

        psf_jac = self._get_jac(cenx=psf_cen[1], ceny=psf_cen[0])

        psf_err = psf_image.max()*0.0001
        psf_weight = psf_image*0 + 1.0/psf_err**2

        return ngmix.Observation(
            image=psf_image,
            weight=psf_weight,
            jacobian=psf_jac,
        )