def test_static_calc_unc(): """ Test uncertainty propagation in static calculations using Uncertainties. """ # FIXME: this shouldn't have to run a model to test the uncertainty test_model_file = os.path.join(PROJ_PATH, 'models', 'sandia_performance_model-Tuscon.json') test_model = sandia_performance_model.SAPM(test_model_file) # create model test_model.command('start') # start simulation # get parameters from model dt = test_model.outputs.reg['timestamps'] # timestamps latitude = test_model.data.reg['latitude'].m # latitude [degrees] longitude = test_model.data.reg['longitude'].m # longitude [degrees] zenith = test_model.outputs.reg['solar_zenith'].m # zenith [degrees] s_ze_ze = test_model.outputs.reg.variance['solar_zenith']['solar_zenith'] azimuth = test_model.outputs.reg['solar_azimuth'].m # azimuth [degrees] s_az_az = test_model.outputs.reg.variance['solar_azimuth']['solar_azimuth'] # get uncertainties percentages in base units lat_unc = test_model.data.reg.uncertainty['latitude']['latitude'] lat_unc = lat_unc.to_base_units().m lon_unc = test_model.data.reg.uncertainty['longitude']['longitude'] lon_unc = lon_unc.to_base_units().m # create ufloat Uncertainties from parameters lat_unc = uncertainties.ufloat(latitude, np.abs(latitude * lat_unc)) lon_unc = uncertainties.ufloat(longitude, np.abs(longitude * lon_unc)) test_unc = [] # empty list to collect return values for n in xrange(96): # Uncertainties wrapped functions must return only scalar float f_ze_unc = uncertainties.wrap( lambda lat, lon: solpos(dt[n], lat, lon)['apparent_zenith'].item() ) f_az_unc = uncertainties.wrap( lambda lat, lon: solpos(dt[n], lat, lon)['azimuth'].item() ) ze_unc, az_unc = f_ze_unc(lat_unc, lon_unc), f_az_unc(lat_unc, lon_unc) LOGGER.debug( '%s: ze = %g +/- %g%%, az = %g +/- %g%%', dt[n].isoformat(), zenith[n], np.sqrt(s_ze_ze[n]) * 100, azimuth[n], np.sqrt(s_az_az[n]) * 100 ) LOGGER.debug( 'Uncertainties test %2d: ze = %g +/- %g%%, az = %g +/- %g%%', n, ze_unc.n, ze_unc.s / ze_unc.n * 100, az_unc.n, az_unc.s / az_unc.n * 100 ) assert np.isclose(zenith[n], ze_unc.n) assert np.isclose(np.sqrt(s_ze_ze[n]), ze_unc.s / ze_unc.n) assert np.isclose(azimuth[n], az_unc.n) assert np.isclose(np.sqrt(s_az_az[n]), az_unc.s / az_unc.n) test_unc.append({'ze': ze_unc, 'az': az_unc}) return test_model, test_unc
def test_wrapped_func_with_kwargs(): """ Test wrapped functions with keyword args """ def cos_plain(angle): return math.cos(angle) def cos_kwargs(angle, **kwargs): return math.cos(angle) def use_kwargs(angle, cos=True): if cos: return math.cos(angle) else: return math.sin(angle) # wrappings of these functions wrap_cos_plain = uncertainties.wrap(cos_plain) wrap_cos_wderiv = uncertainties.wrap(cos_plain, [math.cos]) wrap_cos_kwargs = uncertainties.wrap(cos_kwargs) wrap_use_kwargs = uncertainties.wrap(use_kwargs) umath_cos = umath.cos umath_sin = umath.sin # now test that the wrapped functions give the same results # as the umath versions for a variety of input values for a in (ufloat((0.2, 0.01)), ufloat((0.7, 0.00001)), #ufloat((0.9, 0.3)), ufloat((1.e-4, 0.3)), #ufloat((200.0, 0.3)), ufloat((1.e5, 0.3)), #0, 2, 1.25, 0.0, 1.e-5, 0.707, 1.5708 ): ucos = umath_cos(a) usin = umath_sin(a) assert _numbers_close(ucos, wrap_cos_plain(a)) assert _numbers_close(ucos, wrap_cos_wderiv(a)) assert _numbers_close(ucos, wrap_cos_kwargs(a)) assert _numbers_close(ucos, wrap_cos_kwargs(a, opt=None)) assert _numbers_close(ucos, wrap_cos_kwargs(a, opt=None, opt2=True)) assert _numbers_close(ucos, wrap_use_kwargs(a, cos=True)) assert _numbers_close(usin, wrap_use_kwargs(a, cos=False)) # affirm that calling a wrapped function with unsupported # keyword args raises a TypeError raised = False try: wrap_use_kwargs(a, other=False) except TypeError: raised = True assert raised
def test_uncertainties_comparison_user_defined_funcs(): import uncertainties from uncertainties import ufloat x = UQ_( '15. +/- 0.1 m' ) y = UQ_( '25. +/- 0.2 m' ) w = UQ_( '35. +/- 0.3 m' ) xx = ufloat( 15, 0.1 ) yy = ufloat( 25, 0.2 ) ww = ufloat( 35, 0.3 ) def calc(x,y,w): return ((x - y)/(x - w))*w f = uconv.WithError(calc) ff = uncertainties.wrap(calc) z = f(x,y,w) zz = ff(xx,yy,ww) t_us = timeit.timeit( lambda : f( x, y, w), number = 200 ) t_unc = timeit.timeit( lambda : ff(xx,yy,ww), number = 200 ) assert t_us > t_unc assert Close( z.nominal.magnitude , zz.nominal_value) assert Close( z.uncertainty.magnitude, zz.std_dev) corr = uconv.correlations.matrix( x,y,z,w ) ccorr = uncertainties.correlation_matrix( [xx,yy,zz,ww] ) for i in range(4): for j in range(4): assert Close( corr(i,j), ccorr[i][j], 0.1 )
def __init__(self, list_, err=None, factor=1): self.avr = np.mean(list_)*factor self.std = np.std(list_)*factor self.len = len(list_) self.std_err = self.std / math.sqrt(self.len) self.avr_err = unc.ufloat(self.avr, self.std_err)*factor if not err is None: Umean = unc.wrap(np.mean) self.list_err = unp.uarray(list_, [err]*self.len)*factor self.avr_err_gauss = Umean(self.list_err)*factor
def __init__(self,conc=0): """ initializeaza clasa Water Parametrii ---------- conc:float concentratia in procente Observatii ---------- pentru o concentratie de 50% conc=0.5 implicit concentratia va fi de zero pentru a nu produce timpi de executie mari, la initializare se creaza si functii pentru calcul vectorial si cu incertitudini """ self.__defpress=2.e5 #in Pa self.__conc=conc if self.__conc==0.0: self.__fldName='Water' else: self.__fldName=r'EG-{con}%'.format(con=str(int(self.__conc*100.0))) #intializam functiile wrap astfel incat sa se poata folosii cu ufloat def __w_dens(t): t=float(t) #obligam conversia la float chiar daca este intreg return fld.PropsSI('D','T',t,'P',self.__defpress,self.__fldName) def __w_cp(t): t=float(t) return fld.PropsSI('C','T',t,'P',self.__defpress,self.__fldName) def __w_cond(t): t=float(t) return fld.PropsSI('L','T',t,'P',self.__defpress,self.__fldName) def __w_visc(t): t=float(t) return fld.PropsSI('V','T',t,'P',self.__defpress,self.__fldName) self.__vudens=np.vectorize(un.wrap(__w_dens)) #kg/m3 self.__vucp=np.vectorize(un.wrap(__w_cp)) #J/kg.K self.__vucond=np.vectorize(un.wrap(__w_cond)) #W/m.K self.__vuvisc=np.vectorize(un.wrap(__w_visc)) #Pa.s
def wrapped_fsum(): """ Returns an uncertainty-aware version of math.fsum, which must be contained in _original_func. """ # The fsum function is flattened, in order to use the # wrap() wrapper: flat_fsum = lambda *args: original_func(args) flat_fsum_wrap = uncertainties.wrap( flat_fsum, itertools.repeat(lambda *args: 1)) return wraps(lambda arg_list: flat_fsum_wrap(*arg_list), original_func)
def __numpy_ufunc__(self, ufunc, method, i, inputs, **kwargs): # Calculates the uncertainties wrapped_ufunc = uncert.wrap(ufunc) var_inputs = uquantity_to_variable(inputs) var_out = wrapped_ufunc(*var_inputs, **kwargs) # Calculates the units units_inputs = tuple( [uquant.unit for uquant in inputs] ) try: units_out = ufunc(*units_inputs, **kwargs) except TypeError: # Cases like addition and subtraction units_out = units_inputs[0] except AttributeError: # Cases like trig functions units_out = units_inputs[0] return UQuantity(var_out.nominal_value, var_out.std_dev, units_out, derivatives=var_out.derivatives)
def test_wrapped_func(): """ Test uncertainty-aware functions obtained through wrapping. """ # This function can be wrapped so that it works when 'angle' has # an uncertainty (math.cos does not handle numbers with # uncertainties): def f(angle, list_var): return math.cos(angle) + sum(list_var) f_wrapped = uncertainties.wrap(f) my_list = [1, 2, 3] # Test of a wrapped function that only calls the original function: assert f_wrapped(0, my_list) == 1 + sum(my_list) # As a precaution, the wrapped function does not venture into # calculating f with uncertainties when one of the argument is not # a simple number, because this argument might contain variables: angle = ufloat((0, 0.1)) assert f_wrapped(angle, [angle, angle]) == NotImplemented assert f_wrapped(angle, my_list) == NotImplemented
def autobk(energy, mu=None, group=None, rbkg=1, nknots=None, e0=None, edge_step=None, kmin=0, kmax=None, kweight=1, dk=0, win='hanning', k_std=None, chi_std=None, nfft=2048, kstep=0.05, pre_edge_kws=None, nclamp=4, clamp_lo=1, clamp_hi=1, calc_uncertainties=False, _larch=None, **kws): """Use Autobk algorithm to remove XAFS background Parameters: ----------- energy: 1-d array of x-ray energies, in eV, or group mu: 1-d array of mu(E) group: output group (and input group for e0 and edge_step). rbkg: distance (in Ang) for chi(R) above which the signal is ignored. Default = 1. e0: edge energy, in eV. If None, it will be determined. edge_step: edge step. If None, it will be determined. pre_edge_kws: keyword arguments to pass to pre_edge() nknots: number of knots in spline. If None, it will be determined. kmin: minimum k value [0] kmax: maximum k value [full data range]. kweight: k weight for FFT. [1] dk: FFT window window parameter. [0] win: FFT window function name. ['hanning'] nfft: array size to use for FFT [2048] kstep: k step size to use for FFT [0.05] k_std: optional k array for standard chi(k). chi_std: optional chi array for standard chi(k). nclamp: number of energy end-points for clamp [2] clamp_lo: weight of low-energy clamp [1] clamp_hi: weight of high-energy clamp [1] calc_uncertaintites: Flag to calculate uncertainties in mu_0(E) and chi(k) [False] Output arrays are written to the provided group. Follows the 'First Argument Group' convention. """ msg = _larch.writer.write if 'kw' in kws: kweight = kws.pop('kw') if len(kws) > 0: msg('Unrecognized a:rguments for autobk():\n') msg(' %s\n' % (', '.join(kws.keys()))) return energy, mu, group = parse_group_args(energy, members=('energy', 'mu'), defaults=(mu,), group=group, fcn_name='autobk') energy = remove_dups(energy) # if e0 or edge_step are not specified, get them, either from the # passed-in group or from running pre_edge() group = set_xafsGroup(group, _larch=_larch) if edge_step is None and isgroup(group, 'edge_step'): edge_step = group.edge_step if e0 is None and isgroup(group, 'e0'): e0 = group.e0 if e0 is None or edge_step is None: # need to run pre_edge: pre_kws = dict(nnorm=3, nvict=0, pre1=None, pre2=-50., norm1=100., norm2=None) if pre_edge_kws is not None: pre_kws.update(pre_edge_kws) pre_edge(energy, mu, group=group, _larch=_larch, **pre_kws) if e0 is None: e0 = group.e0 if edge_step is None: edge_step = group.edge_step if e0 is None or edge_step is None: msg('autobk() could not determine e0 or edge_step!: trying running pre_edge first\n') return # get array indices for rkbg and e0: irbkg, ie0 ie0 = index_of(energy, e0) rgrid = np.pi/(kstep*nfft) if rbkg < 2*rgrid: rbkg = 2*rgrid irbkg = int(1.01 + rbkg/rgrid) # save ungridded k (kraw) and grided k (kout) # and ftwin (*k-weighting) for FT in residual enpe = energy[ie0:] - e0 kraw = np.sign(enpe)*np.sqrt(ETOK*abs(enpe)) if kmax is None: kmax = max(kraw) else: kmax = max(0, min(max(kraw), kmax)) kout = kstep * np.arange(int(1.01+kmax/kstep), dtype='float64') iemax = min(len(energy), 2+index_of(energy, e0+kmax*kmax/ETOK)) - 1 # interpolate provided chi(k) onto the kout grid if chi_std is not None and k_std is not None: chi_std = np.interp(kout, k_std, chi_std) # pre-load FT window ftwin = kout**kweight * ftwindow(kout, xmin=kmin, xmax=kmax, window=win, dx=dk) # calc k-value and initial guess for y-values of spline params nspl = max(4, min(128, 2*int(rbkg*(kmax-kmin)/np.pi) + 1)) spl_y, spl_k, spl_e = np.zeros(nspl), np.zeros(nspl), np.zeros(nspl) for i in range(nspl): q = kmin + i*(kmax-kmin)/(nspl - 1) ik = index_nearest(kraw, q) i1 = min(len(kraw)-1, ik + 5) i2 = max(0, ik - 5) spl_k[i] = kraw[ik] spl_e[i] = energy[ik+ie0] spl_y[i] = (2*mu[ik+ie0] + mu[i1+ie0] + mu[i2+ie0] ) / 4.0 # get spline represention: knots, coefs, order=3 # coefs will be varied in fit. knots, coefs, order = splrep(spl_k, spl_y) # set fit parameters from initial coefficients params = Group() for i in range(len(coefs)): name = FMT_COEF % i p = Parameter(coefs[i], name=name, vary=i<len(spl_y)) p._getval() setattr(params, name, p) initbkg, initchi = spline_eval(kraw[:iemax-ie0+1], mu[ie0:iemax+1], knots, coefs, order, kout) # do fit fit = Minimizer(__resid, params, _larch=_larch, toler=1.e-4, fcn_kws = dict(ncoefs=len(coefs), chi_std=chi_std, knots=knots, order=order, kraw=kraw[:iemax-ie0+1], mu=mu[ie0:iemax+1], irbkg=irbkg, kout=kout, ftwin=ftwin, kweight=kweight, nfft=nfft, nclamp=nclamp, clamp_lo=clamp_lo, clamp_hi=clamp_hi)) fit.leastsq() # write final results coefs = [getattr(params, FMT_COEF % i) for i in range(len(coefs))] bkg, chi = spline_eval(kraw[:iemax-ie0+1], mu[ie0:iemax+1], knots, coefs, order, kout) obkg = np.copy(mu) obkg[ie0:ie0+len(bkg)] = bkg # outputs to group group = set_xafsGroup(group, _larch=_larch) group.bkg = obkg group.chie = (mu-obkg)/edge_step group.k = kout group.chi = chi/edge_step # now fill in 'autobk_details' group params.init_bkg = np.copy(mu) params.init_bkg[ie0:ie0+len(bkg)] = initbkg params.init_chi = initchi/edge_step params.knots_e = spl_e params.knots_y = np.array([coefs[i] for i in range(nspl)]) params.init_knots_y = spl_y params.nfev = params.fit_details.nfev params.kmin = kmin params.kmax = kmax group.autobk_details = params # uncertainties in mu0 and chi: fairly slow!! if HAS_UNCERTAIN and calc_uncertainties: vbest, vstd = [], [] for n in fit.var_names: par = getattr(params, n) vbest.append(par.value) vstd.append(par.stderr) uvars = uncertainties.correlated_values(vbest, params.covar) # uncertainty in bkg (aka mu0) # note that much of this is working around # limitations in the uncertainty package that make it # 1. take an argument list (not array) # 2. work on returned scalars (but not arrays) # 3. not handle kw args and *args well (so use # of global "index" is important here) nkx = iemax-ie0 + 1 def my_dsplev(*args): coefs = np.array(args) return splev(kraw[:nkx], [knots, coefs, order])[index] fdbkg = uncertainties.wrap(my_dsplev) dmu0 = [fdbkg(*uvars).std_dev() for index in range(len(bkg))] group.delta_bkg = np.zeros(len(mu)) group.delta_bkg[ie0:ie0+len(bkg)] = np.array(dmu0) # uncertainty in chi (see notes above) def my_dchi(*args): coefs = np.array(args) b,chi = spline_eval(kraw[:nkx], mu[ie0:iemax+1], knots, coefs, order, kout) return chi[index] fdchi = uncertainties.wrap(my_dchi) dchi = [fdchi(*uvars).std_dev() for index in range(len(kout))] group.delta_chi = np.array(dchi)/edge_step
from scipy.constants import atmosphere, zero_Celsius, mmHg, g import scipy as sci import uncertainties from uncertainties import * from uncertainties.unumpy import * import uncertainties as unumpy from numpy import * from pandas import * import pandas as pd import matplotlib.pyplot as plt import pickle # In[2]: # For the calculation of flow rate with uncertainties: wrappedFlowMeter = uncertainties.wrap(differential_pressure_meter_solver) # Firsts definitions airN = Mixture('air', T=293, P=101325) rhoN = airN.rho # In[3]: #Here it is defined all our ambi def set_of_const(P_amb, T_amb): P_amb = P_amb * mmHg # Pressure in Pa T_amb = T_amb + zero_Celsius # T in K # Here we calculate all what it is important with the air at the ambient pressure
pass class NegativeError(Exception): pass # Some default starting points on the sky to consider QSO_RA = "22h20m06.757" # RA QSO_DEC = "-28d03m23.34" # DEC THETA = 1.02 # radians REDSHIFT = 1.5 # Just pick a redshift to start RADIAL_DISTANCE = 1.3 # GLyr # ===================================================================== # = Wrap angles package functions with uncertainties package wrappers = # ===================================================================== wrap_radian_RA = uncertainties.wrap(angles.h2r) wrap_radian_DEC = uncertainties.wrap(angles.d2r) wrap_sep = uncertainties.wrap(angles.sep) # ============================ # = dipole and monopole term = # ============================ # eq. 15 in King et al. 2012 DIP_RA = 17.3 DIP_RA_ERR = 1.0 DIP_DEC = -61.0 DIP_DEC_ERR = 10.0 DIP_AMPLITUDE = 0.97e-5 DIP_AMPLITUDE_ERR = 0.21e-5 # average of asymmetric errors DIP_MONOPOLE = -0.178e-5 DIP_MONOPOLE_ERR = 0.084e-5
plt.savefig("Grafiken/Messreihe_2.pdf") ## Erstellen der Fehler behafteten Parameter uParam_C = ufloat(popt2[0], error2[0]) uParam_D = ufloat(popt2[1], error2[1]) uParam_E = ufloat(popt2[2], error2[2]) uParam_F = ufloat(popt2[3], error2[3]) ## Ableitung der Funktion P mit den Parametern def dP(T): return 3 * noms(uParam_C) * T**2 + 2 * noms(uParam_D) * T + noms(uParam_E) udP = unc.wrap(dP) def L(dp, Vd, Vf, T): return dp * (Vd - Vf) * T uLFunc = unc.wrap(L) ## Volumen des Dampf Usqrt = unc.wrap(np.sqrt) a = 0.9 # J m³/ mol² _vdp = (R * uT2[6::] / (2 * up2[6::])) _vdd = (R * uT2[6::] / (2 * up2[6::]))**2 - (a / up2[6::])
# Functions whose derivatives are calculated numerically by # this module fall here (isinf, fmod,...): derivatives = [] # Means: numerical calculation required elif name not in locally_cst_funcs: continue # 'name' not wrapped by this module (__doc__, e, etc.) func = getattr(math, name) if name in locally_cst_funcs: wrapped_func = wrap_locally_cst_func(func) else: # Function with analytical or numerical derivatives: # Errors during the calculation of the derivatives are converted # to a NaN result: it is assumed that a mathematical calculation # that cannot be calculated indicates a non-defined derivative # (the derivatives in fixed_derivatives must be written this way): wrapped_func = uncertainties.wrap( func, map(uncertainties.nan_if_exception, derivatives)) setattr(this_module, name, wraps(wrapped_func, func)) many_scalars_to_scalar_funcs.append(name) ############################################################################### ######################################## # Special cases: some of the functions from no_std_wrapping: ########## # The math.factorial function is not converted to an uncertainty-aware # function, because it does not handle non-integer arguments: it does # not make sense to give it an argument with a numerical error # (whereas this would be relevant for the gamma function).
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) from aputils.utils import Quantity, ErrorEquation from aputils.latextables.tables import Table Uexp = unc.wrap(np.exp) def temp2press(T): return 5.5e07 * Uexp(-6876/(T + 273.15)) def press2dist(P): return 0.0029 / P # Laden der Temperaturen T = np.loadtxt("Messdaten/Temperaturen.txt") t_err = 0.1 T_err = unp.uarray(T, [t_err]*len(T))
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) from aputils.utils import Quantity, ErrorEquation from aputils.latextables.tables import Table Uexp = unc.wrap(np.exp) def temp2press(T): return 5.5e07 * Uexp(-6876 / (T + 273.15)) def press2dist(P): return 0.0029 / P # Laden der Temperaturen T = np.loadtxt("Messdaten/Temperaturen.txt") t_err = 0.1 T_err = unp.uarray(T, [t_err] * len(T))
## Bestimmung der gemittelten Periodendauer uT_avr # Lade Periodendauer ohne Magnetfeld T = np.loadtxt("../Messdaten/Periodendauer_ohne_Magnetfeld.txt", unpack=True) # Lade Fehler der Zeitmessung T_err = np.loadtxt("../Messdaten/Periodendauer_Fehler.txt") # Periodendauer mit Fehler uT = unp.uarray(T, len(T)*[T_err]) # gemittelte Periodendauer mit Fehler umean = uncertainties.wrap(np.mean) uT_avr = np.mean(uT) T_avr = np.mean(T) T_std = np.std(T)/(len(T)-1) UT_avr = ufloat(T_avr, T_std) #uT_avr = ufloat(unp.nominal_values(uT_avr), unp.std_devs(uT_avr)) print("Mittlere Periodendauer ohne B:", uT_avr, UT_avr) ## Verarbeitung der Drahtdaten # Lade Drahtdurchmesser D_D = np.loadtxt("../Messdaten/Dimension_Draht_Durchmesser.txt", unpack=True) # Lade Drahtdurchmesser Fehler D_D_err = np.loadtxt("../Messdaten/Dimension_Draht_Durchmesser_Fehler.txt") # SI -Einheiten
division, unicode_literals, absolute_import) import math as math import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) umean = unc.wrap(np.mean) #TEST = False # Umrechenung der Termoelementspannung in Temperatur def TensToTemp(U): if isinstance(U, (float, int)): return 25.157 * U - 0.19 * U**2 elif all(isinstance(i, float) for i in U): return 25.157 * U - 0.19 * U**2 # Ermöglicht die Benutzung von ufloats als Funktionsparameter uTensToTemp = unc.wrap(TensToTemp)
import math as m import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) sys.path.append("..\globales\python") import latextables as lxtabs usqrt = unc.wrap(np.sqrt) U0 = 10e-03 # [V] # Messfehler Spannung, Abstand U_err, R_err = np.loadtxt("Messdaten/Fehler.txt") # Offset Abstand R_off = np.loadtxt("Messdaten/AbstandOffset.txt") # Messwerte ohne Rauschen: Phase, Spannung, Gain p1, U1, g1 = np.loadtxt("Messdaten/OhneRauschen.txt", unpack=True) # Fehlerbehaftete Spannung
import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) import sys # Eigene Funktionen #sys.path.append("..\globales\python") #from latextables import toTable as tab #from erroreqs import error ### Uncertianties Funktionen umean = unc.wrap(np.mean) usqrt = unc.wrap(np.sqrt) # Steuermakros PRINT = True TABS = True # Maximalwiderstand des Potentiometers R_max = np.loadtxt("Messdaten/Potentiometer.txt") X2_err = np.loadtxt("Messdaten/Messfehler.txt", usecols=(5, 5))[0] # [%] X2_err *= 1e-02 # [1] # Funktion zur Berechnung von R4 aus R3 def R4(r): return (R_max - r)
import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat from uncertainties.unumpy import uarray import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) import sys sys.path.append("..\_globales\python") import latextables as lxtabs ### Uncertainties Funktionen Umean = unc.wrap(np.mean) ### def gearToIndex(g): return m.trunc((int(g) / 6) - 1) """ Begin der Auswertung zum Dopplereffekt """ # Laden der Daten zur Bestimmung der Geschwindigkeit
def H(x, a, b): return a*np.exp(-b * x) def A(x, RC): return 1/np.sqrt(1 + 4 * const.pi**2 * x**2 * RC**2) def P(x, RC): return np.arctan(RC * 2 * const.pi * x) def Ap(p, RC): return np.cos(p)/(RC) Ulog = unc.wrap(np.log) # Laden der Messdaten der Aufladung t_auf, U_auf = np.loadtxt("Messdaten/Aufladen.txt", unpack=True) # Laden der Messdaten der Entladung t_ent, U_ent = np.loadtxt("Messdaten/Entladen.txt", unpack=True) # Fehlerbehaftete Messwerte (Fehler für Zeit vernachlässigbar) U_err = 1 # [V] uU_ent = unp.uarray(U_ent, [U_err]*len(U_ent))
# for (name, attr) in vars(math).items(): for name in dir(math): if name in fixed_derivatives: # Priority to functions in fixed_derivatives derivatives = fixed_derivatives[name] elif name in num_deriv_funcs: # Functions whose derivatives are calculated numerically by # this module fall here (isinf, fmod,...): derivatives = None # Means: numerical calculation required else: continue # 'name' not wrapped by this module (__doc__, e, etc.) func = getattr(math, name) setattr(this_module, name, wraps(uncertainties.wrap(func, derivatives), func)) many_scalars_to_scalar_funcs.append(name) ############################################################################### ######################################## # Special cases: some of the functions from no_std_wrapping: ########## # The math.factorial function is not converted to an uncertainty-aware # function, because it does not handle non-integer arguments: it does # not make sense to give it an argument with a numerical error # (whereas this would be relevant for the gamma function). ##########
# for (name, attr) in vars(math).items(): for name in dir(math): if name in fixed_derivatives: # Priority to functions in fixed_derivatives derivatives = fixed_derivatives[name] elif name in num_deriv_funcs: # Functions whose derivatives are calculated numerically by # this module fall here (isinf, fmod,...): derivatives = None # Means: numerical calculation required else: continue # 'name' not wrapped by this module (__doc__, e, etc.) func = getattr(math, name) setattr(this_module, name, wraps(uncertainties.wrap(func, derivatives), func)) many_scalar_to_scalar_funcs.append(name) ############################################################################### ######################################## # Special cases: some of the functions from no_std_wrapping: ########## # The math.factorial function is not converted to an uncertainty-aware # function, because it does not handle non-integer arguments: it does # not make sense to give it an argument with a numerical error # (whereas this would be relevant for the gamma function). ##########
def __init__(self,Tabs=Q_(20.,um.degC),Pabs=1*um.atm,Rh=0.0): """ initializeaza proprietatile aerului in functie de umiditiatea acestuia Parametrii ---------- Tabs: float, pint.Quantity or UFloat temperatura de referinta a mediului ambiant [C] Pabs: float, pint.Quantity or UFloat presiunea de referinta a mediului ambiant [atm] Rh:float, pint.Quantity or UFloat [0,1] umiditatea relativa a mediului ambiant Observatii ---------- Se considera ca aerul va suferi transformari termodinamice fara schimbarea cantitatii de umiditate (fara a condensa umiditatea) astfel umiditatea absoluta odata calculata la initializare nu se mai modifica """ if not isinstance(Tabs,Q_): Tabs=Q_(Tabs,'degC') if not isinstance(Pabs,Q_): Pabs=Q_(Pabs,'atm') if isinstance(Rh,Q_): Rh=Rh.magnitude self.__tabs=Tabs self.__pabs=Pabs self.__rh=Rh @um.wraps(um.parse_expression('kg/kg'),[um.degK,um.Pa,None]) @un.wrap def __w_abs(t,p,rh): t=float(t) p=float(p) rh=float(rh) return fld.HAPropsSI('W','T',t,'P',p,'R',rh) self.__abs=__w_abs(self.__tabs, self.__pabs,self.__rh) def __w_dens(t,p,ab): t=float(t) p=float(p) ab=float(ab) return 1.0/fld.HAPropsSI('V','T',t,'P',p,'W',ab) def __w_cp(t,p,ab): t=float(t) p=float(p) ab=float(ab) return fld.HAPropsSI('C','T',t,'P',p,'W',ab) def __w_cond(t,p,ab): t=float(t) p=float(p) ab=float(ab) return fld.HAPropsSI('K','T',t,'P',p,'W',ab) def __w_visc(t,p,ab): t=float(t) p=float(p) ab=float(ab) print 't=',t print 'p=',p print 'ab=',ab rez=fld.HAPropsSI('M','T',t,'P',p,'W',ab) print rez return rez self.__vndens=np.vectorize(un.wrap(__w_dens)) self.__vncp=np.vectorize(un.wrap(__w_cp)) self.__vncond=np.vectorize(un.wrap(__w_cond)) self.__vnvisc=np.vectorize(un.wrap(__w_visc))
def __init__(self, penalizer_coef=0.): super(ParetoNBDModel, self).__init__() self.fitter = ParetoNBDFitter(penalizer_coef) self.param_names = ['r', 'alpha', 's', 'beta'] self.wrapped_static_expected_number_of_purchases_up_to_time = \ uncertainties.wrap(ParetoNBDFitter.static_expected_number_of_purchases_up_to_time)
import math as m import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy.constants as const from scipy.optimize import curve_fit from sympy import * import uncertainties as unc from uncertainties import ufloat import uncertainties.unumpy as unp from uncertainties.unumpy import (nominal_values as noms, std_devs as stds) sys.path.append("..\globales\python") import latextables as lxtabs usqrt = unc.wrap(np.sqrt) U0 = 10e-03 # [V] # Messfehler Spannung, Abstand U_err, R_err = np.loadtxt("Messdaten/Fehler.txt") # Offset Abstand R_off = np.loadtxt("Messdaten/AbstandOffset.txt") # Messwerte ohne Rauschen: Phase, Spannung, Gain p1, U1, g1 = np.loadtxt("Messdaten/OhneRauschen.txt", unpack=True) # Fehlerbehaftete Spannung uU1 = unp.uarray(U1, len(U1) * [U_err])
def autobk(energy, mu=None, group=None, rbkg=1, nknots=None, e0=None, edge_step=None, kmin=0, kmax=None, kweight=1, dk=0, win='hanning', k_std=None, chi_std=None, nfft=2048, kstep=0.05, pre_edge_kws=None, nclamp=4, clamp_lo=1, clamp_hi=1, calc_uncertainties=False, _larch=None, **kws): """Use Autobk algorithm to remove XAFS background Parameters: ----------- energy: 1-d array of x-ray energies, in eV, or group mu: 1-d array of mu(E) group: output group (and input group for e0 and edge_step). rbkg: distance (in Ang) for chi(R) above which the signal is ignored. Default = 1. e0: edge energy, in eV. If None, it will be determined. edge_step: edge step. If None, it will be determined. pre_edge_kws: keyword arguments to pass to pre_edge() nknots: number of knots in spline. If None, it will be determined. kmin: minimum k value [0] kmax: maximum k value [full data range]. kweight: k weight for FFT. [1] dk: FFT window window parameter. [0] win: FFT window function name. ['hanning'] nfft: array size to use for FFT [2048] kstep: k step size to use for FFT [0.05] k_std: optional k array for standard chi(k). chi_std: optional chi array for standard chi(k). nclamp: number of energy end-points for clamp [2] clamp_lo: weight of low-energy clamp [1] clamp_hi: weight of high-energy clamp [1] calc_uncertaintites: Flag to calculate uncertainties in mu_0(E) and chi(k) [False] Output arrays are written to the provided group. Follows the 'First Argument Group' convention. """ msg = _larch.writer.write if 'kw' in kws: kweight = kws.pop('kw') if len(kws) > 0: msg('Unrecognized a:rguments for autobk():\n') msg(' %s\n' % (', '.join(kws.keys()))) return energy, mu, group = parse_group_args(energy, members=('energy', 'mu'), defaults=(mu, ), group=group, fcn_name='autobk') energy = remove_dups(energy) # if e0 or edge_step are not specified, get them, either from the # passed-in group or from running pre_edge() group = set_xafsGroup(group, _larch=_larch) if edge_step is None and isgroup(group, 'edge_step'): edge_step = group.edge_step if e0 is None and isgroup(group, 'e0'): e0 = group.e0 if e0 is None or edge_step is None: # need to run pre_edge: pre_kws = dict(nnorm=3, nvict=0, pre1=None, pre2=-50., norm1=100., norm2=None) if pre_edge_kws is not None: pre_kws.update(pre_edge_kws) pre_edge(energy, mu, group=group, _larch=_larch, **pre_kws) if e0 is None: e0 = group.e0 if edge_step is None: edge_step = group.edge_step if e0 is None or edge_step is None: msg('autobk() could not determine e0 or edge_step!: trying running pre_edge first\n' ) return # get array indices for rkbg and e0: irbkg, ie0 ie0 = index_of(energy, e0) rgrid = np.pi / (kstep * nfft) if rbkg < 2 * rgrid: rbkg = 2 * rgrid irbkg = int(1.01 + rbkg / rgrid) # save ungridded k (kraw) and grided k (kout) # and ftwin (*k-weighting) for FT in residual enpe = energy[ie0:] - e0 kraw = np.sign(enpe) * np.sqrt(ETOK * abs(enpe)) if kmax is None: kmax = max(kraw) else: kmax = max(0, min(max(kraw), kmax)) kout = kstep * np.arange(int(1.01 + kmax / kstep), dtype='float64') iemax = min(len(energy), 2 + index_of(energy, e0 + kmax * kmax / ETOK)) - 1 # interpolate provided chi(k) onto the kout grid if chi_std is not None and k_std is not None: chi_std = np.interp(kout, k_std, chi_std) # pre-load FT window ftwin = kout**kweight * ftwindow( kout, xmin=kmin, xmax=kmax, window=win, dx=dk) # calc k-value and initial guess for y-values of spline params nspl = max(4, min(128, 2 * int(rbkg * (kmax - kmin) / np.pi) + 1)) spl_y, spl_k, spl_e = np.zeros(nspl), np.zeros(nspl), np.zeros(nspl) for i in range(nspl): q = kmin + i * (kmax - kmin) / (nspl - 1) ik = index_nearest(kraw, q) i1 = min(len(kraw) - 1, ik + 5) i2 = max(0, ik - 5) spl_k[i] = kraw[ik] spl_e[i] = energy[ik + ie0] spl_y[i] = (2 * mu[ik + ie0] + mu[i1 + ie0] + mu[i2 + ie0]) / 4.0 # get spline represention: knots, coefs, order=3 # coefs will be varied in fit. knots, coefs, order = splrep(spl_k, spl_y) # set fit parameters from initial coefficients params = Group() for i in range(len(coefs)): name = FMT_COEF % i p = Parameter(coefs[i], name=name, vary=i < len(spl_y)) p._getval() setattr(params, name, p) initbkg, initchi = spline_eval(kraw[:iemax - ie0 + 1], mu[ie0:iemax + 1], knots, coefs, order, kout) # do fit fit = Minimizer(__resid, params, _larch=_larch, toler=1.e-4, fcn_kws=dict(ncoefs=len(coefs), chi_std=chi_std, knots=knots, order=order, kraw=kraw[:iemax - ie0 + 1], mu=mu[ie0:iemax + 1], irbkg=irbkg, kout=kout, ftwin=ftwin, kweight=kweight, nfft=nfft, nclamp=nclamp, clamp_lo=clamp_lo, clamp_hi=clamp_hi)) fit.leastsq() # write final results coefs = [getattr(params, FMT_COEF % i) for i in range(len(coefs))] bkg, chi = spline_eval(kraw[:iemax - ie0 + 1], mu[ie0:iemax + 1], knots, coefs, order, kout) obkg = np.copy(mu) obkg[ie0:ie0 + len(bkg)] = bkg # outputs to group group = set_xafsGroup(group, _larch=_larch) group.bkg = obkg group.chie = (mu - obkg) / edge_step group.k = kout group.chi = chi / edge_step # now fill in 'autobk_details' group params.init_bkg = np.copy(mu) params.init_bkg[ie0:ie0 + len(bkg)] = initbkg params.init_chi = initchi / edge_step params.knots_e = spl_e params.knots_y = np.array([coefs[i] for i in range(nspl)]) params.init_knots_y = spl_y params.nfev = params.fit_details.nfev params.kmin = kmin params.kmax = kmax group.autobk_details = params # uncertainties in mu0 and chi: fairly slow!! if HAS_UNCERTAIN and calc_uncertainties: vbest, vstd = [], [] for n in fit.var_names: par = getattr(params, n) vbest.append(par.value) vstd.append(par.stderr) uvars = uncertainties.correlated_values(vbest, params.covar) # uncertainty in bkg (aka mu0) # note that much of this is working around # limitations in the uncertainty package that make it # 1. take an argument list (not array) # 2. work on returned scalars (but not arrays) # 3. not handle kw args and *args well (so use # of global "index" is important here) nkx = iemax - ie0 + 1 def my_dsplev(*args): coefs = np.array(args) return splev(kraw[:nkx], [knots, coefs, order])[index] fdbkg = uncertainties.wrap(my_dsplev) dmu0 = [fdbkg(*uvars).std_dev() for index in range(len(bkg))] group.delta_bkg = np.zeros(len(mu)) group.delta_bkg[ie0:ie0 + len(bkg)] = np.array(dmu0) # uncertainty in chi (see notes above) def my_dchi(*args): coefs = np.array(args) b, chi = spline_eval(kraw[:nkx], mu[ie0:iemax + 1], knots, coefs, order, kout) return chi[index] fdchi = uncertainties.wrap(my_dchi) dchi = [fdchi(*uvars).std_dev() for index in range(len(kout))] group.delta_chi = np.array(dchi) / edge_step
from libphysics import * from estrazione_segnale_funzione import * from incertezza_H_funzione import * import uncertainties from uncertainties import ufloat from uncertainties import unumpy, wrap from uncertainties.umath import * plt.rc('font', family='serif', size=18) freqs = numpify( [980, 3.6e3, 11.4e3, 38.1e3, 88.6e3, 141.3e3, 200e3, 159e3, 100, 250, 520]) Rc = 9.830e3 Re = 119.25 # Funzioni wrappate per uncertainties wangle = wrap(np.angle) wreal = wrap(np.real) wimag = wrap(np.imag) def mod(Re, Im): return np.sqrt(Re**2 + Im**2) wabs = wrap(mod) def ang(Re, Im): return np.angle(Re + 1j * Im)