def test_numericalunit(): import numericalunits as nu nu.reset_units('SI') l1 = 1000.0 * nu.mm print(l1 / nu.mm) l2 = 1000. print(l2)
def test_save_load(self): for i in range(len(self.all_samples)): data = pickle.dumps(self.all_samples[i]) numericalunits.reset_units() x = pickle.loads(data) self.setUp() testing.assert_allclose(x, self.all_samples[i])
def test_save_load(self): import numericalunits import pickle x = Basis( (numericalunits.angstrom,)*3, kind = 'orthorombic', ) x.units["vectors"] = "m" data = pickle.dumps(x) numericalunits.reset_units() x = pickle.loads(data) testing.assert_allclose(x.vectors, numpy.eye(3)*numericalunits.angstrom)
def test_elastic(): ref = 33.19098343826968 isclose(wr.rate_wimp_std(1, **opts), ref) # Test numericalunits.reset_units() does not affect results nu.reset_units(123) isclose(wr.rate_wimp_std(1, **opts), ref) # Test vectorized call energies = np.linspace(0.01, 40, 100) dr = wr.rate_wimp_std(energies, **opts) assert dr[0] == wr.rate_wimp_std(0.01, **opts)
def test_save_load_uc(self): cell = self.co_cell data = pickle.dumps(cell) numericalunits.reset_units() x = pickle.loads(data) # Assert object is the same wrt numericalunits self.setUp() cell2 = self.co_cell testing.assert_allclose(x.vectors, cell2.vectors) testing.assert_equal(x.coordinates, cell2.coordinates) testing.assert_equal(x.values, cell2.values) testing.assert_allclose(x.meta["length"], cell2.meta["length"])
def test_save_load_json(self): grid = self.bs_grid data = dumps(grid.state_dict()) numericalunits.reset_units() x = BandsGrid.from_state_dict(loads(data)) # Assert object is the same wrt numericalunits self.setUp() grid2 = self.bs_grid testing.assert_allclose(x.vectors, grid2.vectors) testing.assert_equal(x.coordinates, grid2.coordinates) testing.assert_allclose(x.values, grid2.values) testing.assert_allclose(x.fermi, grid2.fermi)
def test_save_load_json(self): cell = self.bs_cell data = dumps(cell.state_dict()) numericalunits.reset_units() x = BandsPath.from_state_dict(loads(data)) # Assert object is the same wrt numericalunits self.setUp() cell2 = self.bs_cell testing.assert_allclose(x.vectors, cell2.vectors) testing.assert_equal(x.coordinates, cell2.coordinates) testing.assert_allclose(x.values, cell2.values) testing.assert_allclose(x.fermi, cell2.fermi)
def test_pickle_units(self): grid = self.bs_grid data = pickle.dumps(grid) numericalunits.reset_units() x = pickle.loads(data) # Assert object is the same wrt numericalunits self.setUp() grid2 = self.bs_grid testing.assert_allclose(x.vectors, grid2.vectors) testing.assert_equal(x.coordinates, grid2.coordinates) testing.assert_allclose(x.values, grid2.values) testing.assert_allclose(x.fermi, grid2.fermi)
def test_save_load_json(self): for i in range(len(self.all_samples)): s = StringIO() data = dumps(self.all_samples[i]) dump(self.all_samples[i], s) s.seek(0) _data = s.read() assert data == _data s.seek(0) numericalunits.reset_units() x = loads(data) _x = load(s) testing.assert_equal(x, _x) self.setUp() testing.assert_allclose(x, self.all_samples[i])
def test_everything(self): """just some very basic smoke tests""" # example from README x = 5 * nu.mL self.assert_almost_equal(x, 5e21 * nu.nm**3, rtol=1e-9) # example from README Efield = 1e5 * (nu.V / nu.cm) force = nu.e * Efield accel = force / nu.me self.assert_almost_equal(accel, 1.75882002e18 * nu.m / nu.s**2, rtol=1e-6) # make sure reset_units('SI') works nu.reset_units('SI') self.assert_almost_equal(nu.G, 1e-4, rtol=1e-9)
def test_everything(self): """just some very basic smoke tests""" # example from README self.assertTrue(isclose(5 * nu.mL, 5e21 * nu.nm**3, rel_tol=1e-9)) # example from README Efield = 1e5 * (nu.V / nu.cm) force = nu.e * Efield accel = force / nu.me self.assertTrue(isclose(accel, 1.75882002e18 * nu.m / nu.s**2, rel_tol=1e-6)) # check nu_eval() self.assertTrue(isclose(nu.nu_eval('kg'), nu.kg, rel_tol=1e-9)) self.assertTrue(isclose(nu.nu_eval('kg * m / s**2'), nu.kg * nu.m / nu.s**2, rel_tol=1e-9)) self.assertTrue(isclose(nu.nu_eval('kg**-3.6'), nu.kg**-3.6, rel_tol=1e-9)) # make sure reset_units('SI') works nu.reset_units('SI') self.assertTrue(isclose(nu.G, 1e-4, rel_tol=1e-9))
def reset_units(seed=None, length=None, mass=None, time=None, energy=None, charge=None): """Allows the working units to be reset to random values or specified accoring to dimensions.""" if length is None and time is None and mass is None and energy is None and charge is None: nu.reset_units(seed) else: try: length = unit[length] except: pass try: mass = unit[mass] except: pass try: time = unit[time] except: pass try: energy = unit[energy] except: pass try: charge = unit[charge] except: pass m = 1. kg = 1. s = 1. C = 1. K = 1. if length is not None: m = nu.m / length if mass is not None: kg = nu.kg / mass if time is not None: s = nu.s / time if charge is not None: C = nu.C / charge if energy is not None: J = nu.J / energy if mass is None: kg = J * s**2 / m**2 elif time is None: s = (kg * m**2 / J)**0.5 elif length is None: m = (J * s**2 / kg) else: raise ValueError('length, mass, time and energy cannot all be defined') nu.m = m nu.kg = kg nu.s = s nu.C = C nu.K = K nu.set_derived_units_and_constants() build_unit()
# publish report print("payload local time: {0}".format(msg_arrival_time_local)) print("payload to be sent: {0}".format(payload)) client.publish("weather/bom_wow/feed", str(payload)) #--------------------------------------------------------------------------------------- # Modules and methods for processing weather data # #--------------------------------------------------------------------------------------- import numericalunits as nu nu.reset_units() # conversion of degrees Celcius to degrees def degCtoF(tempc) : return( float(tempc) * (9/5.0) + 32 ) def dewpoint_calc(tempc, humidity) : # calculate dewpoint based on temperature and humidity from math import log if (tempc > 0.0) : Tn = 243.12 m = 17.62 else : Tn = 272.62 m = 22.46 dewpoint = (Tn*(log(humidity/100.0)+((m*tempc)/(Tn+tempc)))/(m-log(humidity/100.0)-((m*tempc)/(Tn+tempc))))
import numpy as np import pandas as pd #import plots as pl import utils import numericalunits as nu nu.reset_units('SI') import matplotlib.pyplot as plt import matplotlib.gridspec as gs import seaborn as sns sns.set() class Drugs(object): def __init__(self): s_labels = ["drugindication", "medicinalproduct", "drugcharacterization"] s_labels += ["drugadministrationroute", "drugauthorizationnumb", "drugbatchnumb"] s_labels += ["actiondrug", "drugrecurreadministration", "drugseparatedosagenumb"] s_labels += ["drugstartdate", "drugenddate"] s_labels += ["drugtreatmentduration", "drugtreatmentdurationunit"] s_labels += ["drugcumulativedosagenumb", "drugcumulativedosageunit"] s_labels += ["drugintervaldosageunitnumb", "drugintervaldosagedefinition"] s_labels += ["drugstructuredosagenumb", "drugstructuredosageunit"] s_labels += ['drugdosageform', 'drugindication', 'drugdosagetext', 'drugadditional'] self.labels = s_labels # initialize data series information self.df = pd.DataFrame() # initialize conversion format functions
def __init__(self, np_obj): numericalunits.reset_units() base.BenchModule.__init__(self, np_obj)
# publish report print("payload local time: {0}".format(msg_arrival_time_local)) print("payload to be sent: {0}".format(payload)) client.publish("weather/bom_wow/feed", str(payload)) #--------------------------------------------------------------------------------------- # Modules and methods for processing weather data # #--------------------------------------------------------------------------------------- import numericalunits as nu nu.reset_units() # conversion of degrees Celcius to degrees def degCtoF(tempc): return (float(tempc) * (9 / 5.0) + 32) def dewpoint_calc(tempc, humidity): # calculate dewpoint based on temperature and humidity from math import log if (tempc > 0.0): Tn = 243.12 m = 17.62 else: Tn = 272.62
def reset_units(seed=None, **kwargs): """ Extends numericalunits.reset_units() by allowing for working units to be defined. If no working units are specified, then random working units are used just like the default numericalunits behavior. Otherwise, use the specified working units and SI. Parameters ---------- seed : int, optional random number seed to use in generating random working units. seed='SI' will use SI units. Cannot be given with the other parameters. length : str, optional Unit of length to use for the working units. mass : str, optional Unit of mass to use for the working units. time : str, optional Unit of time to use for the working units. energy : str, optional Unit of energy to use for the working units. charge : str, optional Unit of charge to use for the working units. Raises ------ ValueError If seed is given with any other parameters, or if more than four of the working unit parameters are given. """ # Generate random base working units if (len(kwargs) == 0): nu.reset_units(seed) build_unit() # Generate SI + defined working units elif seed is None: # Check that no more than 4 working units are defined if len(kwargs) > 4: raise ValueError('Only four working units can be defined') # Set base units to 1 (working units to SI) nu.reset_units('SI') build_unit() # Scale base units by working units if 'length' in kwargs: nu.m = unit['m'] / unit[kwargs['length']] if 'mass' in kwargs: nu.kg = unit['kg'] / unit[kwargs['mass']] if 'time' in kwargs: nu.s = unit['s'] / unit[kwargs['time']] if 'charge' in kwargs: nu.C = unit['C'] / unit[kwargs['charge']] # Scale derived units by working units if 'energy' in kwargs: J = unit['J'] / unit[kwargs['energy']] # Scale base units by derived units if 'mass' not in kwargs: nu.kg = J * nu.s**2 / nu.m**2 elif 'time' not in kwargs: nu.s = (nu.kg * nu.m**2 / J)**0.5 elif 'length' not in kwargs: nu.m = (J * nu.s**2 / nu.kg) # Rebuild derived units and unit dictionary nu.set_derived_units_and_constants() build_unit() else: raise ValueError('seed cannot be given with any other parameters')
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. # # Copyright (C) 2017 Daniel Schick import numpy as np import os import scipy.constants as constants import numericalunits as u u.reset_units('SI') class atom(object): """atom The atom class is the smallest structural unit of which one can build larger structures. It holds real physical properties of atoms defined in the attrubutes section can return parameters and data necessary for different simulation types. Attributes: symbol (str) : symbol of the element ID (str) : identifier of the atom, may be different from symbol and/or name name (str) : name of the element (generic)
import numericalunits as nu nu.reset_units('SI') # There may be a more graceful way to do this, but this'll work for now. # Settings: proj_unit = 'm' output_unit = 'km' in_unit = getattr(nu, proj_unit) out_unit = getattr(nu, output_unit) def length_in_display_units(length, in_units=in_unit, out_units=out_unit): if in_units.__class__.__name__ == 'str': in_units = getattr(nu, in_units) if out_units.__class__.__name__ == 'str': out_units = getattr(nu, out_units) len_out = (length * in_units) / out_units return len_out