Entry 14

../_images/entry14.png

Authors

  • Tobias Winchen

The Principal Axes of the Directional Energy Distribution of Ultra-High Energy Cosmic Rays

Earth’s atmosphere is constantly hit by cosmic rays with energies up to \(10^21 \mathrm{eV}\), which is more than 10 000 000 times higher than what can be achieved in current human made particle accelerators. The origin of these ultra-high energy cosmic rays (UHECR) is still unknown, presumably because the charged particles are deflected in cosmic magnetic fields and therefore do not point back to their sources (See e.g. reference [1] for a review).

However, from such deflections energy dependent patterns may arise in the distribution of arrival directions of UHECR that contain informations not only on the sources, but also on the intervening cosmic magnetic fields. These patterns can be characterized by a decomposition of the directional energy distribution along its principal axes in selected ‘regions of interest’ (ROI) in the sky [2, 3]. Of particular interest are here the directions of the second principal axes in the individual regions. These axes are expected to point along the direction of deflection in regular magnetic fields. The distribution of the axes thus may hold information on the structure of the magnetic fields.

The plot displays the simulation of a measurement of the principal axes with the Pierre Auger Observatory, the currently largest experiment dedicated to measurements of UHECR [4]. The sky-map (a) shows the investigated regions as red circles in galactic coordinates using a Hammer projection. Black dots denote the direction of the first principal axes, which point always towards the observer. Black lines denote the direction of the second principal axes which are tangential to the unit sphere. The field-of-view and the relative exposure of the observatory are indicated with purple contours. The bottom row of the figure contains close-ups of selected ROI (b, c, d) in which also the arrival directions of the UHECR in vicinity of the ROI are displayed with color-coded energies.

The local patterns and the resulting large-scale pattern of the principal axes hold information about the magnetic fields and source positions in the simulation. However, in an analysis of data of the Pierre Auger Observatory [5] no significant patterns were found so far, so that a wide range of models for the origin and propagation of UHECR that are similar to the scenario used here can be excluded.

[1] K. Kotera and A. V. Olinto, The Astrophysics of Ultrahigh Energy Cosmic Rays, Annual Review of Astronomy and Astrophysics 49, 119–153, arXiv: 1101.4256 (2011).

[2] M. Erdmann and T. Winchen, Detecting Local Deflection Patterns of Ultra-high Energy Cosmic Rays using the Principal Axes of the Directional Energy Distribution, in Proceedings of the 33rd ICRC, Rio de Janeiro (2013), arXiv: 1307.8273.

[3] T. Winchen, The Principal Axes of the Directional Energy Distribution of Cosmic Rays Measured with the Pierre Auger Observatory, PhD thesis RWTH Aachen University, 2013.

[4] The Pierre Auger Collaboration, The Pierre Auger Cosmic Ray Observatory, Submitted to Nuclear Instruments and Methods (NIM) A (2015).

[5] The Pierre Auger Collaboration, Search for patterns by combining cosmic-ray energy and arrival directions at the Pierre Auger Observatory, Submitted to the European Physical Journal C (EPJ C), arXiv: 1410.0515 (2015).

Products

Source

# 11 Apr 2015, Tobias Winchen

import matplotlib
matplotlib.use('Agg')

matplotlib.rcParams['lines.linewidth'] = 3.0
matplotlib.rcParams['patch.linewidth'] = 3.0
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = 'Computer Modern Sans serif'
matplotlib.rcParams['font.size'] = 20.0
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.unicode'] = True
matplotlib.rcParams['text.latex.preamble'] = '\usepackage{lmodern}, \usepackage{sfmath}'
matplotlib.rcParams['axes.linewidth'] = 2.0
matplotlib.rcParams['axes.labelsize'] = 20
matplotlib.rcParams['xtick.labelsize'] = 20
matplotlib.rcParams['ytick.labelsize'] = 20
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib import path, collections
from math import pi

from SkyMap import SkyMap


def plotROI(roi, uhecrs, ax):
    """
    plots a close-up of the region of interest
    """
    # Basemap coordinates
    lon_0 = roi[0] * 180 / pi
    lat_0 = roi[1] * 180 / pi

    if lon_0 < 0:
        lon_0Constructor = 360 + lon_0
    else:
        lon_0Constructor = lon_0
    lon_0Constructor *= -1

    W = 5500000
    m = Basemap(width=W, height=W, resolution='l', projection='stere',
                lat_0=lat_0, lon_0=lon_0Constructor, celestial=True, ax=ax)

    # plot UHECR
    x, y = m(uhecrs[:, 0] * 180. / pi, uhecrs[:, 1] * 180. / pi)
    s = m.scatter(x, y, s=5**2, c=np.log10(uhecrs[:, 2] * 1E18), lw=0,
                  vmin=18.0, vmax=21, zorder=0, rasterized=True)

    # mark ROI
    t = m.tissot(lon_0, lat_0, .25*180./pi, 10000, fill=False, lw=2, zorder=3)
    xyb = np.array([[0., 0.], [1., 0.], [1., 1.], [0., 1.], [0., 0.]]) * W

    p = path.Path(np.concatenate([xyb, t.get_xy()[::-1]]))
    p.codes = np.ones(len(p.vertices), dtype=p.code_type) * p.LINETO
    p.codes[0] = path.Path.MOVETO
    p.codes[4] = path.Path.CLOSEPOLY
    p.codes[5] = path.Path.MOVETO
    p.codes[-1] = path.Path.CLOSEPOLY
    col = collections.PathCollection([p], facecolor='white', alpha=0.4,
                                     zorder=1)
    ax.add_collection(col)

    # mark the ROI center
    x, y = m(lon_0, lat_0)
    m.plot((x), (y), 'm.', markersize=8)

    # mark the principal axes
    # n2
    u = np.array(np.cos(roi[4]))
    v = -1. * np.array(np.sin(roi[4]))

    urot, vrot, x, y = m.rotate_vector(u, v, roi[2] * 180 / pi, roi[3] * 180 /
                                       pi, returnxy=True)
    alpha = np.arctan2(vrot, urot)
    S = .25 * W
    m.plot([x - np.cos(alpha) * S, x + np.cos(alpha)*S],
           [y - np.sin(alpha) * S, y + np.sin(alpha)*S], c='k')

    # n1
    m.plot((x), (y), 'ko', markersize=6)

    # plot grid
    lab = [False, False, True, False]
    if abs(lat_0) > 60:
        parallels = np.arange(-90, 91, 15)
        meridians = np.arange(-180, 181, 60)
    else:
        parallels = np.arange(-90, 91, 20)
        meridians = np.arange(-180, 181, 20)

    m.drawmeridians(meridians, labels=lab)
    m.drawparallels(parallels, labels=[True, True, False, False])

    # add a colorbar
    cb = m.colorbar(s, location='bottom')
    ticks = np.array([18, 19, 20, 21])
    cb.set_ticks(ticks)
    cb.set_label('Energy [eV]')
    t = ['$10^{%i}$' % (f) for f in ticks]
    cb.ax.set_xticklabels(t)


if __name__ == '__main__':
    fig = plt.figure(figsize=[12.4, 10])
    ax = np.empty(4, dtype=object)
    ax[0] = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=2)
    skyMap = SkyMap(ax=ax[0])

    # plot the full sky map
    # plot the coverage of the Observatory
    coverage = np.loadtxt('Data/coverage.dat')
    lons = np.linspace(-180, 180, coverage.shape[0])
    lats = np.linspace(-90, 90, coverage.shape[1])
    lons, lats = np.meshgrid(lons, lats)
    x, y = skyMap(lons, lats)
    skyMap.contourf(x, y, coverage, levels=(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6,
                    0.7), vmin=0, cmap = plt.cm.Purples, alpha=0.4, vmax=0.7,
                    extend='both')

    # plot regions of interest
    rois = np.loadtxt('Data/allROI.dat')
    for i in range(len(rois)):
        skyMap.tissot(rois[i][0] * 180 / pi, rois[i][1] * 180 / pi, 0.25 / pi *
                      180, 300, lw=0, color='r', zorder=0, alpha=0.2)

    # plot n1
    x, y = skyMap(rois[:, 2] * 180. / pi, rois[:, 3] * 180. / pi)
    skyMap.scatter(x, y)

    # plot n2
    u = np.cos(rois[:, 4])
    v = -1. * np.sin(rois[:, 4])
    urot, vrot, x, y = skyMap.rotate_vector(u, v, rois[:, 2] * 180 / pi,
                                            rois[:, 3] * 180 / pi,
                                            returnxy=True)
    skyMap.quiver(x, y, urot, vrot, pivot='middle', headlength=0.0001,
                  headwidth=1, width=0.005, minlength=1, angles='uv',
                  scale_units='width', scale=4 * pi)

    # plot the selected regions
    uhecrs = np.loadtxt('Data/UHECR.dat')

    ax[1] = plt.subplot2grid((3, 3), (2, 0))
    ax[2] = plt.subplot2grid((3, 3), (2, 1))
    ax[3] = plt.subplot2grid((3, 3), (2, 2))

    roisToShow = [2, 18, 4]

    plotROI(rois[18], uhecrs, ax=ax[2])
    plotROI(rois[4], uhecrs, ax=ax[3])

    # Layout and plot labels
    ax[0].text(0.00, .99, '(a)', transform=ax[0].transAxes,
               verticalalignment='top', horizontalalignment='left')

    for i, a in enumerate(ax[1:]):
        roi = rois[roisToShow[i]]
        plotROI(roi, uhecrs, ax=a)
        s = chr(97 + 1 + i)
        a.text(0.04, .96, '(' + s + ')', transform=a.transAxes,
               verticalalignment='top', horizontalalignment='left')
        x, y = skyMap(roi[0] * 180 / pi, roi[1] * 180 / pi)
        ax[0].annotate(s, (x, y), xytext=(x - 10, y + 5),
                       textcoords='offset points', fontsize=14)

    fig.subplots_adjust(left=0.05, bottom=0.11, right=.94, top=.98, wspace=.14,
                        hspace=.25)

    fig.savefig('principal_axes.pdf', dpi=150)
    fig.savefig('principal_axes.png', dpi=150)
"""
SkyMap based on Basemap allskymap example.

AllSkyMap is a subclass of Basemap, specialized for handling common plotting
tasks for celestial data.

It is essentially equivalent to using Basemap with full-sphere projections
(e.g., 'hammer' or 'moll') and the `celestial` keyword set to `True`, but
it adds a few new methods:

* label_meridians for, well, labeling meridians with their longitude values;

* geodesic, a replacement for Basemap.drawgreatcircle, that can correctly
  handle geodesics that cross the limb of the map, and providing the user
  easy control over clipping (which affects thick lines at or near the limb);
  
* tissot, which overrides Basemap.tissot, correctly handling geodesics that
  cross the limb of the map.

Created Jan 2011 by Tom Loredo, based on Jeff Whitaker's code in Basemap's
__init__.py module.
"""

from numpy import *
import matplotlib.pyplot as pl
from matplotlib.pyplot import *
from mpl_toolkits.basemap import Basemap, pyproj
from mpl_toolkits.basemap.pyproj import Geod

__all__ = ['AllSkyMap', 'SkyMap']

def angle_symbol(angle, round_to=1.0):
    """
    Return a string representing an angle, rounded and with a degree symbol.
    
    This is adapted from code in mpl's projections.geo module.
    """
    value = np.round(angle / round_to) * round_to
    if pl.rcParams['text.usetex'] and not pl.rcParams['text.latex.unicode']:
        return r"$%0.0f^\circ$" % value
    else:
        return u"%0.0f\u00b0" % value


class AllSkyMap(Basemap):
    """
    AllSkyMap is a subclass of Basemap, specialized for handling common plotting
    tasks for celestial data.
    
    It is essentially equivalent to using Basemap with full-sphere projections
    (e.g., 'hammer' or 'moll') and the `celestial` keyword set to `True`, but
    it adds a few new methods:
    
    * label_meridians for, well, labeling meridians with their longitude values;
    
    * geodesic, a replacement for Basemap.drawgreatcircle, that can correctly
      handle geodesics that cross the limb of the map, and providing the user
      easy control over clipping (which affects thick lines at or near the
      limb);
      
    * tissot, which overrides Basemap.tissot, correctly handling geodesics that
      cross the limb of the map.
    """

    # Longitudes corresponding to east and west edges, reflecting the
    # convention that 180 deg is the eastern edge, according to basemap's 
    # underlying projections:
    east_lon = 180.
    west_lon = 180.+1.e-10

    def __init__(self, 
                       projection='hammer',
                       lat_0=0., lon_0=0.,
                       suppress_ticks=True,
                       boundinglat=None,
                       fix_aspect=True,
                       anchor='C',
                       ax=None):

        if projection != 'hammer' and projection !='moll':
            raise ValueError('Only hammer and moll projections supported!')

        # Use Basemap's init, enforcing the values of many parameters that
        # aren't used or whose Basemap defaults would not be altered for all-sky
        # celestial maps.
        Basemap.__init__(self, llcrnrlon=None, llcrnrlat=None,
                       urcrnrlon=None, urcrnrlat=None,
                       llcrnrx=None, llcrnry=None,
                       urcrnrx=None, urcrnry=None,
                       width=None, height=None,
                       projection=projection, resolution=None,
                       area_thresh=None, rsphere=1.,
                       lat_ts=None,
                       lat_1=None, lat_2=None,
                       lat_0=lat_0, lon_0=lon_0,
                       suppress_ticks=suppress_ticks,
                       satellite_height=1.,
                       boundinglat=None,
                       fix_aspect=True,
                       anchor=anchor,
                       celestial=True,
                       ax=ax)

        # Keep a local ref to lon_0 for hemisphere checking.
        self._lon_0 = self.projparams['lon_0']
        self._limb = None

    def drawmapboundary(self,color='k',linewidth=1.0,fill_color=None,\
                        zorder=None,ax=None):
        """
        draw boundary around map projection region, optionally
        filling interior of region.

        .. tabularcolumns:: |l|L|

        ==============   ====================================================
        Keyword          Description
        ==============   ====================================================
        linewidth        line width for boundary (default 1.)
        color            color of boundary line (default black)
        fill_color       fill the map region background with this
                         color (default is no fill or fill with axis
                         background color).
        zorder           sets the zorder for filling map background
                         (default 0).
        ax               axes instance to use
                         (default None, use default axes instance).
        ==============   ====================================================

        returns matplotlib.collections.PatchCollection representing map boundary.
        """
        # Just call the base class version, but keep a copy of the limb
        # polygon for clipping.
        self._limb = Basemap.drawmapboundary(self, color=color,
            linewidth=linewidth, fill_color=fill_color, zorder=zorder, ax=ax)
        return self._limb

    def label_meridians(self, lons, fontsize=22, valign='bottom',
        vnudge=1, halign='center', hnudge=-3):
        """
        Label meridians with their longitude values in degrees.
        
        This labels meridians with negative longitude l with the value 360-l;
        for maps in celestial orientation, this means meridians to the right
        of the central meridian are labeled from 360 to 180 (left to right).
        
        `vnudge` and `hnudge` specify amounts in degress to nudge the labels
        from their default placements, vertically and horizontally.  This
        values obey the map orientation, so to nudge to the right, use a
        negative `hnudge` value.
        """
        # Run through (lon, lat) pairs, with lat=0 in each pair.
        lats = len(lons)*[0.]
        x0, y0 = self(0, 0)
        x1, y1 = self(hnudge, vnudge)
        dx = x1-x0
        dy = y1-y0
        for lon,lat in zip(lons, lats):
            x, y = self(lon, lat)
            lon_lbl = lon
            pl.text(x+dx, y+dy, angle_symbol(lon_lbl), fontsize=fontsize,
                    verticalalignment=valign,
                    horizontalalignment=halign)

    def east_hem(self, lon):
        """
        Return True if lon is in the eastern hemisphere of the map wrt lon_0.
        """
        if (lon-self._lon_0) % 360. <= self.east_lon:
            return True
        else:
            return False

    def geodesic(self, lon1, lat1, lon2, lat2, del_s=.01, clip=True, **kwargs):
        """
        Plot a geodesic curve from (lon1, lat1) to (lon2, lat2), with
        points separated by arc length del_s.  Return a list of Line2D
        instances for the curves comprising the geodesic.  If the geodesic does
        not cross the map limb, there will be only a single curve; if it
        crosses the limb, there will be two curves.
        """
        
        # TODO:  Perhaps return a single Line2D instance when there is only a
        # single segment, and a list of segments only when there are two segs?

        # TODO:  Check the units of del_s.
        
        # This is based on Basemap.drawgreatcircle (which draws an *arc* of a
        # great circle), but addresses a limitation of that method, supporting
        # geodesics that cross the map boundary by breaking them into two
        # segments, one in the eastern hemisphere and the other in the western.
        gc = pyproj.Geod(a=self.rmajor,b=self.rminor)
        az12,az21,dist = gc.inv(lon1,lat1,lon2,lat2)
        npoints = int((dist+0.5**del_s)/del_s)
        # Calculate lon & lat for points on the arc.
        lonlats = gc.npts(lon1,lat1,lon2,lat2,npoints)
        lons = [lon1]; lats = [lat1]
        for lon, lat in lonlats:
            lons.append(lon)
            lats.append(lat)
        lons.append(lon2); lats.append(lat2)
        # Break the arc into segments as needed, when there is a longitudinal
        # hemisphere crossing.
        segs = []
        seg_lons, seg_lats = [lon1], [lat1]
        cur_hem = self.east_hem(lon1)
        for lon, lat in zip(lons[1:], lats[1:]):
            if self.east_hem(lon) == cur_hem:
                seg_lons.append(lon)
                seg_lats.append(lat)
            else:
                # We should interpolate a new pt at the boundary, but in
                # the mean time just rely on the step size being small.
                segs.append( (seg_lons, seg_lats) )
                seg_lons, seg_lats = [lon], [lat]
                cur_hem = not cur_hem
        segs.append( (seg_lons, seg_lats) )
        # Plot each segment; return a list of the mpl lines.
        lines = []
        for lons, lats in segs:
            x, y = self(lons, lats)
            if clip and self._limb:
                line = plot(x, y, clip_path=self._limb, **kwargs)[0]
            else:
                line = plot(x, y, **kwargs)[0]
            lines.append(line)
        # If there are multiple segments and no color args, reconcile the
        # colors, which mpl will have autoset to different values.
        # *** Does this screw up mpl's color set sequence for later lines?
        if not kwargs.has_key('c') or kwargs.has_key('color'):
            if len(lines) > 1:
                c1 = lines[0].get_color()
                for line in lines[1:]:
                    line.set_color(c1)
        return lines

    def tissot(self,lon_0,lat_0,radius_deg,npts,ax=None,**kwargs):
        """
        Draw a polygon centered at ``lon_0,lat_0``.  The polygon
        approximates a circle on the surface of the earth with radius
        ``radius_deg`` degrees latitude along longitude ``lon_0``,
        made up of ``npts`` vertices.
        
        The polygon represents a Tissot's indicatrix
        (http://en.wikipedia.org/wiki/Tissot's_Indicatrix),
        which when drawn on a map shows the distortion inherent in the map
        projection.  Tissots can be used to display azimuthally symmetric
        directional uncertainties ("error circles").

        Extra keyword ``ax`` can be used to override the default axis instance.

        Other \**kwargs passed on to matplotlib.patches.Polygon.

        returns a list of matplotlib.patches.Polygon objects, with two polygons
        when the tissot crosses the limb, and just one polygon otherwise.
        """

        #only use modified version if we are in a critical region
        if (abs(lon_0) < radius_deg*2) and (abs(lat_0) + radius_deg <90):
          return Basemap.tissot(self,lon_0,lat_0,radius_deg,npts,ax=None,**kwargs)

        # TODO:  Just return the polygon (not a list) when there is only one
        # polygon?  Or stick with the list for consistency?

        # This is based on Basemap.tissot, but addresses a limitation of that
        # method by handling tissots that cross the limb of the map by finding
        # separate polygons in the eastern and western hemispheres comprising
        # the tissot.
        ax = kwargs.pop('ax', None) or self._check_ax()
        g = pyproj.Geod(a=self.rmajor,b=self.rminor)

        if lat_0 + radius_deg < 90:
          az12,az21,dist = g.inv(lon_0,lat_0,lon_0,lat_0+radius_deg)
        else:
          az12,az21,dist = g.inv(lon_0,lat_0,lon_0,lat_0-radius_deg)
        
        start_hem = self.east_hem(lon_0)
        segs1 = [self(lon_0,lat_0+radius_deg)]
        over, segs2 = [], []
        delaz = 360./npts
        az = az12
        last_lon = lon_0
        
        #handling of the poles
        if (abs(lat_0) + radius_deg >= 90 ):
            # Use half of the points for the part inside the map, the
            # other half of the points is at the map border
            lats = zeros(npts/2)
            lons = zeros(npts/2)
            for n in range(npts/2):
              az = az+delaz *2
              lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist)
              lons[n] = lon
              lats[n] = lat

            a = list(argsort(lons))
            lons = lons[a]
            lats = lats[a]
            x1,y1 = self(lons, lats)

            # Half of the remaining points are used on eastern and
            # western hemisphere.
            N = npts/4
            segs = []
            dL = (90-abs(lats[0]))/ (N-1)
            r = range(N)

            # For the south-pole the order of points is changed to plot
            # the correct polygon
            if lat_0 < 0:
              r.reverse()
              segs.extend(zip(x1,y1))
            #First Half of the map border
            x, y = self(-180 * sign(lat_0) *ones(N) , sign(lat_0)* (90 - array(r)* dL) )
            segs.extend(zip(x,y))

            if lat_0 > 0:
              segs.extend(zip(x1,y1))

            #Second half of the map border
            r.reverse()
            x, y = self(180 * sign(lat_0) *ones(N) , sign(lat_0)* (90 - array(r)* dL) )
            segs.extend(zip(x,y))

            #z = array(segs)
            #self.plot(z[:,0], z[:,1])
            poly = Polygon(segs, **kwargs)
            ax.add_patch(poly)
            return [poly]


        # Note adjacent and opposite edge longitudes, in case the tissot
        # runs over the edge.
        if start_hem:  # eastern case
            adj_lon = self.east_lon
            opp_lon = self.west_lon
        else:
            adj_lon = self.west_lon
            opp_lon = self.east_lon
        for n in range(npts):
            az = az+delaz
            # skip segments along equator (Geod can't handle equatorial arcs)
            if np.allclose(0.,lat_0) and (np.allclose(90.,az) or np.allclose(270.,az)):
                continue
            else:
                lon, lat, az21 = g.fwd(lon_0, lat_0, az, dist)
            # If in the starting hemisphere, add to 1st polygon seg list.
            if self.east_hem(lon) == start_hem:
                x, y = self(lon, lat)
                # Add segment if it is in the map projection region.
                if x < 1.e20 and y < 1.e20:
                    segs1.append( (x, y) )
                    last_lon = lon
            # Otherwise, we cross hemispheres.
            else:
                # Trace the edge of each hemisphere.
                x, y = self(adj_lon, lat)
                if x < 1.e20 and y < 1.e20:
                    segs1.append( (x, y) )
                    # We presume if adj projection is okay, opposite is.
                    segs2.append( self(opp_lon, lat) )
                # Also store the overlap in the opposite hemisphere.
                x, y = self(lon, lat)
                if x < 1.e20 and y < 1.e20:
                    over.append( (x, y) )
                    last_lon = lon
        poly1 = Polygon(segs1, **kwargs)
        ax.add_patch(poly1)
        if segs2:
            over.reverse()
            segs2.extend(over)
            poly2 = Polygon(segs2, **kwargs)
            ax.add_patch(poly2)
            return [poly1, poly2]
        else:
            return [poly1]

    def plotDataArray(self,data, **kwargs):
      """Uses pcolormesh to draw the 2d array on the map. this assumes
      that the array data is defined in equally spaced angular bins on
      the whole map. Additional keyword arguments are passed to
      pcolomesh"""
      nx, ny = data.shape
      lons = linspace(-180,180, nx)
      lats = linspace(-90,90, ny)
      lons, lats = meshgrid(lons, lats)
      X,Y = self(lons, lats)
      self.pcolormesh(X,Y, data.transpose(), **kwargs)


def SkyMap(**kwargs):
  """
  returns AllSkyMap with many preset parameters.
  """
  m = AllSkyMap(**kwargs)
  m.drawmapboundary(fill_color='white')
  m.drawparallels(np.arange(-75,76,15), linewidth=0.5, dashes=[1,2],
      labels=[1,0,0,0])
  m.drawmeridians(np.arange(-180,181,60), linewidth=0.5, dashes=[1,2])

  # Label a subset of meridians.
  lons = np.arange(-180,181,60)
  m.label_meridians(lons,  vnudge=1,
                  halign='left', hnudge=-3)  # hnudge<0 shifts to right
  return m

if __name__ == '__main__':

    # Note that Hammer & Mollweide projections enforce a 2:1 aspect ratio.
    # Use figure size good for a 2:1 plot.
    fig = figure(figsize=(12,6))
    
    # Set up the projection and draw a grid.
    #map = AllSkyMap(projection='hammer')
    map = SkyMap(projection='moll')
    # Save the bounding limb to use as a clip path later.
    limb = map.drawmapboundary(fill_color='white')
    map.drawparallels(np.arange(-75,76,15), linewidth=0.5, dashes=[1,2],
        labels=[1,0,0,0], fontsize=22)
    map.drawmeridians(np.arange(-150,151,30), linewidth=0.5, dashes=[1,2])
    
    # Label a subset of meridians.
    lons = np.arange(-150,151,30)
    map.label_meridians(lons, fontsize=22, vnudge=1,
                    halign='left', hnudge=-1)  # hnudge<0 shifts to right
    
    # x, y limits are [0, 4*rt2], [0, 2*rt2].
    rt2 = sqrt(2)

    # Draw a slanted green line crossing the map limb.
    line = plot([rt2,0], [rt2,2*rt2], 'g-')

    # Draw a slanted magenta line crossing the map limb but clipped.
    line = plot([rt2+.1,0+.1], [rt2,2*rt2], 'm-', clip_path=limb)
    
    # Draw some geodesics.
    # First a transparent thick blue geodesic crossing the limb but not clipped,
    # overlayed by a thinner red geodesic that is clipped (by default), to
    # illustrate the effect of clipping.
    lines = map.geodesic(120, 30, 240, 60, clip=False, c='b', lw=7, alpha=.5)
    lines = map.geodesic(240, 60, 120, 30, c='r', lw=3, alpha=.5)

    # Next two large limb-crossing geodesics with the same path, but rendered
    # in opposite directions, one transparent blue, the other transparent
    # yellow.  They should be right on top of each other, giving a greenish
    # brown hue.
    lines = map.geodesic(240, -60, 120, 30, c='b', lw=2, alpha=.5)
    lines = map.geodesic(120, 30, 240, -60, c='y', lw=2, alpha=.5)

    # What happens if a geodesic is given coordinates spanning more than
    # a single rotation?  Not sure what to expect, but it shoots off the
    # map (clipped here).  Perhaps we should ensure lons are in [0, 360].
    #lines = map.geodesic(120, 20, 240+360, 50, del_s=.2, c='g')
    
    # Two tissots fully within the limb.
    poly = map.tissot(60, -15, 10, 100)
    poly = map.tissot(280, 60, 10, 100)
    #poly = map.tissot(90, -85, 10, 100)
    
    # Limb-spanning tissots in each quadrant.
    # lower left:
    poly = map.tissot(170, -60, 15, 100)
    # upper left:
    poly = map.tissot(175, 70, 15, 100)
    # upper right (note negative longitude):
    poly = map.tissot(-175, 30, 15, 100, color='r', alpha=.6)
    # lower right:
    poly = map.tissot(185, -40, 10, 100)
    
    #poly = map.tissot(-180, -60, 10, 100)

    a,b = -0.951060608587,-2.8631983937
    poly = map.tissot(b*180/pi,a*180/pi ,  0.25/pi*180,300, color='r')
    

    #center 
    poly = map.tissot(0, 0, 10, 100, lw=1, color='m')
    poly = map.tissot(0, -30, 10, 100, lw=1, color='m')

    # poles
    poly = map.tissot(120, -83, 10, 100, lw=1, color='m')
    poly = map.tissot(-120, 84, 10, 100, lw=1, color='m')

    # Plot the tissot centers as "+" symbols.  Note the top left symbol
    # would cross the limb without the clip_path argument; this might be
    # desired to enhance visibility.
    lons = [170, 175, -175, 185]
    lats = [-60, 70, 30, -40]
    x, y = map(lons, lats)
    map.scatter(x, y, s=40, marker='+', linewidths=1, edgecolors='g',
        facecolors='none', clip_path=limb, zorder=10)  # hi zorder -> top
    
    title('AllSkyMap demo:  Clipped lines, markers, geodesics, tissots')
    show()

Table Of Contents

Previous topic

Entry 13

Next topic

Entry 15

This Page