add unicode units (#1471)

* adds unicode units

* keep "u" and "Ohm" for compatibility
* add c, d, da and h
* lint

* py2 compatible u"" strings
This commit is contained in:
Martin Chase 2021-01-03 14:28:56 -08:00 committed by GitHub
parent 64e04e3120
commit 1a71bb53c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,41 +1,41 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## Very simple unit support: # Very simple unit support:
## - creates variable names like 'mV' and 'kHz' # - creates variable names like 'mV' and 'kHz'
## - the value assigned to the variable corresponds to the scale prefix # - the value assigned to the variable corresponds to the scale prefix
## (mV = 0.001) # (mV = 0.001)
## - the actual units are purely cosmetic for making code clearer: # - the actual units are purely cosmetic for making code clearer:
## #
## x = 20*pA is identical to x = 20*1e-12 # x = 20*pA is identical to x = 20*1e-12
#
# No unicode variable names (μ,Ω) allowed until python 3, but just assigning
# them to the globals dict doesn't error in python 2.
import unicodedata
## No unicode variable names (μ,Ω) allowed until python 3 # All unicode identifiers get normalized automatically
SI_PREFIXES = unicodedata.normalize("NFKC", u"yzafpnµm kMGTPEZY")
SI_PREFIXES = 'yzafpnum kMGTPEZY' UNITS = unicodedata.normalize("NFKC", u"m,s,g,W,J,V,A,F,T,Hz,Ohm,Ω,S,N,C,px,b,B,Pa").split(",")
UNITS = 'm,s,g,W,J,V,A,F,T,Hz,Ohm,S,N,C,px,b,B,Pa'.split(',')
allUnits = {} allUnits = {}
def addUnit(p, n):
def addUnit(prefix, val):
g = globals() g = globals()
v = 1000**n
for u in UNITS: for u in UNITS:
g[p+u] = v g[prefix + u] = val
allUnits[p+u] = v allUnits[prefix + u] = val
for p in SI_PREFIXES:
if p == ' ':
p = ''
n = 0
elif p == 'u':
n = -2
else:
n = SI_PREFIXES.index(p) - 8
addUnit(p, n)
cm = 0.01
for pre in SI_PREFIXES:
v = SI_PREFIXES.index(pre) - 8
if pre == " ":
pre = ""
addUnit(pre, 1000 ** v)
addUnit("c", 0.01)
addUnit("d", 0.1)
addUnit("da", 10)
addUnit("h", 100)
# py2 compatibility
addUnit("u", 1e-6)
def evalUnits(unitStr): def evalUnits(unitStr):
@ -47,6 +47,7 @@ def evalUnits(unitStr):
""" """
pass pass
def formatUnits(units): def formatUnits(units):
""" """
Format a unit specification ([numerators,...], [denominators,...]) Format a unit specification ([numerators,...], [denominators,...])
@ -54,11 +55,10 @@ def formatUnits(units):
""" """
pass pass
def simplify(units): def simplify(units):
""" """
Cancel units that appear in both numerator and denominator, then attempt to replace Cancel units that appear in both numerator and denominator, then attempt to replace
groups of units with single units where possible (ie, J/s => W) groups of units with single units where possible (ie, J/s => W)
""" """
pass pass