Welcome, guest | Sign In | My Account | Store | Cart

I implemented dimensions.py perhaps eight years ago as an exercise and have used it occasionally ever since.

It allows doing math with dimensioned values in order to automate unit conversions (you can add m/s to mile/hour) and dimensional checking (you can't add m/s to mile/lightyear). It specifically does not convert 212F to 100C but rather will convert 9F to 5C (valid when converting temperature differences).

It is similar to unums (http://home.scarlet.be/be052320/Unum.html) but with a significant difference:

I used a different syntax Q(25,'m/s') as opposed to 100*m/s (I recall not wanting to have all the base SI units directly in the namespace). I'm not entirely sure which approach is really better.

I also had a specific need to have fractional exponents on units, allowing the following:

``````>>> km=Q(10,'N*m/W^(1/2)')
>>> km
Q(10.0, 'kg**0.5*m/s**0.5')
``````

Looking back I see a few design decisions I might do differently today, but I'll share it anyway.

Some examples are in the source below the line with if __name__ == "__main__":

Note that I've put two files into the code block below, dimensions.py and dimensions.data, so please cut them apart if you want to try it.

Python, 639 lines
 ``` 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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639``` ```======= dimensions.py ============= '''A module for adding dimensions to numeric types for dimensional analysis and automatic unit conversions. ''' from __future__ import division import math import re import os t___add__ = r'(?P<__add__>\+)' t___sub__ = r'(?P<__sub__>\-)' t___pow__ = r'(?P<__pow__>\^|(\*\*))' t___mul__ = r'(?P<__mul__>\*)' t___truediv__ = r'(?P<__truediv__>/)' t_LPAREN = r'(?P\()' t_NUMBER = r'(?P(\+|-)?((\d+\.\d+)|(\.\d+)|(\d+\.)|(\d+))([eE](\+|-)?\d+)?)' t_RPAREN = r'(?P\))' t_IDENT = r'(?P[a-zA-Z]\w*)' # ident names begin with letter ulexres= r'\s*(' + "|".join([t___add__, t_IDENT, t___pow__, t___truediv__, t___sub__, t___mul__, t_NUMBER, t_LPAREN, t_RPAREN]) + r')\s*' lexre = re.compile(ulexres) def tokenize(s): '''return a list of token tuples: (token, value, start)''' l=[] # list to hold tokens start=0 # used to check for bad tokens sc=lexre.scanner(s) while 1: tg=sc.search() if tg: if tg.start()!=start: # we should start at end of last token raise BadToken(start) l.append( [ (token, value, (tg.start(), tg.end())) for (token, value) in tg.groupdict().items() if value][0]) start=tg.end() # prepare start for next pass else: if start!=len(s): raise BadToken(start) break return l class UnmatchedParenthesis(Exception): pass class BadToken(Exception): def __init__(self,value): self.value=value def __str__(self): return repr(self.value) PRIORITY={ '__add__':1, '__sub__':1, '__mul__':2, '__truediv__':2, '__pow__':3} def convert(s): '''convert a list of token tuples from infix order to RPN''' input=s[:] stack=[] # 'Texas' LIFO output=[] # 'California' output accumulator while len(input)>0: # Careful! We're iterating over changing input list. if input[0][0]=='IDENT' or input[0][0]=='NUMBER': # move operands directly to output output.append(input.pop(0)) elif input[0][0]=='LPAREN': # Now handle a left parenthesis stack.append(input.pop(0)) elif input[0][0]=='RPAREN': # Now handle a right parenthesis if not stack: # We shouldn't have an RPAREN without an LPAREN raise UnmatchedParenthesis elif stack[-1][0]=='LPAREN': # when RPAREN catches up with LPAREN, vaporize both stack.pop() input.pop(0) else: # pop operands until we hit LPAREN output.append(stack.pop()) else: # logically, we should have an operand at the input, but # don't know about stack if stack: # there is at least one item in the stack if stack[-1][0]=='LPAREN': # LPAREN on stack, push next operand to stack stack.append(input.pop(0)) elif PRIORITY[input[0][0]]>PRIORITY[stack[-1][0]]: # higher priority input item goes to stack stack.append(input.pop(0)) else: output.append(stack.pop()) else: # no stack, push input to stack stack.append(input.pop(0)) while len(stack)>0: # when input is empty we still may have stack items to move over if stack[-1][0]=='LPAREN': # Shouldn't be any LPARENs left! raise UnmatchedParenthesis else: output.append(stack.pop()) return output def proc_stack(input, vardict): '''process IDENTs, binary operators in input list using vardict namespace''' stack=[] for item in input: # anything left to process? if item[0]=='IDENT': # push object referred to by IDENT onto stack stack.append(vardict[item[1]]) elif item[0]=='NUMBER': stack.append(float(item[1])) else: # we must have a binary operator # and assuming well formed input two operands on stack operand=item[0] y=stack.pop() x=stack.pop() # XXX the following hack should be fixed some time just # because it is really ugly! if operand=='__truediv__' and type(y)!=type(1.0) and \ type(x)==type(1.0) and x==1 : # special case of empty numerator and Q denom x=vardict[''] # this is coordinated with hack in UNITS_LIST in dimensions.py stack.append(x.__getattribute__(operand)(y)) return stack[0] def ap_eval(instr,vardict): '''evaluate an expression string using vardict namespace''' t=tokenize(instr) s=convert(t) ans=proc_stack(s,vardict) return ans class DimensionsError(Exception): def __init__(self, value): self.value=value def __str__(self): return repr(self.value) class Q(object): EXPTOL=1e-14 '''simple class for creating base dimensions''' def __init__(self, value, dimstr, utype=None): '''takes name of base unit and creates a Base object''' if utype=='BASE': # manually create the dimension for a base unit self.value=value # value of dimension self.dims={} # dict of dimensions, keys are base units self.dims[dimstr]=1 else: # we're building a compound unit if dimstr.strip()=='': # no Dim object yet, so build it self.value=value self.dims={} else: tmp=ap_eval(dimstr,units) # At this point we have a Dim object self.value=value*tmp.value self.dims=tmp.dims def copy(self): '''make a copy''' tmp=Q(1,'') tmp.value=self.value tmp.dims=self.dims.copy() return tmp def __neg__(self): '''return negative of self''' tmp=self.copy() tmp.value=-self.value return tmp def __pos__(self): '''unary positive operator''' return self.copy() def __abs__(self): '''abs operator''' tmp=self.copy() tmp.value=abs(self.value) return tmp def __add__(self, other): '''add like units together''' tmp=self.copy() if other.dims==tmp.dims: tmp.value=self.value+other.value return tmp else: raise DimensionsError, 'Units not consistent' # Rich comparison operators def __lt__(self, other): '''lt method for units''' if self.dims!=other.dims: raise DimensionsError, 'Units not consistent' else: return self.valueother.value def __le__(self, other): '''le method for units''' return not self.__gt__(other) def __sub__(self, other): '''subtract like units''' tmp=self.copy() if other.dims==tmp.dims: tmp.value=self.value-other.value return tmp else: raise DimensionsError, 'Units not consistent' def __mul__(self, other): '''multiply two units together''' # get list of dims used in both units try: tmp=Q(1,'') tmp.value=self.value*other.value superset=dict.fromkeys(self.dims.keys()+other.dims.keys()).keys() for dim in superset: tmp.dims[dim]=self.dims.get(dim,0)+ \ other.dims.get(dim,0) if abs(tmp.dims[dim] %1)0] numdims.sort() numstrlist=[] for dim,power in numdims: if power==1: numstrlist.append(dim) else: numstrlist.append(''.join([dim,'**',str(power)])) numstr='*'.join(numstrlist) dendims=[(dim,-self.dims[dim]) for dim in self.dims if self.dims[dim]<0] denstrlist=[] for dim,power in dendims: if power==1: denstrlist.append(dim) else: denstrlist.append(''.join([dim,'**',str(power)])) denstr='*'.join(denstrlist) if len(denstrlist)>1: denstr='(%s)' % denstr if len(numdims)==0 and len(dendims)==0: dimstr='' elif len(numdims)==0: dimstr='1/'+denstr elif len(dendims)==0: dimstr=numstr else: dimstr='%s/%s' % (numstr,denstr) return 'Q(%s, \'%s\')' % (self.value, dimstr) def __call__(self,otherdim, fmt=None): '''return value when expressed in otherdim dimensions''' o=Q(1,otherdim) if self.dims==o.dims: if fmt==None: return self.value/o.value else: return ''.join([fmt % (self.value/o.value),' [', otherdim,']']) else: raise DimensionsError, 'Units not consistent' def str(self,dims,valfmt='%s',dimfmt=' [%s]'): '''return a string in dimensions (dims) using value format specifier (valfmt) and dims format specifier (dimfmt)''' return ''.join(((valfmt % self(dims)),(dimfmt % dims))) class UnitsDatabase(object): def __init__(self, base_types, prefixes): '''create a UnitsDatabase object''' # start creation of units dictionary self.units={} for base in base_types: self.units[base]=Q(1, base, utype='BASE') self.prefixes=prefixes def __getitem__(self, key): '''grab item from dictionary if it exists, otherwise try prefixes''' if key in self.units: return self.units[key] else: if len(key)==1: # don't look for prefix if one letter unit raise DimensionsError, 'unit %s not found' % key for prefix in self.prefixes: if key.startswith(prefix): return self.prefixes[prefix]*self.units[key[len(prefix):]] raise DimensionsError, 'unit %s not found' % key def addUnit(self,name,utuple): '''add a unit to the unit database''' val=utuple[0] dims=utuple[1] self.units[name]=Q(val,dims) def addBase(self,name): '''add a base type to the unit database''' val=1 self.units[name]=Q(val,name,utype='BASE') def addPrefix(self,name,val): '''add a prefix to the unit database''' self.prefixes[name]=val def find(self,s): '''lists units containing the substring s''' re_find=re.compile(r'.*%s.*' % s ,re.I) res=[key for key in units.units.keys() if re_find.match(key)] res.sort() for unit in res: print unit # read the bases, prefixes and units from the dimensions.data file execfile(os.path.join(os.path.dirname(__file__),'dimensions.data')) units=UnitsDatabase(BASE_TYPES, PREFIXES) for unit,tup in UNITS_LIST: units.addUnit(unit,tup) BASE_TYPES=[] PREFIXES={} UNITS_LIST=[] # now add any from the user.data file try: execfile(os.path.join(os.path.dirname(__file__),'user.data')) for base in BASE_TYPES: units.addBase(base) for pref in PREFIXES: units.addPrefix(pref,PREFIXES[pref]) for unit, dimtup in UNITS_LIST: units.addUnit(unit,dimtup) except IOError: pass if __name__=='__main__': # this is where the tests live D0=Q(3, 'mN*m/A') D1=Q(4, 'A') assert(repr(D0*D1)=="Q(0.012, 'kg*m**2/s**2')") D2=Q(0.25, '1/A') assert(repr(D0/D2)=="Q(0.012, 'kg*m**2/s**2')") D3=Q(1,'1/W**(1/2)') D4=Q(1,'1/W**(1/2.)') D5=Q(1,'1/W**(1./2)') D6=Q(1,'1/W**(1./2.)') assert(D3==D4) assert(D3==D5) assert(D3==D6) D7=Q(3.3,'N*cm/W**0.5') assert(repr(D7)=="Q(0.033, 'kg**0.5*m/s**0.5')") assert(repr(D7*D7)=="Q(0.001089, 'kg*m**2/s')") assert(repr(D7**2)=="Q(0.001089, 'kg*m**2/s')") T=Q(15.2,'mN*m') ke=Q(3.6,'V/krpm') assert(repr(T/ke)=="Q(0.442150077172, 'A')") vel=Q(4000,'rpm') P=T*vel assert(str(P)=="Q(6.36696111128, 'kg*m**2/s**3')") assert(str(P('W'))=="6.36696111128") assert(P('horsepower')==0.0085348004172591339) units.addBase('sample') srate=Q(36,'ksample/s') units.addBase('interrupt') irate=Q(600,'interrupt/s') assert(srate/irate==Q(60.0, 'sample/interrupt')) km=Q(2.035,'N*cm/W**0.5') assert(str((T/km)**2)== "Q(0.557902552989, 'kg*m**2/s**3')") assert(((T/km)**2)('W')==0.55790255298854785) AddedInconsistentDims=0 try: Q(2,'ft')+Q(3,'s') except DimensionsError: AddedInconsistentDims=1 assert(AddedInconsistentDims) SubtracedInconsistentDims=0 try: Q(2,'ft')-Q(3,'s') except DimensionsError: SubtracedInconsistentDims=1 assert(SubtracedInconsistentDims) assert (-Q(5,'')==Q(-5,'')) assert (+Q(5,'')==Q(5,'')) assert (abs(Q(-5,''))==Q(5,'')) assert (abs(Q(5,''))==Q(5,'')) ============= dimensions.data ============== # Do not modify this file as it will be replace by the next installation # of the dimensions module. # If you wish to add a file with units that will get added every time # the dimensions module is loaded, add a file called user.data # in the dimensions directory, with the same format as this file. BASE_TYPES=['m', 'kg', 's', 'A', 'K'] PREFIXES=dict( yotta= 1e24, Y= 1e24, zetta= 1e21, Z= 1e21, exa= 1e18, E= 1e18, peta= 1e15, P= 1e15, tera= 1e12, T= 1e12, giga= 1e9, G= 1e9, mega= 1e6, M= 1e6, myria= 1e4, kilo= 1000, k= 1000, hecto= 100, h= 100, deca= 10, deka= 10, da= 10, deci= 1/10, d= 1/10, centi= 1/100, c= 1/100, milli= 1/1000, m= 1/1000, micro= 1e-6, u= 1e-6, nano= 1e-9, n= 1e-9, pico= 1e-12, p= 1e-12, femto= 1e-15, f= 1e-15, atto= 1e-18, a= 1e-18, zepto= 1e-21, z= 1e-21, yocto= 1e-24, y= 1e-24) UNITS_LIST= [('',(1,'')), # a hack to help handle the '1/unit' case ('meter',(1,'m')), ('second',(1,'s')), ('kilogram',(1,'kg')), ('gram',(0.001,'kg')), ('kelvin',(1,'K')), ('ampere',(1,'A')), ('amp',(1,'A')), ('radian',(1,'')), ('rd',(1,'radian')), ('newton',(1,'kg*m/s**2')), ('N',(1,'newton')), ('pascal',(1,'N/m**2')), ('Pa',(1,'pascal')), ('joule',(1,'N*m')), ('J',(1,'joule')), ('watt',(1,'J/s')), ('W',(1,'watt')), ('coulomb',(1, 'A*s')), ('C',(1,'coulomb')), ('volt',(1,'W/A')), ('V',(1,'volt')), ('ohm',(1,'V/A')), ('siemens',(1,'1/ohm')), ('S',(1,'siemens')), ('farad',(1,'C/V')), ('F',(1,'farad')), ('weber',(1,'V*s')), ('Wb',(1,'weber')), ('henry',(1,'Wb/A')), ('H',(1,'henry')), ('tesla',(1,'Wb/m**2')), ('T',(1,'tesla')), ('hertz',(1,'1/s')), ('Hz',(1, 'hertz')), ('sec',(1, 's')), ('minute',(60,'s')), ('min',(1,'minute')), ('hour',(60,'min')), ('hr',(1,'hour')), ('day',(24, 'hr')), ('week',(7,'day')), ('fortnight',(14,'day')), ('gm',(1,'gram')), ('g',(1,'gm')), ('tonne',(1000,'kg')), ('t',(1,'tonne')), ('cc',(1,'cm**3')), ('liter',(1000,'cc')), ('l',(1,'liter')), ('L',(1,'l')), ('mho',(1,'siemens')), ('angstrom',(1e-10, 'm')), ('fermi',(1e-15, 'm')), ('barn',(1e-28, 'm**2')), ('c',(299792458, 'm/s')), ('G',(6.6742e-11, 'N*m**2/kg**2')), ('au',(1.49559787e11,'m')), ('pi',(math.pi,'')), ('e',(math.e,'')), ('circle',(2,'pi')), ('rev',(1,'circle')), ('rpm',(1,'rev/min')), ('degC',(1,'K')), ('degF',(5/9, 'degC')), ('gravity',(9.80665, 'm/s**2')), ('force',(1,'gravity')), ('inch', (2.54, 'cm')), ('in', (2.54, 'cm')), ('foot', (12, 'inch')), ('feet', (1, 'foot')), ('ft', (1,'feet')), ('nauticalmile',(6080,'feet')), ('acre',(43560,'feet**2')), ('yard',(3,'ft')), ('mile',(5280,'ft')), ('calorie',(4.1868,'J')), ('cal',(1,'calorie')), ('lightyear',(365.25, 'day*c')), ('ly', (1,'lightyear')), ('torr',(101325/760, 'Pa')), ('Torr',(1,'torr')), ('kgf',(1, 'kg*gravity')), ('at',(1,'kgf/cm**2')), ('pound',(0.45359237,'kg')), ('lb',(1,'pound')), ('lbf',(1,'pound*force')), ('ounce',(1/16,'lb')), ('oz',(1,'ounce')), ('ozf',(1,'ounce*force')), ('ton',(2000,'lb')), ('gallon',(231,'inch**3')), ('gal', (1, 'gallon')), ('quart',(1/4, 'gal')), ('pint',(1/2, 'quart')), ('fluidounce',(1/16, 'pint')), ('floz',(1,'fluidounce')), ('cup', (8, 'floz')), ('tablespoon', (1/16, 'cup')), ('tbl', (1,'tablespoon')), ('tbsp',(1,'tbl')), ('Tbsp',(1,'tbsp')), ('Tsp', (1,'tablespoon')), ('teaspoon', (1/3, 'tablespoon')), ('tsp', (1,'teaspoon')), ('psi', (1, 'pound*force/inch**2')), ('slug', (1,'lbf*s**2/ft')), ('Btu',(1, 'cal*lb/gram')), ('btu',(1,'Btu')), ('BTU',(1,'Btu')), ('horsepower',(746, 'W')), ('hp',(1,'horsepower')), ('Wh',(1,'W*hour'))] ```
 Created by David Klaffenbach on Sat, 24 Jul 2010 (MIT)

### Required Modules

• (none specified)