| 1 |
# Copyright (c) 2007, Robert Coup <[email protected]> |
| 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 |
|
| 33 |
Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio |
| 34 |
|
| 35 |
Inspired by GeoPy (https://github.com/geopy/geopy) |
| 36 |
and Geoff Biggs' PhD work on dimensioned units for robotics. |
| 37 |
""" |
| 38 |
|
| 39 |
from decimal import Decimal |
| 40 |
from functools import total_ordering |
| 41 |
|
| 42 |
__all__ = ["A", "Area", "D", "Distance"] |
| 43 |
|
| 44 |
NUMERIC_TYPES = (int, float, Decimal) |
| 45 |
AREA_PREFIX = "sq_" |
| 46 |
|
| 47 |
|
| 48 |
def pretty_name(obj): |
| 49 |
return obj.__name__ if obj.__class__ == type else obj.__class__.__name__ |
| 50 |
|
| 51 |
|
| 52 |
@total_ordering |
| 53 |
class MeasureBase: |
| 54 |
STANDARD_UNIT = None |
| 55 |
ALIAS = {} |
| 56 |
UNITS = {} |
| 57 |
LALIAS = {} |
| 58 |
|
| 59 |
def __init__(self, default_unit=None, **kwargs): |
| 60 |
value, self._default_unit = self.default_units(kwargs) |
| 61 |
setattr(self, self.STANDARD_UNIT, value) |
| 62 |
if default_unit and isinstance(default_unit, str): |
| 63 |
self._default_unit = default_unit |
| 64 |
|
| 65 |
def _get_standard(self): |
| 66 |
return getattr(self, self.STANDARD_UNIT) |
| 67 |
|
| 68 |
def _set_standard(self, value): |
| 69 |
setattr(self, self.STANDARD_UNIT, value) |
| 70 |
|
| 71 |
standard = property(_get_standard, _set_standard) |
| 72 |
|
| 73 |
def __getattr__(self, name): |
| 74 |
if name in self.UNITS: |
| 75 |
return self.standard / self.UNITS[name] |
| 76 |
else: |
| 77 |
raise AttributeError("Unknown unit type: %s" % name) |
| 78 |
|
| 79 |
def __repr__(self): |
| 80 |
return "%s(%s=%s)" % ( |
| 81 |
pretty_name(self), |
| 82 |
self._default_unit, |
| 83 |
getattr(self, self._default_unit), |
| 84 |
) |
| 85 |
|
| 86 |
def __str__(self): |
| 87 |
return "%s %s" % (getattr(self, self._default_unit), self._default_unit) |
| 88 |
|
| 89 |
# **** Comparison methods **** |
| 90 |
|
| 91 |
def __eq__(self, other): |
| 92 |
if isinstance(other, self.__class__): |
| 93 |
return self.standard == other.standard |
| 94 |
else: |
| 95 |
return NotImplemented |
| 96 |
|
| 97 |
def __hash__(self): |
| 98 |
return hash(self.standard) |
| 99 |
|
| 100 |
def __lt__(self, other): |
| 101 |
if isinstance(other, self.__class__): |
| 102 |
return self.standard < other.standard |
| 103 |
else: |
| 104 |
return NotImplemented |
| 105 |
|
| 106 |
# **** Operators methods **** |
| 107 |
|
| 108 |
def __add__(self, other): |
| 109 |
if isinstance(other, self.__class__): |
| 110 |
return self.__class__( |
| 111 |
default_unit=self._default_unit, |
| 112 |
**{self.STANDARD_UNIT: (self.standard + other.standard)}, |
| 113 |
) |
| 114 |
else: |
| 115 |
raise TypeError( |
| 116 |
"%(class)s must be added with %(class)s" % {"class": pretty_name(self)} |
| 117 |
) |
| 118 |
|
| 119 |
def __iadd__(self, other): |
| 120 |
if isinstance(other, self.__class__): |
| 121 |
self.standard += other.standard |
| 122 |
return self |
| 123 |
else: |
| 124 |
raise TypeError( |
| 125 |
"%(class)s must be added with %(class)s" % {"class": pretty_name(self)} |
| 126 |
) |
| 127 |
|
| 128 |
def __sub__(self, other): |
| 129 |
if isinstance(other, self.__class__): |
| 130 |
return self.__class__( |
| 131 |
default_unit=self._default_unit, |
| 132 |
**{self.STANDARD_UNIT: (self.standard - other.standard)}, |
| 133 |
) |
| 134 |
else: |
| 135 |
raise TypeError( |
| 136 |
"%(class)s must be subtracted from %(class)s" |
| 137 |
% {"class": pretty_name(self)} |
| 138 |
) |
| 139 |
|
| 140 |
def __isub__(self, other): |
| 141 |
if isinstance(other, self.__class__): |
| 142 |
self.standard -= other.standard |
| 143 |
return self |
| 144 |
else: |
| 145 |
raise TypeError( |
| 146 |
"%(class)s must be subtracted from %(class)s" |
| 147 |
% {"class": pretty_name(self)} |
| 148 |
) |
| 149 |
|
| 150 |
def __mul__(self, other): |
| 151 |
if isinstance(other, NUMERIC_TYPES): |
| 152 |
return self.__class__( |
| 153 |
default_unit=self._default_unit, |
| 154 |
**{self.STANDARD_UNIT: (self.standard * other)}, |
| 155 |
) |
| 156 |
else: |
| 157 |
raise TypeError( |
| 158 |
"%(class)s must be multiplied with number" |
| 159 |
% {"class": pretty_name(self)} |
| 160 |
) |
| 161 |
|
| 162 |
def __imul__(self, other): |
| 163 |
if isinstance(other, NUMERIC_TYPES): |
| 164 |
self.standard *= float(other) |
| 165 |
return self |
| 166 |
else: |
| 167 |
raise TypeError( |
| 168 |
"%(class)s must be multiplied with number" |
| 169 |
% {"class": pretty_name(self)} |
| 170 |
) |
| 171 |
|
| 172 |
def __rmul__(self, other): |
| 173 |
return self * other |
| 174 |
|
| 175 |
def __truediv__(self, other): |
| 176 |
if isinstance(other, self.__class__): |
| 177 |
return self.standard / other.standard |
| 178 |
if isinstance(other, NUMERIC_TYPES): |
| 179 |
return self.__class__( |
| 180 |
default_unit=self._default_unit, |
| 181 |
**{self.STANDARD_UNIT: (self.standard / other)}, |
| 182 |
) |
| 183 |
else: |
| 184 |
raise TypeError( |
| 185 |
"%(class)s must be divided with number or %(class)s" |
| 186 |
% {"class": pretty_name(self)} |
| 187 |
) |
| 188 |
|
| 189 |
def __itruediv__(self, other): |
| 190 |
if isinstance(other, NUMERIC_TYPES): |
| 191 |
self.standard /= float(other) |
| 192 |
return self |
| 193 |
else: |
| 194 |
raise TypeError( |
| 195 |
"%(class)s must be divided with number" % {"class": pretty_name(self)} |
| 196 |
) |
| 197 |
|
| 198 |
def __bool__(self): |
| 199 |
return bool(self.standard) |
| 200 |
|
| 201 |
def default_units(self, kwargs): |
| 202 |
""" |
| 203 |
Return the unit value and the default units specified |
| 204 |
from the given keyword arguments dictionary. |
| 205 |
""" |
| 206 |
val = 0.0 |
| 207 |
default_unit = self.STANDARD_UNIT |
| 208 |
for unit, value in kwargs.items(): |
| 209 |
if not isinstance(value, float): |
| 210 |
value = float(value) |
| 211 |
if unit in self.UNITS: |
| 212 |
val += self.UNITS[unit] * value |
| 213 |
default_unit = unit |
| 214 |
elif unit in self.ALIAS: |
| 215 |
u = self.ALIAS[unit] |
| 216 |
val += self.UNITS[u] * value |
| 217 |
default_unit = u |
| 218 |
else: |
| 219 |
lower = unit.lower() |
| 220 |
if lower in self.UNITS: |
| 221 |
val += self.UNITS[lower] * value |
| 222 |
default_unit = lower |
| 223 |
elif lower in self.LALIAS: |
| 224 |
u = self.LALIAS[lower] |
| 225 |
val += self.UNITS[u] * value |
| 226 |
default_unit = u |
| 227 |
else: |
| 228 |
raise AttributeError("Unknown unit type: %s" % unit) |
| 229 |
return val, default_unit |
| 230 |
|
| 231 |
@classmethod |
| 232 |
def unit_attname(cls, unit_str): |
| 233 |
""" |
| 234 |
Retrieve the unit attribute name for the given unit string. |
| 235 |
For example, if the given unit string is 'metre', return 'm'. |
| 236 |
Raise an AttributeError if an attribute cannot be found. |
| 237 |
""" |
| 238 |
lower = unit_str.lower() |
| 239 |
if unit_str in cls.UNITS: |
| 240 |
return unit_str |
| 241 |
elif lower in cls.UNITS: |
| 242 |
return lower |
| 243 |
elif lower in cls.LALIAS: |
| 244 |
return cls.LALIAS[lower] |
| 245 |
else: |
| 246 |
raise AttributeError(f"Unknown unit type: {unit_str}") |
| 247 |
|
| 248 |
|
| 249 |
class Distance(MeasureBase): |
| 250 |
STANDARD_UNIT = "m" |
| 251 |
UNITS = { |
| 252 |
"chain": 20.1168, |
| 253 |
"chain_benoit": 20.116782, |
| 254 |
"chain_sears": 20.1167645, |
| 255 |
"british_chain_benoit": 20.1167824944, |
| 256 |
"british_chain_sears": 20.1167651216, |
| 257 |
"british_chain_sears_truncated": 20.116756, |
| 258 |
"cm": 0.01, |
| 259 |
"british_ft": 0.304799471539, |
| 260 |
"british_yd": 0.914398414616, |
| 261 |
"clarke_ft": 0.3047972654, |
| 262 |
"clarke_link": 0.201166195164, |
| 263 |
"fathom": 1.8288, |
| 264 |
"ft": 0.3048, |
| 265 |
"furlong": 201.168, |
| 266 |
"german_m": 1.0000135965, |
| 267 |
"gold_coast_ft": 0.304799710181508, |
| 268 |
"indian_yd": 0.914398530744, |
| 269 |
"inch": 0.0254, |
| 270 |
"km": 1000.0, |
| 271 |
"link": 0.201168, |
| 272 |
"link_benoit": 0.20116782, |
| 273 |
"link_sears": 0.20116765, |
| 274 |
"m": 1.0, |
| 275 |
"mi": 1609.344, |
| 276 |
"mm": 0.001, |
| 277 |
"nm": 1852.0, |
| 278 |
"nm_uk": 1853.184, |
| 279 |
"rod": 5.0292, |
| 280 |
"sears_yd": 0.91439841, |
| 281 |
"survey_ft": 0.304800609601, |
| 282 |
"um": 0.000001, |
| 283 |
"yd": 0.9144, |
| 284 |
} |
| 285 |
|
| 286 |
# Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. |
| 287 |
ALIAS = { |
| 288 |
"centimeter": "cm", |
| 289 |
"foot": "ft", |
| 290 |
"inches": "inch", |
| 291 |
"kilometer": "km", |
| 292 |
"kilometre": "km", |
| 293 |
"meter": "m", |
| 294 |
"metre": "m", |
| 295 |
"micrometer": "um", |
| 296 |
"micrometre": "um", |
| 297 |
"millimeter": "mm", |
| 298 |
"millimetre": "mm", |
| 299 |
"mile": "mi", |
| 300 |
"yard": "yd", |
| 301 |
"British chain (Benoit 1895 B)": "british_chain_benoit", |
| 302 |
"British chain (Sears 1922)": "british_chain_sears", |
| 303 |
"British chain (Sears 1922 truncated)": "british_chain_sears_truncated", |
| 304 |
"British foot (Sears 1922)": "british_ft", |
| 305 |
"British foot": "british_ft", |
| 306 |
"British yard (Sears 1922)": "british_yd", |
| 307 |
"British yard": "british_yd", |
| 308 |
"Clarke's Foot": "clarke_ft", |
| 309 |
"Clarke's link": "clarke_link", |
| 310 |
"Chain (Benoit)": "chain_benoit", |
| 311 |
"Chain (Sears)": "chain_sears", |
| 312 |
"Foot (International)": "ft", |
| 313 |
"Furrow Long": "furlong", |
| 314 |
"German legal metre": "german_m", |
| 315 |
"Gold Coast foot": "gold_coast_ft", |
| 316 |
"Indian yard": "indian_yd", |
| 317 |
"Link (Benoit)": "link_benoit", |
| 318 |
"Link (Sears)": "link_sears", |
| 319 |
"Nautical Mile": "nm", |
| 320 |
"Nautical Mile (UK)": "nm_uk", |
| 321 |
"US survey foot": "survey_ft", |
| 322 |
"U.S. Foot": "survey_ft", |
| 323 |
"Yard (Indian)": "indian_yd", |
| 324 |
"Yard (Sears)": "sears_yd", |
| 325 |
} |
| 326 |
LALIAS = {k.lower(): v for k, v in ALIAS.items()} |
| 327 |
|
| 328 |
def __mul__(self, other): |
| 329 |
if isinstance(other, self.__class__): |
| 330 |
return Area( |
| 331 |
default_unit=AREA_PREFIX + self._default_unit, |
| 332 |
**{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)}, |
| 333 |
) |
| 334 |
elif isinstance(other, NUMERIC_TYPES): |
| 335 |
return self.__class__( |
| 336 |
default_unit=self._default_unit, |
| 337 |
**{self.STANDARD_UNIT: (self.standard * other)}, |
| 338 |
) |
| 339 |
else: |
| 340 |
raise TypeError( |
| 341 |
"%(distance)s must be multiplied with number or %(distance)s" |
| 342 |
% { |
| 343 |
"distance": pretty_name(self.__class__), |
| 344 |
} |
| 345 |
) |
| 346 |
|
| 347 |
|
| 348 |
class Area(MeasureBase): |
| 349 |
STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT |
| 350 |
# Getting the square units values and the alias dictionary. |
| 351 |
UNITS = {"%s%s" % (AREA_PREFIX, k): v**2 for k, v in Distance.UNITS.items()} | { |
| 352 |
"ha": 10000, |
| 353 |
} |
| 354 |
ALIAS = {k: "%s%s" % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()} | { |
| 355 |
"hectare": "ha", |
| 356 |
} |
| 357 |
|
| 358 |
LALIAS = {k.lower(): v for k, v in ALIAS.items()} |
| 359 |
|
| 360 |
def __truediv__(self, other): |
| 361 |
if isinstance(other, NUMERIC_TYPES): |
| 362 |
return self.__class__( |
| 363 |
default_unit=self._default_unit, |
| 364 |
**{self.STANDARD_UNIT: (self.standard / other)}, |
| 365 |
) |
| 366 |
else: |
| 367 |
raise TypeError( |
| 368 |
"%(class)s must be divided by a number" % {"class": pretty_name(self)} |
| 369 |
) |
| 370 |
|
| 371 |
|
| 372 |
# Shortcuts |
| 373 |
D = Distance |
| 374 |
A = Area |