Last active
December 11, 2015 11:59
-
-
Save juhasch/4597994 to your computer and use it in GitHub Desktop.
Allow to use units with numbers in iPython, e.g.
"1n"=1e-9 or "1G"=1e9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
IPython extension for engineering units | |
See README.txt for usage examples. | |
Author: Juergen Hasch <[email protected]> | |
Parts taken from the physics.py extension by Georg Brandl <[email protected]> | |
This file has been placed in the public domain. | |
Allows units to be specified like | |
1n | |
or | |
1 n | |
or | |
1e3p | |
""" | |
import re | |
import sys | |
from math import pi | |
number = r'(-?[\d0-9.-]+)' | |
unit = r'([a-df-zA-Z1°µ][a-df-zA-Z0-9°µ/^-]*)' | |
match = number + r'\s*' + unit | |
_prefixes = { | |
'Y': 1.e24 , 'Z': 1.e21, 'E': 1.e18, 'P': 1.e15, 'T': 1.e12, | |
'G': 1.e9, 'M': 1.e6, 'k': 1.e3, 'h': 1.e2, 'da': 1.e1, | |
'd': 1.e-1, 'c': 1.e-2, 'm': 1.e-3, 'mu': 1.e-6, 'u': 1.e-6, 'n': 1.e-9, | |
'p': 1.e-12, 'f': 1.e-15, 'a': 1.e-18, 'z': 1.e-2, | |
'y': 1.e-24, | |
} | |
def replace_inline(mo): | |
"""Replace unit by quantity | |
""" | |
try: | |
return mo.group(1) + "*" + str(_prefixes[mo.group(2)]) | |
except KeyError: | |
return mo.group(2) | |
class QTransformer(object): | |
"""IPython command line transformer that recognizes and replaces unit | |
expressions. | |
""" | |
# XXX: inheriting from PrefilterTransformer as documented gives TypeErrors, | |
# but apparently is not needed after all | |
priority = 99 | |
enabled = True | |
def transform(self, line, continue_prompt): | |
line = re.sub(match,replace_inline, line) | |
return line | |
q_transformer = QTransformer() | |
def load_ipython_extension(ip): | |
ip.prefilter_manager.register_transformer(q_transformer) | |
print 'Engineering Units extension activated.' | |
def unload_ipython_extension(ip): | |
ip.prefilter_manager.unregister_transformer(q_transformer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment