Ejemplo n.º 1
0
def _GetAngleValue(param):
    """ @brief Convert a string consisting of a value and an angle unit into an Angle.
    """
    try :
        value, unit = param.rsplit(None,1)
        value = float(value)
        unit = galsim.angle.get_angle_unit(unit)
        return galsim.Angle(value, unit)
    except (TypeError, AttributeError) as e: # pragma: no cover
        raise AttributeError("Unable to parse %s as an Angle.  Caught %s"%(param,e))
Ejemplo n.º 2
0
def _GetAngleValue(param):
    """ @brief Convert a string consisting of a value and an angle unit into an Angle.
    """
    try :
        value, unit = param.rsplit(None,1)
        value = float(value)
        unit = galsim.AngleUnit.from_name(unit)
        return galsim.Angle(value, unit)
    except (ValueError, TypeError, AttributeError) as e:
        raise galsim.GalSimConfigError("Unable to parse %s as an Angle. Caught %s"%(param,e))
Ejemplo n.º 3
0
def _GetAngleValue(param, param_name):
    """ @brief Convert a string consisting of a value and an angle unit into an Angle.
    """
    try :
        value, unit = param.rsplit(None,1)
        value = float(value)
        unit = galsim.angle.get_angle_unit(unit)
        return galsim.Angle(value, unit)
    except Exception as e:
        raise AttributeError("Unable to parse %s param = %s as an Angle."%(param_name,param))
def interp_galsim_sinc(data_hr, data_lr, diff_psf, angle, h_hr, h_lr):
    '''Apply resampling from galsim

    Prameters
    ---------
    data_hr: galsim Image
        galsim Image object with the high resolution simulated image and its WCS
    data_lr: galsim Image
        galsim Image object with the low resolution simulated image and its WCS
    diff_hr: numpy array
        difference kernel betwee the high and low resolution psf
    angle: float
        angle between high and low resolution images
    h_hr: float
        scale of the high resolution pixel (arcsec)
    h_lr: float
        scale of the low resolution pixel (arcsec)

    Returns
    -------
    interp_gal: galsim.Image
        image interpolated at low resolution
    '''
    # Load data
    im_hr = data_hr[None, :, :]
    im_lr = data_lr[None, :, :]
    _, n_hr, n_hr = im_hr.shape
    _, n_lr, n_lr = im_lr.shape

    # Interpolate hr image
    gal_hr = galsim.InterpolatedImage(
        galsim.Image(im_hr[0]),
        scale=h_hr,
        gsparams=galsim.GSParams(kvalue_accuracy=10**-3.5),
        x_interpolant='Sinc')

    # Rotate hr galaxy to lr frame
    rot_gal = gal_hr.rotate(galsim.Angle(angle, galsim.radians))

    # Convolve hr galaxy by diff kernel at hr
    conv_gal = galsim.Convolve(rot_gal, diff_psf)

    # Downsamples to low resolution
    interp_gal = conv_gal.drawImage(
        nx=n_lr,
        ny=n_lr,
        scale=h_lr,
        method='no_pixel',
    )

    return interp_gal
Ejemplo n.º 5
0
def encode_examples(hparams, task_id=0, sample="25.2", cosmos_dir=None, exclusion_level="marginal", min_flux=0.):
    """
    Generates and yields postage stamps obtained with GalSim.
    """
    catalog = galsim.COSMOSCatalog(sample=sample, dir=cosmos_dir, exclusion_level=exclusion_level, min_flux=min_flux)

    index = range(task_id * hparams.example_per_shard,
                  min((task_id+1) * hparams.example_per_shard, catalog.getNObjects()))

    # Extracts additional information about the galaxies
    cat_param = catalog.param_cat[catalog.orig_index]
    # bparams = cat_param['bulgefit']
    sparams = cat_param['sersicfit']

    cat_param = append_fields(cat_param, 'sersic_q', sparams[:, 3])
    cat_param = append_fields(cat_param, 'sersic_n', sparams[:, 2])

    for ind in index:
        # Draw a galaxy using GalSim, any kind of operation can be done here
        gal = catalog.makeGalaxy(ind, noise_pad_size=hparams.img_len * hparams.pixel_scale)
        psf = gal.original_psf

        # Apply random rotation if requested
        if hasattr(hparams, "rotation") and hparams.rotation:
            rotation_angle = galsim.Angle(-np.random.rand() * 2 * np.pi,
                                          galsim.radians)
            gal = gal.rotate(rotation_angle)
            psf = psf.rotate(rotation_angle)

        # We save the corresponding attributes for this galaxy
        if hasattr(hparams, 'attributes'):
            params = cat_param[ind]
            attributes = {k: params[k] for k in hparams.attributes}
        else:
            attributes = None

        # Utility function encodes the postage stamp for serialized features
        yield draw_and_encode_stamp(gal, psf,
                                    stamp_size=hparams.img_len,
                                    pixel_scale=hparams.pixel_scale,
                                    attributes=attributes)
Ejemplo n.º 6
0
def generateGaussianTrainingSet():
    img_size = 32
    destination = 'testImages/'
    #sizes = np.array([3.,3.5,4.,4.5,5.,5.5,6.])
    sizes = np.array([2.5, 3.75, 4.25, 5.35, 5.9, 6.2])
    N_sizes = len(sizes)
    N_shears = 4  #16
    N_angles = 10  #72
    N_train = N_sizes * N_shears * N_angles
    if N_train < img_size**2:
        print "Too few training images to generate an \
               overcomplete dictionary"

    pos_angles = np.linspace(0., 180., N_angles)
    shears = np.arange(0., 1., 1. / N_shears)

    print "No. of training images = ", N_train

    img = galsim.Image(img_size, img_size)
    print "Generating training images ... "

    gal_flux = 1.e5
    noise = 30

    for N_size in xrange(N_sizes):
        for N_shear in xrange(N_shears):
            for N_angle in xrange(N_angles):
                g = galsim.Gaussian(sigma=sizes[N_size], flux=gal_flux)
                theta = galsim.Angle(pos_angles[N_angle], galsim.degrees)
                g = g.shear(g=shears[N_shear], beta=theta)
                g.drawImage(image=img)
                img.addNoise(galsim.GaussianNoise(sigma=noise))
                fname = 'test_' + str(N_size).zfill(2) + '_' + str(
                    N_shear).zfill(2) + '_' + str(N_angle).zfill(2)
                img.write(fname + '.fits', dir=destination)

    print "Finished generating " + str(N_train) + " training images."
    print "Destination folder: " + str(destination)
Ejemplo n.º 7
0
def simReal(real_galaxy,
            target_PSF,
            target_pixel_scale,
            g1=0.0,
            g2=0.0,
            rotation_angle=None,
            rand_rotate=True,
            rng=None,
            target_flux=1000.0,
            image=None):
    """Function to simulate images (no added noise) from real galaxy training data.

    This function takes a RealGalaxy from some training set, and manipulates it as needed to 
    simulate a (no-noise-added) image from some lower-resolution telescope.  It thus requires a
    target PSF (which could be an image, or one of our base classes) that represents all PSF 
    components including the pixel response, and a target pixel scale.  

    The default rotation option is to impose a random rotation to make irrelevant any real shears 
    in the galaxy training data (optionally, the RNG can be supplied).  This default can be turned 
    off by setting `rand_rotate = False` or by requesting a specific rotation angle using the
    `rotation_angle` keyword, in which case `rand_rotate` is ignored.

    Optionally, the user can specify a shear (default 0).  Finally, they can specify a flux 
    normalization for the final image, default 1000.

    @param real_galaxy         The RealGalaxy object to use, not modified in generating the
                               simulated image.
    @param target_PSF          The target PSF, either one of our base classes or an ImageView/Image.
    @param target_pixel_scale  The pixel scale for the final image, in arcsec.
    @param g1                  First component of shear to impose (components defined with respect
                               to pixel coordinates), default `g1 = 0.`
    @param g2                  Second component of shear to impose, default `g2 = 0.`
    @param rotation_angle      Angle by which to rotate the galaxy (must be a galsim.Angle 
                               instance).
    @param rand_rotate         If `rand_rotate = True` (default) then impose a random rotation on 
                               the training galaxy; this is ignored if `rotation_angle` is set.
    @param rng                 A random number generator to use for selection of the random 
                               rotation angle. (optional, may be any kind of galsim.BaseDeviate 
                               or None)
    @param target_flux         The target flux in the output galaxy image, default 
                               `target_flux = 1000.`
    @param image               As with the GSObject.draw() function, if an image is provided,
                               then it will be used and returned.
                               If `image=None`, then an appropriately sized image will be created.
    @return A simulated galaxy image.  The input RealGalaxy is unmodified. 
    """
    # do some checking of arguments
    if not isinstance(real_galaxy, galsim.RealGalaxy):
        raise RuntimeError("Error: simReal requires a RealGalaxy!")
    for Class in galsim.Image.itervalues():
        if isinstance(target_PSF, Class):
            lan5 = galsim.Lanczos(5, conserve_flux=True, tol=1.e-4)
            interp2d = galsim.InterpolantXY(lan5)
            target_PSF = galsim.SBInterpolatedImage(target_PSF.view(),
                                                    xInterp=interp2d,
                                                    dx=target_pixel_scale)
            break
    for Class in galsim.ImageView.itervalues():
        if isinstance(target_PSF, Class):
            lan5 = galsim.Lanczos(5, conserve_flux=True, tol=1.e-4)
            interp2d = galsim.InterpolantXY(lan5)
            target_PSF = galsim.SBInterpolatedImage(target_PSF,
                                                    xInterp=interp2d,
                                                    dx=target_pixel_scale)
            break
    if isinstance(target_PSF, galsim.GSObject):
        target_PSF = target_PSF.SBProfile
    if not isinstance(target_PSF, galsim.SBProfile):
        raise RuntimeError(
            "Error: target PSF is not an Image, ImageView, SBProfile, or GSObject!"
        )
    if rotation_angle != None and not isinstance(rotation_angle, galsim.Angle):
        raise RuntimeError(
            "Error: specified rotation angle is not an Angle instance!")
    if (target_pixel_scale < real_galaxy.pixel_scale):
        import warnings
        message = "Warning: requested pixel scale is higher resolution than original!"
        warnings.warn(message)
    import math  # needed for pi, sqrt below
    g = math.sqrt(g1**2 + g2**2)
    if g > 1:
        raise RuntimeError("Error: requested shear is >1!")

    # make sure target PSF is normalized
    target_PSF.setFlux(1.0)

    real_galaxy_copy = real_galaxy.copy()

    # rotate
    if rotation_angle != None:
        real_galaxy_copy.applyRotation(rotation_angle)
    elif rotation_angle == None and rand_rotate == True:
        if rng == None:
            uniform_deviate = galsim.UniformDeviate()
        elif isinstance(rng, galsim.BaseDeviate):
            uniform_deviate = galsim.UniformDeviate(rng)
        else:
            raise TypeError(
                "The rng provided to drawShoot is not a BaseDeviate")
        rand_angle = galsim.Angle(math.pi * uniform_deviate(), galsim.radians)
        real_galaxy_copy.applyRotation(rand_angle)

    # set fluxes
    real_galaxy_copy.setFlux(target_flux)

    # shear
    if (g1 != 0.0 or g2 != 0.0):
        real_galaxy_copy.applyShear(g1=g1, g2=g2)

    # convolve, resample
    out_gal = galsim.Convolve([real_galaxy_copy, galsim.GSObject(target_PSF)])
    image = out_gal.draw(image=image, dx=target_pixel_scale)

    # return simulated image
    return image
Ejemplo n.º 8
0
def test_angle():
    """Test basic construction and use of Angle and AngleUnit classes
    """
    # First Angle:
    theta1 = numpy.pi / 4. * galsim.radians
    theta2 = 45 * galsim.degrees
    theta3 = 3 * galsim.hours
    theta4 = 45 * 60 * galsim.arcmin
    theta5 = galsim.Angle(45 * 3600,
                          galsim.arcsec)  # Check explicit installation too.

    assert theta1.rad() == numpy.pi / 4.
    numpy.testing.assert_almost_equal(theta2.rad(), numpy.pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta3.rad(), numpy.pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta4.rad(), numpy.pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta5.rad(), numpy.pi / 4., decimal=12)

    # Check wrapping
    theta6 = (45 + 360) * galsim.degrees
    assert abs(theta6.rad() - theta1.rad()) > 6.
    numpy.testing.assert_almost_equal(theta6.wrap().rad(),
                                      theta1.rad(),
                                      decimal=12)

    theta7 = (45 - 360) * galsim.degrees
    assert abs(theta7.rad() - theta1.rad()) > 6.
    numpy.testing.assert_almost_equal(theta7.wrap().rad(),
                                      theta1.rad(),
                                      decimal=12)

    # Check wrapping with non-default center
    pi_rad = pi * galsim.radians
    numpy.testing.assert_almost_equal(theta6.wrap(pi_rad).rad(),
                                      theta1.rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.rad(),
                                      theta1.wrap(2 * pi_rad).rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.rad(),
                                      theta1.wrap(3 * pi_rad).rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.rad(),
                                      theta1.wrap(-pi_rad).rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.rad(),
                                      theta1.wrap(-2 * pi_rad).rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.wrap(27 * galsim.radians).rad(),
                                      theta1.wrap(27 * galsim.radians).rad(),
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.wrap(-127 * galsim.radians).rad(),
                                      theta1.wrap(-127 * galsim.radians).rad(),
                                      decimal=12)

    # Make a new AngleUnit as described in the AngleUnit docs
    gradians = galsim.AngleUnit(2. * numpy.pi / 400.)
    theta8 = 50 * gradians
    numpy.testing.assert_almost_equal(theta8.rad(), numpy.pi / 4., decimal=12)

    # Check simple math
    numpy.testing.assert_almost_equal((theta1 + theta2).rad(),
                                      numpy.pi / 2.,
                                      decimal=12)
    numpy.testing.assert_almost_equal((4 * theta3).rad(), numpy.pi, decimal=12)
    numpy.testing.assert_almost_equal((4 * theta4 - theta2).rad(),
                                      0.75 * numpy.pi,
                                      decimal=12)
    numpy.testing.assert_almost_equal((theta5 / 2.).rad(),
                                      numpy.pi / 8.,
                                      decimal=12)

    numpy.testing.assert_almost_equal(theta3 / galsim.radians,
                                      numpy.pi / 4.,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta1 / galsim.hours, 3., decimal=12)
    numpy.testing.assert_almost_equal(galsim.hours / galsim.arcmin,
                                      15 * 60,
                                      decimal=12)

    # Check picklability
    do_pickle(galsim.radians)
    do_pickle(galsim.degrees)
    do_pickle(galsim.hours)
    do_pickle(galsim.arcmin)
    do_pickle(galsim.arcsec)
    do_pickle(gradians)
    do_pickle(theta1)
    do_pickle(theta2)
    do_pickle(theta3)
    do_pickle(theta4)
    do_pickle(theta5)
    do_pickle(theta6)
    do_pickle(theta7)
    do_pickle(theta8)
Ejemplo n.º 9
0
    def generator(self, data_dir, tmp_dir, dataset_split, task_id=-1):
        """
    Generates and yields postage stamps obtained with GalSim.
    """
        p = self.get_hparams()

        try:
            # try to use default galsim path to the data
            catalog = galsim.COSMOSCatalog()
        except:
            # If that fails, tries to use the specified tmp_dir
            catalog = galsim.COSMOSCatalog(dir=tmp_dir +
                                           '/COSMOS_25.2_training_sample')

        # Create a list of galaxy indices for this task, remember, there is a task
        # per shard, each shard is 1000 galaxies.
        assert (task_id > -1)
        index = range(
            task_id * p.example_per_shard,
            min((task_id + 1) * p.example_per_shard, catalog.getNObjects()))

        # Extracts additional information about the galaxies
        cat_param = catalog.param_cat[catalog.orig_index]
        from numpy.lib.recfunctions import append_fields
        import numpy as np

        bparams = cat_param['bulgefit']
        sparams = cat_param['sersicfit']
        # Parameters for a 2 component fit
        cat_param = append_fields(cat_param, 'bulge_q', bparams[:, 11])
        cat_param = append_fields(cat_param, 'bulge_beta', bparams[:, 15])
        cat_param = append_fields(cat_param, 'disk_q', bparams[:, 3])
        cat_param = append_fields(cat_param, 'disk_beta', bparams[:, 7])
        cat_param = append_fields(cat_param, 'bulge_hlr', cat_param['hlr'][:,
                                                                           1])
        cat_param = append_fields(
            cat_param, 'bulge_flux_log10',
            np.where(cat_param['use_bulgefit'] == 1,
                     np.log10(cat_param['flux'][:, 1]),
                     np.zeros(len(cat_param))))
        cat_param = append_fields(cat_param, 'disk_hlr', cat_param['hlr'][:,
                                                                          2])
        cat_param = append_fields(
            cat_param, 'disk_flux_log10',
            np.where(cat_param['use_bulgefit'] == 1,
                     np.log10(cat_param['flux'][:, 2]),
                     np.log10(cat_param['flux'][:, 0])))

        # Parameters for a single component fit
        cat_param = append_fields(cat_param, 'sersic_flux_log10',
                                  np.log10(sparams[:, 0]))
        cat_param = append_fields(cat_param, 'sersic_q', sparams[:, 3])
        cat_param = append_fields(cat_param, 'sersic_hlr', sparams[:, 1])
        cat_param = append_fields(cat_param, 'sersic_n', sparams[:, 2])
        cat_param = append_fields(cat_param, 'sersic_beta', sparams[:, 7])

        for ind in index:
            # Draw a galaxy using GalSim, any kind of operation can be done here
            gal = catalog.makeGalaxy(ind,
                                     noise_pad_size=p.img_len * p.pixel_scale *
                                     2)

            # We apply the orginal psf if a different PSF is not requested
            if hasattr(p, "psf"):
                psf = p.psf
            else:
                psf = gal.original_psf

            # Apply random rotation if requested
            if hasattr(p, "rotation") and p.rotation:
                rotation_angle = galsim.Angle(-np.random.rand() * 2 * np.pi,
                                              galsim.radians)
                gal = gal.rotate(rotation_angle)
                psf = psf.rotate(rotation_angle)

            # We save the corresponding attributes for this galaxy
            if hasattr(p, 'attributes'):
                params = cat_param[ind]
                attributes = {k: params[k] for k in p.attributes}
            else:
                attributes = None

            # Utility function encodes the postage stamp for serialized features
            yield galsim_utils.draw_and_encode_stamp(gal,
                                                     psf,
                                                     stamp_size=p.img_len,
                                                     pixel_scale=p.pixel_scale,
                                                     attributes=attributes)
Ejemplo n.º 10
0
def simReal(real_galaxy, target_PSF, target_pixel_scale, g1=0.0, g2=0.0, rotation_angle=None,
            rand_rotate=True, rng=None, target_flux=1000.0, image=None): # pragma: no cover
    """Deprecated method to simulate images (no added noise) from real galaxy training data.

    This function takes a RealGalaxy from some training set, and manipulates it as needed to
    simulate a (no-noise-added) image from some lower-resolution telescope.  It thus requires a
    target PSF (which could be an image, or one of our base classes) that represents all PSF
    components including the pixel response, and a target pixel scale.

    The default rotation option is to impose a random rotation to make irrelevant any real shears
    in the galaxy training data (optionally, the RNG can be supplied).  This default can be turned
    off by setting `rand_rotate = False` or by requesting a specific rotation angle using the
    `rotation_angle` keyword, in which case `rand_rotate` is ignored.

    Optionally, the user can specify a shear (default 0).  Finally, they can specify a flux
    normalization for the final image, default 1000.

    @param real_galaxy      The RealGalaxy object to use, not modified in generating the
                            simulated image.
    @param target_PSF       The target PSF, either one of our base classes or an Image.
    @param target_pixel_scale  The pixel scale for the final image, in arcsec.
    @param g1               First component of shear to impose (components defined with respect
                            to pixel coordinates), [default: 0]
    @param g2               Second component of shear to impose, [default: 0]
    @param rotation_angle   Angle by which to rotate the galaxy (must be an Angle
                            instance). [default: None]
    @param rand_rotate      Should the galaxy be rotated by some random angle?  [default: True;
                            unless `rotation_angle` is set, then False]
    @param rng              A BaseDeviate instance to use for the random selection or rotation
                            angle. [default: None]
    @param target_flux      The target flux in the output galaxy image, [default: 1000.]
    @param image            As with the GSObject.drawImage() function, if an image is provided,
                            then it will be used and returned.  [default: None, which means an
                            appropriately-sized image will be created.]

    @return a simulated galaxy image.
    """
    from .deprecated import depr
    depr('simReal', 1.5, '',
         'This method has been deprecated due to lack of widespread use.  If you '+
         'have a need for it, please open an issue requesting that it be reinstated.')
    # do some checking of arguments
    if not isinstance(real_galaxy, galsim.RealGalaxy):
        raise RuntimeError("Error: simReal requires a RealGalaxy!")
    if isinstance(target_PSF, galsim.Image):
        target_PSF = galsim.InterpolatedImage(target_PSF, scale=target_pixel_scale)
    if not isinstance(target_PSF, galsim.GSObject):
        raise RuntimeError("Error: target PSF is not an Image or GSObject!")
    if rotation_angle is not None and not isinstance(rotation_angle, galsim.Angle):
        raise RuntimeError("Error: specified rotation angle is not an Angle instance!")
    if (target_pixel_scale < real_galaxy.pixel_scale):
        import warnings
        message = "Warning: requested pixel scale is higher resolution than original!"
        warnings.warn(message)
    import math # needed for pi, sqrt below
    g = math.sqrt(g1**2 + g2**2)
    if g > 1:
        raise RuntimeError("Error: requested shear is >1!")

    # make sure target PSF is normalized
    target_PSF = target_PSF.withFlux(1.0)

    # rotate
    if rotation_angle is not None:
        real_galaxy = real_galaxy.rotate(rotation_angle)
    elif rotation_angle is None and rand_rotate == True:
        if rng is None:
            ud = galsim.UniformDeviate()
        elif isinstance(rng,galsim.BaseDeviate):
            ud = galsim.UniformDeviate(rng)
        else:
            raise TypeError("The rng provided is not a BaseDeviate")
        rand_angle = galsim.Angle(math.pi*ud(), galsim.radians)
        real_galaxy = real_galaxy.rotate(rand_angle)

    # set fluxes
    real_galaxy = real_galaxy.withFlux(target_flux)

    # shear
    if (g1 != 0.0 or g2 != 0.0):
        real_galaxy = real_galaxy.shear(g1=g1, g2=g2)

    # convolve, resample
    out_gal = galsim.Convolve([real_galaxy, target_PSF])
    image = out_gal.drawImage(image=image, scale=target_pixel_scale, method='no_pixel')

    # return simulated image
    return image
Ejemplo n.º 11
0
def test_angle():
    """Test basic construction and use of Angle and AngleUnit classes
    """
    # First Angle:
    theta1 = pi / 4. * galsim.radians
    theta2 = 45 * galsim.degrees
    theta3 = 3 * galsim.hours
    theta4 = 45 * 60 * galsim.arcmin
    theta5 = galsim.Angle(45 * 3600,
                          galsim.arcsec)  # Check explicit installation too.
    theta6 = galsim._Angle(
        pi / 4.)  # Underscore constructor implicitly uses radians

    assert theta1.rad == pi / 4.
    numpy.testing.assert_almost_equal(theta2.rad, pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta3.rad, pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta4.rad, pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta5.rad, pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta6.rad, pi / 4., decimal=12)

    # Check wrapping
    theta6 = (45 + 360) * galsim.degrees
    assert abs(theta6.rad - theta1.rad) > 6.
    numpy.testing.assert_almost_equal(theta6.wrap().rad,
                                      theta1.rad,
                                      decimal=12)

    # Check trig calls
    numpy.testing.assert_almost_equal(theta6.sin(), theta1.sin(), decimal=12)
    numpy.testing.assert_almost_equal(theta6.cos(), theta1.cos(), decimal=12)
    numpy.testing.assert_almost_equal(theta6.tan(), theta1.tan(), decimal=12)
    numpy.testing.assert_almost_equal(theta6.sin(), math.sqrt(0.5), decimal=12)
    numpy.testing.assert_almost_equal(theta6.cos(), math.sqrt(0.5), decimal=12)
    numpy.testing.assert_almost_equal(theta6.tan(), 1., decimal=12)
    numpy.testing.assert_array_almost_equal(theta6.sincos(),
                                            math.sqrt(0.5),
                                            decimal=12)

    theta7 = (45 - 360) * galsim.degrees
    assert abs(theta7.rad - theta1.rad) > 6.
    numpy.testing.assert_almost_equal(theta7.wrap().rad,
                                      theta1.rad,
                                      decimal=12)

    # Check wrapping with non-default center
    pi_rad = pi * galsim.radians
    numpy.testing.assert_almost_equal(theta6.wrap(pi_rad).rad,
                                      theta1.rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.rad,
                                      theta1.wrap(2 * pi_rad).rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.rad,
                                      theta1.wrap(3 * pi_rad).rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.rad,
                                      theta1.wrap(-pi_rad).rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.rad,
                                      theta1.wrap(-2 * pi_rad).rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta6.wrap(27 * galsim.radians).rad,
                                      theta1.wrap(27 * galsim.radians).rad,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta7.wrap(-127 * galsim.radians).rad,
                                      theta1.wrap(-127 * galsim.radians).rad,
                                      decimal=12)

    # Make a new AngleUnit as described in the AngleUnit docs
    gradians = galsim.AngleUnit(2. * pi / 400.)
    theta8 = 50 * gradians
    numpy.testing.assert_almost_equal(theta8.rad, pi / 4., decimal=12)
    numpy.testing.assert_almost_equal(theta8 / gradians, 50., decimal=12)
    numpy.testing.assert_almost_equal(gradians.value,
                                      2. * pi / 400.,
                                      decimal=12)
    numpy.testing.assert_almost_equal(gradians / galsim.radians,
                                      2. * pi / 400.,
                                      decimal=12)

    # Check simple math
    numpy.testing.assert_almost_equal((theta1 + theta2).rad,
                                      pi / 2.,
                                      decimal=12)
    numpy.testing.assert_almost_equal((4 * theta3).rad, pi, decimal=12)
    numpy.testing.assert_almost_equal((4 * theta4 - theta2).rad,
                                      0.75 * pi,
                                      decimal=12)
    numpy.testing.assert_almost_equal((theta5 / 2.).rad, pi / 8., decimal=12)

    numpy.testing.assert_almost_equal(theta3 / galsim.radians,
                                      pi / 4.,
                                      decimal=12)
    numpy.testing.assert_almost_equal(theta1 / galsim.hours, 3., decimal=12)
    numpy.testing.assert_almost_equal(galsim.hours / galsim.arcmin,
                                      15 * 60,
                                      decimal=12)

    # Check copy constructor
    theta9 = galsim.Angle(theta1)
    numpy.testing.assert_equal(theta9.rad, theta1.rad)

    # Check picklability
    do_pickle(galsim.radians)
    do_pickle(galsim.degrees)
    do_pickle(galsim.hours)
    do_pickle(galsim.arcmin)
    do_pickle(galsim.arcsec)
    do_pickle(gradians)
    do_pickle(theta1)
    do_pickle(theta2)
    do_pickle(theta3)
    do_pickle(theta4)
    do_pickle(theta5)
    do_pickle(theta6)
    do_pickle(theta7)
    do_pickle(theta8)

    # Check invalid constructors
    assert_raises(TypeError, galsim.AngleUnit, galsim.degrees)
    assert_raises(ValueError, galsim.AngleUnit, 'spam')
    assert_raises(TypeError, galsim.AngleUnit, 1, 3)
    assert_raises(TypeError, galsim.Angle, 3.4)
    assert_raises(TypeError, galsim.Angle, theta1, galsim.degrees)
    assert_raises(ValueError, galsim.Angle, 'spam', galsim.degrees)
    assert_raises(TypeError, galsim.Angle, 1, 3)
Ejemplo n.º 12
0
def _make_galaxy(params):
    """
    Draws the galaxy, psf and noise power spectrum on a postage stamp
    """
    gal, psf, noise_image, in_pixel_scale, var, stamp_size, pixel_scale = params

    real_params = (galsim.Image(np.ascontiguousarray(gal),
                                scale=in_pixel_scale),
                   galsim.Image(np.ascontiguousarray(psf),
                                scale=in_pixel_scale),
                   galsim.Image(np.ascontiguousarray(noise_image),
                                scale=in_pixel_scale), in_pixel_scale, var)

    gal = galsim.RealGalaxy(real_params,
                            noise_pad_size=stamp_size * pixel_scale)

    psf = gal.original_psf
    gal = galsim.Convolve(gal, gal.original_psf)

    # Random rotation of the galaxy
    rotation_angle = galsim.Angle(-np.random.rand() * 2 * np.pi,
                                  galsim.radians)
    g = gal.rotate(rotation_angle)
    p = psf.rotate(rotation_angle)

    # Draw the Fourier domain image of the galaxy
    imC = galsim.ImageCF(stamp_size,
                         stamp_size,
                         scale=2. * np.pi / (pixel_scale * stamp_size))
    imCp = galsim.ImageCF(stamp_size,
                          stamp_size,
                          scale=2. * np.pi / (pixel_scale * stamp_size))
    g.drawKImage(image=imC)
    p.drawKImage(image=imCp)

    # Keep track of the pixels with 0 value
    mask = ~(np.fft.fftshift(imC.array)[:, :(stamp_size) // 2 + 1] == 0)

    # Inverse Fourier transform of the image
    # TODO: figure out why we need 2 fftshifts....
    im = np.fft.fftshift(np.fft.ifft2(np.fft.fftshift(
        imC.array))).real.astype('float32')

    # Transform the psf array into proper format for Theano
    im_psf = np.fft.fftshift(imCp.array)[:, :(stamp_size // 2 +
                                              1)].astype('complex64')

    # Compute noise power spectrum
    ps = g.noise._get_update_rootps((stamp_size, stamp_size),
                                    wcs=galsim.PixelScale(pixel_scale))

    # The following comes from correlatednoise.py
    rt2 = np.sqrt(2.)
    shape = (stamp_size, stamp_size)
    ps[0, 0] = rt2 * ps[0, 0]
    # Then make the changes necessary for even sized arrays
    if shape[1] % 2 == 0:  # x dimension even
        ps[0, shape[1] // 2] = rt2 * ps[0, shape[1] // 2]
    if shape[0] % 2 == 0:  # y dimension even
        ps[shape[0] // 2, 0] = rt2 * ps[shape[0] // 2, 0]
        # Both dimensions even
        if shape[1] % 2 == 0:
            ps[shape[0] // 2, shape[1] // 2] = rt2 * \
                ps[shape[0] // 2, shape[1] // 2]

    # Apply mask to power spectrum so that it is very large outside maxk
    ps = np.where(mask, np.log(ps**2), 10).astype('float32')

    return im, im_psf, ps
Ejemplo n.º 13
0
def generateBDTrainingSet(btt):
    gsp = galsim.GSParams(maximum_fft_size=16384)
    img_size = 64
    destination = 'trainImages/'

    # PSF description
    lam = 1580  #nm
    diam = 2.4  #m
    obscuration = 0.3
    PSF = galsim.OpticalPSF(lam=lam, diameter=diam, obscuration=obscuration)

    # Bulge component
    n_bulge = 4.0
    bulge_Re_arr = np.array([3.5, 4., 4.5, 5., 5.5, 6., 6.5])  # pixels
    #sizes = np.array([2.5,3.75,4.25,5.35,5.9,6.2])

    #Disk component
    n_disk = 1.0
    disk_scaleRadius_arr = bulge_Re_arr

    N_sizes = len(bulge_Re_arr) * len(disk_scaleRadius_arr)
    N_shears = 4  #16
    N_angles = 10  #72

    N_train = N_sizes * (N_shears**2) * (N_angles**2)
    if N_train < img_size**2:
        print "Too few training images to generate an \
               overcomplete dictionary"

    theta_values = np.linspace(0., 180., N_angles).tolist()  # degrees
    pos_angles = [
        galsim.Angle(theta, galsim.degrees) for theta in theta_values
    ]
    shears = np.arange(0., 1., 1. / N_shears)

    print "No. of training images = ", N_train

    img = galsim.Image(img_size, img_size)
    print "Generating training images ... "

    gal_flux = 5.e5
    noise = 10

    for N_bulge_size in xrange(len(bulge_Re_arr)):
        for N_disk_size in xrange(len(disk_scaleRadius_arr)):
            bulge = galsim.Sersic(n=n_bulge,
                                  half_light_radius=bulge_Re_arr[N_bulge_size],
                                  gsparams=gsp)
            disk = galsim.Sersic(
                n=n_disk,
                scale_radius=disk_scaleRadius_arr[N_disk_size],
                gsparams=gsp)
            for N_bulge_shear in xrange(N_shears):
                for N_bulge_pos in xrange(N_angles):
                    B = bulge.shear(g=shears[N_bulge_shear],
                                    beta=pos_angles[N_bulge_pos])
                    for N_disk_shear in xrange(N_shears):
                        for N_disk_pos in xrange(N_angles):
                            D = disk.shear(g=shears[N_disk_shear],
                                           beta=pos_angles[N_disk_pos])
                            gal = btt * gal_flux * B + (1. -
                                                        btt) * gal_flux * D
                            gal = galsim.Convolve([gal, PSF])
                            gal.drawImage(image=img)
                            img.addNoise(galsim.GaussianNoise(sigma=noise))
                            fname = 'trainBD_'+str(N_btt).zfill(2)+'_'+str(N_bulge_size).zfill(2)+'_'+str(N_disk_size).zfill(2)+\
                                    '_'+str(N_bulge_shear).zfill(2)+'_'+str(N_bulge_pos).zfill(2)+'_'+str(N_disk_shear).zfill(2)+\
                                    '_'+str(N_disk_pos).zfill(2)
                            img.write(fname + '.fits', dir=destination)

    print "Finished generating " + str(
        N_train) + " training images with bulge+disk components"