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.

measure.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. from decimal import Decimal
  37. from functools import total_ordering
  38. __all__ = ['A', 'Area', 'D', 'Distance']
  39. NUMERIC_TYPES = (int, float, Decimal)
  40. AREA_PREFIX = "sq_"
  41. def pretty_name(obj):
  42. return obj.__name__ if obj.__class__ == type else obj.__class__.__name__
  43. @total_ordering
  44. class MeasureBase:
  45. STANDARD_UNIT = None
  46. ALIAS = {}
  47. UNITS = {}
  48. LALIAS = {}
  49. def __init__(self, default_unit=None, **kwargs):
  50. value, self._default_unit = self.default_units(kwargs)
  51. setattr(self, self.STANDARD_UNIT, value)
  52. if default_unit and isinstance(default_unit, str):
  53. self._default_unit = default_unit
  54. def _get_standard(self):
  55. return getattr(self, self.STANDARD_UNIT)
  56. def _set_standard(self, value):
  57. setattr(self, self.STANDARD_UNIT, value)
  58. standard = property(_get_standard, _set_standard)
  59. def __getattr__(self, name):
  60. if name in self.UNITS:
  61. return self.standard / self.UNITS[name]
  62. else:
  63. raise AttributeError('Unknown unit type: %s' % name)
  64. def __repr__(self):
  65. return '%s(%s=%s)' % (pretty_name(self), self._default_unit, getattr(self, self._default_unit))
  66. def __str__(self):
  67. return '%s %s' % (getattr(self, self._default_unit), self._default_unit)
  68. # **** Comparison methods ****
  69. def __eq__(self, other):
  70. if isinstance(other, self.__class__):
  71. return self.standard == other.standard
  72. else:
  73. return NotImplemented
  74. def __lt__(self, other):
  75. if isinstance(other, self.__class__):
  76. return self.standard < other.standard
  77. else:
  78. return NotImplemented
  79. # **** Operators methods ****
  80. def __add__(self, other):
  81. if isinstance(other, self.__class__):
  82. return self.__class__(
  83. default_unit=self._default_unit,
  84. **{self.STANDARD_UNIT: (self.standard + other.standard)}
  85. )
  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__(
  97. default_unit=self._default_unit,
  98. **{self.STANDARD_UNIT: (self.standard - other.standard)}
  99. )
  100. else:
  101. raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
  102. def __isub__(self, other):
  103. if isinstance(other, self.__class__):
  104. self.standard -= other.standard
  105. return self
  106. else:
  107. raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
  108. def __mul__(self, other):
  109. if isinstance(other, NUMERIC_TYPES):
  110. return self.__class__(
  111. default_unit=self._default_unit,
  112. **{self.STANDARD_UNIT: (self.standard * other)}
  113. )
  114. else:
  115. raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
  116. def __imul__(self, other):
  117. if isinstance(other, NUMERIC_TYPES):
  118. self.standard *= float(other)
  119. return self
  120. else:
  121. raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
  122. def __rmul__(self, other):
  123. return self * other
  124. def __truediv__(self, other):
  125. if isinstance(other, self.__class__):
  126. return self.standard / other.standard
  127. if isinstance(other, NUMERIC_TYPES):
  128. return self.__class__(
  129. default_unit=self._default_unit,
  130. **{self.STANDARD_UNIT: (self.standard / other)}
  131. )
  132. else:
  133. raise TypeError('%(class)s must be divided with number or %(class)s' % {"class": pretty_name(self)})
  134. def __itruediv__(self, other):
  135. if isinstance(other, NUMERIC_TYPES):
  136. self.standard /= float(other)
  137. return self
  138. else:
  139. raise TypeError('%(class)s must be divided with number' % {"class": pretty_name(self)})
  140. def __bool__(self):
  141. return bool(self.standard)
  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 kwargs.items():
  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. Retrieve the unit attribute name for the given unit string.
  175. For example, if the given unit string is 'metre', return 'm'.
  176. Raise an exception 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(
  265. default_unit=AREA_PREFIX + self._default_unit,
  266. **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)}
  267. )
  268. elif isinstance(other, NUMERIC_TYPES):
  269. return self.__class__(
  270. default_unit=self._default_unit,
  271. **{self.STANDARD_UNIT: (self.standard * other)}
  272. )
  273. else:
  274. raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
  275. "distance": pretty_name(self.__class__),
  276. })
  277. class Area(MeasureBase):
  278. STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT
  279. # Getting the square units values and the alias dictionary.
  280. UNITS = {'%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.UNITS.items()}
  281. ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()}
  282. LALIAS = {k.lower(): v for k, v in ALIAS.items()}
  283. def __truediv__(self, other):
  284. if isinstance(other, NUMERIC_TYPES):
  285. return self.__class__(
  286. default_unit=self._default_unit,
  287. **{self.STANDARD_UNIT: (self.standard / other)}
  288. )
  289. else:
  290. raise TypeError('%(class)s must be divided by a number' % {"class": pretty_name(self)})
  291. # Shortcuts
  292. D = Distance
  293. A = Area