Package pyproj

Source Code for Package pyproj

  1  """ 
  2  Cython wrapper to provide python interfaces to 
  3  PROJ.4 (http://trac.osgeo.org/proj/) functions. 
  4   
  5  Performs cartographic transformations and geodetic computations. 
  6   
  7  The Proj class can convert from geographic (longitude,latitude) 
  8  to native map projection (x,y) coordinates and vice versa, or 
  9  from one map projection coordinate system directly to another. 
 10  The module variable pj_list is a dictionary containing all the 
 11  available projections and their descriptions. 
 12   
 13  The Geod class can perform forward and inverse geodetic, or 
 14  Great Circle, computations.  The forward computation involves 
 15  determining latitude, longitude and back azimuth of a terminus 
 16  point given the latitude and longitude of an initial point, plus 
 17  azimuth and distance. The inverse computation involves 
 18  determining the forward and back azimuths and distance given the 
 19  latitudes and longitudes of an initial and terminus point. 
 20   
 21  Input coordinates can be given as python arrays, lists/tuples, 
 22  scalars or numpy/Numeric/numarray arrays. Optimized for objects 
 23  that support the Python buffer protocol (regular python and 
 24  numpy array objects). 
 25   
 26  Download: http://code.google.com/p/pyproj/downloads/list 
 27   
 28  Requirements: python 2.4 or higher. 
 29   
 30  Example scripts are in 'test' subdirectory of source distribution. 
 31  The 'test()' function will run the examples in the docstrings. 
 32   
 33  Contact:  Jeffrey Whitaker <jeffrey.s.whitaker@noaa.gov 
 34   
 35  copyright (c) 2006 by Jeffrey Whitaker. 
 36   
 37  Permission to use, copy, modify, and distribute this software 
 38  and its documentation for any purpose and without fee is hereby 
 39  granted, provided that the above copyright notice appear in all 
 40  copies and that both the copyright notice and this permission 
 41  notice appear in supporting documentation. THE AUTHOR DISCLAIMS 
 42  ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL 
 43  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT 
 44  SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR 
 45  CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 
 46  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, 
 47  NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
 48  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ 
 49   
 50  from pyproj import _proj 
 51  from pyproj.datadir import pyproj_datadir 
 52  __version__ =  _proj.__version__ 
 53  set_datapath =  _proj.set_datapath 
 54  from array import array 
 55  import os, math 
 56  #import numpy as np 
 57  pj_list={ 
 58  'aea': "Albers Equal Area", 
 59  'aeqd': "Azimuthal Equidistant", 
 60  'airy': "Airy", 
 61  'aitoff': "Aitoff", 
 62  'alsk': "Mod. Stererographics of Alaska", 
 63  'apian': "Apian Globular I", 
 64  'august': "August Epicycloidal", 
 65  'bacon': "Bacon Globular", 
 66  'bipc': "Bipolar conic of western hemisphere", 
 67  'boggs': "Boggs Eumorphic", 
 68  'bonne': "Bonne (Werner lat_1=90)", 
 69  'cass': "Cassini", 
 70  'cc': "Central Cylindrical", 
 71  'cea': "Equal Area Cylindrical", 
 72  'chamb': "Chamberlin Trimetric", 
 73  'collg': "Collignon", 
 74  'crast': "Craster Parabolic (Putnins P4)", 
 75  'denoy': "Denoyer Semi-Elliptical", 
 76  'eck1': "Eckert I", 
 77  'eck2': "Eckert II", 
 78  'eck3': "Eckert III", 
 79  'eck4': "Eckert IV", 
 80  'eck5': "Eckert V", 
 81  'eck6': "Eckert VI", 
 82  'eqc': "Equidistant Cylindrical (Plate Caree)", 
 83  'eqdc': "Equidistant Conic", 
 84  'etmerc': "Extended Transverse Mercator" , 
 85  'euler': "Euler", 
 86  'fahey': "Fahey", 
 87  'fouc': "Foucaut", 
 88  'fouc_s': "Foucaut Sinusoidal", 
 89  'gall': "Gall (Gall Stereographic)", 
 90  'geocent': "Geocentric", 
 91  'geos': "Geostationary Satellite View", 
 92  'gins8': "Ginsburg VIII (TsNIIGAiK)", 
 93  'gn_sinu': "General Sinusoidal Series", 
 94  'gnom': "Gnomonic", 
 95  'goode': "Goode Homolosine", 
 96  'gs48': "Mod. Stererographics of 48 U.S.", 
 97  'gs50': "Mod. Stererographics of 50 U.S.", 
 98  'hammer': "Hammer & Eckert-Greifendorff", 
 99  'hatano': "Hatano Asymmetrical Equal Area", 
100  'healpix': "HEALPix", 
101  'rhealpix': "rHEALPix", 
102  'igh':  "Interrupted Goode Homolosine", 
103  'imw_p': "Internation Map of the World Polyconic", 
104  'isea':  "Icosahedral Snyder Equal Area", 
105  'kav5': "Kavraisky V", 
106  'kav7': "Kavraisky VII", 
107  'krovak': "Krovak", 
108  'labrd': "Laborde", 
109  'laea': "Lambert Azimuthal Equal Area", 
110  'lagrng': "Lagrange", 
111  'larr': "Larrivee", 
112  'lask': "Laskowski", 
113  'lonlat': "Lat/long (Geodetic)", 
114  'latlon': "Lat/long (Geodetic alias)", 
115  'latlong': "Lat/long (Geodetic alias)", 
116  'longlat': "Lat/long (Geodetic alias)", 
117  'lcc': "Lambert Conformal Conic", 
118  'lcca': "Lambert Conformal Conic Alternative", 
119  'leac': "Lambert Equal Area Conic", 
120  'lee_os': "Lee Oblated Stereographic", 
121  'loxim': "Loximuthal", 
122  'lsat': "Space oblique for LANDSAT", 
123  'mbt_s': "McBryde-Thomas Flat-Polar Sine", 
124  'mbt_fps': "McBryde-Thomas Flat-Pole Sine (No. 2)", 
125  'mbtfpp': "McBride-Thomas Flat-Polar Parabolic", 
126  'mbtfpq': "McBryde-Thomas Flat-Polar Quartic", 
127  'mbtfps': "McBryde-Thomas Flat-Polar Sinusoidal", 
128  'merc': "Mercator", 
129  'mil_os': "Miller Oblated Stereographic", 
130  'mill': "Miller Cylindrical", 
131  'moll': "Mollweide", 
132  'murd1': "Murdoch I", 
133  'murd2': "Murdoch II", 
134  'murd3': "Murdoch III", 
135  'natearth': "Natural Earth", 
136  'nell': "Nell", 
137  'nell_h': "Nell-Hammer", 
138  'nicol': "Nicolosi Globular", 
139  'nsper': "Near-sided perspective", 
140  'nzmg': "New Zealand Map Grid", 
141  'ob_tran': "General Oblique Transformation", 
142  'ocea': "Oblique Cylindrical Equal Area", 
143  'oea': "Oblated Equal Area", 
144  'omerc': "Oblique Mercator", 
145  'ortel': "Ortelius Oval", 
146  'ortho': "Orthographic", 
147  'pconic': "Perspective Conic", 
148  'poly': "Polyconic (American)", 
149  'putp1': "Putnins P1", 
150  'putp2': "Putnins P2", 
151  'putp3': "Putnins P3", 
152  'putp3p': "Putnins P3'", 
153  'putp4p': "Putnins P4'", 
154  'putp5': "Putnins P5", 
155  'putp5p': "Putnins P5'", 
156  'putp6': "Putnins P6", 
157  'putp6p': "Putnins P6'", 
158  'qua_aut': "Quartic Authalic", 
159  'robin': "Robinson", 
160  'rouss': "Roussilhe Stereographic", 
161  'rpoly': "Rectangular Polyconic", 
162  'sinu': "Sinusoidal (Sanson-Flamsteed)", 
163  'somerc': "Swiss. Obl. Mercator", 
164  'stere': "Stereographic", 
165  'sterea': "Oblique Stereographic Alternative", 
166  'gstmerc': "Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)", 
167  'tcc': "Transverse Central Cylindrical", 
168  'tcea': "Transverse Cylindrical Equal Area", 
169  'tissot': "Tissot Conic", 
170  'tmerc': "Transverse Mercator", 
171  'tpeqd': "Two Point Equidistant", 
172  'tpers': "Tilted perspective", 
173  'ups': "Universal Polar Stereographic", 
174  'urm5': "Urmaev V", 
175  'urmfps': "Urmaev Flat-Polar Sinusoidal", 
176  'utm': "Universal Transverse Mercator (UTM)", 
177  'vandg': "van der Grinten (I)", 
178  'vandg2': "van der Grinten II", 
179  'vandg3': "van der Grinten III", 
180  'vandg4': "van der Grinten IV", 
181  'vitk1': "Vitkovsky I", 
182  'wag1': "Wagner I (Kavraisky VI)", 
183  'wag2': "Wagner II", 
184  'wag3': "Wagner III", 
185  'wag4': "Wagner IV", 
186  'wag5': "Wagner V", 
187  'wag6': "Wagner VI", 
188  'wag7': "Wagner VII", 
189  'weren': "Werenskiold I", 
190  'wink1': "Winkel I", 
191  'wink2': "Winkel II", 
192  'wintri': "Winkel Tripel"} 
193   
194  pj_ellps={ 
195  "MERIT":        {'a':6378137.0,'rf':298.257,'description':"MERIT 1983"}, 
196  "SGS85":        {'a':6378136.0,'rf':298.257,'description':"Soviet Geodetic System 85"}, 
197  "GRS80":        {'a':6378137.0,'rf':298.257222101,'description':"GRS 1980(IUGG, 1980)"}, 
198  "IAU76":        {'a':6378140.0,'rf':298.257,'description':"IAU 1976"}, 
199  "airy":         {'a':6377563.396,'b':6356256.910,'description':"Airy 1830"}, 
200  "APL4.9":       {'a':6378137.0,'rf':298.25,'description':"Appl. Physics. 1965"}, 
201  "NWL9D":        {'a':6378145.0,'rf':298.25,'description':" Naval Weapons Lab., 1965"}, 
202  "mod_airy":     {'a':6377340.189,'b':6356034.446,'description':"Modified Airy"}, 
203  "andrae":       {'a':6377104.43,'rf':300.0,'description':"Andrae 1876 (Den., Iclnd.)"}, 
204  "aust_SA":      {'a':6378160.0,'rf':298.25,'description':"Australian Natl & S. Amer. 1969"}, 
205  "GRS67":        {'a':6378160.0,'rf':298.2471674270,'description':"GRS 67(IUGG 1967)"}, 
206  "bessel":       {'a':6377397.155,'rf':299.1528128,'description':"Bessel 1841"}, 
207  "bess_nam":     {'a':6377483.865,'rf':299.1528128,'description':"Bessel 1841 (Namibia)"}, 
208  "clrk66":       {'a':6378206.4,'b':6356583.8,'description':"Clarke 1866"}, 
209  "clrk80":       {'a':6378249.145,'rf':293.4663,'description':"Clarke 1880 mod."}, 
210  "CPM":          {'a':6375738.7,'rf':334.29,'description':"Comm. des Poids et Mesures 1799"}, 
211  "delmbr":       {'a':6376428.,'rf':311.5,'description':"Delambre 1810 (Belgium)"}, 
212  "engelis":      {'a':6378136.05,'rf':298.2566,'description':"Engelis 1985"}, 
213  "evrst30":      {'a':6377276.345,'rf':300.8017,'description':"Everest 1830"}, 
214  "evrst48":      {'a':6377304.063,'rf':300.8017,'description':"Everest 1948"}, 
215  "evrst56":      {'a':6377301.243,'rf':300.8017,'description':"Everest 1956"}, 
216  "evrst69":      {'a':6377295.664,'rf':300.8017,'description':"Everest 1969"}, 
217  "evrstSS":      {'a':6377298.556,'rf':300.8017,'description':"Everest (Sabah & Sarawak)"}, 
218  "fschr60":      {'a':6378166.,'rf':298.3,'description':"Fischer (Mercury Datum) 1960"}, 
219  "fschr60m":     {'a':6378155.,'rf':298.3,'description':"Modified Fischer 1960"}, 
220  "fschr68":      {'a':6378150.,'rf':298.3,'description':"Fischer 1968"}, 
221  "helmert":      {'a':6378200.,'rf':298.3,'description':"Helmert 1906"}, 
222  "hough":        {'a':6378270.0,'rf':297.,'description':"Hough"}, 
223  "intl":         {'a':6378388.0,'rf':297.,'description':"International 1909 (Hayford)"}, 
224  "krass":        {'a':6378245.0,'rf':298.3,'description':"Krassovsky, 1942"}, 
225  "kaula":        {'a':6378163.,'rf':298.24,'description':"Kaula 1961"}, 
226  "lerch":        {'a':6378139.,'rf':298.257,'description':"Lerch 1979"}, 
227  "mprts":        {'a':6397300.,'rf':191.,'description':"Maupertius 1738"}, 
228  "new_intl":     {'a':6378157.5,'b':6356772.2,'description':"New International 1967"}, 
229  "plessis":      {'a':6376523.,'b':6355863.,'description':"Plessis 1817 (France)"}, 
230  "SEasia":       {'a':6378155.0,'b':6356773.3205,'description':"Southeast Asia"}, 
231  "walbeck":      {'a':6376896.0,'b':6355834.8467,'description':"Walbeck"}, 
232  "WGS60":        {'a':6378165.0,'rf':298.3,'description':"WGS 60"}, 
233  "WGS66":        {'a':6378145.0,'rf':298.25,'description':"WGS 66"}, 
234  "WGS72":        {'a':6378135.0,'rf':298.26,'description':"WGS 72"}, 
235  "WGS84":        {'a':6378137.0,'rf':298.257223563,'description':"WGS 84"}, 
236  "sphere":       {'a':6370997.0,'b':6370997.0,'description':"Normal Sphere"}, 
237  } 
238   
239  #if not os.path.isdir(pyproj_datadir): 
240  #    msg="proj data directory not found. Expecting it at: %s"%pyproj_datadir 
241  #    raise IOError(msg) 
242   
243  set_datapath(pyproj_datadir) 
244   
245 -class Proj(_proj.Proj):
246 """ 247 performs cartographic transformations (converts from 248 longitude,latitude to native map projection x,y coordinates and 249 vice versa) using proj (http://trac.osgeo.org/proj/). 250 251 A Proj class instance is initialized with proj map projection 252 control parameter key/value pairs. The key/value pairs can 253 either be passed in a dictionary, or as keyword arguments, 254 or as a proj4 string (compatible with the proj command). See 255 http://www.remotesensing.org/geotiff/proj_list for examples of 256 key/value pairs defining different map projections. 257 258 Calling a Proj class instance with the arguments lon, lat will 259 convert lon/lat (in degrees) to x/y native map projection 260 coordinates (in meters). If optional keyword 'inverse' is True 261 (default is False), the inverse transformation from x/y to 262 lon/lat is performed. If optional keyword 'radians' is True 263 (default is False) lon/lat are interpreted as radians instead of 264 degrees. If optional keyword 'errcheck' is True (default is 265 False) an exception is raised if the transformation is invalid. 266 If errcheck=False and the transformation is invalid, no 267 exception is raised and 1.e30 is returned. If the optional keyword 268 'preserve_units' is True, the units in map projection coordinates 269 are not forced to be meters. 270 271 Works with numpy and regular python array objects, python 272 sequences and scalars. 273 """ 274
275 - def __new__(self, projparams=None, preserve_units=False, **kwargs):
276 """ 277 initialize a Proj class instance. 278 279 Proj4 projection control parameters must either be given in a 280 dictionary 'projparams' or as keyword arguments. See the proj 281 documentation (http://trac.osgeo.org/proj/) for more information 282 about specifying projection parameters. 283 284 Example usage: 285 286 >>> from pyproj import Proj 287 >>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs 288 >>> x,y = p(-120.108, 34.36116666) 289 >>> 'x=%9.3f y=%11.3f' % (x,y) 290 'x=765975.641 y=3805993.134' 291 >>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True) 292 'lon=-120.108 lat=34.361' 293 >>> # do 3 cities at a time in a tuple (Fresno, LA, SF) 294 >>> lons = (-119.72,-118.40,-122.38) 295 >>> lats = (36.77, 33.93, 37.62 ) 296 >>> x,y = p(lons, lats) 297 >>> 'x: %9.3f %9.3f %9.3f' % x 298 'x: 792763.863 925321.537 554714.301' 299 >>> 'y: %9.3f %9.3f %9.3f' % y 300 'y: 4074377.617 3763936.941 4163835.303' 301 >>> lons, lats = p(x, y, inverse=True) # inverse transform 302 >>> 'lons: %8.3f %8.3f %8.3f' % lons 303 'lons: -119.720 -118.400 -122.380' 304 >>> 'lats: %8.3f %8.3f %8.3f' % lats 305 'lats: 36.770 33.930 37.620' 306 >>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string 307 >>> x,y = p2(-120.108, 34.36116666) 308 >>> 'x=%9.3f y=%11.3f' % (x,y) 309 'x=765975.641 y=3805993.134' 310 >>> p = Proj(init="epsg:32667") 311 >>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045) 312 'x=-1783486.760 y= 6193833.196 (meters)' 313 >>> p = Proj("+init=epsg:32667",preserve_units=True) 314 >>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045) 315 'x=-5851322.810 y=20320934.409 (feet)' 316 """ 317 # if projparams is None, use kwargs. 318 if projparams is None: 319 if len(kwargs) == 0: 320 raise RuntimeError('no projection control parameters specified') 321 else: 322 projstring = _dict2string(kwargs) 323 elif type(projparams) == str: 324 # if projparams is a string, interpret as a proj4 init string. 325 projstring = projparams 326 else: # projparams a dict 327 projstring = _dict2string(projparams) 328 # make sure units are meters if preserve_units is False. 329 if not projstring.count('+units=') and not preserve_units: 330 projstring = '+units=m '+projstring 331 else: 332 kvpairs = [] 333 for kvpair in projstring.split(): 334 if kvpair.startswith('+units') and not preserve_units: 335 k,v = kvpair.split('=') 336 kvpairs.append(k+'=m ') 337 else: 338 kvpairs.append(kvpair+' ') 339 projstring = ''.join(kvpairs) 340 # look for EPSG, replace with epsg (EPSG only works 341 # on case-insensitive filesystems). 342 projstring = projstring.replace('EPSG','epsg') 343 return _proj.Proj.__new__(self, projstring)
344
345 - def __call__(self, *args, **kw):
346 #,lon,lat,inverse=False,radians=False,errcheck=False): 347 """ 348 Calling a Proj class instance with the arguments lon, lat will 349 convert lon/lat (in degrees) to x/y native map projection 350 coordinates (in meters). If optional keyword 'inverse' is True 351 (default is False), the inverse transformation from x/y to 352 lon/lat is performed. If optional keyword 'radians' is True 353 (default is False) the units of lon/lat are radians instead of 354 degrees. If optional keyword 'errcheck' is True (default is 355 False) an exception is raised if the transformation is invalid. 356 If errcheck=False and the transformation is invalid, no 357 exception is raised and 1.e30 is returned. 358 359 Instead of calling with lon, lat, a single ndarray of 360 shape n,2 may be used, and one of the same shape will 361 be returned; this is more efficient. 362 363 Inputs should be doubles (they will be cast to doubles if they 364 are not, causing a slight performance hit). 365 366 Works with numpy and regular python array objects, python 367 sequences and scalars, but is fastest for array objects. 368 """ 369 inverse = kw.get('inverse', False) 370 radians = kw.get('radians', False) 371 errcheck = kw.get('errcheck', False) 372 #if len(args) == 1: 373 # latlon = np.array(args[0], copy=True, 374 # order='C', dtype=float, ndmin=2) 375 # if inverse: 376 # _proj.Proj._invn(self, latlon, radians=radians, errcheck=errcheck) 377 # else: 378 # _proj.Proj._fwdn(self, latlon, radians=radians, errcheck=errcheck) 379 # return latlon 380 lon, lat = args 381 # process inputs, making copies that support buffer API. 382 inx, xisfloat, xislist, xistuple = _copytobuffer(lon) 383 iny, yisfloat, yislist, yistuple = _copytobuffer(lat) 384 # call proj4 functions. inx and iny modified in place. 385 if inverse: 386 _proj.Proj._inv(self, inx, iny, radians=radians, errcheck=errcheck) 387 else: 388 _proj.Proj._fwd(self, inx, iny, radians=radians, errcheck=errcheck) 389 # if inputs were lists, tuples or floats, convert back. 390 outx = _convertback(xisfloat,xislist,xistuple,inx) 391 outy = _convertback(yisfloat,yislist,xistuple,iny) 392 return outx, outy
393
394 - def is_latlong(self):
395 """returns True if projection in geographic (lon/lat) coordinates""" 396 return _proj.Proj.is_latlong(self)
397
398 - def is_geocent(self):
399 """returns True if projection in geocentric (x/y) coordinates""" 400 return _proj.Proj.is_geocent(self)
401
402 -def transform(p1, p2, x, y, z=None, radians=False):
403 """ 404 x2, y2, z2 = transform(p1, p2, x1, y1, z1, radians=False) 405 406 Transform points between two coordinate systems defined by the 407 Proj instances p1 and p2. 408 409 The points x1,y1,z1 in the coordinate system defined by p1 are 410 transformed to x2,y2,z2 in the coordinate system defined by p2. 411 412 z1 is optional, if it is not set it is assumed to be zero (and 413 only x2 and y2 are returned). 414 415 In addition to converting between cartographic and geographic 416 projection coordinates, this function can take care of datum 417 shifts (which cannot be done using the __call__ method of the 418 Proj instances). It also allows for one of the coordinate 419 systems to be geographic (proj = 'latlong'). 420 421 If optional keyword 'radians' is True (default is False) and p1 422 is defined in geographic coordinate (pj.is_latlong() is True), 423 x1,y1 is interpreted as radians instead of the default degrees. 424 Similarly, if p2 is defined in geographic coordinates and 425 radians=True, x2, y2 are returned in radians instead of degrees. 426 if p1.is_latlong() and p2.is_latlong() both are False, the 427 radians keyword has no effect. 428 429 x,y and z can be numpy or regular python arrays, python 430 lists/tuples or scalars. Arrays are fastest. For projections in 431 geocentric coordinates, values of x and y are given in meters. 432 z is always meters. 433 434 Example usage: 435 436 >>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum 437 >>> # (defined by epsg code 26915) 438 >>> p1 = Proj(init='epsg:26915') 439 >>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum 440 >>> p2 = Proj(init='epsg:26715') 441 >>> # find x,y of Jefferson City, MO. 442 >>> x1, y1 = p1(-92.199881,38.56694) 443 >>> # transform this point to projection 2 coordinates. 444 >>> x2, y2 = transform(p1,p2,x1,y1) 445 >>> '%9.3f %11.3f' % (x1,y1) 446 '569704.566 4269024.671' 447 >>> '%9.3f %11.3f' % (x2,y2) 448 '569722.342 4268814.027' 449 >>> '%8.3f %5.3f' % p2(x2,y2,inverse=True) 450 ' -92.200 38.567' 451 >>> # process 3 points at a time in a tuple 452 >>> lats = (38.83,39.32,38.75) # Columbia, KC and StL Missouri 453 >>> lons = (-92.22,-94.72,-90.37) 454 >>> x1, y1 = p1(lons,lats) 455 >>> x2, y2 = transform(p1,p2,x1,y1) 456 >>> xy = x1+y1 457 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy 458 '567703.344 351730.944 728553.093 4298200.739 4353698.725 4292319.005' 459 >>> xy = x2+y2 460 >>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy 461 '567721.149 351747.558 728569.133 4297989.112 4353489.644 4292106.305' 462 >>> lons, lats = p2(x2,y2,inverse=True) 463 >>> xy = lons+lats 464 >>> '%8.3f %8.3f %8.3f %5.3f %5.3f %5.3f' % xy 465 ' -92.220 -94.720 -90.370 38.830 39.320 38.750' 466 >>> # test datum shifting, installation of extra datum grid files. 467 >>> p1 = Proj(proj='latlong',datum='WGS84') 468 >>> x1 = -111.5; y1 = 45.25919444444 469 >>> p2 = Proj(proj="utm",zone=10,datum='NAD27') 470 >>> x2, y2 = transform(p1, p2, x1, y1) 471 >>> "%12.3f %12.3f" % (x2,y2) 472 ' 1402285.991 5076292.423' 473 """ 474 # process inputs, making copies that support buffer API. 475 inx, xisfloat, xislist, xistuple = _copytobuffer(x) 476 iny, yisfloat, yislist, yistuple = _copytobuffer(y) 477 if z is not None: 478 inz, zisfloat, zislist, zistuple = _copytobuffer(z) 479 else: 480 inz = None 481 # call pj_transform. inx,iny,inz buffers modified in place. 482 _proj._transform(p1,p2,inx,iny,inz,radians) 483 # if inputs were lists, tuples or floats, convert back. 484 outx = _convertback(xisfloat,xislist,xistuple,inx) 485 outy = _convertback(yisfloat,yislist,xistuple,iny) 486 if inz is not None: 487 outz = _convertback(zisfloat,zislist,zistuple,inz) 488 return outx, outy, outz 489 else: 490 return outx, outy
491
492 -def _copytobuffer_return_scalar(x):
493 try: 494 # inx,isfloat,islist,istuple 495 return array('d',(float(x),)),True,False,False 496 except: 497 raise TypeError('input must be an array, list, tuple or scalar')
498
499 -def _copytobuffer(x):
500 """ 501 return a copy of x as an object that supports the python Buffer 502 API (python array if input is float, list or tuple, numpy array 503 if input is a numpy array). returns copyofx, isfloat, islist, 504 istuple (islist is True if input is a list, istuple is true if 505 input is a tuple, isfloat is true if input is a float). 506 """ 507 # make sure x supports Buffer API and contains doubles. 508 isfloat = False; islist = False; istuple = False 509 # first, if it's a numpy array scalar convert to float 510 # (array scalars don't support buffer API) 511 if hasattr(x,'shape'): 512 if x.shape == (): 513 return _copytobuffer_return_scalar(x) 514 else: 515 try: 516 # typecast numpy arrays to double. 517 # (this makes a copy - which is crucial 518 # since buffer is modified in place) 519 x.dtype.char 520 inx = x.astype('d') 521 # inx,isfloat,islist,istuple 522 return inx,False,False,False 523 except: 524 try: # perhaps they are Numeric/numarrays? 525 # sorry, not tested yet. 526 # i don't know Numeric/numarrays has `shape'. 527 x.typecode() 528 inx = x.astype('d') 529 # inx,isfloat,islist,istuple 530 return inx,False,False,False 531 except: 532 raise TypeError('input must be an array, list, tuple or scalar') 533 else: 534 # perhaps they are regular python arrays? 535 if hasattr(x, 'typecode'): 536 #x.typecode 537 inx = array('d',x) 538 # try to convert to python array 539 # a list. 540 elif type(x) == list: 541 inx = array('d',x) 542 islist = True 543 # a tuple. 544 elif type(x) == tuple: 545 inx = array('d',x) 546 istuple = True 547 # a scalar? 548 else: 549 return _copytobuffer_return_scalar(x) 550 return inx,isfloat,islist,istuple
551
552 -def _convertback(isfloat,islist,istuple,inx):
553 # if inputs were lists, tuples or floats, convert back to original type. 554 if isfloat: 555 return inx[0] 556 elif islist: 557 return inx.tolist() 558 elif istuple: 559 return tuple(inx) 560 else: 561 return inx
562
563 -def _dict2string(projparams):
564 # convert a dict to a proj4 string. 565 pjargs = [] 566 for key,value in projparams.items(): 567 pjargs.append('+'+key+"="+str(value)+' ') 568 return ''.join(pjargs)
569
570 -class Geod(_proj.Geod):
571 """ 572 performs forward and inverse geodetic, or Great Circle, 573 computations. The forward computation (using the 'fwd' method) 574 involves determining latitude, longitude and back azimuth of a 575 computations. The forward computation (using the 'fwd' method) 576 involves determining latitude, longitude and back azimuth of a 577 terminus point given the latitude and longitude of an initial 578 point, plus azimuth and distance. The inverse computation (using 579 the 'inv' method) involves determining the forward and back 580 azimuths and distance given the latitudes and longitudes of an 581 initial and terminus point. 582 """
583 - def __new__(self, initstring=None, **kwargs):
584 """ 585 initialize a Geod class instance. 586 587 Geodetic parameters for specifying the ellipsoid 588 can be given in a dictionary 'initparams', as keyword arguments, 589 or as as proj4 geod initialization string. 590 Following is a list of the ellipsoids that may be defined using the 591 'ellps' keyword (these are stored in the model variable pj_ellps):: 592 593 MERIT a=6378137.0 rf=298.257 MERIT 1983 594 SGS85 a=6378136.0 rf=298.257 Soviet Geodetic System 85 595 GRS80 a=6378137.0 rf=298.257222101 GRS 1980(IUGG, 1980) 596 IAU76 a=6378140.0 rf=298.257 IAU 1976 597 airy a=6377563.396 b=6356256.910 Airy 1830 598 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 599 airy a=6377563.396 b=6356256.910 Airy 1830 600 APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965 601 NWL9D a=6378145.0. rf=298.25 Naval Weapons Lab., 1965 602 mod_airy a=6377340.189 b=6356034.446 Modified Airy 603 andrae a=6377104.43 rf=300.0 Andrae 1876 (Den., Iclnd.) 604 aust_SA a=6378160.0 rf=298.25 Australian Natl & S. Amer. 1969 605 GRS67 a=6378160.0 rf=298.247167427 GRS 67(IUGG 1967) 606 bessel a=6377397.155 rf=299.1528128 Bessel 1841 607 bess_nam a=6377483.865 rf=299.1528128 Bessel 1841 (Namibia) 608 clrk66 a=6378206.4 b=6356583.8 Clarke 1866 609 clrk80 a=6378249.145 rf=293.4663 Clarke 1880 mod. 610 CPM a=6375738.7 rf=334.29 Comm. des Poids et Mesures 1799 611 delmbr a=6376428. rf=311.5 Delambre 1810 (Belgium) 612 engelis a=6378136.05 rf=298.2566 Engelis 1985 613 evrst30 a=6377276.345 rf=300.8017 Everest 1830 614 evrst48 a=6377304.063 rf=300.8017 Everest 1948 615 evrst56 a=6377301.243 rf=300.8017 Everest 1956 616 evrst69 a=6377295.664 rf=300.8017 Everest 1969 617 evrstSS a=6377298.556 rf=300.8017 Everest (Sabah & Sarawak) 618 fschr60 a=6378166. rf=298.3 Fischer (Mercury Datum) 1960 619 fschr60m a=6378155. rf=298.3 Modified Fischer 1960 620 fschr68 a=6378150. rf=298.3 Fischer 1968 621 helmert a=6378200. rf=298.3 Helmert 1906 622 hough a=6378270.0 rf=297. Hough 623 helmert a=6378200. rf=298.3 Helmert 1906 624 hough a=6378270.0 rf=297. Hough 625 intl a=6378388.0 rf=297. International 1909 (Hayford) 626 krass a=6378245.0 rf=298.3 Krassovsky, 1942 627 kaula a=6378163. rf=298.24 Kaula 1961 628 lerch a=6378139. rf=298.257 Lerch 1979 629 mprts a=6397300. rf=191. Maupertius 1738 630 new_intl a=6378157.5 b=6356772.2 New International 1967 631 plessis a=6376523. b=6355863. Plessis 1817 (France) 632 SEasia a=6378155.0 b=6356773.3205 Southeast Asia 633 walbeck a=6376896.0 b=6355834.8467 Walbeck 634 WGS60 a=6378165.0 rf=298.3 WGS 60 635 WGS66 a=6378145.0 rf=298.25 WGS 66 636 WGS72 a=6378135.0 rf=298.26 WGS 72 637 WGS84 a=6378137.0 rf=298.257223563 WGS 84 638 sphere a=6370997.0 b=6370997.0 Normal Sphere (r=6370997) 639 640 The parameters of the ellipsoid may also be set directly using 641 the 'a' (semi-major or equatorial axis radius) keyword, and 642 any one of the following keywords: 'b' (semi-minor, 643 or polar axis radius), 'e' (eccentricity), 'es' (eccentricity 644 squared), 'f' (flattening), or 'rf' (reciprocal flattening). 645 646 See the proj documentation (http://trac.osgeo.org/proj/) for more 647 648 See the proj documentation (http://trac.osgeo.org/proj/) for more 649 information about specifying ellipsoid parameters (specifically, 650 the chapter 'Specifying the Earth's figure' in the main Proj 651 users manual). 652 653 Example usage: 654 655 >>> from pyproj import Geod 656 >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. 657 >>> # specify the lat/lons of some cities. 658 >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) 659 >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) 660 >>> newyork_lat = 40.+(47./60.); newyork_lon = -73.-(58./60.) 661 >>> london_lat = 51.+(32./60.); london_lon = -(5./60.) 662 >>> # compute forward and back azimuths, plus distance 663 >>> # between Boston and Portland. 664 >>> az12,az21,dist = g.inv(boston_lon,boston_lat,portland_lon,portland_lat) 665 >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) 666 '-66.531 75.654 4164192.708' 667 >>> # compute latitude, longitude and back azimuth of Portland, 668 >>> # given Boston lat/lon, forward azimuth and distance to Portland. 669 >>> endlon, endlat, backaz = g.fwd(boston_lon, boston_lat, az12, dist) 670 >>> "%6.3f %6.3f %13.3f" % (endlat,endlon,backaz) 671 '45.517 -123.683 75.654' 672 >>> # compute the azimuths, distances from New York to several 673 >>> # cities (pass a list) 674 >>> lons1 = 3*[newyork_lon]; lats1 = 3*[newyork_lat] 675 >>> lons2 = [boston_lon, portland_lon, london_lon] 676 >>> lats2 = [boston_lat, portland_lat, london_lat] 677 >>> az12,az21,dist = g.inv(lons1,lats1,lons2,lats2) 678 >>> for faz,baz,d in list(zip(az12,az21,dist)): "%7.3f %7.3f %9.3f" % (faz,baz,d) 679 ' 54.663 -123.448 288303.720' 680 '-65.463 79.342 4013037.318' 681 ' 51.254 -71.576 5579916.651' 682 >>> g2 = Geod('+ellps=clrk66') # use proj4 style initialization string 683 >>> az12,az21,dist = g2.inv(boston_lon,boston_lat,portland_lon,portland_lat) 684 >>> "%7.3f %6.3f %12.3f" % (az12,az21,dist) 685 '-66.531 75.654 4164192.708' 686 """ 687 # if initparams is a proj-type init string, 688 # convert to dict. 689 ellpsd = {} 690 if initstring is not None: 691 for kvpair in initstring.split(): 692 k,v = kvpair.split('=') 693 k = k.lstrip('+') 694 if k in ['a','b','rf','f','es','e']: 695 v = float(v) 696 ellpsd[k] = v 697 # merge this dict with kwargs dict. 698 kwargs = dict(list(kwargs.items()) + list(ellpsd.items())) 699 self.sphere = False 700 if 'ellps' in kwargs: 701 # ellipse name given, look up in pj_ellps dict 702 ellps_dict = pj_ellps[kwargs['ellps']] 703 a = ellps_dict['a'] 704 if ellps_dict['description']=='Normal Sphere': 705 self.sphere = True 706 if 'b' in ellps_dict: 707 b = ellps_dict['b'] 708 es = 1. - (b * b) / (a * a) 709 f = (a - b)/a 710 elif 'rf' in ellps_dict: 711 f = 1./ellps_dict['rf'] 712 b = a*(1. - f) 713 es = 1. - (b * b) / (a * a) 714 else: 715 # a (semi-major axis) and one of 716 # b the semi-minor axis 717 # rf the reciprocal flattening 718 # f flattening 719 # es eccentricity squared 720 # must be given. 721 a = kwargs['a'] 722 if 'b' in kwargs: 723 b = kwargs['b'] 724 es = 1. - (b * b) / (a * a) 725 f = (a - b)/a 726 elif 'rf' in kwargs: 727 f = 1./kwargs['rf'] 728 b = a*(1. - f) 729 es = 1. - (b * b) / (a * a) 730 elif 'f' in kwargs: 731 f = kwargs['f'] 732 b = a*(1. - f) 733 es = 1. - (b/a)**2 734 elif 'es' in kwargs: 735 es = kwargs['es'] 736 b = math.sqrt(a**2 - es*a**2) 737 f = (a - b)/a 738 elif 'e' in kwargs: 739 es = kwargs['e']**2 740 b = math.sqrt(a**2 - es*a**2) 741 f = (a - b)/a 742 else: 743 b = a 744 f = 0. 745 es = 0. 746 #msg='ellipse name or a, plus one of f,es,b must be given' 747 #raise ValueError(msg) 748 if math.fabs(f) < 1.e-8: self.sphere = True 749 self.a = a 750 self.b = b 751 self.f = f 752 self.es = es 753 return _proj.Geod.__new__(self, a, f)
754
755 - def fwd(self, lons, lats, az, dist, radians=False):
756 """ 757 forward transformation - Returns longitudes, latitudes and back 758 azimuths of terminus points given longitudes (lons) and 759 latitudes (lats) of initial points, plus forward azimuths (az) 760 and distances (dist). 761 latitudes (lats) of initial points, plus forward azimuths (az) 762 and distances (dist). 763 764 Works with numpy and regular python array objects, python 765 sequences and scalars. 766 767 if radians=True, lons/lats and azimuths are radians instead of 768 degrees. Distances are in meters. 769 """ 770 # process inputs, making copies that support buffer API. 771 inx, xisfloat, xislist, xistuple = _copytobuffer(lons) 772 iny, yisfloat, yislist, yistuple = _copytobuffer(lats) 773 inz, zisfloat, zislist, zistuple = _copytobuffer(az) 774 ind, disfloat, dislist, distuple = _copytobuffer(dist) 775 _proj.Geod._fwd(self, inx, iny, inz, ind, radians=radians) 776 # if inputs were lists, tuples or floats, convert back. 777 outx = _convertback(xisfloat,xislist,xistuple,inx) 778 outy = _convertback(yisfloat,yislist,xistuple,iny) 779 outz = _convertback(zisfloat,zislist,zistuple,inz) 780 return outx, outy, outz
781
782 - def inv(self,lons1,lats1,lons2,lats2,radians=False):
783 """ 784 inverse transformation - Returns forward and back azimuths, plus 785 distances between initial points (specified by lons1, lats1) and 786 terminus points (specified by lons2, lats2). 787 788 Works with numpy and regular python array objects, python 789 sequences and scalars. 790 791 if radians=True, lons/lats and azimuths are radians instead of 792 degrees. Distances are in meters. 793 """ 794 # process inputs, making copies that support buffer API. 795 inx, xisfloat, xislist, xistuple = _copytobuffer(lons1) 796 iny, yisfloat, yislist, yistuple = _copytobuffer(lats1) 797 inz, zisfloat, zislist, zistuple = _copytobuffer(lons2) 798 ind, disfloat, dislist, distuple = _copytobuffer(lats2) 799 _proj.Geod._inv(self,inx,iny,inz,ind,radians=radians) 800 # if inputs were lists, tuples or floats, convert back. 801 outx = _convertback(xisfloat,xislist,xistuple,inx) 802 outy = _convertback(yisfloat,yislist,xistuple,iny) 803 outz = _convertback(zisfloat,zislist,zistuple,inz) 804 return outx, outy, outz
805
806 - def npts(self, lon1, lat1, lon2, lat2, npts, radians=False):
807 """ 808 Given a single initial point and terminus point (specified by 809 python floats lon1,lat1 and lon2,lat2), returns a list of 810 longitude/latitude pairs describing npts equally spaced 811 intermediate points along the geodesic between the initial and 812 terminus points. 813 814 if radians=True, lons/lats are radians instead of degrees. 815 816 Example usage: 817 818 >>> from pyproj import Geod 819 >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. 820 >>> # specify the lat/lons of Boston and Portland. 821 >>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid. 822 >>> # specify the lat/lons of Boston and Portland. 823 >>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.) 824 >>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.) 825 >>> # find ten equally spaced points between Boston and Portland. 826 >>> lonlats = g.npts(boston_lon,boston_lat,portland_lon,portland_lat,10) 827 >>> for lon,lat in lonlats: '%6.3f %7.3f' % (lat, lon) 828 '43.528 -75.414' 829 '44.637 -79.883' 830 '45.565 -84.512' 831 '46.299 -89.279' 832 '46.830 -94.156' 833 '47.149 -99.112' 834 '47.251 -104.106' 835 '47.136 -109.100' 836 '46.805 -114.051' 837 '46.262 -118.924' 838 >>> # test with radians=True (inputs/outputs in radians, not degrees) 839 >>> import math 840 >>> dg2rad = math.radians(1.) 841 >>> rad2dg = math.degrees(1.) 842 >>> lonlats = g.npts(dg2rad*boston_lon,dg2rad*boston_lat,dg2rad*portland_lon,dg2rad*portland_lat,10,radians=True) 843 >>> for lon,lat in lonlats: '%6.3f %7.3f' % (rad2dg*lat, rad2dg*lon) 844 '43.528 -75.414' 845 '44.637 -79.883' 846 '45.565 -84.512' 847 '46.299 -89.279' 848 '46.830 -94.156' 849 '47.149 -99.112' 850 '47.251 -104.106' 851 '47.136 -109.100' 852 '46.805 -114.051' 853 '46.262 -118.924' 854 """ 855 lons, lats = _proj.Geod._npts(self, lon1, lat1, lon2, lat2, npts, radians=radians) 856 return list(zip(lons, lats))
857
858 -def test():
859 """run the examples in the docstrings using the doctest module""" 860 import doctest, pyproj 861 doctest.testmod(pyproj,verbose=True)
862 863 if __name__ == "__main__": test() 864