{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Custom projection\n\nShowcase Hammer projection by alleviating many features of Matplotlib.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import numpy as np\n\nimport matplotlib\nfrom matplotlib.axes import Axes\nimport matplotlib.axis as maxis\nfrom matplotlib.patches import Circle\nfrom matplotlib.path import Path\nfrom matplotlib.projections import register_projection\nimport matplotlib.spines as mspines\nfrom matplotlib.ticker import FixedLocator, Formatter, NullLocator\nfrom matplotlib.transforms import Affine2D, BboxTransformTo, Transform\n\nrcParams = matplotlib.rcParams\n\n# This example projection class is rather long, but it is designed to\n# illustrate many features, not all of which will be used every time.\n# It is also common to factor out a lot of these methods into common\n# code used by a number of projections with similar characteristics\n# (see geo.py).\n\n\nclass GeoAxes(Axes):\n    \"\"\"\n    An abstract base class for geographic projections\n    \"\"\"\n    class ThetaFormatter(Formatter):\n        \"\"\"\n        Used to format the theta tick labels.  Converts the native\n        unit of radians into degrees and adds a degree symbol.\n        \"\"\"\n        def __init__(self, round_to=1.0):\n            self._round_to = round_to\n\n        def __call__(self, x, pos=None):\n            degrees = round(np.rad2deg(x) / self._round_to) * self._round_to\n            return f\"{degrees:0.0f}\\N{DEGREE SIGN}\"\n\n    RESOLUTION = 75\n\n    def _init_axis(self):\n        self.xaxis = maxis.XAxis(self)\n        self.yaxis = maxis.YAxis(self)\n        # Do not register xaxis or yaxis with spines -- as done in\n        # Axes._init_axis() -- until GeoAxes.xaxis.clear() works.\n        # self.spines['geo'].register_axis(self.yaxis)\n\n    def clear(self):\n        # docstring inherited\n        super().clear()\n\n        self.set_longitude_grid(30)\n        self.set_latitude_grid(15)\n        self.set_longitude_grid_ends(75)\n        self.xaxis.set_minor_locator(NullLocator())\n        self.yaxis.set_minor_locator(NullLocator())\n        self.xaxis.set_ticks_position('none')\n        self.yaxis.set_ticks_position('none')\n        self.yaxis.set_tick_params(label1On=True)\n        # Why do we need to turn on yaxis tick labels, but\n        # xaxis tick labels are already on?\n\n        self.grid(rcParams['axes.grid'])\n\n        Axes.set_xlim(self, -np.pi, np.pi)\n        Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)\n\n    def _set_lim_and_transforms(self):\n        # A (possibly non-linear) projection on the (already scaled) data\n\n        # There are three important coordinate spaces going on here:\n        #\n        # 1. Data space: The space of the data itself\n        #\n        # 2. Axes space: The unit rectangle (0, 0) to (1, 1)\n        #    covering the entire plot area.\n        #\n        # 3. Display space: The coordinates of the resulting image,\n        #    often in pixels or dpi/inch.\n\n        # This function makes heavy use of the Transform classes in\n        # ``lib/matplotlib/transforms.py.`` For more information, see\n        # the inline documentation there.\n\n        # The goal of the first two transformations is to get from the\n        # data space (in this case longitude and latitude) to Axes\n        # space.  It is separated into a non-affine and affine part so\n        # that the non-affine part does not have to be recomputed when\n        # a simple affine change to the figure has been made (such as\n        # resizing the window or changing the dpi).\n\n        # 1) The core transformation from data space into\n        # rectilinear space defined in the HammerTransform class.\n        self.transProjection = self._get_core_transform(self.RESOLUTION)\n\n        # 2) The above has an output range that is not in the unit\n        # rectangle, so scale and translate it so it fits correctly\n        # within the Axes.  The peculiar calculations of xscale and\n        # yscale are specific to an Aitoff-Hammer projection, so don't\n        # worry about them too much.\n        self.transAffine = self._get_affine_transform()\n\n        # 3) This is the transformation from Axes space to display\n        # space.\n        self.transAxes = BboxTransformTo(self.bbox)\n\n        # Now put these 3 transforms together -- from data all the way\n        # to display coordinates.  Using the '+' operator, these\n        # transforms will be applied \"in order\".  The transforms are\n        # automatically simplified, if possible, by the underlying\n        # transformation framework.\n        self.transData = \\\n            self.transProjection + \\\n            self.transAffine + \\\n            self.transAxes\n\n        # The main data transformation is set up.  Now deal with\n        # gridlines and tick labels.\n\n        # Longitude gridlines and ticklabels.  The input to these\n        # transforms are in display space in x and Axes space in y.\n        # Therefore, the input values will be in range (-xmin, 0),\n        # (xmax, 1).  The goal of these transforms is to go from that\n        # space to display space.  The tick labels will be offset 4\n        # pixels from the equator.\n        self._xaxis_pretransform = \\\n            Affine2D() \\\n            .scale(1.0, self._longitude_cap * 2.0) \\\n            .translate(0.0, -self._longitude_cap)\n        self._xaxis_transform = \\\n            self._xaxis_pretransform + \\\n            self.transData\n        self._xaxis_text1_transform = \\\n            Affine2D().scale(1.0, 0.0) + \\\n            self.transData + \\\n            Affine2D().translate(0.0, 4.0)\n        self._xaxis_text2_transform = \\\n            Affine2D().scale(1.0, 0.0) + \\\n            self.transData + \\\n            Affine2D().translate(0.0, -4.0)\n\n        # Now set up the transforms for the latitude ticks.  The input to\n        # these transforms are in Axes space in x and display space in\n        # y.  Therefore, the input values will be in range (0, -ymin),\n        # (1, ymax).  The goal of these transforms is to go from that\n        # space to display space.  The tick labels will be offset 4\n        # pixels from the edge of the Axes ellipse.\n        yaxis_stretch = Affine2D().scale(np.pi*2, 1).translate(-np.pi, 0)\n        yaxis_space = Affine2D().scale(1.0, 1.1)\n        self._yaxis_transform = \\\n            yaxis_stretch + \\\n            self.transData\n        yaxis_text_base = \\\n            yaxis_stretch + \\\n            self.transProjection + \\\n            (yaxis_space +\n             self.transAffine +\n             self.transAxes)\n        self._yaxis_text1_transform = \\\n            yaxis_text_base + \\\n            Affine2D().translate(-8.0, 0.0)\n        self._yaxis_text2_transform = \\\n            yaxis_text_base + \\\n            Affine2D().translate(8.0, 0.0)\n\n    def _get_affine_transform(self):\n        transform = self._get_core_transform(1)\n        xscale, _ = transform.transform((np.pi, 0))\n        _, yscale = transform.transform((0, np.pi/2))\n        return Affine2D() \\\n            .scale(0.5 / xscale, 0.5 / yscale) \\\n            .translate(0.5, 0.5)\n\n    def get_xaxis_transform(self, which='grid'):\n        \"\"\"\n        Override this method to provide a transformation for the\n        x-axis tick labels.\n\n        Returns a tuple of the form (transform, valign, halign)\n        \"\"\"\n        if which not in ['tick1', 'tick2', 'grid']:\n            raise ValueError(\n                \"'which' must be one of 'tick1', 'tick2', or 'grid'\")\n        return self._xaxis_transform\n\n    def get_xaxis_text1_transform(self, pad):\n        return self._xaxis_text1_transform, 'bottom', 'center'\n\n    def get_xaxis_text2_transform(self, pad):\n        \"\"\"\n        Override this method to provide a transformation for the\n        secondary x-axis tick labels.\n\n        Returns a tuple of the form (transform, valign, halign)\n        \"\"\"\n        return self._xaxis_text2_transform, 'top', 'center'\n\n    def get_yaxis_transform(self, which='grid'):\n        \"\"\"\n        Override this method to provide a transformation for the\n        y-axis grid and ticks.\n        \"\"\"\n        if which not in ['tick1', 'tick2', 'grid']:\n            raise ValueError(\n                \"'which' must be one of 'tick1', 'tick2', or 'grid'\")\n        return self._yaxis_transform\n\n    def get_yaxis_text1_transform(self, pad):\n        \"\"\"\n        Override this method to provide a transformation for the\n        y-axis tick labels.\n\n        Returns a tuple of the form (transform, valign, halign)\n        \"\"\"\n        return self._yaxis_text1_transform, 'center', 'right'\n\n    def get_yaxis_text2_transform(self, pad):\n        \"\"\"\n        Override this method to provide a transformation for the\n        secondary y-axis tick labels.\n\n        Returns a tuple of the form (transform, valign, halign)\n        \"\"\"\n        return self._yaxis_text2_transform, 'center', 'left'\n\n    def _gen_axes_patch(self):\n        \"\"\"\n        Override this method to define the shape that is used for the\n        background of the plot.  It should be a subclass of Patch.\n\n        In this case, it is a Circle (that may be warped by the Axes\n        transform into an ellipse).  Any data and gridlines will be\n        clipped to this shape.\n        \"\"\"\n        return Circle((0.5, 0.5), 0.5)\n\n    def _gen_axes_spines(self):\n        return {'geo': mspines.Spine.circular_spine(self, (0.5, 0.5), 0.5)}\n\n    def set_yscale(self, *args, **kwargs):\n        if args[0] != 'linear':\n            raise NotImplementedError\n\n    # Prevent the user from applying scales to one or both of the\n    # axes.  In this particular case, scaling the axes wouldn't make\n    # sense, so we don't allow it.\n    set_xscale = set_yscale\n\n    # Prevent the user from changing the axes limits.  In our case, we\n    # want to display the whole sphere all the time, so we override\n    # set_xlim and set_ylim to ignore any input.  This also applies to\n    # interactive panning and zooming in the GUI interfaces.\n    def set_xlim(self, *args, **kwargs):\n        raise TypeError(\"Changing axes limits of a geographic projection is \"\n                        \"not supported.  Please consider using Cartopy.\")\n\n    set_ylim = set_xlim\n\n    def format_coord(self, lon, lat):\n        \"\"\"\n        Override this method to change how the values are displayed in\n        the status bar.\n\n        In this case, we want them to be displayed in degrees N/S/E/W.\n        \"\"\"\n        lon, lat = np.rad2deg([lon, lat])\n        ns = 'N' if lat >= 0.0 else 'S'\n        ew = 'E' if lon >= 0.0 else 'W'\n        return ('%f\\N{DEGREE SIGN}%s, %f\\N{DEGREE SIGN}%s'\n                % (abs(lat), ns, abs(lon), ew))\n\n    def set_longitude_grid(self, degrees):\n        \"\"\"\n        Set the number of degrees between each longitude grid.\n\n        This is an example method that is specific to this projection\n        class -- it provides a more convenient interface to set the\n        ticking than set_xticks would.\n        \"\"\"\n        # Skip -180 and 180, which are the fixed limits.\n        grid = np.arange(-180 + degrees, 180, degrees)\n        self.xaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n        self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n    def set_latitude_grid(self, degrees):\n        \"\"\"\n        Set the number of degrees between each longitude grid.\n\n        This is an example method that is specific to this projection\n        class -- it provides a more convenient interface than\n        set_yticks would.\n        \"\"\"\n        # Skip -90 and 90, which are the fixed limits.\n        grid = np.arange(-90 + degrees, 90, degrees)\n        self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))\n        self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))\n\n    def set_longitude_grid_ends(self, degrees):\n        \"\"\"\n        Set the latitude(s) at which to stop drawing the longitude grids.\n\n        Often, in geographic projections, you wouldn't want to draw\n        longitude gridlines near the poles.  This allows the user to\n        specify the degree at which to stop drawing longitude grids.\n\n        This is an example method that is specific to this projection\n        class -- it provides an interface to something that has no\n        analogy in the base Axes class.\n        \"\"\"\n        self._longitude_cap = np.deg2rad(degrees)\n        self._xaxis_pretransform \\\n            .clear() \\\n            .scale(1.0, self._longitude_cap * 2.0) \\\n            .translate(0.0, -self._longitude_cap)\n\n    def get_data_ratio(self):\n        \"\"\"\n        Return the aspect ratio of the data itself.\n\n        This method should be overridden by any Axes that have a\n        fixed data ratio.\n        \"\"\"\n        return 1.0\n\n    # Interactive panning and zooming is not supported with this projection,\n    # so we override all of the following methods to disable it.\n    def can_zoom(self):\n        \"\"\"\n        Return whether this Axes supports the zoom box button functionality.\n\n        This Axes object does not support interactive zoom box.\n        \"\"\"\n        return False\n\n    def can_pan(self):\n        \"\"\"\n        Return whether this Axes supports the pan/zoom button functionality.\n\n        This Axes object does not support interactive pan/zoom.\n        \"\"\"\n        return False\n\n    def start_pan(self, x, y, button):\n        pass\n\n    def end_pan(self):\n        pass\n\n    def drag_pan(self, button, key, x, y):\n        pass\n\n\nclass HammerAxes(GeoAxes):\n    \"\"\"\n    A custom class for the Aitoff-Hammer projection, an equal-area map\n    projection.\n\n    https://en.wikipedia.org/wiki/Hammer_projection\n    \"\"\"\n\n    # The projection must specify a name. This will be used by the\n    # user to select the projection,\n    # i.e. ``subplot(projection='custom_hammer')``.\n    name = 'custom_hammer'\n\n    class HammerTransform(Transform):\n        \"\"\"The base Hammer transform.\"\"\"\n        input_dims = output_dims = 2\n\n        def __init__(self, resolution):\n            \"\"\"\n            Create a new Hammer transform.  Resolution is the number of steps\n            to interpolate between each input line segment to approximate its\n            path in curved Hammer space.\n            \"\"\"\n            Transform.__init__(self)\n            self._resolution = resolution\n\n        def transform_non_affine(self, ll):\n            longitude, latitude = ll.T\n\n            # Pre-compute some values\n            half_long = longitude / 2\n            cos_latitude = np.cos(latitude)\n            sqrt2 = np.sqrt(2)\n\n            alpha = np.sqrt(1 + cos_latitude * np.cos(half_long))\n            x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha\n            y = (sqrt2 * np.sin(latitude)) / alpha\n            return np.column_stack([x, y])\n\n        def transform_path_non_affine(self, path):\n            # vertices = path.vertices\n            ipath = path.interpolated(self._resolution)\n            return Path(self.transform(ipath.vertices), ipath.codes)\n\n        def inverted(self):\n            return HammerAxes.InvertedHammerTransform(self._resolution)\n\n    class InvertedHammerTransform(Transform):\n        input_dims = output_dims = 2\n\n        def __init__(self, resolution):\n            Transform.__init__(self)\n            self._resolution = resolution\n\n        def transform_non_affine(self, xy):\n            x, y = xy.T\n            z = np.sqrt(1 - (x / 4) ** 2 - (y / 2) ** 2)\n            longitude = 2 * np.arctan((z * x) / (2 * (2 * z ** 2 - 1)))\n            latitude = np.arcsin(y*z)\n            return np.column_stack([longitude, latitude])\n\n        def inverted(self):\n            return HammerAxes.HammerTransform(self._resolution)\n\n    def __init__(self, *args, **kwargs):\n        self._longitude_cap = np.pi / 2.0\n        super().__init__(*args, **kwargs)\n        self.set_aspect(0.5, adjustable='box', anchor='C')\n        self.clear()\n\n    def _get_core_transform(self, resolution):\n        return self.HammerTransform(resolution)\n\n\n# Now register the projection with Matplotlib so the user can select it.\nregister_projection(HammerAxes)\n\n\nif __name__ == '__main__':\n    import matplotlib.pyplot as plt\n\n    # Now make a simple example using the custom projection.\n    fig, ax = plt.subplots(subplot_kw={'projection': 'custom_hammer'})\n    ax.plot([-1, 1, 1], [-1, -1, 1], \"o-\")\n    ax.grid()\n\n    plt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}