File: make_projection.py

package info (click to toggle)
python-cartopy 0.17.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,320 kB
  • sloc: python: 14,779; cpp: 545; makefile: 157
file content (195 lines) | stat: -rw-r--r-- 6,210 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# (C) British Crown Copyright 2011 - 2018, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cartopy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with cartopy.  If not, see <https://www.gnu.org/licenses/>.

from __future__ import (absolute_import, division, print_function)
import os
import inspect
import textwrap
import numpy as np
import cartopy.crs as ccrs

#: A dictionary to allow examples to use non-default parameters to the CRS
#: constructor.
SPECIFIC_PROJECTION_KWARGS = {
    ccrs.RotatedPole: {'pole_longitude': 177.5, 'pole_latitude': 37.5},
    ccrs.AzimuthalEquidistant: {'central_latitude': 90},
    ccrs.NearsidePerspective: {
        'central_longitude': -3.53, 'central_latitude': 50.72,
        'satellite_height': 10.0e6},
}


def plate_carree_plot():
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs

    nplots = 2

    fig = plt.figure(figsize=(6, 6))

    for i in range(0, nplots):
        central_longitude = 0 if i == 0 else 180
        ax = fig.add_subplot(
            nplots, 1, i+1,
            projection=ccrs.PlateCarree(central_longitude=central_longitude))
        ax.coastlines(resolution='110m')
        ax.gridlines()


def utm_plot():
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs

    nplots = 60

    fig = plt.figure(figsize=(10, 3))

    for i in range(0, nplots):
        ax = fig.add_subplot(1, nplots, i+1,
                             projection=ccrs.UTM(zone=i+1,
                                                 southern_hemisphere=True))
        ax.coastlines(resolution='110m')
        ax.gridlines()


MULTI_PLOT_CASES = {
    ccrs.PlateCarree: plate_carree_plot,
    ccrs.UTM: utm_plot,
}


COASTLINE_RESOLUTION = {ccrs.OSNI: '10m',
                        ccrs.OSGB: '50m',
                        ccrs.EuroPP: '50m'}


PRJ_SORT_ORDER = {'PlateCarree': 1,
                  'Mercator': 2, 'Mollweide': 2, 'Robinson': 2,
                  'TransverseMercator': 2, 'LambertCylindrical': 2,
                  'LambertConformal': 2, 'EquidistantConic': 2,
                  'Stereographic': 2, 'Miller': 2,
                  'Orthographic': 2, 'UTM': 2, 'AlbersEqualArea': 2,
                  'AzimuthalEquidistant': 2, 'Sinusoidal': 2,
                  'InterruptedGoodeHomolosine': 3, 'RotatedPole': 3,
                  'OSGB': 4, 'EuroPP': 5,
                  'Geostationary': 6, 'NearsidePerspective': 7,
                  'EckertI': 8.1, 'EckertII': 8.2, 'EckertIII': 8.3,
                  'EckertIV': 8.4, 'EckertV': 8.5, 'EckertVI': 8.6}


def find_projections():
    for obj_name, o in vars(ccrs).copy().items():
        if isinstance(o, type) and issubclass(o, ccrs.Projection) and \
           not obj_name.startswith('_') and obj_name not in ['Projection']:

            yield o


def create_instance(prj_cls, instance_args):
    name = prj_cls.__name__

    # Format instance arguments into strings
    instance_params = ',\n                            '.join(
        '{}={}'.format(k, v)
        for k, v in sorted(instance_args.items()))

    if instance_params:
        instance_params = '\n                            ' \
                          + instance_params

    instance_creation_code = '{}({})'.format(name, instance_params)

    prj_inst = prj(**instance_args)

    return prj_inst, instance_creation_code


if __name__ == '__main__':
    fname = os.path.join(os.path.dirname(__file__), 'source',
                         'crs', 'projections.rst')
    table = open(fname, 'w')

    notes = """
        .. (comment): DO NOT EDIT this file.
        .. It is auto-generated by running : cartopy/docs/make_projection.py
        .. Please adjust by making changes there.
        .. It is included in the repository only to aid detection of changes.

        .. _cartopy_projections:

        Cartopy projection list
        =======================

        """
    table.write(textwrap.dedent(notes))

    def prj_class_sorter(cls):
        return (PRJ_SORT_ORDER.get(cls.__name__, 100),
                cls.__name__)

    for prj in sorted(find_projections(), key=prj_class_sorter):
        name = prj.__name__

        table.write(name + '\n')
        table.write('-' * len(name) + '\n\n')

        table.write('.. autoclass:: cartopy.crs.%s\n' % name)

        if prj not in MULTI_PLOT_CASES:
            # Get instance arguments and number of plots
            instance_args = SPECIFIC_PROJECTION_KWARGS.get(prj, {})

            prj_inst, instance_repr = create_instance(prj, instance_args)

            aspect = (np.diff(prj_inst.x_limits) /
                      np.diff(prj_inst.y_limits))[0]

            width = 3 * aspect
            width = '{:.4f}'.format(width).rstrip('0').rstrip('.')

            # Generate plotting code
            code = textwrap.dedent("""
            .. plot::

                import matplotlib.pyplot as plt
                import cartopy.crs as ccrs

                plt.figure(figsize=({width}, 3))
                ax = plt.axes(projection=ccrs.{proj_constructor})
                ax.coastlines(resolution={coastline_resolution!r})
                ax.gridlines()


            """).format(width=width,
                        proj_constructor=instance_repr,
                        coastline_resolution=COASTLINE_RESOLUTION.get(prj,
                                                                      '110m'))

        else:
            func = MULTI_PLOT_CASES[prj]

            lines = inspect.getsourcelines(func)
            func_code = "".join(lines[0][1:])

            code = textwrap.dedent("""
            .. plot::

            {func_code}

            """).format(func_code=func_code)

        table.write(code)