Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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)" % (
  66. pretty_name(self),
  67. self._default_unit,
  68. getattr(self, self._default_unit),
  69. )
  70. def __str__(self):
  71. return "%s %s" % (getattr(self, self._default_unit), self._default_unit)
  72. # **** Comparison methods ****
  73. def __eq__(self, other):
  74. if isinstance(other, self.__class__):
  75. return self.standard == other.standard
  76. else:
  77. return NotImplemented
  78. def __hash__(self):
  79. return hash(self.standard)
  80. def __lt__(self, other):
  81. if isinstance(other, self.__class__):
  82. return self.standard < other.standard
  83. else:
  84. return NotImplemented
  85. # **** Operators methods ****
  86. def __add__(self, other):
  87. if isinstance(other, self.__class__):
  88. return self.__class__(
  89. default_unit=self._default_unit,
  90. **{self.STANDARD_UNIT: (self.standard + other.standard)},
  91. )
  92. else:
  93. raise TypeError(
  94. "%(class)s must be added with %(class)s" % {"class": pretty_name(self)}
  95. )
  96. def __iadd__(self, other):
  97. if isinstance(other, self.__class__):
  98. self.standard += other.standard
  99. return self
  100. else:
  101. raise TypeError(
  102. "%(class)s must be added with %(class)s" % {"class": pretty_name(self)}
  103. )
  104. def __sub__(self, other):
  105. if isinstance(other, self.__class__):
  106. return self.__class__(
  107. default_unit=self._default_unit,
  108. **{self.STANDARD_UNIT: (self.standard - other.standard)},
  109. )
  110. else:
  111. raise TypeError(
  112. "%(class)s must be subtracted from %(class)s"
  113. % {"class": pretty_name(self)}
  114. )
  115. def __isub__(self, other):
  116. if isinstance(other, self.__class__):
  117. self.standard -= other.standard
  118. return self
  119. else:
  120. raise TypeError(
  121. "%(class)s must be subtracted from %(class)s"
  122. % {"class": pretty_name(self)}
  123. )
  124. def __mul__(self, other):
  125. if isinstance(other, NUMERIC_TYPES):
  126. return self.__class__(
  127. default_unit=self._default_unit,
  128. **{self.STANDARD_UNIT: (self.standard * other)},
  129. )
  130. else:
  131. raise TypeError(
  132. "%(class)s must be multiplied with number"
  133. % {"class": pretty_name(self)}
  134. )
  135. def __imul__(self, other):
  136. if isinstance(other, NUMERIC_TYPES):
  137. self.standard *= float(other)
  138. return self
  139. else:
  140. raise TypeError(
  141. "%(class)s must be multiplied with number"
  142. % {"class": pretty_name(self)}
  143. )
  144. def __rmul__(self, other):
  145. return self * other
  146. def __truediv__(self, other):
  147. if isinstance(other, self.__class__):
  148. return self.standard / other.standard
  149. if isinstance(other, NUMERIC_TYPES):
  150. return self.__class__(
  151. default_unit=self._default_unit,
  152. **{self.STANDARD_UNIT: (self.standard / other)},
  153. )
  154. else:
  155. raise TypeError(
  156. "%(class)s must be divided with number or %(class)s"
  157. % {"class": pretty_name(self)}
  158. )
  159. def __itruediv__(self, other):
  160. if isinstance(other, NUMERIC_TYPES):
  161. self.standard /= float(other)
  162. return self
  163. else:
  164. raise TypeError(
  165. "%(class)s must be divided with number" % {"class": pretty_name(self)}
  166. )
  167. def __bool__(self):
  168. return bool(self.standard)
  169. def default_units(self, kwargs):
  170. """
  171. Return the unit value and the default units specified
  172. from the given keyword arguments dictionary.
  173. """
  174. val = 0.0
  175. default_unit = self.STANDARD_UNIT
  176. for unit, value in kwargs.items():
  177. if not isinstance(value, float):
  178. value = float(value)
  179. if unit in self.UNITS:
  180. val += self.UNITS[unit] * value
  181. default_unit = unit
  182. elif unit in self.ALIAS:
  183. u = self.ALIAS[unit]
  184. val += self.UNITS[u] * value
  185. default_unit = u
  186. else:
  187. lower = unit.lower()
  188. if lower in self.UNITS:
  189. val += self.UNITS[lower] * value
  190. default_unit = lower
  191. elif lower in self.LALIAS:
  192. u = self.LALIAS[lower]
  193. val += self.UNITS[u] * value
  194. default_unit = u
  195. else:
  196. raise AttributeError("Unknown unit type: %s" % unit)
  197. return val, default_unit
  198. @classmethod
  199. def unit_attname(cls, unit_str):
  200. """
  201. Retrieve the unit attribute name for the given unit string.
  202. For example, if the given unit string is 'metre', return 'm'.
  203. Raise an exception if an attribute cannot be found.
  204. """
  205. lower = unit_str.lower()
  206. if unit_str in cls.UNITS:
  207. return unit_str
  208. elif lower in cls.UNITS:
  209. return lower
  210. elif lower in cls.LALIAS:
  211. return cls.LALIAS[lower]
  212. else:
  213. raise Exception(
  214. 'Could not find a unit keyword associated with "%s"' % unit_str
  215. )
  216. class Distance(MeasureBase):
  217. STANDARD_UNIT = "m"
  218. UNITS = {
  219. "chain": 20.1168,
  220. "chain_benoit": 20.116782,
  221. "chain_sears": 20.1167645,
  222. "british_chain_benoit": 20.1167824944,
  223. "british_chain_sears": 20.1167651216,
  224. "british_chain_sears_truncated": 20.116756,
  225. "cm": 0.01,
  226. "british_ft": 0.304799471539,
  227. "british_yd": 0.914398414616,
  228. "clarke_ft": 0.3047972654,
  229. "clarke_link": 0.201166195164,
  230. "fathom": 1.8288,
  231. "ft": 0.3048,
  232. "furlong": 201.168,
  233. "german_m": 1.0000135965,
  234. "gold_coast_ft": 0.304799710181508,
  235. "indian_yd": 0.914398530744,
  236. "inch": 0.0254,
  237. "km": 1000.0,
  238. "link": 0.201168,
  239. "link_benoit": 0.20116782,
  240. "link_sears": 0.20116765,
  241. "m": 1.0,
  242. "mi": 1609.344,
  243. "mm": 0.001,
  244. "nm": 1852.0,
  245. "nm_uk": 1853.184,
  246. "rod": 5.0292,
  247. "sears_yd": 0.91439841,
  248. "survey_ft": 0.304800609601,
  249. "um": 0.000001,
  250. "yd": 0.9144,
  251. }
  252. # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
  253. ALIAS = {
  254. "centimeter": "cm",
  255. "foot": "ft",
  256. "inches": "inch",
  257. "kilometer": "km",
  258. "kilometre": "km",
  259. "meter": "m",
  260. "metre": "m",
  261. "micrometer": "um",
  262. "micrometre": "um",
  263. "millimeter": "mm",
  264. "millimetre": "mm",
  265. "mile": "mi",
  266. "yard": "yd",
  267. "British chain (Benoit 1895 B)": "british_chain_benoit",
  268. "British chain (Sears 1922)": "british_chain_sears",
  269. "British chain (Sears 1922 truncated)": "british_chain_sears_truncated",
  270. "British foot (Sears 1922)": "british_ft",
  271. "British foot": "british_ft",
  272. "British yard (Sears 1922)": "british_yd",
  273. "British yard": "british_yd",
  274. "Clarke's Foot": "clarke_ft",
  275. "Clarke's link": "clarke_link",
  276. "Chain (Benoit)": "chain_benoit",
  277. "Chain (Sears)": "chain_sears",
  278. "Foot (International)": "ft",
  279. "Furrow Long": "furlong",
  280. "German legal metre": "german_m",
  281. "Gold Coast foot": "gold_coast_ft",
  282. "Indian yard": "indian_yd",
  283. "Link (Benoit)": "link_benoit",
  284. "Link (Sears)": "link_sears",
  285. "Nautical Mile": "nm",
  286. "Nautical Mile (UK)": "nm_uk",
  287. "US survey foot": "survey_ft",
  288. "U.S. Foot": "survey_ft",
  289. "Yard (Indian)": "indian_yd",
  290. "Yard (Sears)": "sears_yd",
  291. }
  292. LALIAS = {k.lower(): v for k, v in ALIAS.items()}
  293. def __mul__(self, other):
  294. if isinstance(other, self.__class__):
  295. return Area(
  296. default_unit=AREA_PREFIX + self._default_unit,
  297. **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)},
  298. )
  299. elif isinstance(other, NUMERIC_TYPES):
  300. return self.__class__(
  301. default_unit=self._default_unit,
  302. **{self.STANDARD_UNIT: (self.standard * other)},
  303. )
  304. else:
  305. raise TypeError(
  306. "%(distance)s must be multiplied with number or %(distance)s"
  307. % {
  308. "distance": pretty_name(self.__class__),
  309. }
  310. )
  311. class Area(MeasureBase):
  312. STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT
  313. # Getting the square units values and the alias dictionary.
  314. UNITS = {"%s%s" % (AREA_PREFIX, k): v**2 for k, v in Distance.UNITS.items()}
  315. ALIAS = {k: "%s%s" % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()}
  316. LALIAS = {k.lower(): v for k, v in ALIAS.items()}
  317. def __truediv__(self, other):
  318. if isinstance(other, NUMERIC_TYPES):
  319. return self.__class__(
  320. default_unit=self._default_unit,
  321. **{self.STANDARD_UNIT: (self.standard / other)},
  322. )
  323. else:
  324. raise TypeError(
  325. "%(class)s must be divided by a number" % {"class": pretty_name(self)}
  326. )
  327. # Shortcuts
  328. D = Distance
  329. A = Area