/django/contrib/gis/measure.py

https://code.google.com/p/mango-py/ · Python · 336 lines · 300 code · 0 blank · 36 comment · 15 complexity · fc0142a37292eb9c41893aabb9a7b12f MD5 · raw file

  1. # Copyright (c) 2007, Robert Coup <robert.coup@onetrackmind.co.nz>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without modification,
  5. # are permitted provided that the following conditions are met:
  6. #
  7. # 1. Redistributions of source code must retain the above copyright notice,
  8. # this list of conditions and the following disclaimer.
  9. #
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. #
  14. # 3. Neither the name of Distance nor the names of its contributors may be used
  15. # to endorse or promote products derived from this software without
  16. # specific prior written permission.
  17. #
  18. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  22. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  25. # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. #
  29. """
  30. Distance and Area objects to allow for sensible and convienient calculation
  31. and conversions.
  32. Authors: Robert Coup, Justin Bronn
  33. Inspired by GeoPy (http://exogen.case.edu/projects/geopy/)
  34. and Geoff Biggs' PhD work on dimensioned units for robotics.
  35. """
  36. __all__ = ['A', 'Area', 'D', 'Distance']
  37. from decimal import Decimal
  38. class MeasureBase(object):
  39. def default_units(self, kwargs):
  40. """
  41. Return the unit value and the default units specified
  42. from the given keyword arguments dictionary.
  43. """
  44. val = 0.0
  45. for unit, value in kwargs.iteritems():
  46. if not isinstance(value, float): value = float(value)
  47. if unit in self.UNITS:
  48. val += self.UNITS[unit] * value
  49. default_unit = unit
  50. elif unit in self.ALIAS:
  51. u = self.ALIAS[unit]
  52. val += self.UNITS[u] * value
  53. default_unit = u
  54. else:
  55. lower = unit.lower()
  56. if lower in self.UNITS:
  57. val += self.UNITS[lower] * value
  58. default_unit = lower
  59. elif lower in self.LALIAS:
  60. u = self.LALIAS[lower]
  61. val += self.UNITS[u] * value
  62. default_unit = u
  63. else:
  64. raise AttributeError('Unknown unit type: %s' % unit)
  65. return val, default_unit
  66. @classmethod
  67. def unit_attname(cls, unit_str):
  68. """
  69. Retrieves the unit attribute name for the given unit string.
  70. For example, if the given unit string is 'metre', 'm' would be returned.
  71. An exception is raised if an attribute cannot be found.
  72. """
  73. lower = unit_str.lower()
  74. if unit_str in cls.UNITS:
  75. return unit_str
  76. elif lower in cls.UNITS:
  77. return lower
  78. elif lower in cls.LALIAS:
  79. return cls.LALIAS[lower]
  80. else:
  81. raise Exception('Could not find a unit keyword associated with "%s"' % unit_str)
  82. class Distance(MeasureBase):
  83. UNITS = {
  84. 'chain' : 20.1168,
  85. 'chain_benoit' : 20.116782,
  86. 'chain_sears' : 20.1167645,
  87. 'british_chain_benoit' : 20.1167824944,
  88. 'british_chain_sears' : 20.1167651216,
  89. 'british_chain_sears_truncated' : 20.116756,
  90. 'cm' : 0.01,
  91. 'british_ft' : 0.304799471539,
  92. 'british_yd' : 0.914398414616,
  93. 'clarke_ft' : 0.3047972654,
  94. 'clarke_link' : 0.201166195164,
  95. 'fathom' : 1.8288,
  96. 'ft': 0.3048,
  97. 'german_m' : 1.0000135965,
  98. 'gold_coast_ft' : 0.304799710181508,
  99. 'indian_yd' : 0.914398530744,
  100. 'inch' : 0.0254,
  101. 'km': 1000.0,
  102. 'link' : 0.201168,
  103. 'link_benoit' : 0.20116782,
  104. 'link_sears' : 0.20116765,
  105. 'm': 1.0,
  106. 'mi': 1609.344,
  107. 'mm' : 0.001,
  108. 'nm': 1852.0,
  109. 'nm_uk' : 1853.184,
  110. 'rod' : 5.0292,
  111. 'sears_yd' : 0.91439841,
  112. 'survey_ft' : 0.304800609601,
  113. 'um' : 0.000001,
  114. 'yd': 0.9144,
  115. }
  116. # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
  117. ALIAS = {
  118. 'centimeter' : 'cm',
  119. 'foot' : 'ft',
  120. 'inches' : 'inch',
  121. 'kilometer' : 'km',
  122. 'kilometre' : 'km',
  123. 'meter' : 'm',
  124. 'metre' : 'm',
  125. 'micrometer' : 'um',
  126. 'micrometre' : 'um',
  127. 'millimeter' : 'mm',
  128. 'millimetre' : 'mm',
  129. 'mile' : 'mi',
  130. 'yard' : 'yd',
  131. 'British chain (Benoit 1895 B)' : 'british_chain_benoit',
  132. 'British chain (Sears 1922)' : 'british_chain_sears',
  133. 'British chain (Sears 1922 truncated)' : 'british_chain_sears_truncated',
  134. 'British foot (Sears 1922)' : 'british_ft',
  135. 'British foot' : 'british_ft',
  136. 'British yard (Sears 1922)' : 'british_yd',
  137. 'British yard' : 'british_yd',
  138. "Clarke's Foot" : 'clarke_ft',
  139. "Clarke's link" : 'clarke_link',
  140. 'Chain (Benoit)' : 'chain_benoit',
  141. 'Chain (Sears)' : 'chain_sears',
  142. 'Foot (International)' : 'ft',
  143. 'German legal metre' : 'german_m',
  144. 'Gold Coast foot' : 'gold_coast_ft',
  145. 'Indian yard' : 'indian_yd',
  146. 'Link (Benoit)': 'link_benoit',
  147. 'Link (Sears)': 'link_sears',
  148. 'Nautical Mile' : 'nm',
  149. 'Nautical Mile (UK)' : 'nm_uk',
  150. 'US survey foot' : 'survey_ft',
  151. 'U.S. Foot' : 'survey_ft',
  152. 'Yard (Indian)' : 'indian_yd',
  153. 'Yard (Sears)' : 'sears_yd'
  154. }
  155. LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()])
  156. def __init__(self, default_unit=None, **kwargs):
  157. # The base unit is in meters.
  158. self.m, self._default_unit = self.default_units(kwargs)
  159. if default_unit and isinstance(default_unit, str):
  160. self._default_unit = default_unit
  161. def __getattr__(self, name):
  162. if name in self.UNITS:
  163. return self.m / self.UNITS[name]
  164. else:
  165. raise AttributeError('Unknown unit type: %s' % name)
  166. def __repr__(self):
  167. return 'Distance(%s=%s)' % (self._default_unit, getattr(self, self._default_unit))
  168. def __str__(self):
  169. return '%s %s' % (getattr(self, self._default_unit), self._default_unit)
  170. def __cmp__(self, other):
  171. if isinstance(other, Distance):
  172. return cmp(self.m, other.m)
  173. else:
  174. return NotImplemented
  175. def __add__(self, other):
  176. if isinstance(other, Distance):
  177. return Distance(default_unit=self._default_unit, m=(self.m + other.m))
  178. else:
  179. raise TypeError('Distance must be added with Distance')
  180. def __iadd__(self, other):
  181. if isinstance(other, Distance):
  182. self.m += other.m
  183. return self
  184. else:
  185. raise TypeError('Distance must be added with Distance')
  186. def __sub__(self, other):
  187. if isinstance(other, Distance):
  188. return Distance(default_unit=self._default_unit, m=(self.m - other.m))
  189. else:
  190. raise TypeError('Distance must be subtracted from Distance')
  191. def __isub__(self, other):
  192. if isinstance(other, Distance):
  193. self.m -= other.m
  194. return self
  195. else:
  196. raise TypeError('Distance must be subtracted from Distance')
  197. def __mul__(self, other):
  198. if isinstance(other, (int, float, long, Decimal)):
  199. return Distance(default_unit=self._default_unit, m=(self.m * float(other)))
  200. elif isinstance(other, Distance):
  201. return Area(default_unit='sq_' + self._default_unit, sq_m=(self.m * other.m))
  202. else:
  203. raise TypeError('Distance must be multiplied with number or Distance')
  204. def __imul__(self, other):
  205. if isinstance(other, (int, float, long, Decimal)):
  206. self.m *= float(other)
  207. return self
  208. else:
  209. raise TypeError('Distance must be multiplied with number')
  210. def __rmul__(self, other):
  211. return self * other
  212. def __div__(self, other):
  213. if isinstance(other, (int, float, long, Decimal)):
  214. return Distance(default_unit=self._default_unit, m=(self.m / float(other)))
  215. else:
  216. raise TypeError('Distance must be divided with number')
  217. def __idiv__(self, other):
  218. if isinstance(other, (int, float, long, Decimal)):
  219. self.m /= float(other)
  220. return self
  221. else:
  222. raise TypeError('Distance must be divided with number')
  223. def __nonzero__(self):
  224. return bool(self.m)
  225. class Area(MeasureBase):
  226. # Getting the square units values and the alias dictionary.
  227. UNITS = dict([('sq_%s' % k, v ** 2) for k, v in Distance.UNITS.items()])
  228. ALIAS = dict([(k, 'sq_%s' % v) for k, v in Distance.ALIAS.items()])
  229. LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()])
  230. def __init__(self, default_unit=None, **kwargs):
  231. self.sq_m, self._default_unit = self.default_units(kwargs)
  232. if default_unit and isinstance(default_unit, str):
  233. self._default_unit = default_unit
  234. def __getattr__(self, name):
  235. if name in self.UNITS:
  236. return self.sq_m / self.UNITS[name]
  237. else:
  238. raise AttributeError('Unknown unit type: ' + name)
  239. def __repr__(self):
  240. return 'Area(%s=%s)' % (self._default_unit, getattr(self, self._default_unit))
  241. def __str__(self):
  242. return '%s %s' % (getattr(self, self._default_unit), self._default_unit)
  243. def __cmp__(self, other):
  244. if isinstance(other, Area):
  245. return cmp(self.sq_m, other.sq_m)
  246. else:
  247. return NotImplemented
  248. def __add__(self, other):
  249. if isinstance(other, Area):
  250. return Area(default_unit=self._default_unit, sq_m=(self.sq_m + other.sq_m))
  251. else:
  252. raise TypeError('Area must be added with Area')
  253. def __iadd__(self, other):
  254. if isinstance(other, Area):
  255. self.sq_m += other.sq_m
  256. return self
  257. else:
  258. raise TypeError('Area must be added with Area')
  259. def __sub__(self, other):
  260. if isinstance(other, Area):
  261. return Area(default_unit=self._default_unit, sq_m=(self.sq_m - other.sq_m))
  262. else:
  263. raise TypeError('Area must be subtracted from Area')
  264. def __isub__(self, other):
  265. if isinstance(other, Area):
  266. self.sq_m -= other.sq_m
  267. return self
  268. else:
  269. raise TypeError('Area must be subtracted from Area')
  270. def __mul__(self, other):
  271. if isinstance(other, (int, float, long, Decimal)):
  272. return Area(default_unit=self._default_unit, sq_m=(self.sq_m * float(other)))
  273. else:
  274. raise TypeError('Area must be multiplied with number')
  275. def __imul__(self, other):
  276. if isinstance(other, (int, float, long, Decimal)):
  277. self.sq_m *= float(other)
  278. return self
  279. else:
  280. raise TypeError('Area must be multiplied with number')
  281. def __rmul__(self, other):
  282. return self * other
  283. def __div__(self, other):
  284. if isinstance(other, (int, float, long, Decimal)):
  285. return Area(default_unit=self._default_unit, sq_m=(self.sq_m / float(other)))
  286. else:
  287. raise TypeError('Area must be divided with number')
  288. def __idiv__(self, other):
  289. if isinstance(other, (int, float, long, Decimal)):
  290. self.sq_m /= float(other)
  291. return self
  292. else:
  293. raise TypeError('Area must be divided with number')
  294. def __nonzero__(self):
  295. return bool(self.sq_m)
  296. # Shortcuts
  297. D = Distance
  298. A = Area