PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/gdal/srs.py

https://code.google.com/p/mango-py/
Python | 337 lines | 324 code | 1 blank | 12 comment | 12 complexity | 2d225133c23fdd5793fe0a0542fa5839 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. The Spatial Reference class, represensents OGR Spatial Reference objects.
  3. Example:
  4. >>> from django.contrib.gis.gdal import SpatialReference
  5. >>> srs = SpatialReference('WGS84')
  6. >>> print srs
  7. GEOGCS["WGS 84",
  8. DATUM["WGS_1984",
  9. SPHEROID["WGS 84",6378137,298.257223563,
  10. AUTHORITY["EPSG","7030"]],
  11. TOWGS84[0,0,0,0,0,0,0],
  12. AUTHORITY["EPSG","6326"]],
  13. PRIMEM["Greenwich",0,
  14. AUTHORITY["EPSG","8901"]],
  15. UNIT["degree",0.01745329251994328,
  16. AUTHORITY["EPSG","9122"]],
  17. AUTHORITY["EPSG","4326"]]
  18. >>> print srs.proj
  19. +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
  20. >>> print srs.ellipsoid
  21. (6378137.0, 6356752.3142451793, 298.25722356300003)
  22. >>> print srs.projected, srs.geographic
  23. False True
  24. >>> srs.import_epsg(32140)
  25. >>> print srs.name
  26. NAD83 / Texas South Central
  27. """
  28. import re
  29. from ctypes import byref, c_char_p, c_int, c_void_p
  30. # Getting the error checking routine and exceptions
  31. from django.contrib.gis.gdal.base import GDALBase
  32. from django.contrib.gis.gdal.error import OGRException, SRSException
  33. from django.contrib.gis.gdal.prototypes import srs as capi
  34. #### Spatial Reference class. ####
  35. class SpatialReference(GDALBase):
  36. """
  37. A wrapper for the OGRSpatialReference object. According to the GDAL Web site,
  38. the SpatialReference object "provide[s] services to represent coordinate
  39. systems (projections and datums) and to transform between them."
  40. """
  41. #### Python 'magic' routines ####
  42. def __init__(self, srs_input=''):
  43. """
  44. Creates a GDAL OSR Spatial Reference object from the given input.
  45. The input may be string of OGC Well Known Text (WKT), an integer
  46. EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand
  47. string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83').
  48. """
  49. buf = c_char_p('')
  50. srs_type = 'user'
  51. if isinstance(srs_input, basestring):
  52. # Encoding to ASCII if unicode passed in.
  53. if isinstance(srs_input, unicode):
  54. srs_input = srs_input.encode('ascii')
  55. try:
  56. # If SRID is a string, e.g., '4326', then make acceptable
  57. # as user input.
  58. srid = int(srs_input)
  59. srs_input = 'EPSG:%d' % srid
  60. except ValueError:
  61. pass
  62. elif isinstance(srs_input, (int, long)):
  63. # EPSG integer code was input.
  64. srs_type = 'epsg'
  65. elif isinstance(srs_input, self.ptr_type):
  66. srs = srs_input
  67. srs_type = 'ogr'
  68. else:
  69. raise TypeError('Invalid SRS type "%s"' % srs_type)
  70. if srs_type == 'ogr':
  71. # Input is already an SRS pointer.
  72. srs = srs_input
  73. else:
  74. # Creating a new SRS pointer, using the string buffer.
  75. srs = capi.new_srs(buf)
  76. # If the pointer is NULL, throw an exception.
  77. if not srs:
  78. raise SRSException('Could not create spatial reference from: %s' % srs_input)
  79. else:
  80. self.ptr = srs
  81. # Importing from either the user input string or an integer SRID.
  82. if srs_type == 'user':
  83. self.import_user_input(srs_input)
  84. elif srs_type == 'epsg':
  85. self.import_epsg(srs_input)
  86. def __del__(self):
  87. "Destroys this spatial reference."
  88. if self._ptr: capi.release_srs(self._ptr)
  89. def __getitem__(self, target):
  90. """
  91. Returns the value of the given string attribute node, None if the node
  92. doesn't exist. Can also take a tuple as a parameter, (target, child),
  93. where child is the index of the attribute in the WKT. For example:
  94. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
  95. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  96. >>> print srs['GEOGCS']
  97. WGS 84
  98. >>> print srs['DATUM']
  99. WGS_1984
  100. >>> print srs['AUTHORITY']
  101. EPSG
  102. >>> print srs['AUTHORITY', 1] # The authority value
  103. 4326
  104. >>> print srs['TOWGS84', 4] # the fourth value in this wkt
  105. 0
  106. >>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbole.
  107. EPSG
  108. >>> print srs['UNIT|AUTHORITY', 1] # The authority value for the untis
  109. 9122
  110. """
  111. if isinstance(target, tuple):
  112. return self.attr_value(*target)
  113. else:
  114. return self.attr_value(target)
  115. def __str__(self):
  116. "The string representation uses 'pretty' WKT."
  117. return self.pretty_wkt
  118. #### SpatialReference Methods ####
  119. def attr_value(self, target, index=0):
  120. """
  121. The attribute value for the given target node (e.g. 'PROJCS'). The index
  122. keyword specifies an index of the child node to return.
  123. """
  124. if not isinstance(target, basestring) or not isinstance(index, int):
  125. raise TypeError
  126. return capi.get_attr_value(self.ptr, target, index)
  127. def auth_name(self, target):
  128. "Returns the authority name for the given string target node."
  129. return capi.get_auth_name(self.ptr, target)
  130. def auth_code(self, target):
  131. "Returns the authority code for the given string target node."
  132. return capi.get_auth_code(self.ptr, target)
  133. def clone(self):
  134. "Returns a clone of this SpatialReference object."
  135. return SpatialReference(capi.clone_srs(self.ptr))
  136. def from_esri(self):
  137. "Morphs this SpatialReference from ESRI's format to EPSG."
  138. capi.morph_from_esri(self.ptr)
  139. def identify_epsg(self):
  140. """
  141. This method inspects the WKT of this SpatialReference, and will
  142. add EPSG authority nodes where an EPSG identifier is applicable.
  143. """
  144. capi.identify_epsg(self.ptr)
  145. def to_esri(self):
  146. "Morphs this SpatialReference to ESRI's format."
  147. capi.morph_to_esri(self.ptr)
  148. def validate(self):
  149. "Checks to see if the given spatial reference is valid."
  150. capi.srs_validate(self.ptr)
  151. #### Name & SRID properties ####
  152. @property
  153. def name(self):
  154. "Returns the name of this Spatial Reference."
  155. if self.projected: return self.attr_value('PROJCS')
  156. elif self.geographic: return self.attr_value('GEOGCS')
  157. elif self.local: return self.attr_value('LOCAL_CS')
  158. else: return None
  159. @property
  160. def srid(self):
  161. "Returns the SRID of top-level authority, or None if undefined."
  162. try:
  163. return int(self.attr_value('AUTHORITY', 1))
  164. except (TypeError, ValueError):
  165. return None
  166. #### Unit Properties ####
  167. @property
  168. def linear_name(self):
  169. "Returns the name of the linear units."
  170. units, name = capi.linear_units(self.ptr, byref(c_char_p()))
  171. return name
  172. @property
  173. def linear_units(self):
  174. "Returns the value of the linear units."
  175. units, name = capi.linear_units(self.ptr, byref(c_char_p()))
  176. return units
  177. @property
  178. def angular_name(self):
  179. "Returns the name of the angular units."
  180. units, name = capi.angular_units(self.ptr, byref(c_char_p()))
  181. return name
  182. @property
  183. def angular_units(self):
  184. "Returns the value of the angular units."
  185. units, name = capi.angular_units(self.ptr, byref(c_char_p()))
  186. return units
  187. @property
  188. def units(self):
  189. """
  190. Returns a 2-tuple of the units value and the units name,
  191. and will automatically determines whether to return the linear
  192. or angular units.
  193. """
  194. if self.projected or self.local:
  195. return capi.linear_units(self.ptr, byref(c_char_p()))
  196. elif self.geographic:
  197. return capi.angular_units(self.ptr, byref(c_char_p()))
  198. else:
  199. return (None, None)
  200. #### Spheroid/Ellipsoid Properties ####
  201. @property
  202. def ellipsoid(self):
  203. """
  204. Returns a tuple of the ellipsoid parameters:
  205. (semimajor axis, semiminor axis, and inverse flattening)
  206. """
  207. return (self.semi_major, self.semi_minor, self.inverse_flattening)
  208. @property
  209. def semi_major(self):
  210. "Returns the Semi Major Axis for this Spatial Reference."
  211. return capi.semi_major(self.ptr, byref(c_int()))
  212. @property
  213. def semi_minor(self):
  214. "Returns the Semi Minor Axis for this Spatial Reference."
  215. return capi.semi_minor(self.ptr, byref(c_int()))
  216. @property
  217. def inverse_flattening(self):
  218. "Returns the Inverse Flattening for this Spatial Reference."
  219. return capi.invflattening(self.ptr, byref(c_int()))
  220. #### Boolean Properties ####
  221. @property
  222. def geographic(self):
  223. """
  224. Returns True if this SpatialReference is geographic
  225. (root node is GEOGCS).
  226. """
  227. return bool(capi.isgeographic(self.ptr))
  228. @property
  229. def local(self):
  230. "Returns True if this SpatialReference is local (root node is LOCAL_CS)."
  231. return bool(capi.islocal(self.ptr))
  232. @property
  233. def projected(self):
  234. """
  235. Returns True if this SpatialReference is a projected coordinate system
  236. (root node is PROJCS).
  237. """
  238. return bool(capi.isprojected(self.ptr))
  239. #### Import Routines #####
  240. def import_epsg(self, epsg):
  241. "Imports the Spatial Reference from the EPSG code (an integer)."
  242. capi.from_epsg(self.ptr, epsg)
  243. def import_proj(self, proj):
  244. "Imports the Spatial Reference from a PROJ.4 string."
  245. capi.from_proj(self.ptr, proj)
  246. def import_user_input(self, user_input):
  247. "Imports the Spatial Reference from the given user input string."
  248. capi.from_user_input(self.ptr, user_input)
  249. def import_wkt(self, wkt):
  250. "Imports the Spatial Reference from OGC WKT (string)"
  251. capi.from_wkt(self.ptr, byref(c_char_p(wkt)))
  252. def import_xml(self, xml):
  253. "Imports the Spatial Reference from an XML string."
  254. capi.from_xml(self.ptr, xml)
  255. #### Export Properties ####
  256. @property
  257. def wkt(self):
  258. "Returns the WKT representation of this Spatial Reference."
  259. return capi.to_wkt(self.ptr, byref(c_char_p()))
  260. @property
  261. def pretty_wkt(self, simplify=0):
  262. "Returns the 'pretty' representation of the WKT."
  263. return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)
  264. @property
  265. def proj(self):
  266. "Returns the PROJ.4 representation for this Spatial Reference."
  267. return capi.to_proj(self.ptr, byref(c_char_p()))
  268. @property
  269. def proj4(self):
  270. "Alias for proj()."
  271. return self.proj
  272. @property
  273. def xml(self, dialect=''):
  274. "Returns the XML representation of this Spatial Reference."
  275. return capi.to_xml(self.ptr, byref(c_char_p()), dialect)
  276. class CoordTransform(GDALBase):
  277. "The coordinate system transformation object."
  278. def __init__(self, source, target):
  279. "Initializes on a source and target SpatialReference objects."
  280. if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference):
  281. raise TypeError('source and target must be of type SpatialReference')
  282. self.ptr = capi.new_ct(source._ptr, target._ptr)
  283. self._srs1_name = source.name
  284. self._srs2_name = target.name
  285. def __del__(self):
  286. "Deletes this Coordinate Transformation object."
  287. if self._ptr: capi.destroy_ct(self._ptr)
  288. def __str__(self):
  289. return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)