You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

334 lines
12 KiB

  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 convenient calculation
  31. and conversions.
  32. Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio
  33. Inspired by GeoPy (https://github.com/geopy/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. from functools import total_ordering
  39. from django.utils import six
  40. NUMERIC_TYPES = six.integer_types + (float, Decimal)
  41. AREA_PREFIX = "sq_"
  42. def pretty_name(obj):
  43. return obj.__name__ if obj.__class__ == type else obj.__class__.__name__
  44. @total_ordering
  45. class MeasureBase(object):
  46. STANDARD_UNIT = None
  47. ALIAS = {}
  48. UNITS = {}
  49. LALIAS = {}
  50. def __init__(self, default_unit=None, **kwargs):
  51. value, self._default_unit = self.default_units(kwargs)
  52. setattr(self, self.STANDARD_UNIT, value)
  53. if default_unit and isinstance(default_unit, six.string_types):
  54. self._default_unit = default_unit
  55. def _get_standard(self):
  56. return getattr(self, self.STANDARD_UNIT)
  57. def _set_standard(self, value):
  58. setattr(self, self.STANDARD_UNIT, value)
  59. standard = property(_get_standard, _set_standard)
  60. def __getattr__(self, name):
  61. if name in self.UNITS:
  62. return self.standard / self.UNITS[name]
  63. else:
  64. raise AttributeError('Unknown unit type: %s' % name)
  65. def __repr__(self):
  66. return '%s(%s=%s)' % (pretty_name(self), self._default_unit,
  67. getattr(self, self._default_unit))
  68. def __str__(self):
  69. return '%s %s' % (getattr(self, self._default_unit), self._default_unit)
  70. # **** Comparison methods ****
  71. def __eq__(self, other):
  72. if isinstance(other, self.__class__):
  73. return self.standard == other.standard
  74. else:
  75. return NotImplemented
  76. def __lt__(self, other):
  77. if isinstance(other, self.__class__):
  78. return self.standard < other.standard
  79. else:
  80. return NotImplemented
  81. # **** Operators methods ****
  82. def __add__(self, other):
  83. if isinstance(other, self.__class__):
  84. return self.__class__(default_unit=self._default_unit,
  85. **{self.STANDARD_UNIT: (self.standard + other.standard)})
  86. else:
  87. raise TypeError('%(class)s must be added with %(class)s' % {"class": pretty_name(self)})
  88. def __iadd__(self, other):
  89. if isinstance(other, self.__class__):
  90. self.standard += other.standard
  91. return self
  92. else:
  93. raise TypeError('%(class)s must be added with %(class)s' % {"class": pretty_name(self)})
  94. def __sub__(self, other):
  95. if isinstance(other, self.__class__):
  96. return self.__class__(default_unit=self._default_unit,
  97. **{self.STANDARD_UNIT: (self.standard - other.standard)})
  98. else:
  99. raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
  100. def __isub__(self, other):
  101. if isinstance(other, self.__class__):
  102. self.standard -= other.standard
  103. return self
  104. else:
  105. raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
  106. def __mul__(self, other):
  107. if isinstance(other, NUMERIC_TYPES):
  108. return self.__class__(default_unit=self._default_unit,
  109. **{self.STANDARD_UNIT: (self.standard * other)})
  110. else:
  111. raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
  112. def __imul__(self, other):
  113. if isinstance(other, NUMERIC_TYPES):
  114. self.standard *= float(other)
  115. return self
  116. else:
  117. raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
  118. def __rmul__(self, other):
  119. return self * other
  120. def __truediv__(self, other):
  121. if isinstance(other, self.__class__):
  122. return self.standard / other.standard
  123. if isinstance(other, NUMERIC_TYPES):
  124. return self.__class__(default_unit=self._default_unit,
  125. **{self.STANDARD_UNIT: (self.standard / other)})
  126. else:
  127. raise TypeError('%(class)s must be divided with number or %(class)s' % {"class": pretty_name(self)})
  128. def __div__(self, other): # Python 2 compatibility
  129. return type(self).__truediv__(self, other)
  130. def __itruediv__(self, other):
  131. if isinstance(other, NUMERIC_TYPES):
  132. self.standard /= float(other)
  133. return self
  134. else:
  135. raise TypeError('%(class)s must be divided with number' % {"class": pretty_name(self)})
  136. def __idiv__(self, other): # Python 2 compatibility
  137. return type(self).__itruediv__(self, other)
  138. def __bool__(self):
  139. return bool(self.standard)
  140. def __nonzero__(self): # Python 2 compatibility
  141. return type(self).__bool__(self)
  142. def default_units(self, kwargs):
  143. """
  144. Return the unit value and the default units specified
  145. from the given keyword arguments dictionary.
  146. """
  147. val = 0.0
  148. default_unit = self.STANDARD_UNIT
  149. for unit, value in six.iteritems(kwargs):
  150. if not isinstance(value, float):
  151. value = float(value)
  152. if unit in self.UNITS:
  153. val += self.UNITS[unit] * value
  154. default_unit = unit
  155. elif unit in self.ALIAS:
  156. u = self.ALIAS[unit]
  157. val += self.UNITS[u] * value
  158. default_unit = u
  159. else:
  160. lower = unit.lower()
  161. if lower in self.UNITS:
  162. val += self.UNITS[lower] * value
  163. default_unit = lower
  164. elif lower in self.LALIAS:
  165. u = self.LALIAS[lower]
  166. val += self.UNITS[u] * value
  167. default_unit = u
  168. else:
  169. raise AttributeError('Unknown unit type: %s' % unit)
  170. return val, default_unit
  171. @classmethod
  172. def unit_attname(cls, unit_str):
  173. """
  174. Retrieves the unit attribute name for the given unit string.
  175. For example, if the given unit string is 'metre', 'm' would be returned.
  176. An exception is raised if an attribute cannot be found.
  177. """
  178. lower = unit_str.lower()
  179. if unit_str in cls.UNITS:
  180. return unit_str
  181. elif lower in cls.UNITS:
  182. return lower
  183. elif lower in cls.LALIAS:
  184. return cls.LALIAS[lower]
  185. else:
  186. raise Exception('Could not find a unit keyword associated with "%s"' % unit_str)
  187. class Distance(MeasureBase):
  188. STANDARD_UNIT = "m"
  189. UNITS = {
  190. 'chain': 20.1168,
  191. 'chain_benoit': 20.116782,
  192. 'chain_sears': 20.1167645,
  193. 'british_chain_benoit': 20.1167824944,
  194. 'british_chain_sears': 20.1167651216,
  195. 'british_chain_sears_truncated': 20.116756,
  196. 'cm': 0.01,
  197. 'british_ft': 0.304799471539,
  198. 'british_yd': 0.914398414616,
  199. 'clarke_ft': 0.3047972654,
  200. 'clarke_link': 0.201166195164,
  201. 'fathom': 1.8288,
  202. 'ft': 0.3048,
  203. 'german_m': 1.0000135965,
  204. 'gold_coast_ft': 0.304799710181508,
  205. 'indian_yd': 0.914398530744,
  206. 'inch': 0.0254,
  207. 'km': 1000.0,
  208. 'link': 0.201168,
  209. 'link_benoit': 0.20116782,
  210. 'link_sears': 0.20116765,
  211. 'm': 1.0,
  212. 'mi': 1609.344,
  213. 'mm': 0.001,
  214. 'nm': 1852.0,
  215. 'nm_uk': 1853.184,
  216. 'rod': 5.0292,
  217. 'sears_yd': 0.91439841,
  218. 'survey_ft': 0.304800609601,
  219. 'um': 0.000001,
  220. 'yd': 0.9144,
  221. }
  222. # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
  223. ALIAS = {
  224. 'centimeter': 'cm',
  225. 'foot': 'ft',
  226. 'inches': 'inch',
  227. 'kilometer': 'km',
  228. 'kilometre': 'km',
  229. 'meter': 'm',
  230. 'metre': 'm',
  231. 'micrometer': 'um',
  232. 'micrometre': 'um',
  233. 'millimeter': 'mm',
  234. 'millimetre': 'mm',
  235. 'mile': 'mi',
  236. 'yard': 'yd',
  237. 'British chain (Benoit 1895 B)': 'british_chain_benoit',
  238. 'British chain (Sears 1922)': 'british_chain_sears',
  239. 'British chain (Sears 1922 truncated)': 'british_chain_sears_truncated',
  240. 'British foot (Sears 1922)': 'british_ft',
  241. 'British foot': 'british_ft',
  242. 'British yard (Sears 1922)': 'british_yd',
  243. 'British yard': 'british_yd',
  244. "Clarke's Foot": 'clarke_ft',
  245. "Clarke's link": 'clarke_link',
  246. 'Chain (Benoit)': 'chain_benoit',
  247. 'Chain (Sears)': 'chain_sears',
  248. 'Foot (International)': 'ft',
  249. 'German legal metre': 'german_m',
  250. 'Gold Coast foot': 'gold_coast_ft',
  251. 'Indian yard': 'indian_yd',
  252. 'Link (Benoit)': 'link_benoit',
  253. 'Link (Sears)': 'link_sears',
  254. 'Nautical Mile': 'nm',
  255. 'Nautical Mile (UK)': 'nm_uk',
  256. 'US survey foot': 'survey_ft',
  257. 'U.S. Foot': 'survey_ft',
  258. 'Yard (Indian)': 'indian_yd',
  259. 'Yard (Sears)': 'sears_yd'
  260. }
  261. LALIAS = {k.lower(): v for k, v in ALIAS.items()}
  262. def __mul__(self, other):
  263. if isinstance(other, self.__class__):
  264. return Area(default_unit=AREA_PREFIX + self._default_unit,
  265. **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)})
  266. elif isinstance(other, NUMERIC_TYPES):
  267. return self.__class__(default_unit=self._default_unit,
  268. **{self.STANDARD_UNIT: (self.standard * other)})
  269. else:
  270. raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
  271. "distance": pretty_name(self.__class__),
  272. })
  273. class Area(MeasureBase):
  274. STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT
  275. # Getting the square units values and the alias dictionary.
  276. UNITS = {'%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.UNITS.items()}
  277. ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()}
  278. LALIAS = {k.lower(): v for k, v in ALIAS.items()}
  279. def __truediv__(self, other):
  280. if isinstance(other, NUMERIC_TYPES):
  281. return self.__class__(default_unit=self._default_unit,
  282. **{self.STANDARD_UNIT: (self.standard / other)})
  283. else:
  284. raise TypeError('%(class)s must be divided by a number' % {"class": pretty_name(self)})
  285. def __div__(self, other): # Python 2 compatibility
  286. return type(self).__truediv__(self, other)
  287. # Shortcuts
  288. D = Distance
  289. A = Area