How to use the healpy.rotator.Rotator function in healpy

To help you get started, we’ve selected a few healpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github healpy / healpy / healpy / rotator.py View on Github external
def __rmul__(self, b):
        if not isinstance(b, Rotator):
            raise TypeError(
                "A Rotator can only be multiplied by another Rotator "
                "(composition of rotations)"
            )
        rots = b._rots + self._rots
        coords = b._coords + self._coords
        invs = self._invs + a._invs
        return Rotator(rot=rots, coord=coords, inv=invs, deg=False)
github healpy / healpy / healpy / projector.py View on Github external
- a 2D array with the projection of the map.

        Note: the Projector must contain information on the array.
        """
        x, y = self.ij2xy()
        if np.__version__ >= "1.1":
            matype = np.ma.core.MaskedArray
        else:
            matype = np.ma.array
        if type(x) is matype and x.mask is not np.ma.nomask:
            w = x.mask == False
        else:
            w = slice(None)
        img = np.zeros(x.shape, np.float64) - np.inf
        vec = self.xy2vec(np.asarray(x[w]), np.asarray(y[w]))
        vec = (R.Rotator(rot=rot, coord=self.mkcoord(coord))).I(vec)
        pix = vec2pix_func(vec[0], vec[1], vec[2])
        # support masked array for map, or a dictionnary (for explicit pixelisation)
        if isinstance(map, matype) and map.mask is not np.ma.nomask:
            mpix = map[pix]
            mpix[map.mask[pix]] = UNSEEN
        elif isinstance(map, dict):
            is_pix_seen = np.in1d(pix, map.keys()).reshape(pix.shape)
            is_pix_unseen = ~is_pix_seen
            mpix = np.zeros_like(img[w])
            mpix[is_pix_unseen] = UNSEEN
            pix_seen = pix[is_pix_seen]
            iterable = (map[p] for p in pix_seen)
            mpix[is_pix_seen] = np.fromiter(iterable, mpix.dtype, count=pix_seen.size)
        else:
            mpix = map[pix]
        img[w] = mpix
github healpy / healpy / healpy / rotator.py View on Github external
Note: the coord system conversion is applied first, then the rotation.
        """
        rot_is_seq = hasattr(rot, "__len__") and hasattr(rot[0], "__len__")
        coord_is_seq = (
            hasattr(coord, "__len__")
            and hasattr(coord[0], "__len__")
            and type(coord[0]) is not str
        )
        if rot_is_seq and coord_is_seq:
            if len(rot) != len(coord):
                raise ValueError(Rotator.ErrMessWrongPar)
            else:
                rots = rot
                coords = coord
        elif (rot_is_seq or coord_is_seq) and (rot is not None and coord is not None):
            raise ValueError(Rotator.ErrMessWrongPar)
        else:
            rots = [rot]
            coords = [coord]
        inv_is_seq = hasattr(inv, "__len__")
        if inv_is_seq:
            if len(inv) != len(rots):
                raise ValueError("inv must have same length as rot and/or coord")
            invs = inv
        else:
            invs = [inv] * len(rots)
        # check the argument and normalize them
        if eulertype in ["ZYX", "X", "Y"]:
            self._eultype = eulertype
        else:
            self._eultype = "ZYX"
        self._rots = []
github healpy / healpy / healpy / rotator.py View on Github external
array([ 1.45937485,  1.05047962, -3.14119347])
    >>> np.array(coordsys2euler_zyz('CG'))
    array([-0.22443941,  1.09730866,  2.14556934])
    >>> np.array(coordsys2euler_zyz('E'))
    array([ 0.,  0.,  0.])
    """

    coord_norm = normalise_coord(coord)

    if coord_norm[0] == coord_norm[1]:
        psi, theta, phi = np.zeros(3)
    else:
        # Convert basis vectors

        xin, yin, zin = np.eye(3)
        rot = Rotator(coord=coord_norm)
        xout, yout, zout = rot([xin, yin, zin]).T

        # Normalize

        xout /= np.sqrt(np.dot(xout, xout))
        yout /= np.sqrt(np.dot(yout, yout))
        zout /= np.sqrt(np.dot(zout, zout))

        # Get the angles

        psi = np.arctan2(yout[2], -xout[2])
        theta = np.arccos(np.dot(zin, zout))
        phi = np.arctan2(zout[1], zout[0])

    return psi, theta, phi
github healpy / healpy / healpy / projaxes.py View on Github external
if type(args[2]) is not str:
                raise TypeError("Third argument must be a string")
            else:
                theta, phi = np.asarray(args[0]), np.asarray(args[1])
                fmt = args[2]
        else:
            raise TypeError("Three args maximum")
        rot = kwds.pop("rot", None)
        if rot is not None:
            rot = np.array(np.atleast_1d(rot), copy=1)
            rot.resize(3)
            rot[1] = rot[1] - 90.0
        coord = self.proj.mkcoord(kwds.pop("coord", None))[::-1]
        lonlat = kwds.pop("lonlat", False)
        vec = R.dir2vec(theta, phi, lonlat=lonlat)
        vec = (R.Rotator(rot=rot, coord=coord, eulertype="Y")).I(vec)
        x, y = self.proj.vec2xy(vec, direct=kwds.pop("direct", False))
        x, y = self._make_segment(
            x, y, threshold=kwds.pop("threshold", self._segment_threshold)
        )
        thelines = []
        for xx, yy in zip(x, y):
            if fmt is not None:
                try:  # works in matplotlib 1.3 and earlier
                    linestyle, marker, color = matplotlib.axes._process_plot_format(fmt)
                except:  # matplotlib 1.4 and later
                    linestyle, marker, color = matplotlib.axes._axes._process_plot_format(
                        fmt
                    )
                kwds.setdefault("linestyle", linestyle)
                kwds.setdefault("marker", marker)
                if color is not None:
github rodluger / starry / starry / _sht.py View on Github external
def healpix2map(healpix_map, lmax=10, **kwargs):
    """Return a map vector corresponding to a healpix array."""
    if hp is None:
        raise ImportError(
            "Please install the `healpy` Python package to "
            "enable this feature. See `https://healpy.readthedocs.io`."
        )
    # Get the complex spherical harmonic coefficients
    alm = hp.sphtfunc.map2alm(healpix_map, lmax=lmax)

    # We first need to do a rotation to get our axes aligned correctly,
    # since we use a different convention than `healpy`
    alm = hp.rotator.Rotator((-90, 0, -90)).rotate_alm(alm)

    # Smooth the map?
    sigma = kwargs.pop("sigma", None)
    if sigma is not None:
        alm = hp.sphtfunc.smoothalm(alm, sigma=sigma, verbose=False)

    # Convert them to real coefficients
    ylm = np.zeros(lmax ** 2 + 2 * lmax + 1, dtype="float")
    i = 0
    for l in range(0, lmax + 1):
        for m in range(-l, l + 1):
            j = hp.sphtfunc.Alm.getidx(lmax, l, np.abs(m))
            if m < 0:
                ylm[i] = np.sqrt(2) * (-1) ** m * alm[j].imag
            elif m == 0:
                ylm[i] = alm[j].real
github DarkEnergySurvey / ugali / ugali / scratch / PlotAllSkyHealpix.py View on Github external
if not targets.shape: targets = targets.reshape(-1)
        coord = 'CG' # For RA/DEC input
        healpy.projscatter(targets['f1'],targets['f2'],
                           lonlat=True,coord=coord,marker='o',c='w')
        fig = plt.gcf()
        # This is pretty hackish (but is how healpy does it...)
        for ax in fig.get_axes():
            if isinstance(ax,healpy.projaxes.SphericalProjAxes): break

        for target in targets:
            text = TARGETS[target[0]][0]
            kwargs = TARGETS[target[0]][1]
            glon,glat = celToGal(target[1],target[2])

            vec = healpy.rotator.dir2vec(glon,glat,lonlat=True)
            vec = (healpy.rotator.Rotator(rot=None,coord='G',eulertype='Y')).I(vec)

            x,y = ax.proj.vec2xy(vec,direct=False)
            ax.annotate(text,xy=(x,y),xycoords='data',**kwargs)

    plt.savefig(opts.outfile)
github healpy / healpy / healpy / projector.py View on Github external
def __init__(self, rot=None, coord=None, flipconv=None, **kwds):
        self.rotator = R.Rotator(rot=rot, coord=None, eulertype="ZYX")
        self.coordsys = R.Rotator(coord=coord).coordout
        self.coordsysstr = R.Rotator(coord=coord).coordoutstr
        self.set_flip(flipconv)
        self.set_proj_plane_info(**kwds)
github healpy / healpy / healpy / rotator.py View on Github external
def __rmul__(self, b):
        if not isinstance(b, Rotator):
            raise TypeError(
                "A Rotator can only be multiplied by another Rotator "
                "(composition of rotations)"
            )
        rots = b._rots + self._rots
        coords = b._coords + self._coords
        invs = self._invs + a._invs
        return Rotator(rot=rots, coord=coords, inv=invs, deg=False)