Menu

[r1844]: / trunk / toolkits / basemap / src / proj4.pyx  Maximize  Restore  History

Download this file

339 lines (308 with data), 13.3 kB

  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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
"""
Pyrex wrapper to provide python interfaces to
PROJ.4 (http://proj.maptools.org) functions.
Performs cartographic transformations (converts from longitude,latitude
to native map projection x,y coordinates and vice versa).
Example usage:
>>> from pyproj import Proj
>>> params = {}
>>> params['proj'] = 'utm'
>>> params['zone'] = 10
>>> p = Proj(params)
>>> x,y = p(-120.108, 34.36116666)
>>> print x,y
>>> print p(x,y,inverse=True)
765975.641091.4805993.13406
(-120.10799999995851, 34.361166659972767)
Input coordinates can be given as python arrays, sequences, scalars
or Numeric/numarray arrays. Optimized for objects that support
the Python buffer protocol (regular python, Numeric and numarray arrays).
Download http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/pyproj-1.6.tar.gz
See pyproj.Proj.__doc__ for more documentation.
Contact: Jeffrey Whitaker <jeffrey.s.whitaker@noaa.gov
copyright (c) 2004 by Jeffrey Whitaker.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notices appear in all copies and that
both the copyright notices and this permission notice appear in
supporting documentation.
THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""
# Make changes to this file, not the c-wrappers that Pyrex generates.
import math, array
cdef double _rad2dg, _dg2rad
cdef int _doublesize
_dg2rad = math.radians(1.)
_rad2dg = math.degrees(1.)
_doublesize = sizeof(double)
__version__ = 1.6
cdef extern from "proj_api.h":
ctypedef double *projPJ
ctypedef struct projUV:
double u
double v
projPJ pj_init_plus(char *)
projUV pj_fwd(projUV, projPJ)
projUV pj_inv(projUV, projPJ)
void pj_free(projPJ)
cdef extern from "Python.h":
int PyObject_AsWriteBuffer(object, void **rbuf, int *len)
int PyObject_CheckReadBuffer(object)
cdef class Proj:
"""
performs cartographic transformations (converts from longitude,latitude
to native map projection x,y coordinates and vice versa) using proj
(http://proj.maptools.org/)
A Proj class instance is initialized with a dictionary containing
proj map projection control parameter key/value pairs.
See http://www.remotesensing.org/geotiff/proj_list and the
proj man page for details.
Calling a Proj class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword 'inverse' is
True (default is False), the inverse transformation from x/y
to lon/lat is performed. If optional keyword 'radians' is True
(default is False) lon/lat are interpreted as radians instead
of degrees. Works with numarray or Numeric arrays, python arrays,
sequences or scalars (fastest for arrays containing doubles).
"""
cdef double *projpj
cdef object projparams
cdef char *pjinitstring
def __new__(self, projparams):
"""
initialize a Proj class instance.
Input 'projparams' is a dictionary containing proj map
projection control parameter key/value pairs.
See the proj documentation (http://proj.maptools.org) for details.
"""
# set units to meters.
if not projparams.has_key('units'):
projparams['units']='m'
elif projparams['units'] != 'm':
print 'resetting units to meters ...'
projparams['units']='m'
# make sure proj parameter specified.
# (no other checking done in proj parameters)
if 'proj' not in projparams.keys():
raise KeyError, "need to specify proj parameter"
pjargs = []
for key,value in projparams.iteritems():
pjargs.append('+'+key+"="+str(value)+' ')
self.projparams = projparams
pjinitstring = ''.join(pjargs)
self.projpj = pj_init_plus(pjinitstring)
def __dealloc__(self):
"""destroy projection definition"""
pj_free(self.projpj)
def __reduce__(self):
"""special method that allows projlib.Proj instance to be pickled"""
return (self.__class__,(self.projparams,))
def _fwd(self, object lons, object lats, radians=False):
"""
forward transformation - lons,lats to x,y.
if radians=True, lons/lats are radians instead of degrees.
"""
cdef projUV projxyout, projlonlatin
cdef int ndim, i, buflenx, bufleny
cdef double u, v
cdef double *lonsdata, *latsdata
cdef void *londata, *latdata
try:
# if buffer api is supported, get pointer to data buffers.
if PyObject_AsWriteBuffer(lons, &londata, &buflenx) <> 0:
raise RuntimeError
if PyObject_AsWriteBuffer(lats, &latdata, &bufleny) <> 0:
raise RuntimeError
hasbufapi= True
except:
hasbufapi = False
if hasbufapi:
# process data in buffer (for Numeric, numarray and python arrays).
if buflenx != bufleny:
raise RuntimeError("Buffer lengths not the same")
ndim = buflenx/_doublesize
lonsdata = <double *>londata
latsdata = <double *>latdata
if radians:
for i from 0 <= i < ndim:
projlonlatin.u = lonsdata[i]
projlonlatin.v = latsdata[i]
projxyout = pj_fwd(projlonlatin,self.projpj)
lonsdata[i] = projxyout.u
latsdata[i] = projxyout.v
else:
for i from 0 <= i < ndim:
projlonlatin.u = _dg2rad*lonsdata[i]
projlonlatin.v = _dg2rad*latsdata[i]
projxyout = pj_fwd(projlonlatin,self.projpj)
lonsdata[i] = projxyout.u
latsdata[i] = projxyout.v
return lons, lats
else:
try: # inputs are sequences.
ndim = len(lons)
if len(lats) != ndim:
raise RuntimeError("Sequences must have the same number of elements")
x = []; y = []
if radians:
for i from 0 <= i < ndim:
projlonlatin.u = lons[i]
projlonlatin.v = lats[i]
projxyout = pj_fwd(projlonlatin,self.projpj)
x.append(projxyout.u)
y.append(projxyout.v)
else:
for i from 0 <= i < ndim:
projlonlatin.u = _dg2rad*lons[i]
projlonlatin.v = _dg2rad*lats[i]
projxyout = pj_fwd(projlonlatin,self.projpj)
x.append(projxyout.u)
y.append(projxyout.v)
except: # inputs are scalars.
if radians:
projlonlatin.u = lons
projlonlatin.v = lats
else:
projlonlatin.u = lons*_dg2rad
projlonlatin.v = lats*_dg2rad
projxyout = pj_fwd(projlonlatin,self.projpj)
x = projxyout.u
y = projxyout.v
return x,y
def _inv(self, object x, object y, radians=False):
"""
inverse transformation - x,y to lons,lats.
if radians=True, lons/lats are radians instead of degrees.
"""
cdef projUV projxyin, projlonlatout
cdef int ndim, i, buflenx, bufleny
cdef double u, v
cdef void *xdata, *ydata
cdef double *xdatab, *ydatab
try:
# if buffer api is supported, get pointer to data buffers.
if PyObject_AsWriteBuffer(x, &xdata, &buflenx) <> 0:
raise RuntimeError
if PyObject_AsWriteBuffer(y, &ydata, &bufleny) <> 0:
raise RuntimeError
hasbufapi= True
except:
hasbufapi = False
if hasbufapi:
# process data in buffer (for Numeric, numarray and python arrays).
if buflenx != bufleny:
raise RuntimeError("Buffer lengths not the same")
ndim = buflenx/_doublesize
xdatab = <double *>xdata
ydatab = <double *>ydata
if radians:
for i from 0 <= i < ndim:
projxyin.u = xdatab[i]
projxyin.v = ydatab[i]
projlonlatout = pj_inv(projxyin,self.projpj)
xdatab[i] = projlonlatout.u
ydatab[i] = projlonlatout.v
else:
for i from 0 <= i < ndim:
projxyin.u = xdatab[i]
projxyin.v = ydatab[i]
projlonlatout = pj_inv(projxyin,self.projpj)
xdatab[i] = _rad2dg*projlonlatout.u
ydatab[i] = _rad2dg*projlonlatout.v
return x,y
else:
try: # inputs are sequences.
ndim = len(x)
if len(y) != ndim:
raise RuntimeError("Sequences must have the same number of elements")
lons = []; lats = []
if radians:
for i from 0 <= i < ndim:
projxyin.u = x[i]
projxyin.v = y[i]
projlonlatout = pj_inv(projxyin, self.projpj)
lons.append(projlonlatout.u)
lats.append(projlonlatout.v)
else:
for i from 0 <= i < ndim:
projxyin.u = x[i]
projxyin.v = y[i]
projlonlatout = pj_inv(projxyin, self.projpj)
lons.append(projlonlatout.u*_rad2dg)
lats.append(projlonlatout.v*_rad2dg)
except: # inputs are scalars.
projxyin.u = x
projxyin.v = y
projlonlatout = pj_inv(projxyin, self.projpj)
if radians:
lons = projlonlatout.u
lats = projlonlatout.v
else:
lons = projlonlatout.u*_rad2dg
lats = projlonlatout.v*_rad2dg
return lons, lats
def __call__(self,lon,lat,inverse=False,radians=False):
"""
Calling a Proj class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword 'inverse' is
True (default is False), the inverse transformation from x/y
to lon/lat is performed. If optional keyword 'radians' is
True (default is False) the units of lon/lat are radians instead
of degrees.
Inputs should be doubles (they will be cast to doubles
if they are not, causing a slight performance hit).
Works with Numeric or numarray arrays, python sequences or scalars
(fastest for arrays containing doubles).
"""
try:
# typecast Numeric/numarray arrays to double, if necessary.
if lon.typecode() != 'd':
lon = lon.astype('d')
if lat.typecode() != 'd':
lat = lat.astype('d')
except:
# typecast regular python arrays to double, if necessary.
try:
if lon.typecode != 'd':
lon = array.array('d',lon)
if lat.typecode != 'd':
lat = array.array('d',lat)
except:
pass
# If the buffer API is supported, make copies of inputs.
# This is necessary since the data buffer of the inputs
# will be modified in place. Raise an exception if
# copies cannot be made.
# Buffer API will be used if inputs are arrays (regular python,
# Numeric or numarray).
if PyObject_CheckReadBuffer(lon) and PyObject_CheckReadBuffer(lat):
try:
# try to make copy using __copy__ method.
inx = lon.__copy__(); iny = lat.__copy__()
except:
msg = """could not create copy of inputs.
This could be because your are using regular python arrays with Python 2.3
(python arrays are not copy-able before python 2.4). Try using lists
or Numeric/numarray arrays instead (the latter will be faster)."""
raise RuntimeError, msg
# call proj4 functions.
if inverse:
outx, outy = self._inv(inx, iny, radians=radians)
else:
outx, outy = self._fwd(inx, iny, radians=radians)
# copy not needed if buffer API not supported.
else:
if inverse:
outx, outy = self._inv(lon, lat, radians=radians)
else:
outx, outy = self._fwd(lon, lat, radians=radians)
# all done.
return outx,outy
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.