1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
# Classes for measurement units
#
# Copyright (C) 1996-2001 Chris Lawrence
# This file may be freely distributed under the terms of the RoutePlanner
# license. A copy should appear as 'LICENSE' in the archive that this
# file was included in.
#
# db = rpdbase.RPDatabase(filename) - Load a database
# db.Open(filename) - Replace the database by loading another
# db.Save(filename) - Write the database
#
# db.cities - The list of city instances
# db.routes - The list of route instances
UNITS_METRIC = 'km'
UNITS_US = 'mi'
UNITS_IMPERIAL = 'mi2'
VALID_UNITS = [UNITS_METRIC, UNITS_US, UNITS_IMPERIAL]
UNITS = { 'Metric (km, l)' : UNITS_METRIC,
'U.S. (mi, gal = 3.785 liters)' : UNITS_US,
'Imperial (mi, gal = 4.546 liters)' : UNITS_IMPERIAL}
class Distance:
def __init__(self, initval=0.0, units=UNITS_US):
self.value = float(initval)
if units == UNITS_IMPERIAL:
units = UNITS_US
self.units = units
def __float__(self):
return self.value
def __add__(self, other):
if type(other) == type(self):
if self.units == other.units:
return Distance(self.value+other.value, self.units)
else:
return self+other.AsUnit(self.units)
def __div__(self, other):
if type(other) == type(self):
if self.units == other.units:
return Distance(self.value/other.value, self.units)
else:
return self/other.AsUnit(self.units)
def __str__(self):
return '%d %s' % (self.value, self.units)
def __nonzero__(self):
return bool(self.value)
def __cmp__(self, other):
if type(other) != type(self):
return cmp(self.value, other)
elif self.units == other.units:
return cmp(self.value, other.value)
else:
return cmp(self.value, other.AsUnit(self.units))
def AsUnit(self, units):
if units == self.units:
return self
if units == UNITS_IMPERIAL and self.units == UNITS_US:
return self
if units == UNITS_METRIC:
return Distance(self.value * 1.609344, units)
return Distance(self.value / 1.609344, units)
def ConvertEfficiency(amt, oldunits, newunits):
if oldunits == newunits: return amt
if oldunits == UNITS_METRIC:
if newunits == UNITS_US:
return 235.21458 / amt
else:
return 282.48094 / amt
elif oldunits == UNITS_US:
if newunits == UNITS_METRIC:
return 235.21458 / amt
else:
return amt * 1.20094
else:
if newunits == UNITS_METRIC:
return 282.48094 / amt
else:
return amt / 1.20094
|