Debian Codegraph @

cylc/flow/etc/tutorial/runtime-tutorial/lib/python/mercator.py

raw
1 # -*- coding: utf-8 -*-
2 # -----------------------------------------------------------------------------
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # -----------------------------------------------------------------------------
19 # This is illustrative code developed for tutorial purposes, it is not
20 # intended for scientific use and is not guarantied to be accurate or correct.
21 import math
22
23
24 R_0 = 6356752.3
25
26
27 def get_offset(bbox, scale=(1., 1.)):
28 """Define an offset from the origin using the provided bbox.
29
30 Args:
31 bbox: The coordinates of the domain as a dictionary {'lat1', 'lng1',
32 'lat2', 'lng2'}
33 scale: The x, y scale factor as returned by get_scale().
34
35 """
36 return coord_to_pos(bbox['lng1'], bbox['lat1'], scale=scale)
37
38
39 def get_scale(bbox, width):
40 """Define the scale of the transformation.
41
42 Args:
43 bbox: The coordinates of the domain as a dictionary {'lat1', 'lng1',
44 'lat2', 'lng2'}
45 width: The width of the projection.
46
47 """
48 scale = width * (180. / abs(bbox['lng2'] - bbox['lng1']))
49 return (
50 (math.pi * R_0) / scale,
51 (math.pi * R_0 * 2.) / scale)
52
53
54 def coord_to_pos(lng, lat, offset=(0., 0.), scale=(1., 1.)):
55 """Convert a lng, lat coord to an x, y position in a mercator projection.
56
57 proj equivalent:
58 $ echo <lng> <lat> | proj +proj=merc
59 # Divide by scale.
60 # Subtract offset.
61
62 """
63 lng = math.radians(lng)
64 lat = math.radians(lat)
65 pos_x = R_0 * lng
66 pos_y = R_0 * math.log(math.tan((math.pi / 4.) + (lat / 2.)))
67 pos_x /= scale[0]
68 pos_y /= scale[1]
69 pos_x -= offset[0]
70 pos_y -= offset[1]
71 return pos_x, pos_y
72
73
74 def pos_to_coord(pos_x, pos_y, offset=(0., 0.), scale=(1., 1.)):
75 """Convert an x, y coordinate in a mercator projection to a lng, lat coord.
76
77 proj equivalent:
78 # Add offset
79 # Multiply by scale.
80 $ echo <pos_x> <pos_y> | proj -I +proj=merc
81
82 """
83 pos_x += offset[0]
84 pos_y += offset[1]
85 pos_x *= scale[0]
86 pos_y *= scale[1]
87 lng = pos_x / R_0
88 lat = 2 * math.atan(math.exp(pos_y / R_0)) - (math.pi / 2.)
89 return math.degrees(lng), math.degrees(lat)