This repository has been archived by the owner on Nov 10, 2022. It is now read-only.
forked from imnp/pygestalt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unitsOld.py
326 lines (246 loc) · 12.6 KB
/
unitsOld.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# pyGestalt Units Module
"""A set of common measurement units typically associated with numbers.
NOTE: The user should avoid doing substantial math using the dimensional dFloat type defined here.
It is very inefficient and is largely intended to keep things straight and avoid unit mistakes when
defining machine kinematics or performing analysis.
"""
import errors
import math
class unitDict(dict):
"""A dictionary sublcass used to store units and their powers."""
def update(self, other):
"""Overrides dict.update to modify powers if unit is already present.
other -- a dictionary of {unit:power} mappings to be used in updating this dictionary
"""
for key in other: #increment over keys in dictionary
if key in self:
dict.update(self, {key: self[key]+other[key]}) #unit already is in dictionary, so add powers
else:
dict.update(self, {key: other[key]})
self.reduce()
def reduce(self):
"""Removes any units whose power is 0.
Ruthless, no?
"""
hitList = filter(lambda unitPower: self[unitPower] == 0, self)
for thisUnit in hitList:
self.pop(thisUnit)
def __neg__(self):
"""Overrides the negative operator to invert the powers of the contained units."""
newUnitDict = unitDict(self) #create new copy
for key in newUnitDict: #invert powers of all units
newUnitDict[key] *= -1
return newUnitDict
def __mul__(self, other):
"""Overrides the multiplication operator to return units whose powers have been multiplied by other."""
newUnitDict = unitDict(self)
for key in newUnitDict:
newUnitDict[key] *= other
return newUnitDict
def __init__(self, value):
"""Initialization function for unit dictionary"""
dict.__init__(self, value)
self.reduce()
def __str__(self):
"""String representation of the unit dictionary."""
numeratorUnitList = filter(lambda unitPower: self[unitPower] > 0, self)
denominatorUnitList = filter(lambda unitPower: self[unitPower] < 0, self)
returnString = '' #this is the seed of the return string that will be built upon
#fill in numerator string if no units are in the numerator
if numeratorUnitList == [] and denominatorUnitList != []:
returnString += "1"
#fill in numerator string
for numeratorUnit in numeratorUnitList: #iterate over all units in numerator
if self[numeratorUnit] > 1: #more than to the first power
returnString += numeratorUnit.abbreviation + '^' + str(self[numeratorUnit]) + '*'
else:
returnString += numeratorUnit.abbreviation + '*'
if numeratorUnitList != []: returnString = returnString[:-1] #remove trailing *
if denominatorUnitList != []: returnString += '/' #add trailing /
for denominatorUnit in denominatorUnitList: #iterate over all units in denominator
if self[denominatorUnit] < -1: #more than to the first power
returnString += denominatorUnit.abbreviation + '^' + str(-self[denominatorUnit]) + '*'
else:
returnString += denominatorUnit.abbreviation + '*'
if denominatorUnitList != []: returnString = returnString[:-1] #remove trailing *
return returnString
class unit(object):
"""The base class for all measurement units."""
def __init__(self, dimension, conversion, abbreviation, fullName, derivedUnits = {}):
"""Generates a new unit type.
abbreviation -- the abbreviation to be used when printing the unit.
fullName -- the full name of the unit
derivedUnits -- a dictionary containing key pairs of {unitObject: power} for all units in the numerator from which this unit is derived
"""
self.dimension = dimension #the dimension of the unit
self.conversion = conversion #the conversion factor FROM BASE UNITS INTO THIS UNIT
self.abbreviation = abbreviation
self.fullName = fullName
#keep track of base units for unit conversion and display purposes
if derivedUnits != {}:
self.baseUnits = unitDict(derivedUnits) #base units come from derived units
else:
self.baseUnits = unitDict({self, 1}) #base units are simply self
dimension.addUnit(self, conversion) #adds this unit to the dimension object
def __call__(self, value):
"""Generates a new dFloat with the units of this unit object.
value -- a floating point value for the dimensional number.
"""
if self.derivedUnits != {}: #this is a derived unit
return dFloat(value, self.derivedUnits)
else: #not a derived unit, return dFloat with this as unit in numerator
return dFloat(value, {self:1})
class dimension(object):
"""This class defines a dimension such as distance or time."""
def __init__(self):
self.associatedUnits = {} #dictionary keeps track of which units are associated with this dimension
# conversion factors are stored as {unitObject: conversion}
# conversion is going from base units to associated unit
def addUnit(self, unit, conversion):
self.associatedUnits.update({unit:conversion})
def convert(self, sourceUnit, targetUnit):
"""Finds the scaling factor between the source and target units
Returns the scaling factor as a dFloat with target units, or False if no conversion is found.
"""
if sourceUnit in self.associatedUnits:
baseFactor = self.associatedUnits[sourceUnit] #this is the number of source units in the base unit
else:
raise errors.UnitConversionError("Source unit not found in dimension")
return False #source units not found
if targetUnit in self.associatedUnits:
targetFactor = self.associatedUnits[targetUnit]
else:
raise errors.unitConversionError("Target unit not found in dimension")
return False
value = float(baseFactor)/float(targetFactor)
units = unitDict({targetUnit:1})
return dFloat(value, units)
def convert(number, targetUnits):
"""Attempts to convert a dimensional number into target units.
number -- a dFloat to be converted.
targetUnits -- a unit type into which the dFloat should be converted.
returns a dFloat in target units, or None if conversion isn't possible.
"""
sourceUnits = number.units
targetUnits = targetUnits.baseUnits
class dFloat(float):
"""A dimensional floating-point number, i.e. a float with units."""
def __new__(self, value, units = {}):
"""Constructor for dFloat that overrides float.__new__
value -- the value of the floating point number.
numeratorUnits -- a dictionary containing key pairs of {unitObject: power} for all units in the numerator
denominatorUnits -- a dictionary containing key pairs of {unitObject: power} for all units in the denominator
"""
return float.__new__(self, value)
def __init__(self, value, units = {}):
"""Initializes the dFloat.
units -- a dictionary containing key pairs of {unitObject: power} for all units
"""
self.units = unitDict(units)
def __str__(self):
"""String representation of the dFloat number"""
return str(float(self)) + ' ' + str(self.units)
#--- OVERRIDE MATH FUNCTIONS ---
def __add__(self, other):
"""Overrides addition.
other -- the right-hand number to add
A unit check will be performed if right-hand operand is of type dFloat. Otherwise the units
of this dFloat will be passed along into the result.
"""
value = float(self) + float(other) #perform numerical addition
units = unitDict(self.units) #make a copy of unit dictionary
if type(other) == dFloat:
if self.units != other.units: #check to make sure units match
raise errors.UnitError("addition operand units don't match")
return dFloat(value, units)
def __radd__(self, other):
"""Overrides right-handed addition.
other -- the left-hand number to add.
The units of this dFloat will be passed along into the result.
"""
value = float(self) + float(other)
units = unitDict(self.units)
return dFloat(value, units)
def __sub__(self, other):
"""Overrides subtraction.
other -- the right-hand number to subract.
A unit check will be performed if right-hand operand is of type dFloat. Otherwise the units
of this dFloat will be passed along into the result.
"""
value = float(self) - float(other) #perform numerical addition
units = unitDict(self.units) #make a copy of unit dictionary
if type(other) == dFloat:
if self.units != other.units: #check to make sure units match
raise errors.UnitError("addition operand units don't match")
return dFloat(value, units)
def __rsub__(self, other):
"""Overrides right-handed subtraction.
other -- the left-hand number to subtract.
The units of this dFloat will be passed along into the result.
"""
value = float(other) - float(self)
units = unitDict(self.units)
return dFloat(value, units)
def __mul__(self, other):
"""Overrides left-hand multiplication.
other -- right-hand number to be multiplied.
"""
value = float(self) * float(other) #perform numerical multiplication
units = unitDict(self.units) #copy units dictionary
if type(other) == dFloat: #mix in units of other operand units
units.update(other.units)
return dFloat(value, units)
def __rmul__(self, other):
"""Overrides right-hand multiplication.
other -- left-hand number to be multiplied.
Note that this will only be called if the left-hand number is not a dFloat.
"""
value = float(other) * float(self)
return dFloat(value, self.units)
def __div__(self, other):
"""Overrides left-hand division.
other -- the right-hand number to be divided by.
"""
value = float(self)/ float(other) #perform numerical division
units = unitDict(self.units) #copy units dictionary
if type(other) == dFloat: #mix in inverse of right-hand operand units
units.update(-other.units)
return dFloat(value, units)
def __rdiv__(self, other):
"""Overrides right-hand division.
other -- the left-hand number to divide.
Note that this will only be called if the left-hand number is not a dFloat.
"""
value = float(other) / float(self)
return dFloat(value, -self.units) #inverted unit powers
def __pow__(self, other):
"""Overrides exponential.
other -- the power to raise this value to.
"""
value = float(self)**float(other)
units = unitDict(self.units * other)
return dFloat(value, units)
#--- DEFINE DIMENSIONS HERE ---
distance = dimension() #base unit is meters
angle = dimension() #base unit is radians
time = dimension() #base unit is seconds
force = dimension() #base unit is newtons
mass = dimension() #base unit is kg
#--- DEFINE UNITS HERE ---
# distance
m = unit(distance, 1.0, 'm', 'meters') #meters are the base units of distance
mm = unit(distance, 0.001, 'mm', 'millimeters')
cm = unit(distance, 0.01, 'cm', 'centimeters')
inches = unit(distance, 0.0254, 'in', 'inches')
# angle
rad = unit(angle, 1.0, 'rad', 'radians') #radians are the base units of angle
deg = unit(angle, (2.0*math.pi)/360.0, 'deg', 'degrees')
rev = unit(angle, 2.0*math.pi, 'rev', 'revolutions')
# time
s = unit(time, 1.0, 's', 'seconds') #seconds are the base units of time
min = unit(time, 60.0, 'min', 'minutes')
h = unit(time, 3600.0, 'h', 'hours')
# force
N = unit(force, 1.0, 'N', 'newtons') #newtons are the base unit of force
kgf = unit(force, 9.806, 'kgf', 'kilograms force')
ozf = unit(force, 9.806/35.274, 'oz', 'ounces')