from unum.units import Hz, kg, g, mg, ug, ng, pg, V, m, mm, um, nm, K, mK, uK, nK, BAR, N, s, ms, us, ns, W, A, mA, uA, nA, J, rad, deg from unum import IncompatibleUnitsError, ShouldBeUnitlessError import math from unum import Unum import numpy import re #regular expressions for helping recognize strange units #mBAR = Unum.unit("mBar",1e-3*BAR) mHz = Unum.unit("mHz", 0.1 * Hz) kHz = Unum.unit("kHz", 1000 * Hz) MHz = Unum.unit("MHz", 1e6 * Hz) GHz = Unum.unit("GHz", 1e9 * Hz) mW = Unum.unit("mW", 1e-3 * W) uW = Unum.unit("uW", 1e-6 * W) nW = Unum.unit("nW", 1e-9 * W) pW = Unum.unit("pW", 1e-12 * W) mV = Unum.unit("mV", 1e-3 * V) uV = Unum.unit("uV", 1e-6 * V) #nV = Unum.unit("nV",1e-9*V) mrad = Unum.unit("mrad", 1e-3 * rad) dBm = Unum.unit("dBm") def getName(u): if isUnit(u, Hz): return "frequency" if isUnit(u, s):
""" Units Defines/registers custom units for Pint @author: Nick Ruggero @organization: Covert Lab, Department of Bioengineering, Stanford University @date: Created 8/14/2014 """ import scipy.constants import numpy as np from unum.units import * from unum import Unum count = Unum.unit('count',mol/(scipy.constants.Avogadro)) nt = Unum.unit('nucleotide', count) aa = Unum.unit('amino_acid', count) def sort(a, axis=-1, kind='quicksort', order=None): if not hasUnit(a): raise Exception('Only works on Unum!') a_unit = getUnit(a) a = a.asNumber() return a_unit * np.sort(a, axis=-1, kind='quicksort', order=None) def nanmean(a, axis=None, dtype=None, out=None, keepdims=False): if not hasUnit(a): raise Exception('Only works on Unum!') a_unit = getUnit(a) a = a.asNumber()
from unum import Unum from unum.units import M as __M from unum.units import J as __J from unum.units import ANGSTROM as __ANGSTROM from unum.units import ARCDEG as __ARCDEG from unum.units import RAD as __RAD from unum.units import U as __U from unum.units import EV as __EV from unum.units import C as __C meter = __M bohr = Unum.unit('bohr', 5.2917720859e-11 * meter) angstrom = __ANGSTROM Ang = angstrom degrees = __ARCDEG deg = degrees radians = __RAD rad = radians # space occupation byte = Unum.unit("byte") kbyte = Unum.unit("kilobyte", 1000 * byte) Mbyte = Unum.unit("megabyte", 1000000 * byte) Gbyte = Unum.unit("gigabyte", 1000000000 * byte) kibyte = Unum.unit("kibibyte", 1024 * byte) Mibyte = Unum.unit("mebibyte", 1024 * 1024 * byte) Gibyte = Unum.unit("gibibyte", 1024 * 1024 * 1024 * byte)
from unum.units import Hz,kg,g,mg,ug,ng,pg,V,m,mm,um,nm,K,mK,uK,nK,BAR,N,s,ms,us,ns,W,A,mA,uA,nA,J,rad,deg from unum import IncompatibleUnitsError,ShouldBeUnitlessError import math from unum import Unum import numpy import re #regular expressions for helping recognize strange units #mBAR = Unum.unit("mBar",1e-3*BAR) mHz = Unum.unit("mHz",0.1*Hz) kHz = Unum.unit("kHz",1000*Hz) MHz = Unum.unit("MHz",1e6*Hz) GHz = Unum.unit("GHz",1e9*Hz) mW = Unum.unit("mW", 1e-3*W) uW = Unum.unit("uW", 1e-6*W) nW = Unum.unit("nW", 1e-9*W) pW = Unum.unit("pW", 1e-12*W) mV = Unum.unit("mV",1e-3*V) uV = Unum.unit("uV",1e-6*V) #nV = Unum.unit("nV",1e-9*V) mrad = Unum.unit("mrad",1e-3*rad) dBm = Unum.unit("dBm")
from unum.units import * from unum import Unum # Defined units KM = Unum.unit('km' , 1000. * M ) CM = Unum.unit('cm' , .01 * M ) GRAM = Unum.unit('g' , .001 * KG) # Constants G = 6.6720E-11 * N*M**2/KG**2 earth_mass = 5.980E24 * KG c = 299792458 * M/S earth_radius = 6.37E+06 * M # Input data distances = (5*CM, earth_radius, c * 365*24*H) masses = (5*GRAM, earth_mass, 1000*earth_mass) # -- Processing and display print "G = %s" % G print "Earth mass = %s" % earth_mass print "Earth radius = %s" % earth_radius.asUnit(KM) print "distances = %s" % str(distances) print "masses = %s" % str(masses) print
from unum import Unum, units mps = Unum.unit("m/s", units.m / units.s, "meters per second") radps = Unum.unit("rad/s", units.rad / units.s, "radians per second")
# Para importar as unidades e trabalhar com elas no script, execute o # código abaixo: # # .. code:: python from unum import Unum from unum.units import m, s, N, Pa, kg # A fim de facilitar o desenvolvimento de cálculos nesta seção, seguem # abaixo algumas definições: # # .. code:: python Unum.VALUE_FORMAT = "%.2f" grav = Unum.unit('grav',10*m/s**2,'gravity') # gravV = grav * np.array([0,0,-1]) kN = Unum.unit('kN',1000*N,'kilo Newton') MPa = Unum.unit('MPa',10**6*Pa,'mega Pascal') # # Objetos e Funções # ----------------- # # Segue abaixo um objeto base para facilitar atividades comuns como, por # exemplo, impressão de resultados, controle de alteração, etc: # # .. code:: python class base(object): def __init__(self):
class CSS(File): """ CSS.styles: the style rules are keys in the "styles" dict. This is limiting, but it works -- it happens to result in things being ordered correctly (with @-rules first), and it allows us to effectively query and manipulate the contents of the stylesheet at any time. CSS.pt, CSS.px, CSS.em, CSS.en, CSS.inch, CSS.pi, CSS.percent: All the main units are supported and are defined in terms of points, with 1.0em = 12.0pt """ pt = Unum.unit('pt') px = Unum.unit('px', 1.0 * pt) em = Unum.unit('em', 12. * pt) # but em is variable to the font-size of the context. rem = Unum.unit('rem', 12. * pt) en = Unum.unit('en', 6. * pt) ex = Unum.unit('ex', 1. * en) inch = Unum.unit('in', 72. * pt) pi = Unum.unit('pi', 12. * pt) percent = Unum.unit('%', 0.01 * em) units = { 'pt': pt, 'px': px, 'em': em, 'rem': rem, 'ex': ex, 'in': inch, 'pi': pi, '%': percent } def __init__(self, fn=None, styles=None, text=None, encoding='UTF-8', **args): File.__init__(self, fn=fn, encoding=encoding, **args) if styles is not None: self.styles = styles elif text is not None: self.styles = Styles.from_css(text) elif fn is not None and os.path.exists(fn): self.styles = Styles.from_css( open(fn, 'rb').read().decode(encoding)) else: self.styles = Styles() @classmethod def to_unit(C, val, unit=None): """convert a string measurement to a Unum""" md = re.match(r'^(?P<num>[\d\.]+)(?P<unit>.*)$', val) if md is not None: un = float(md.group('num')) * CSS.units[md.group('unit')] if unit is not None: return un.asUnit(unit) else: return un @classmethod def unit_string(C, unum): n = unum.asNumber() u = unum.strUnit() return "%.2f%s" % (n, u) @property def text(self): return self.render_styles() def render_styles(self, margin='', indent='\t'): return Styles.render(self.styles, margin=margin, indent=indent) def write(self, fn=None, encoding='UTF-8', **args): text = self.render_styles() File.write(self, fn=fn, data=text.encode(encoding)) @classmethod def merge_stylesheets(Class, fn, *cssfns): """merge the given CSS files, in order, into a single stylesheet. First listed takes priority. """ stylesheet = Class(fn=fn) for cssfn in cssfns: css = Class(fn=cssfn) for sel in sorted(css.styles.keys()): if sel not in stylesheet.styles: stylesheet.styles[sel] = css.styles[sel] else: for prop in [ prop for prop in css.styles[sel] if prop not in stylesheet.styles[sel] ]: stylesheet.styles[sel][prop] = css.styles[sel][prop] return stylesheet @classmethod def all_selectors(Class, fn): """return a sorted list of selectors that occur in the stylesheet""" selectors = [] cssparser = cssutils.CSSParser(validate=False) css = cssparser.parseFile(fn) for rule in [ r for r in css.cssRules if type(r) == cssutils.css.CSSStyleRule ]: selectors += [sel.selectorText for sel in rule.selectorList] selectors = sorted(list(set(selectors))) return selectors @classmethod def selector_to_xpath(cls, selector, xmlns=None): """convert a css selector into an xpath expression. xmlns is option single-item dict with namespace prefix and href """ selector = selector.replace(' .', ' *.') if selector[0] == '.': selector = '*' + selector log.debug(selector) if '#' in selector: selector = selector.replace('#', '*#') log.debug(selector) if xmlns is not None: prefix = list(xmlns.keys())[0] href = xmlns[prefix] selector = ' '.join([ (n.strip() != '>' and prefix + '|' + n.strip() or n.strip()) for n in selector.split(' ') ]) log.debug(selector) path = cssselect.GenericTranslator().css_to_xpath(selector) path = path.replace("descendant-or-self::", "") path = path.replace("/descendant::", "//") path = path.replace('/*/', '//') log.debug(' ==> %s' % path) return path @classmethod def cmyk_to_rgb(Class, c, m, y, k): """CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231# """ c = float(c) / 100.0 m = float(m) / 100.0 y = float(y) / 100.0 k = float(k) / 100.0 nc = (c * (1 - k)) + k nm = (m * (1 - k)) + k ny = (y * (1 - k)) + k r = int((1 - nc) * 255) g = int((1 - nm) * 255) b = int((1 - ny) * 255) return dict(r=r, g=g, b=b) @classmethod def rgb_to_hex(Class, r, g, b): """RGB in 0-255 to hex (RRGGBB)""" return ("%2s%2s%2s" % (hex(int(r)).lstrip('0x'), hex( int(g)).lstrip('0x'), hex(int(b)).lstrip('0x'))).replace( ' ', '0').upper()
# Example of a custom units file. To use, just place in your path # and type:: # from my_units import * from unum.units import * from unum import Unum SPAM = Unum.unit('spam') KSPAM = Unum.unit('kilospam', 1000 * SPAM) MSPAM = Unum.unit('millispam', 0.001 * SPAM) SPS = Unum.unit('sps', SPAM / S)
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 14:03:14 2014 @author: sophie """ print "Hello world!" import unum from unum import Unum from unum.units import * unit = Unum.unit ft = Unum.unit('foot',M/3.28084) lbf= Unum.unit('lbf',4.4482216*N) torque = 181 * ft * lbf print torque.asUnit(N*M) units1 = (1*W*V*F*ohm*S)/(1*C*Hz*J) print units1
from unum.units import * from unum import Unum MSOL = Unum.unit("MSOL", 1.98892e30 * KG) RSOL = Unum.unit("RSOL", 6.955e8 * M) PC = Unum.unit("pc", 3.08568025e16 * M) KPC = Unum.unit("Kpc", PC * 1e3) MPC = Unum.unit("Mpc", PC * 1e6) CM = Unum.unit("cm", 1e-2 * M) KM = Unum.unit("km", 1e3 * M) YR = Unum.unit("yr", 31556926. * S) MYR = Unum.unit("Myr", YR * 1e6) GYR = Unum.unit("Gyr", YR * 1e9) AMU = Unum.unit("amu", 1.66053886e-27 * KG) MH = Unum.unit("mh", 1.007825 * AMU) MHe = Unum.unit("mhe", 4.002602 * AMU) hubbleH = Unum.unit("hubbleH") LSOL = 3.839e26 * J / S
import pylab import random import log import argparse import os USE_UNITS = False if USE_UNITS: from unum.units import * from unum import Unum else: from fastunits import * ## Setup Units mV = Unum.unit('mV', 10**-3 * V) # millivolts mF = Unum.unit('mF', 10**-3 * F) # milliFarads uF = Unum.unit('uF', 10**-6 * F) # microFarads mS = Unum.unit('mS', 10**-3 * S) # milliSiemens mohm = Unum.unit('mohm', 10**-3 * ohm) # milliohms kohm = Unum.unit('kohm', 10**3 * ohm) # kiloohms # strips the unit from a number and returns just the number. `unit` is a Unum unit. def mag(v, unit): return float(v/unit) # little utility for getting the last element of a list def last(l): return l[len(l) - 1]
import numpy import scipy as sp import scipy.interpolate from unum import Unum from unum.units import * ml = Unum.unit('ml', 1e-3*L) SUSCEPTIBLE = "Susceptible" EXPOSED = "Exposed" INFECTED = "Infection" RECOVERED = "Recovered" def log_interp1d(xx, yy, kind='linear'): logy = numpy.log10(yy) lin_interp = sp.interpolate.interp1d(xx, logy, kind=kind) log_interp = lambda zz: numpy.power(10.0, lin_interp(zz)) return log_interp
from unum import Unum from unum import units Bohr = Unum.unit('Bohr', 5.2917720859e-11 * units.M) Angstrom = units.ANGSTROM Ang = Angstrom degrees = units.ARCDEG deg = degrees radians = units.RAD rad = radians
m2 = m**2 # [m2] unit definition cm2 = cm**2 # [cm2] unit definition mm2 = mm**2 # [mm2] unit definition from unum.units import ha # [ha] unit definition m3 = m**3 # [m3] unit definition dm3 = dm**3 # [cm3] unit definition cm3 = cm**3 # [cm3] unit definition mm3 = mm**3 # [mm3] unit definition m4 = m**4 # [m4] unit definition cm4 = cm**4 # [cm4] unit definition mm4 = mm**4 # [mm4] unit definition from unum.units import N # [N] unit definition kN = __Unum.unit('kN', 1E3 * N) # [kN] unit definition Nm = __Unum.unit('Nm', N * m) # [Nm] unit definition kNm = __Unum.unit('kNm', 1E3 * N * m) # [kNm] unit definition from unum.units import J # [J] unit definition from unum.units import Pa as Pa # [Pa] unit definition from unum.units import bar # [bar] unit definition kPa = __Unum.unit('kPa', 1E3 * Pa) # [kPa] unit definition MPa = __Unum.unit('MPa', 1E6 * Pa) # [MPa] unit definition GPa = __Unum.unit('GPa', 1E9 * Pa) # [MPa] unit definition #--------------------------------------------------------------------- #Imperial units