Пример #1
0
def salt2mu_aberr(x1=None,x1err=None,
                  c=None,cerr=None,
                  mb=None,mberr=None,
                  cov_x1_c=None,cov_x1_x0=None,cov_c_x0=None,
                  alpha=None,beta=None,
                  alphaerr=None,betaerr=None,
                  M=None,x0=None,sigint=None,z=None,peczerr=0.0005):
    from uncertainties import ufloat, correlated_values, correlated_values_norm
    alphatmp,betatmp = alpha,beta
    alpha,beta = ufloat(alpha,alphaerr),ufloat(beta,betaerr)

    sf = -2.5/(x0*np.log(10.0))
    cov_mb_c = cov_c_x0*sf
    cov_mb_x1 = cov_x1_x0*sf

    mu_out,muerr_out = np.array([]),np.array([])
    for i in range(len(x1)):

        covmat = np.array([[mberr[i]**2.,cov_mb_x1[i],cov_mb_c[i]],
                           [cov_mb_x1[i],x1err[i]**2.,cov_x1_c[i]],
                           [cov_mb_c[i],cov_x1_c[i],cerr[i]**2.]])
        mb_single,x1_single,c_single = correlated_values([mb[i],x1[i],c[i]],covmat)

        mu = mb_single + x1_single*alpha - beta*c_single + 19.36
        if sigint: mu = mu + ufloat(0,sigint)
        zerr = peczerr*5.0/np.log(10)*(1.0+z[i])/(z[i]*(1.0+z[i]/2.0))

        mu = mu + ufloat(0,np.sqrt(zerr**2. + 0.055**2.*z[i]**2.))
        mu_out,muerr_out = np.append(mu_out,mu.n),np.append(muerr_out,mu.std_dev)

    return(mu_out,muerr_out)
Пример #2
0
def test_pseudo_inverse():
    "Tests of the pseudo-inverse"

    # Numerical version of the pseudo-inverse:
    pinv_num = core.wrap_array_func(numpy.linalg.pinv)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat((10, 1)), -3.1],
                       [0, ufloat((3, 0))],
                       [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    rcond = 1e-8  # Test of the second argument to pinv()
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)

    ##########
    # Example with a non-full rank rectangular matrix:
    vector = [ufloat((10, 1)), -3.1, 11]
    m = unumpy.matrix([vector, vector])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)

    ##########
    # Example with a non-full-rank square matrix:
    m = unumpy.matrix([[ufloat((10, 1)), 0], [3, 0]])
    m_pinv_num = pinv_num(m, rcond)
    m_pinv_package = core._pinv(m, rcond)
    assert matrices_close(m_pinv_num, m_pinv_package)
Пример #3
0
def test_wrap_array_func():
    '''
    Test of numpy.wrap_array_func(), with optional arguments and
    keyword arguments.
    '''

    # Function that works with numbers with uncertainties in mat (if
    # mat is an uncertainties.unumpy.matrix):
    def f_unc(mat, *args, **kwargs):
        return mat.I + args[0]*kwargs['factor']

    # Test with optional arguments and keyword arguments:
    def f(mat, *args, **kwargs):
        # This function is wrapped: it should only be called with pure
        # numbers:
        assert not any(isinstance(v, uncert_core.UFloat) for v in mat.flat)
        return f_unc(mat, *args, **kwargs)


    # Wrapped function:
    f_wrapped = core.wrap_array_func(f)

    ##########
    # Full rank rectangular matrix:
    m = unumpy.matrix([[ufloat(10, 1), -3.1],
                       [0, ufloat(3, 0)],
                       [1, -3.1]])

    # Numerical and package (analytical) pseudo-inverses: they must be
    # the same:
    m_f_wrapped = f_wrapped(m, 2, factor=10)
    m_f_unc = f_unc(m, 2, factor=10)

    assert arrays_close(m_f_wrapped, m_f_unc)
Пример #4
0
def getPerformanceOnMC(
    files,
    histogramForEstimation="QCDStudy/PFIsolation_WithMETCutAndAsymJetCuts_DR03",
    bjetBin="",
    function="expo",
    fitRange=(0.3, 1.6),
    additionFitRanges=[(0.2, 1.6), (0.4, 1.6)],
):
    if bjetBin:
        histogramForEstimation = histogramForEstimation + "_" + bjetBin

    hists = [histogramForEstimation]
    hists = getHistsFromFiles(hists, files)
    hists = addSampleSum(hists)

    histogramForComparison = hists["qcd"][histogramForEstimation]
    histogramForEstimation = hists["allMC"][histogramForEstimation]

    estimate, absoluteError = getQCDEstimateFor(
        histogramForEstimation, function, fitRange=fitRange, additionFitRanges=additionFitRanges
    )

    qcdInSignalRegion, qcdError = getIntegral(histogramForComparison, (0, 0.1))

    N_est = ufloat((estimate, absoluteError))
    N_qcd = ufloat((qcdInSignalRegion, qcdError))

    relativeDeviation = N_est / N_qcd

    result = {}
    result["performance"] = (relativeDeviation.nominal_value, relativeDeviation.std_dev())
    result["estimate"] = (estimate, absoluteError)
    result["qcdInSignalRegion"] = (qcdInSignalRegion, qcdError)

    return result
Пример #5
0
def split_dat(data):
    """
        Takes the row in the form r_n e_r_n ext_n e_ext_n and returns two lists
        one with the radii and the other with the extinction values both lists
        are of ufloats

        Parameters
        --------
                data : list
                A list of floats of the radii and errors and extinctions and 
                errors.

        Returns 
        --------
                rad : list
                List of ufloats of the radii.

                ext : list
                List of ufloats of the extinctions.
    """
    rad, ext = [], []

    for i in range(0, len(data) - 1, 4):
        vec = [data[i], data[i+1], data[i+2], data[i+3]]
        
        if vec[0].strip() != '':
            radius = ufloat(vec[0], vec[1])
            extinct = ufloat(vec[2], vec[3])

            rad.append(radius)
            ext.append(extinct)

    return ext, rad
Пример #6
0
def exponential_fit_offset(x, y, amp_guess=1, decay_guess=1, offset_guess=0, errors=True):
    """
    Simple helper function that speeds up single exponetial fit with offset. Uses lmfit
    
    Parameters
    ----------
    x, y (float)
        Sample length x, y arrays of data to be fitted

    Returns
    -------
    Returns slope and intercept, with uncertainties (use uncertainties package if availabe)

    !!!!!
    not tested or working
    !!!!!
    """
    from lmfit.models import ExpressionModel
    mod = ExpressionModel("offset + amp * exp(-x/decay)")
    par = mod.make_params(amp=amp_guess, decay=decay_guess, offset_guess=offset_guess)
    out = mod.fit(y, params=par, x=x)

    s = out.params['slope']
    i = out.params['intercept']

    if errors:
        try:
            from uncertainties import ufloat
            return ufloat(s.value, s.stderr), ufloat(i.value, i.stderr)
        except:
            return s.value, s.stderr, i.value, i.stderr
    else:
        return s.value, i.value
def get_vhtt_yield(mass):
    log.warning("Get VHTT yield %s", mass)
    mmt_yield = results_file.Get('mmt_mumu_final_count/VH%i' % mass).Integral()
    emt_yield = results_file.Get('emt_emu_final_count/VH%i' % mass).Integral()

    _, (mmt_passed, mmt_total) = get_stat_error('VH%i' % mass, mmt_yield)
    _, (emt_passed, emt_total) = get_stat_error('VH%i' % mass, emt_yield)

    assert(mmt_total == emt_total)

    mmt_passed = ufloat( (mmt_passed, math.sqrt(mmt_passed) ))
    emt_passed = ufloat( (emt_passed, math.sqrt(emt_passed) ))
    total = ufloat( (mmt_total, math.sqrt(mmt_total) ))

    all_passed = mmt_passed + emt_passed

    log.warning("total %s", total)
    log.warning("all %s", all_passed)

    #multply by fraction of ZH_WH_ttH that is WH
    wh_xsec = ROOT.HiggsCSandWidth().HiggsCS(3, mass, 7)
    zh_xsec = ROOT.HiggsCSandWidth().HiggsCS(4, mass, 7)
    tth_xsec = ROOT.HiggsCSandWidth().HiggsCS(5, mass, 7)

    wh_fraction = wh_xsec/(wh_xsec + zh_xsec + tth_xsec)

    log.warning("wh_frac %s", wh_fraction)

    br_bonus = 1.0/(0.1075+0.1057+0.1125)

    log.warning("br_bonus %s", br_bonus)

    return 100*br_bonus*(all_passed/total)/wh_fraction
Пример #8
0
def regression(f, x_u, y_u, beta0 ):
    for i, y in enumerate(y_u):
        if ustd(y) == 0:
            y_u[i] = ufloat(y_u[i].nominal_value, y_u[i].nominal_value/1e15)
    if len(x_u.shape) == 2:
        x_nom = range(len(x_u))
        x_error = range(len(x_u))
        for i, col in enumerate(x_u):
            for j, elem in enumerate(col):
                if ustd(elem) == 0:
                    x_u[i,j] = ufloat(elem.nominal_value, elem.nominal_value/1e15)
            x_nom[i] = unom(x_u[i])
            x_error[i] = ustd(x_u[i])
        x_nom = np.array(x_nom)
        x_error = np.array(x_error)
    elif np.sum(ustd(x_u)) == 0:
        x_error = None
    else:
        x_error = ustd(x_u)
        x_nom = unom(x_u)
    linear = odrpack.Model(f)
    mydata = odrpack.RealData(x_nom, unom(y_u),sy=ustd(y_u), sx=x_error)
    myodr = odrpack.ODR(mydata, linear, beta0=beta0)
    myoutput = myodr.run()
    #myoutput.pprint()
    #print "Chi-squared =", np.sum((myoutput.delta**2 + myoutput.eps**2)/(ustd(x_u)**2+ ustd(y_u)**2))
    print "Chi-squared =", myoutput.sum_square
    beta_u = unumpy.uarray(myoutput.beta, myoutput.sd_beta)
    print "beta = ",  beta_u
    print "reduced chi-square =", myoutput.res_var
    degrees_of_freedom = myoutput.sum_square/myoutput.res_var
    p_value = 1-scipy.stats.chi2.cdf(myoutput.sum_square, degrees_of_freedom)
    print "p-value =", p_value
    return beta_u
Пример #9
0
def line_fit(x, y, errors=True):
    """
    Simple helper function that speeds up line fitting. Uses lmfit
    
    Parameters
    ----------
    x, y (float)
        Sample length x, y arrays of data to be fitted

    Returns
    -------
    Returns slope and intercept, with uncertainties (use uncertainties package if availabe)
    Also returns fit object out, can be dropped
    """
    from lmfit.models import LinearModel
    mod = LinearModel()
    par = mod.guess(y, x=x)
    out = mod.fit(y, par, x=x)

    s = out.params['slope']
    i = out.params['intercept']

    if errors:
        try:
            from uncertainties import ufloat
            return ufloat(s.value, s.stderr), ufloat(i.value, i.stderr), out
        except:
            return s.value, s.stderr, i.value, i.stderr, out
    else:
        return s.value, i.value, out
Пример #10
0
        def func(ra):
            u, l = ra.split(':')
            try:
                ru = self.signals[u]
                rl = self.signals[l]
            except KeyError:
                return ''

            if cfb:
                bu = ufloat(0, 0)
                bl = ufloat(0, 0)
                try:
                    bu = self.baselines[u]
                    bl = self.baselines[l]
                except KeyError:
                    pass
                try:
                    rr = (ru - bu) / (rl - bl)
                except ZeroDivisionError:
                    rr = ufloat(0, 0)
            else:
                try:
                    rr = ru / rl
                except ZeroDivisionError:
                    rr = ufloat(0, 0)

            res = '{}/{}={} '.format(u, l, pad('{:0.4f}'.format(rr.nominal_value))) + \
                  PLUSMINUS + pad(format('{:0.4f}'.format(rr.std_dev)), n=6) + \
                    self._get_pee(rr)
            return res
Пример #11
0
 def fit_single_line_BS(self, x, y, zero_lev, err_continuum, fitting_parameters, bootstrap_iterations = 1000):
     
     #Declare parameters and containers for the fit
     params_dict     = fitting_parameters.valuesdict()
     initial_values  = [params_dict['A0'], params_dict['mu0'], params_dict['sigma0']]
     area_array      = empty(bootstrap_iterations)
     params_array    = empty([3, bootstrap_iterations])
     n_points        = len(x)
                         
     #Perform the fit
     for i in range(bootstrap_iterations):
         y_new               = y + np_normal_dist(0, err_continuum, n_points)
         area_array[i]       = simps(y_new, x) - simps(zero_lev, x)
         best_vals, covar    = curve_fit(gaussian_curveBS, (x, zero_lev), y_new, p0=initial_values, maxfev = 1600)
         params_array[:,i]   = best_vals
                 
     #Compute Bootstrap output
     mean_area, std_area = mean(area_array), std(area_array)
     mean_params_array, stdev_params_array = params_array.mean(1), params_array.std(1)
     
     #Store the data
     self.fit_dict['area_intg'],     self.fit_dict['area_intg_er']   = mean_area, std_area
     self.fit_dict['A0_norm'],       self.fit_dict['A0_norm_er']     = mean_params_array[0], stdev_params_array[0]
     self.fit_dict['mu0_norm'],      self.fit_dict['mu0_norm_er']    = mean_params_array[1], stdev_params_array[1]  
     self.fit_dict['sigma0_norm'],   self.fit_dict['sigma0_norm_er'] = mean_params_array[2], stdev_params_array[2]  
             
     A = ufloat(mean_params_array[0], stdev_params_array[0]) 
     sigma = ufloat(mean_params_array[2], stdev_params_array[2])         
     fwhm0_norm = 2.354820045 * sigma
     areaG0_norm = A * sigma * self.sqrt2pi
   
     self.fit_dict['fwhm0_norm'], self.fit_dict['fwhm0_norm_er'] = fwhm0_norm.nominal_value, fwhm0_norm.std_dev
     self.fit_dict['area_G0_norm'], self.fit_dict['area_G0_norm_er'] = areaG0_norm.nominal_value, areaG0_norm.std_dev
                        
     return
Пример #12
0
    def get_mean_raw(self, tau=None):
        vs = []
        corrfunc = self._deadtime_correct
        for r in six.itervalues(self._cp):
            n = int(r['NShots'])
            nv = ufloat(float(r['Ar40']), float(r['Ar40err'])) * 6240
            dv = ufloat(float(r['Ar36']), float(r['Ar36err'])) * 6240
            if tau:
                dv = corrfunc(dv, tau * 1e-9)

            vs.append((n, nv / dv))

        key = lambda x: x[0]
        vs = sorted(vs, key=key)

        mxs = []
        mys = []
        mes = []
        for n, gi in groupby(vs, key=key):
            mxs.append(n)
            ys, es = list(zip(*[(nominal_value(xi[1]), std_dev(xi[1])) for xi in gi]))

            wm, werr = calculate_weighted_mean(ys, es)
            mys.append(wm)
            mes.append(werr)

        return mxs, mys, mes
Пример #13
0
def combine_complex_df( df1, df2 ):
	'''
	Takes a 2 pandii dataframes of the form:
		A 	| 	B   	 	A 	| 	B 
	  (v,e) | (v,e)		  (v,e) | (v,e) 

	Returns 1 pandas dataframe of the form
			      A   |   B 
	  			(v,e) | (v,e)
	'''
	from uncertainties import ufloat
	l1=df1.columns.tolist()
	l2=df2.columns.tolist()
	if l1 != l2:
		print "Trying to combine two non compatible dataframes"
		print l1
		print l2
		return

	combined_result = {}
	for sample in l1:
		results = []
		for entry1, entry2 in zip(df1[sample], df2[sample]):
			v1 = ufloat(entry1[0], entry1[1])
			v2 = ufloat(entry2[0], entry2[1])
			s = v1 + v2
			results.append( ( s.nominal_value, s.std_dev ) )
		combined_result[sample] = results
	df = dict_to_df(combined_result)
	return df
Пример #14
0
    def get_data(self) :

        self.sampdata=collections.OrderedDict()
        self.data = {}

        for sname, samp in self.samples.iteritems() : 
            if samp['files'] and samp['fields'] :
                sdata = self.get_data_from_pickle( samp['files'], samp['fields'] )
                self.sampdata[sname] = { 'val' : sdata[0],'err' : samp['err']  }
            else :
                self.sampdata[sname] = { 'val' : ufloat(0, 0),'err' : None  }
                
        if self.datasamp['use_sample_sum'] :
            ddata = ufloat(0, 0)
            for sname, samp in self.samples.iteritems() : 
                if samp['isSig'] : 
                    continue
                samp_val = self.sampdata[sname]
                ddata = ddata + samp_val['val']
            self.data = {'val' : ddata }
        else :
            
            ddata = self.get_data_from_pickle( self.datasamp['files'], self.datasamp['fields'] )
            self.data = {'val' : ddata[0] }

        if self.datasamp['generate'] :
            genval = rand.Poisson( self.data['val'].n )
            self.data = {'val' : ufloat( genval, math.sqrt( genval ) ) }
def calculate_latencies(version_dates):
    linux_latencies = latency(version_dates['linux'], OrderedDict(avo.os_to_kernel))
    set_latex_value('linuxMeanUpdateLatency', ufloat(statistics.mean(linux_latencies.values()),statistics.stdev(linux_latencies.values())))
    openssl_latencies = latency(version_dates['openssl'], OrderedDict(avo.os_to_project['openssl']))
    set_latex_value('opensslMeanUpdateLatency', ufloat(statistics.mean(openssl_latencies.values()),statistics.stdev(openssl_latencies.values())))
    bouncycastle_latencies = latency(version_dates['bouncycastle'], OrderedDict(avo.os_to_project['bouncycastle']))
    set_latex_value('bouncycastleMeanUpdateLatency',ufloat(statistics.mean(bouncycastle_latencies.values()),statistics.stdev(bouncycastle_latencies.values())))
def Compute_HeliumAbundance(FileFolder, CodeName):

    OI_HI       = pv.GetParameter_ObjLog(CodeName, FileFolder, Parameter='OI_HI_pn', Assumption='float')
    SI_HI       = pv.GetParameter_ObjLog(CodeName, FileFolder, Parameter='SI_HI_ArCorr_pn', Assumption='float')
    HeIII_HII   = pv.GetParameter_ObjLog(CodeName, FileFolder, Parameter='HeIII_HII_pn', Assumption='float')

    if OI_HI != None:
        HeII_HII_Inference = ufloat(bp.statistics_dict['He_abud']['mean'], bp.statistics_dict['He_abud']['standard deviation'])
        
        #Add the HeIII component if observed
        if HeIII_HII != None:
            HeI_HI = HeII_HII_Inference + HeIII_HII
        else:
            HeI_HI = HeII_HII_Inference
        
        Y_mass_InferenceO = (4 * HeI_HI * (1 - 20 * OI_HI)) / (1 + 4 * HeI_HI)
    
    else:
        Y_mass_InferenceO = None
      
    if SI_HI != None:
        HeII_HII_Inference = ufloat(bp.statistics_dict['He_abud']['mean'], bp.statistics_dict['He_abud']['standard deviation'])
        
        #Add the HeIII component if observed
        if HeIII_HII != None:
            HeI_HI = HeII_HII_Inference + HeIII_HII
        else:
            HeI_HI = HeII_HII_Inference
            
        Y_mass_InferenceS = (4 * HeI_HI * (1 - 20 * ch_an.OI_SI * SI_HI)) / (1 + 4 * HeI_HI)
    
    else:
        Y_mass_InferenceS = None    
        
    return Y_mass_InferenceO, Y_mass_InferenceS
Пример #17
0
 def test_decimal_places(self):
     cases = [(0, '0'), (-1, '-1'), (0.012, '0.01'), (0.016, '0.02')
             , (ufloat(0,0), r'$0.0 \pm 0.0$'), (ufloat(10,0), r'$10.0 \pm 0.0$')
             , (ufloat(0.12, 0.012), r'$0.12 \pm 0.01$'), (ufloat(0.12, 0.016), r'$0.12 \pm 0.02$')
             , (ufloat(-0.12, 0.016), r'$-0.12 \pm 0.02$')]
     for test_case, result in cases:
         self.assertEqual(display_num(test_case, decimal_places=2), result)
Пример #18
0
def age_equation(j, f,
                 include_decay_error=False,
                 lambda_k=None,
                 scalar=None,
                 arar_constants=None):
    if isinstance(j, tuple):
        j = ufloat(*j)
    elif isinstance(j, str):
        j = ufloat(j)

    if isinstance(f, tuple):
        f = ufloat(*f)
    elif isinstance(f, str):
        f = ufloat(f)

    if not lambda_k:
        if arar_constants is None:
            arar_constants = ArArConstants()
        lambda_k = arar_constants.lambda_k

    if not scalar:
        if arar_constants is None:
            arar_constants = ArArConstants()
        scalar = float(arar_constants.age_scalar)

    if not include_decay_error:
        lambda_k = nominal_value(lambda_k)
    try:
        return (lambda_k ** -1 * umath.log(1 + j * f)) / scalar
    except (ValueError, TypeError):
        return ufloat(0, 0)
Пример #19
0
    def get_value(self, attr):
        # print 'get attr', attr, self.isotopes
        r = ufloat(0, 0, tag=attr)
        if attr.endswith('bs'):
            iso = attr[:-2]
            if iso in self.isotopes:
                r = self.isotopes[iso].baseline.uvalue
        elif '/' in attr:
            non_ic_corr = attr.startswith('u')
            if non_ic_corr:
                attr = attr[1:]
            r = self.get_ratio(attr, non_ic_corr)
        elif attr == 'icf_40_36':
            r = self.get_corrected_ratio('Ar40', 'Ar36')
        elif attr.endswith('ic'):
            # ex. attr='Ar40ic'
            isok = attr[:-2]
            try:
                r = self.isotopes[isok].ic_factor
            except KeyError:
                r = ufloat(0, 0)

        elif attr in self.computed:
            r = self.computed[attr]
        elif attr in self.isotopes:
            r = self.isotopes[attr].get_intensity()
        elif hasattr(self, attr):
            r = getattr(self, attr)
        # else:
        #     iso = self._get_iso_by_detector(attr)
        #     # iso=next((i for i in self.isotopes if i.detector==attr), None)
        #     if iso:
        #         r = ufloat(iso.ys[-1], tag=attr)

        return r
Пример #20
0
def interference_corrections(a39, a37,
                             production_ratios,
                             arar_constants=None,
                             fixed_k3739=False):
    if production_ratios is None:
        production_ratios = {}

    if arar_constants is None:
        arar_constants = ArArConstants()

    pr = production_ratios
    k37 = ufloat(0, 0, tag='k37')

    if arar_constants.k3739_mode.lower() == 'normal' and not fixed_k3739:
        # iteratively calculate 37, 39
        for _ in range(5):
            ca37 = a37 - k37
            ca39 = pr.get('Ca3937', 0) * ca37
            k39 = a39 - ca39
            k37 = pr.get('K3739', 0) * k39
    else:
        if not fixed_k3739:
            fixed_k3739 = arar_constants.fixed_k3739

        ca37, ca39, k37, k39 = apply_fixed_k3739(a39, pr, fixed_k3739)

    k38 = pr.get('K3839', 0) * k39

    if not arar_constants.allow_negative_ca_correction:
        ca37 = max(ufloat(0, 0), ca37)

    ca36 = pr.get('Ca3637', 0) * ca37
    ca38 = pr.get('Ca3837', 0) * ca37

    return k37, k38, k39, ca36, ca37, ca38, ca39
Пример #21
0
    def calc_f(pr):
        k37, k38, k39, ca36, ca37, ca38, ca39 = interference_corrections(a39, a37, pr, arar_constants, fixed_k3739)
        atm36, cl36, cl38 = calculate_atmospheric(a38, a36, k38, ca38, ca36,
                                                  decay_time,
                                                  pr,
                                                  arar_constants)

        # calculate radiogenic
        trapped_4036 = copy(arar_constants.atm4036)
        trapped_4036.tag = 'trapped_4036'
        atm40 = atm36 * trapped_4036

        k4039 = pr.get('K4039', 0)
        k40 = k39 * k4039

        rad40 = a40 - atm40 - k40
        try:
            ff = rad40 / k39
        except ZeroDivisionError:
            ff = ufloat(1.0, 0)

        nar = {'k40': k40, 'ca39': ca39, 'k38': k38, 'ca38': ca38, 'cl38': cl38, 'k37': k37, 'ca37': ca37, 'ca36': ca36,
               'cl36': cl36}
        try:
            rp = rad40 / a40 * 100
        except ZeroDivisionError:
            rp = ufloat(0, 0)

        comp = {'rad40': rad40, 'a40': a40, 'rad40_percent': rp, 'ca37': ca37, 'ca39': ca39, 'ca36': ca36, 'k39': k39,
                'atm40': atm40}

        ifc = {'Ar40': a40 - k40, 'Ar39': k39, 'Ar38': a38, 'Ar37': a37, 'Ar36': atm36}
        return ff, nar, comp, ifc
Пример #22
0
def small_sep13 ( mx , mxErr, lag=0):
	""" 
	Given a frequency matrix and errors calculates the (scaled) small 
	separation d13 and propagates errors.
	
	Notes
	-----
	The parameter lag is the difference between the radial orders of
	the first modes of l=1 and l=3.  
	"""

	(Nn, Nl) = np.shape(mx)
	d13    = np.zeros((1,Nn))
	d13Err = np.zeros((1,Nn))
	d13.fill(None)      # values that can't be calculated remain NaN

	for n in range(1-lag,Nn):
		if (mx[n,1] != 0. and mx[n-1+lag,3] != 0.):     
        		a = un.ufloat( (mx[n,1], mxErr[n,1]) )
        		b = un.ufloat( (mx[n-1+lag,3], mxErr[n-1+lag,3]) )
        		result = (a-b) / 5.
        		d13[0,n-1+lag]    = un.nominal_value(result)
        		d13Err[0,n-1+lag] = un.std_dev(result)

	return d13, d13Err
Пример #23
0
def calculate_flux(f, age, arar_constants=None):
    """
        #rad40: radiogenic 40Ar
        #k39: 39Ar from potassium
        f: F value rad40Ar/39Ar
        age: age of monitor in years

        solve age equation for J
    """
    # if isinstance(rad40, (list, tuple)):
    # rad40 = ufloat(*rad40)
    # if isinstance(k39, (list, tuple)):
    # k39 = ufloat(*k39)

    if isinstance(f, (list, tuple)):
        f = ufloat(*f)

    if isinstance(age, (list, tuple)):
        age = ufloat(*age)
        #    age = (1 / constants.lambdak) * umath.log(1 + JR)
    try:
        # r = rad40 / k39
        if arar_constants is None:
            arar_constants = ArArConstants()

        j = (umath.exp(age * arar_constants.lambda_k.nominal_value) - 1) / f
        return j.nominal_value, j.std_dev
    except ZeroDivisionError:
        return 1, 0
Пример #24
0
def day3_vacuum():
    plt.clf()
    ux = unp.uarray([800, 1000, 500], ux_error)  # V
    ug_crit = unp.uarray([110, 140, 30], ug_error)  # V
    omega = 2 * math.pi * ufloat(48, 1)  # Hz

    ug_crit = _apply_additional_proportional_error(ug_crit, stability_uncertainty_vacuum)
    ux *= ux_correction
    ug_crit *= ug_correction

    stability(ux, ug_crit, omega, label="Particle V1")

    plt.title("p = 300 mbar")
    plt.legend(loc=2)
    plt.savefig("images/stability_vacuum_1.pdf")

    plt.clf()
    ux = unp.uarray([700, 800], ux_error)  # V
    ug_crit = unp.uarray([100, 140], ug_error)  # V
    omega = 2 * math.pi * ufloat(45, 1)  # Hz

    ug_crit = _apply_additional_proportional_error(ug_crit, stability_uncertainty_vacuum)
    ux *= ux_correction
    ug_crit *= ug_correction

    stability(ux, ug_crit, omega, label="Particle V2")

    plt.title("p = 180 mbar")
    plt.legend(loc=2)
    plt.savefig("images/stability_vacuum_2.pdf")
Пример #25
0
def safe_div(n, d):
    if n.size == 0:
        return None
    if n.shape != d.shape:
        return None
    if isinstance(n[0, 0], UFloat) is False:
        return None
    z = np.zeros_like(n)
    z.fill(ufloat(np.nan, np.nan))
    it = np.nditer(d, op_flags=["readonly"], flags=["multi_index", "refs_ok"])
    while not it.finished:
        i = it.multi_index[0]
        j = it.multi_index[1]
        if abs(d[i, j].n) == 0.0:
            # z[i,j] = ufloat(0.,0.)
            z[i, j] = ufloat(np.nan, np.nan)
        #            if abs(n[i,j].n) > 0. :
        #                z[i,j] = ufloat(np.nan,np.nan)
        #            else :
        #                err = np.sqrt( n[i,j].s**2. + d[i,j].s**2. )
        #                z[i,j] = ufloat(0.,err)
        # z[i,j] = ufloat(np.nan,np.nan)
        # z[i,j] = ufloat(np.inf,np.inf)
        else:
            z[i, j] = n[i, j] / d[i, j]
        it.iternext()
    return z
Пример #26
0
def get_1d_loose_efficiencies( int_stat, int_syst, lead_reg, lead_ptrange, systematics=None) :

    eff_stat = {}
    eff_syst = {}

    if int_stat['lead']['real']['loose'].n == 0 :
        eff_stat['eff_R_T_lead'] = ufloat( 1.0, int_stat['lead']['real']['tight'].s/int_stat['lead']['real']['tight'].n )
    else :
        eff_stat['eff_R_T_lead'] = int_stat['lead']['real']['tight'] / (int_stat['lead']['real']['tight']+int_stat['lead']['real']['loose'])
    eff_stat['eff_F_T_lead'] = int_stat['lead']['fake']['tight'] / (int_stat['lead']['fake']['tight']+int_stat['lead']['fake']['loose'])
    eff_stat['eff_R_L_lead'] = int_stat['lead']['real']['loose'] / (int_stat['lead']['real']['tight']+int_stat['lead']['real']['loose'])
    eff_stat['eff_F_L_lead'] = int_stat['lead']['fake']['loose'] / (int_stat['lead']['fake']['tight']+int_stat['lead']['fake']['loose'])

    eff_syst['eff_R_T_lead'] = int_syst['lead']['real']['tight'] / (int_syst['lead']['real']['tight']+int_syst['lead']['real']['loose'])
    eff_syst['eff_F_T_lead'] = int_syst['lead']['fake']['tight'] / (int_syst['lead']['fake']['tight']+int_syst['lead']['fake']['loose'])
    eff_syst['eff_R_L_lead'] = int_syst['lead']['real']['loose'] / (int_syst['lead']['real']['tight']+int_syst['lead']['real']['loose'])
    eff_syst['eff_F_L_lead'] = int_syst['lead']['fake']['loose'] / (int_syst['lead']['fake']['tight']+int_syst['lead']['fake']['loose'])


    # Do systematics
    # the integrals may already have some systematics
    # that are propagated to the eff_*
    # therefore, don't overwrite the existing 
    # systematics, but make a ufloat with a
    # zero value, and non-zero syst
    eff_syst['eff_R_L_lead'] = eff_syst['eff_R_L_lead'] + ufloat( 0.0, math.fabs(eff_syst['eff_R_L_lead'].n)*get_syst_uncertainty( 'RealTemplateNom', lead_reg, lead_ptrange, 'real', 'loose' ), 'Template_lead_real_loose')
    eff_syst['eff_F_L_lead'] = eff_syst['eff_F_L_lead'] + ufloat( 0.0, math.fabs(eff_syst['eff_F_L_lead'].n)*get_syst_uncertainty( 'FakeTemplate%s'%systematics, lead_reg, lead_ptrange, 'fake', 'loose' ), 'Template_lead_fake_loose' )
    eff_syst['eff_R_T_lead'] = eff_syst['eff_R_T_lead'] + ufloat( 0.0, math.fabs(eff_syst['eff_R_T_lead'].n)*get_syst_uncertainty( 'RealTemplateNom', lead_reg, lead_ptrange, 'real', 'loose' ), 'Template_lead_real_loose')
    eff_syst['eff_F_T_lead'] = eff_syst['eff_F_T_lead'] + ufloat( 0.0, math.fabs(eff_syst['eff_F_T_lead'].n)*get_syst_uncertainty( 'FakeTemplate%s'%systematics, lead_reg, lead_ptrange, 'fake', 'loose' ), 'Template_lead_fake_loose' )

    return eff_stat, eff_syst
Пример #27
0
def day2_air():
    plt.clf()
    ux = unp.uarray([1000, 860, 800, 760, 1000, 920, 620], ux_error)  # V
    ug_crit_1 = unp.uarray([390, 170, 600, 120, 225, 175, 53], ug_error)  # V
    ug_crit_2 = unp.uarray([390, 170, 600, 120, 160, 145, 67], ug_error)  # V
    ug_crit_3 = unp.uarray([390, 370, 600, 120, 225, 175, 67], ug_error)  # V
    omega = 2 * math.pi * ufloat(28, 1)  # Hz

    ux *= ux_correction
    for i, ug_crit in enumerate((ug_crit_1, ug_crit_2, ug_crit_3), 1):
        ug_crit = _apply_additional_proportional_error(ug_crit, stability_uncertainty_air)
        ug_crit *= ug_correction

        stability(ux, ug_crit, omega, "Particle A%d" % i)

    plt.legend(loc=2)
    plt.savefig("images/stability_air_1.pdf")

    plt.clf()
    ux = unp.uarray([550, 740, 870, 1040], ux_error)
    ug_crit = unp.uarray([39, 84, 133, 147], ug_error)
    omega = 2 * math.pi * ufloat(32, 1)  # Hz

    ug_crit = _apply_additional_proportional_error(ug_crit, stability_uncertainty_air)
    ux *= ux_correction
    ug_crit *= ug_correction

    stability(ux, ug_crit, omega, label="Particle A4")

    plt.legend(loc=2)
    plt.savefig("images/stability_air_2.pdf")
Пример #28
0
def small_sep02 ( mx , mxErr, lag=0):
	""" 
	Given a frequency matrix and errors calculates the (scaled) small 
	separation d02 and propagates errors.
	
	Notes
	-----
	The parameter lag is the difference between the radial orders of
	the first modes of l=0 and l=2.  
	"""

	(Nn, Nl) = np.shape(mx)
	d02    = np.zeros((1,Nn))
	d02Err = np.zeros((1,Nn))
	d02.fill(None)      # values that can't be calculated are NaN

	
	for n in range(1-lag,Nn):
		if (mx[n,0] != 0. and mx[n-1+lag,2] != 0.):
		    a = un.ufloat( (mx[n,0], mxErr[n,0]) )
		    b = un.ufloat( (mx[n-1+lag,2], mxErr[n-1+lag,2]) )
		    result = (a-b) / 3.	
		    d02[0,n-1+lag]    = un.nominal_value(result)
		    d02Err[0,n-1+lag] = un.std_dev(result)
		
	return d02, d02Err
Пример #29
0
    def _set_age_values(self, f, include_decay_error=False):
        arc = self.arar_constants
        j = copy(self.j)
        if j is None:
            j = ufloat(1e-4, 1e-7)
        j.tag = 'Position'
        j.std_dev = self.position_jerr or 0
        age = age_equation(j, f, include_decay_error=include_decay_error, arar_constants=arc)
        self.uage_w_position_err = age

        j = self.j
        if j is None:
            j = ufloat(1e-4, 1e-7, tag='J')

        age = age_equation(j, f, include_decay_error=include_decay_error, arar_constants=arc)
        self.uage_w_j_err = age

        j = copy(self.j)
        if j is None:
            j = ufloat(1e-4, 1e-7, tag='J')

        j.std_dev = 0
        age = age_equation(j, f, include_decay_error=include_decay_error, arar_constants=arc)
        self.uage = age

        self.age = nominal_value(age)
        self.age_err = std_dev(age)
        self.age_err_wo_j = std_dev(age)

        for iso in self.itervalues():
            iso.age_error_component = self.get_error_component(iso.name)
Пример #30
0
    def eval(self, vertex_generator, nevals, nreps=16, ndaq=50):
        """
        Return the negative log likelihood that the detector event set in the
        constructor or by set_event() was the result of a particle generated
        by `vertex_generator`.  If `nreps` set to > 1, each set of photon
        vertices will be propagated `nreps` times.
        """
        ntotal = nevals * nreps * ndaq

        hit_prob, pdf_prob, pdf_prob_uncert = \
            self.eval_channel_vbin(vertex_generator, nevals, nreps, ndaq)

        # NLL calculation: note that negation is at the end
        # Start with the probabilties of hitting (or not) the channels
        
        # Flip probability for channels in event that were not hit
        hit_prob[~self.event.channels.hit] = 1.0 - hit_prob[~self.event.channels.hit]
        # Apply a floor so that we don't take the log of zero
        hit_prob = np.maximum(hit_prob, 0.5 / ntotal)

        hit_channel_prob = np.log(hit_prob).sum()
        log_likelihood = ufloat((hit_channel_prob, 0.0))

        # Then include the probability densities of the observed
        # charges and times.
        log_likelihood += ufloat((np.log(pdf_prob[self.event.channels.hit]).sum(),
                                  0.0))
        
        return -log_likelihood
Пример #31
0
import numpy as np
from uncertainties import ufloat
import uncertainties.unumpy as unp

Lrund = np.array([60.05, 61.00, 60.00, 60.00, 60.00])  #cm
Leckig = np.array([60.30, 60.30, 60.30, 60.30, 60.34])  #cm
drund = np.array([10.00, 9.95, 10.00, 10.00, 10.00])  #mm
aeckig = np.array([12.00, 12.00, 11.95, 12.00, 12.00])  #mm
beckig = np.array([10.00, 9.95, 9.90, 9.95, 10.00])  #mm

u_Lrund = ufloat(np.mean(Lrund), np.std(Lrund))
u_Leckig = ufloat(np.mean(Leckig), np.std(Leckig))
u_drund = ufloat(np.mean(drund), np.std(drund))
u_aeckig = ufloat(np.mean(aeckig), np.std(aeckig))
u_beckig = ufloat(np.mean(beckig), np.std(beckig))

print('u_Lrund', u_Lrund)
print('u_Leckig', u_Leckig)
print('u_drund', u_drund)
print('u_aeckig', u_aeckig)
print('u_beckig', u_beckig)

# –––––––––

# !!! vmtl. falsch ↓
# # Flächenträgheitsmoment:
# I = (u_aeckig*u_beckig**3)/12
# print("––––––")
# print(f"{I=} mm^4")
Пример #32
0
    def read(self, fileobj):
        line = self._read_until_line_startswith(fileobj, 'Simulation time')
        val, = self._read_all_values(line)
        self.simulation_time_s = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj, 'Simulation speed')
        val, = self._read_all_values(line)
        self.simulation_speed_1_per_s = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj,
                                                'Simulated primary showers')
        val, = self._read_all_values(line)
        self.simulated_primary_showers = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj,
                                                'Upbound primary particles')
        val, = self._read_all_values(line)
        self.upbound_primary_particles = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj,
                                                'Downbound primary particles')
        val, = self._read_all_values(line)
        self.downbound_primary_particles = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj,
                                                'Absorbed primary particles')
        val, = self._read_all_values(line)
        self.absorbed_primary_particles = ufloat(val, 0.0)

        line = self._read_until_line_startswith(fileobj, 'Upbound fraction')
        val, unc = self._read_all_values(line)
        self.upbound_fraction = ufloat(val, unc / 3)

        line = self._read_until_line_startswith(fileobj, 'Downbound fraction')
        val, unc = self._read_all_values(line)
        self.downbound_fraction = ufloat(val, unc / 3)

        line = self._read_until_line_startswith(fileobj, 'Absorption fraction')
        val, unc = self._read_all_values(line)
        self.absorbed_fraction = ufloat(val, unc / 3)

        self._read_until_line_startswith(
            fileobj, 'Secondary-particle generation probabilities')
        fileobj.readline()  # skip header
        fileobj.readline()  # skip header

        fileobj.readline()  # skip header
        val_el, val_ph, val_po = self._read_all_values(fileobj.readline())
        unc_el, unc_ph, unc_po = self._read_all_values(fileobj.readline())
        self.upbound_secondary_electron_generation_probabilities = ufloat(
            val_el, unc_el / 3)
        self.upbound_secondary_photon_generation_probabilities = ufloat(
            val_ph, unc_ph / 3)
        self.upbound_secondary_positron_generation_probabilities = ufloat(
            val_po, unc_po / 3)

        fileobj.readline()  # skip header
        val_el, val_ph, val_po = self._read_all_values(fileobj.readline())
        unc_el, unc_ph, unc_po = self._read_all_values(fileobj.readline())
        self.downbound_secondary_electron_generation_probabilities = ufloat(
            val_el, unc_el / 3)
        self.downbound_secondary_photon_generation_probabilities = ufloat(
            val_ph, unc_ph / 3)
        self.downbound_secondary_positron_generation_probabilities = ufloat(
            val_po, unc_po / 3)

        fileobj.readline()  # skip header
        val_el, val_ph, val_po = self._read_all_values(fileobj.readline())
        unc_el, unc_ph, unc_po = self._read_all_values(fileobj.readline())
        self.absorbed_secondary_electron_generation_probabilities = ufloat(
            val_el, unc_el / 3)
        self.absorbed_secondary_photon_generation_probabilities = ufloat(
            val_ph, unc_ph / 3)
        self.absorbed_secondary_positron_generation_probabilities = ufloat(
            val_po, unc_po / 3)

        self.average_deposited_energy_eV.clear()
        self._read_until_line_startswith(
            fileobj, 'Average deposited energies (bodies)')
        line = fileobj.readline().strip()
        while line.startswith('Body'):
            body = int(line[5:9])
            val, unc, _effic = self._read_all_values(line)
            self.average_deposited_energy_eV[body] = ufloat(val, unc / 3)
            line = fileobj.readline().strip()

        self.average_photon_energy_eV.clear()
        self._read_until_line_startswith(
            fileobj, 'Average photon energy at the detectors')
        line = fileobj.readline().strip()
        while line.startswith('Detector'):
            detector = int(line[10:12])
            val, unc, _effic = self._read_all_values(line)
            self.average_photon_energy_eV[detector] = ufloat(val, unc / 3)
            line = fileobj.readline().strip()

        line = self._read_until_line_startswith(fileobj, 'Last random seeds')
        seed1, seed2 = map(int, line.split('=')[1].split(','))
        self.last_random_seed1 = ufloat(seed1, 0.0)
        self.last_random_seed2 = ufloat(seed2, 0.0)

        try:
            self._read_until_line_startswith(fileobj, 'Reference line')
            val, = self._read_all_values(fileobj.readline())
            self.reference_line_uncertainty = ufloat(val, 0.0)
        except IOError:
            self.reference_line_uncertainty = ufloat(0.0, 0.0)
Пример #33
0
    def __init__(self):
        super().__init__()

        self.simulation_time_s = ufloat(0.0, 0.0)
        self.simulation_speed_1_per_s = ufloat(0.0, 0.0)
        self.simulated_primary_showers = ufloat(0.0, 0.0)

        self.upbound_primary_particles = ufloat(0.0, 0.0)
        self.downbound_primary_particles = ufloat(0.0, 0.0)
        self.absorbed_primary_particles = ufloat(0.0, 0.0)

        self.upbound_fraction = ufloat(0.0, 0.0)
        self.downbound_fraction = ufloat(0.0, 0.0)
        self.absorbed_fraction = ufloat(0.0, 0.0)

        self.upbound_secondary_electron_generation_probabilities = ufloat(
            0.0, 0.0)
        self.downbound_secondary_electron_generation_probabilities = ufloat(
            0.0, 0.0)
        self.absorbed_secondary_electron_generation_probabilities = ufloat(
            0.0, 0.0)
        self.upbound_secondary_photon_generation_probabilities = ufloat(
            0.0, 0.0)
        self.downbound_secondary_photon_generation_probabilities = ufloat(
            0.0, 0.0)
        self.absorbed_secondary_photon_generation_probabilities = ufloat(
            0.0, 0.0)
        self.upbound_secondary_positron_generation_probabilities = ufloat(
            0.0, 0.0)
        self.downbound_secondary_positron_generation_probabilities = ufloat(
            0.0, 0.0)
        self.absorbed_secondary_positron_generation_probabilities = ufloat(
            0.0, 0.0)

        self.average_deposited_energy_eV = {}
        self.average_photon_energy_eV = {}

        self.last_random_seed1 = ufloat(0.0, 0.0)
        self.last_random_seed2 = ufloat(0.0, 0.0)

        self.reference_line_uncertainty = ufloat(0.0, 0.0)
Пример #34
0
lpos, spos, B = np.genfromtxt("data/linse1.csv",delimiter=",", unpack = True)

g=lpos-20
b=spos-lpos


V1= B/3
V2= b/g
print("Durch Bildgroesse berechneter Massstab V=", V1)
print("Durch b und g berechneter Massstab V=", V2)
print("b = ", b)
print("g = ", g)

f= 1 / (1/b + 1/g)
print ("Berechnete Brennpunkte:",f)
fmitt = ufloat(np.mean(f),sem(f))
print("Gemittelter Brennpunkt mit Fehler:",fmitt)

x2=np.linspace(0,15,1000)

def f(x,a,c):
    return a * x + c

m= b/(-g)

plt.xlim(0,np.max(g)+2)
plt.ylim(0,np.max(b)+2)
plt.plot(x2, f(x2,m[0],b[0]), 'k--', linewidth=0.5)
plt.plot(x2, f(x2,m[1],b[1]), 'k--', linewidth=0.5)
plt.plot(x2, f(x2,m[2],b[2]), 'k-', linewidth=0.5)
plt.plot(x2, f(x2,m[3],b[3]), 'k-', linewidth=0.5)
Пример #35
0
    def eval_kernel(self,
                    vertex_generator,
                    nevals,
                    nreps=16,
                    ndaq=50,
                    navg=10):
        """
        Return the negative log likelihood that the detector event set in the
        constructor or by set_event() was the result of a particle generated
        by `vertex_generator`.  If `nreps` set to > 1, each set of photon
        vertices will be propagated `nreps` times.
        """
        ntotal = nevals * nreps * ndaq

        mom0 = 0
        mom1 = 0.0
        mom2 = 0.0
        for i in xrange(navg):
            kernel_generator = islice(vertex_generator, nevals)
            hitcount, pdf_prob, pdf_prob_uncert = \
                self.sim.eval_kernel(self.event.channels,
                                     kernel_generator,
                                     self.trange,
                                     self.qrange,
                                     nreps=nreps,
                                     ndaq=ndaq,
                                     time_only=self.time_only)

            # Normalize probabilities and put a floor to keep the log finite
            hit_prob = hitcount.astype(np.float32) / ntotal
            hit_prob[self.event.channels.hit] = np.maximum(
                hit_prob[self.event.channels.hit], 0.5 / ntotal)

            # Set all zero or nan probabilities to limiting PDF value
            bad_value = (pdf_prob <= 0.0) | np.isnan(pdf_prob)
            if self.time_only:
                pdf_floor = 1.0 / (self.trange[1] - self.trange[0])
            else:
                pdf_floor = 1.0 / (self.trange[1] - self.trange[0]) / (
                    self.qrange[1] - self.qrange[0])
            pdf_prob[bad_value] = pdf_floor
            pdf_prob_uncert[bad_value] = pdf_floor

            print 'channels with no data:', (
                bad_value & self.event.channels.hit).astype(int).sum()

            # NLL calculation: note that negation is at the end
            # Start with the probabilties of hitting (or not) the channels
            log_likelihood = np.log(hit_prob[self.event.channels.hit]).sum(
            ) + np.log(1.0 - hit_prob[~self.event.channels.hit]).sum()
            log_likelihood = 0.0  # FIXME: Skipping hit/not-hit probabilities for now

            # Then include the probability densities of the observed
            # charges and times.
            log_likelihood += np.log(pdf_prob[self.event.channels.hit]).sum()
            print 'll', log_likelihood
            if np.isfinite(log_likelihood):
                mom0 += 1
                mom1 += log_likelihood
                mom2 += log_likelihood**2

        avg_like = mom1 / mom0
        rms_like = (mom2 / mom0 - avg_like**2)**0.5
        # Don't forget to return a negative log likelihood
        return ufloat((-avg_like, rms_like / sqrt(mom0)))
Пример #36
0

# Entladung des Kondensators

Uc, t = np.genfromtxt('data/abfallende_flanke.txt',
                      unpack=True)  # Uc in mV, t in ms
U0 = 1090
Uc[0] = 1088
params, covariance_matrix = optimize.curve_fit(linfit, t, np.log(Uc / U0))

errors = np.sqrt(np.diag(covariance_matrix))

print('a =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])

a = ufloat(params[0], errors[0])
b = ufloat(params[1], errors[1])

print('RC =', (-1 / a))

plt.plot(t, np.log(Uc / U0), 'rx', label='Messwerte')
plt.plot(t, linfit(t, *params), 'k-', label='Ausgleichsfunktion')
plt.xlabel(r'$t/$ms')
plt.ylabel(r'$\ln{\left(\frac{U_\mathrm{C}}{U_0}\right)}$')
plt.legend()
plt.grid()
plt.tight_layout()
plt.savefig('build/uc.pdf')

plt.clf()
Пример #37
0
                        comments=['@', '#'])
                calc_stuff=True
            else:
                calc_stuff=False

            if calc_stuff:
                composition_data['{0}-{1}_hbnum_mean'.format(first,second)].append(
                        np.mean(num_file[:,1]))
                composition_data['{0}-{1}_hbnum_std'.format(first,second)].append(
                        np.std(num_file[:,1]))
                composition_data['{0}-{1}_hblife_mean'.format(first,second)].append(
                        10*np.sum(life_file[:,2]))

    # After gathering all raw, sim data, propagate error
    for first, second in all_hbond_pairs:
        ufloats = [ufloat(val,std) for val,std 
            in zip(composition_data['{0}-{1}_hbnum_mean'.format(first, second)], 
                composition_data['{0}-{1}_hbnum_std'.format(first, second)])]
        foo = np.mean(ufloats)
        composition_data['{0}-{1}_hbnum_mean'.format(first, second)] = foo.n
        composition_data['{0}-{1}_hbnum_std'.format(first, second)] = foo.s

        composition_data['{0}-{1}_hblife_std'.format(first, second)] = np.std(
                composition_data['{0}-{1}_hblife_mean'.format(first, second)]) / len(
                    composition_data['{0}-{1}_hblife_mean'.format(first, second)])
        composition_data['{0}-{1}_hblife_mean'.format(first, second)] = np.mean(
                composition_data['{0}-{1}_hblife_mean'.format(first, second)])

    summary_df = summary_df.append(composition_data, ignore_index=True)
os.chdir(curr_dir)
summary_df.to_csv('specific_hbonds.csv')
Пример #38
0
print('---' * 25)
print("We find standard deviations: ")
print("Water - {}".format(std_water))
print("Olive Oil - {}".format(std_oil))
print("---" * 25)

lit_water = 7.28e-2
lit_oil = 3.3e-2
print('---' * 25)
print("Literature Values: ")
print("Water - {} N/m".format(lit_water))
print("Olive Oild - {} N/m".format(lit_oil))
print("---" * 25)
""" Calculating with uncertainties """

du = ufloat(0.0045, 0.0005)

wat_De_avg = np.average(wat_De)
wat_Ds_avg = np.average(wat_Ds)
wat_De_std = np.std(wat_De)
wat_Ds_std = np.std(wat_Ds)

watu_De = ufloat(wat_De_avg, wat_De_std)  #with uncertainties
watu_Ds = ufloat(wat_Ds_avg, wat_Ds_std)

oil_De_avg = np.average(o_De)
oil_Ds_avg = np.average(o_Ds)
oil_De_std = np.std(o_De)
oil_Ds_std = np.std(o_Ds)

oilu_De = ufloat(oil_De_avg, oil_De_std)  #with uncertainties
def simpleFit(tree, cuts, xmean, xmin=4000, xmax=7000):
    """
    This function fits the "Lb_M" variable of a given TTree
    with a model formed by a Gaussian and an exponential pdf.
    All shape parameters are allowed to float in the fit. The 
    initial and range values are hardcoded in the code, except
    for the initial value of the Gaussian mean and the range
    of the Lb_M variable to be used.
    Returns the dataset and the composed model (RooAbsPdf)
    Definition of the arguments:
    :tree: type TTree
    the root TTree that contains the variable to be fitted
    :cuts: type str
    optional cuts to apply to the TTree before fitting
    :mean: type float
    initial value for the Gaussian mean that will be floated
    during the fit
    :xmin: type float, optional
    minimum value of the Lb_M range to be fitted. Default: 4000
    :xmax: type float, optional
    maximum value of the Lb_M range to be fitted. Default: 7000
    """

    # define variables and pdfs
    Lb_M = RooRealVar("Lb_M", "Lb_M", xmin, xmax)

    mean = RooRealVar("mean", "mean", xmean, xmean - 50, xmean + 50)
    sigma = RooRealVar("sigma", "sigma", 20, 10, 50)
    gauss = RooGaussian("gauss", "gauss", Lb_M, mean, sigma)

    tau = RooRealVar("tau", "tau", -0.005, -0.01, 0.)
    exp = RooExponential("exp", "exp", Lb_M, tau)

    # define coefficiencts
    nsig = RooRealVar("nsig", "nsig", 100, 0, 2000)
    nbkg = RooRealVar("nbkg", "nbkg", 100, 0, 2000)

    # build model
    suma = RooArgList()
    coeff = RooArgList()

    suma.add(gauss)
    suma.add(exp)

    coeff.add(nsig)
    coeff.add(nbkg)

    model = ROOT.RooAddPdf("model", "model", suma, coeff)

    # define dataset
    if (cuts != ""): tree = tree.CopyTree(cuts)
    ds = RooDataSet("data", "dataset with x", tree, RooArgSet(Lb_M))

    #  fit and save results
    fitResults = model.fitTo(ds, RooFit.Save(True))

    # plot dataset and fit results
    c = ROOT.TCanvas()
    massFrame = Lb_M.frame()
    ds.plotOn(massFrame, RooFit.Name("histo_data"))

    model.plotOn(massFrame)
    model.plotOn(massFrame, RooFit.Components("gauss"), RooFit.LineColor(2))
    model.plotOn(massFrame, RooFit.Components("exp"), RooFit.LineColor(3))
    model.paramOn(massFrame, RooFit.Layout(.55, .95, .93))
    massFrame.Draw()
    c.SaveAs("fit.png")

    # print results
    print("{} has been fit to {}".format(model.GetName(), tree.GetName()))
    print("Total number of entries is: {}".format(ds.numEntries()))
    print("Number of sig entries is: {:.0f} +- {:.0f}".format(
        nsig.getValV(), nsig.getError()))
    print("Number of bkg entries is: {:.0f} +- {:.0f}".format(
        nbkg.getValV(), nbkg.getError()))

    # compute S/B with error propagation from uncertainties module
    nsigu = ufloat(nsig.getValV(), nsig.getError())
    nbkgu = ufloat(nbkg.getValV(), nbkg.getError())
    signif = nsigu / nbkgu
    print("S/B = {:.2f} +- {:.2f}".format(signif.nominal_value,
                                          signif.std_dev))

    return ds, model, c
Пример #40
0
import uncertainties
from uncertainties import ufloat
import numpy as np

A = ufloat(33.717, 0.9866)  #mm⁻¹·s⁻¹
#A = ufloat (34, 0.9866) #mm⁻¹·s⁻¹

rho_1 = 7.82  #g·cm⁻³
rho_2 = 1.2  #g·cm⁻³
g = 9.8  #m·s⁻²

#A = 2/9·(rho_1 - rho_2)·g / eta
eta = 2 * (rho_1 - rho_2) * g / (9 * A)  #Pa·s
eta = 1000 * eta  #mPa·s

print('eta =', eta, 'mPa·s')
Пример #41
0
def candid_grid(
    input_data: Union[str, List[str]],
    step: int = 10,
    rmin: float = 20,
    rmax: float = 400,
    diam: float = 0,
    obs: Optional[List[str]] = None,
    extra_error_cp: float = 0,
    err_scale: float = 1,
    extra_error_v2: float = 0,
    instruments=None,
    doNotFit=None,
    ncore: int = 1,
    save: bool = False,
    outputfile: Optional[str] = None,
    verbose: bool = False,
):
    """This function is an user friendly interface between the users of amical
    pipeline and the CANDID analysis package (https://github.com/amerand/CANDID).

    Parameters:
    -----------
    `input_data`:
        oifits file names or list of oifits files,\n
    `step`:
        step used to compute the binary grid positions,\n
    `rmin`, `rmax`:
        Bounds of the grid [mas],\n
    `diam`:
        Stellar diameter of the primary star [mas] (default=0),\n
    `obs`:
        List of observables to be fitted (default: ['cp', 'v2']),\n
    `doNotFit`:
        Parameters not fitted (default: ['diam*']),\n
    `verbose`:
        print some informations {default: False}.

    Outputs:
    --------
    `res` {dict}:
        Dictionnary of the results ('best'), uncertainties ('uncer'),
        reduced chi2 ('chi2') and sigma detection ('nsigma').
    """
    if obs is None:
        obs = ["cp", "v2"]
    if doNotFit is None:
        doNotFit = ["diam*"]

    cprint(" | --- Start CANDID fitting --- :", "green")
    o = candid.Open(
        input_data,
        extra_error=extra_error_cp,
        err_scale=err_scale,
        extra_error_v2=extra_error_v2,
        instruments=instruments,
    )

    o.observables = obs

    o.fitMap(
        rmax=rmax,
        rmin=rmin,
        ncore=ncore,
        fig=0,
        step=step,
        addParam={"diam*": diam},
        doNotFit=doNotFit,
        verbose=verbose,
    )

    if save:
        if isinstance(input_data, list):
            first_input = input_data[0]
        else:
            first_input = input_data
        filename = os.path.basename(first_input) + "_detection_map_candid.pdf"
        if outputfile is not None:
            filename = outputfile
        plt.savefig(filename, dpi=300)

    fit = o.bestFit["best"]
    e_fit = o.bestFit["uncer"]
    chi2 = o.bestFit["chi2"]
    nsigma = o.bestFit["nsigma"]

    f = fit["f"] / 100.0
    e_f = e_fit["f"] / 100.0
    if (e_f < 0) or (e_fit["x"] < 0) or (e_fit["y"] < 0):
        print("Warning: error dm is negative.")
        e_f = abs(e_f)
        e_fit["x"] = 0
        e_fit["y"] = 0

    f_u = ufloat(f, e_f)
    x, y = fit["x"], fit["y"]
    x_u = ufloat(x, e_fit["x"])
    y_u = ufloat(y, e_fit["y"])

    dm = -2.5 * umath.log10(f_u)
    s = (x_u ** 2 + y_u ** 2) ** 0.5
    posang = umath.atan2(x_u, y_u) * 180 / np.pi
    if posang.nominal_value < 0:
        posang = 360 + posang

    cr = 1 / f_u
    cprint(f"\nResults binary fit (χ2 = {chi2:2.1f}, nσ = {nsigma:2.1f}):", "cyan")
    cprint("-------------------", "cyan")

    print(f"Sep = {s.nominal_value:2.1f} +/- {s.std_dev:2.1f} mas")
    print(f"Theta = {posang.nominal_value:2.1f} +/- {posang.std_dev:2.1f} deg")
    print(f"CR = {cr.nominal_value:2.1f} +/- {cr.std_dev:2.1f}")
    print(f"dm = {dm.nominal_value:2.2f} +/- {dm.std_dev:2.2f}")
    res = {
        "best": {
            "model": "binary_res",
            "dm": dm.nominal_value,
            "theta": posang.nominal_value,
            "sep": s.nominal_value,
            "diam": fit["diam*"],
            "x0": 0,
            "y0": 0,
        },
        "uncer": {"dm": dm.std_dev, "theta": posang.std_dev, "sep": s.std_dev},
        "chi2": chi2,
        "nsigma": nsigma,
        "comp": o.bestFit["best"],
    }

    return res
Пример #42
0
def U2(g, B, Mf, EHy):
    return g**2 * µB**2 * B**2 * (1 - Mf) / EHy


def exp(x, a, b, c):
    return a * np.exp(b * x) + c


def hyp(x, a, b, c):
    return a + b / (x - c)


# Naturkonstanten
µ = const.mu_0
me = ufloat(const.physical_constants['electron mass'][0],
            const.physical_constants['electron mass'][2])
e0 = ufloat(const.physical_constants['elementary charge'][0],
            const.physical_constants['elementary charge'][2])
µB = ufloat(const.physical_constants['Bohr magneton'][0],
            const.physical_constants['Bohr magneton'][2])

# Messwerte
f = np.array([100, 200, 300, 400, 500, 600, 700, 800, 900, 1000])
Us = np.array([
    [4.75, 3.20, 5.50, 2.65, 2.64, 2.05, 0.87, 3.24, 1.22, 2.44],  #1.Dip
    [5.95, 5.60, 9.00, 7.40, 8.55, 9.05, 9.12, 7.16, 6.33, 7.61]
])  #2.Dip
Uh = np.array([
    [0.00, 0.10, 0.10, 0.22, 0.27, 0.34, 0.42, 0.42, 0.53, 0.55],  #1.Dip
    [0.00, 0.10, 0.10, 0.22, 0.27, 0.34, 0.42, 0.55, 0.65, 0.70]
])  #2.Dip
Пример #43
0
DATA_PATH = '../results/'

for version in ['sequential', 'block', 'cyclic']:
    print("Working on", version)

    times = []
    fname = '{}_benchmark.out'.format(version)
    with open(DATA_PATH + fname, 'r') as fstream:
        lines = fstream.readlines()
    for line in lines:
        if line.startswith('Time elapsed'):
            times.append(float(line[14:23]))
    times = np.asarray(times)/10000000
    if version == 'sequential':
        tau_s = ufloat(np.mean(times), np.std(times, ddof=1))
        tau = tau_s
    elif version == 'block':
        tau_b = ufloat(np.mean(times), np.std(times, ddof=1))
        tau = tau_b
    elif version == 'cyclic':
        tau_c = ufloat(np.mean(times), np.std(times, ddof=1))
        tau = tau_c
    print('Tau for {} is: {}'.format(version, tau))

print('Worst case for sequential:',
      tau_s*pow(2, 32), 's =', tau_s*pow(2, 32)/3600)

km = pow(2, 32)

k1 = 13 * km//14
Пример #44
0
def mittel(x):
    return ufloat(np.mean(x),np.std(x,ddof=1)/np.sqrt(len(x)))
Пример #45
0
import numpy as np
import uncertainties.unumpy as unp
from uncertainties import ufloat
from scipy.stats import sem
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.constants as const

num = np.arange(1, 11)
b1 = ufloat(9.5, 0.8)
b2 = ufloat(0.177, 0.09)
v3z = ufloat(0.005, 0.001)
v3o = ufloat(0.015, 0.002)
s1 = ufloat(0.087, 0.011)
s2 = ufloat(0.8, 0.1)
v4 = ufloat(0.025, 0.005)
b4 = ufloat(0.067, 0.004)
v1o = ufloat(0.044, 0.004)
v1z = ufloat(0.022, 0.002)

#b5 Volumen berechnen
di = ufloat(10, 0.5)
l1 = ufloat(80, 0.5)
l2 = ufloat(30, 1)

b5 = np.pi * ((di / 2)**2) * l1 + 2 * np.pi * ((di / 2)**2) * l2
b5 = b5 * 1e-6
print("Vol B5 in l:", b5)
b5a = ufloat(0.016, 0.002)
print("B5 aus Anleitung:", b5a)
#b3 Volumen berechnen
Пример #46
0
#erstelle eine .txt Datei, aus der die Werte fuer die Funktion genommen werden koennen. Das, was in der ersten Spalte steht, sind automaisch die x-Werte,
#die zweite die y-Werte.

x, y = np.genfromtxt('werte1.txt', unpack=True)


#linregress vorbereitung(Fkt definieren m=Steigung, n=y-Schnittpkt)
def f(x, m, n):
    return x * m + n


paramsI, covarianceI = curve_fit(
    f, x, y
)  #das muss hier einfach alles hin...kann nicht genau sagen, was es macht.
errorsI = np.sqrt(np.diag(covarianceI))
n = ufloat(paramsI[1], errorsI[1])
m = ufloat(paramsI[0], errorsI[0])
print(
    m, n
)  #Dieser Befehl gibt euch in der Kommandozeile als ersten Wert fuer m mit Fehler und den zweiten Wert
#fuer n wieder mit Fehler.

#with plt.xkcd(): (macht, dass die ganze Sache in comic sans ms optik ausgegeben wird. Sieht sehr fein aus, ist aber vielleicht nicht sooo wichtig)
#Plot der Messwerte:

L1plot = np.linspace(
    0,
    0.35)  #Grenzen fuer linregr. guckt nach den Grenzwerten fuer die x-Werte.
plt.title('Rechteckiger Stab, einseitige Einspannung'
          )  #Ueberschrift, die ueber dem PLot stehen wird
plt.plot(
Пример #47
0
def Restframe(string, name):
    dirName = f'{name}'
    dirName = dirName.split('/')[0]

    if not os.path.exists(dirName):
        os.mkdir(dirName)
        print("Directory ", dirName, " Created ")
    else:
        print("Directory ", dirName, " already exists")

    #Creating a line dict from NIST
    line_dict = {
        'CIV_1548': [1548.202, 0.01, r'C \Rn{4} $\lambda$ 1548'],
        'SiIV_1402': [1402.77, 0.1, r'Si \Rn{4} $\lambda$ 1403'],
        'Ly_a': [1215.6701, 0.0021, r'Ly-$\alpha$ $\lambda$ 1216'],
        'CIII_1897': [1897.57, 0.1, r'C \Rn{3} $\lambda$ 1898'],
        'MgII_2796': [2795.528, 0.01, r'Mg \Rn{2} $\lambda$ 2796'],
        'MgII_2803': [2802.705, 0.01, r'Mg \Rn{2} $\lambda$ 2803'],
        'OIII_5007': [5006.843, 0.01, r'O \Rn{3} $\lambda$ 5007'],
        'H_b': [4861.283363, 0.000024, r'H-$\beta$ $\lambda$ 4861'],
        'H_a': [6562.85117, 0.00003, r'H-$\alpha$ $\lambda$ 6563'],
        'SiII_989': [989.87, 0.1, r'Si \Rn{2} $\lambda$ 989'],
        'BeIII_4487': [4487.30, 0.10, r'Be \Rn{3} $\lambda$ 4487'],
        'AlII_1670': [1670.7874, 0.001, r'Al \Rn{2} $\lambda$ 1670'],
        'NV_1239': [1238.8210, 0.01, r'N \Rn{5} $\lambda$ 1239'],
        'CuII_10852': [10852.401, 0.004, r'Cu \Rn{2} $\lambda$ 10852'],
        'CuII_5007': [5006.79978, 0.00015, r'Cu \Rn{2} $\lambda$ 5007'],
        'TiIII_4971': [4971.194, 0.010, r'Ti \Rn{3} $\lambda$ 4971'],
        'ZnII_2026': [2025.4845, 0.001, r'Zn \Rn{2} $\lambda$ 2026'],
        'ZnII_2062': [2062.0011, 0.0010, r'Zn \Rn{2} $\lambda$ 2062'],
        'ZnII_2064': [2064.2266, 0.0010, r'Zn \Rn{2} $\lambda$ 2064'],
        'SiII_1808': [1808.00, 0.10, r'Si \Rn{2} $\lambda$ 1808'],
        'FeII_1611': [1610.9229, 0.0005, r'Fe \Rn{2} $\lambda$ 1611'],
        'FeII_2249': [2249.05864, 0.00011, r'Fe \Rn{2} $\lambda$ 2249'],
        'FeII_2260': [2260.5173, 0.0019, r'Fe \Rn{2} $\lambda$ 2260'],
        'SiII_1526': [1526.734, 0.10, r'Si \Rn{2} $\lambda$ 1526'],
        'FeI_3021': [3021.0725, 0.0003, r'Fe \Rn{2} $\lambda$ 3021'],
        'FeII_2344': [2344.9842, 0.0001, r'Fe \Rn{2} $\lambda$ 2344'],
        'FeII_2374': [2374.6530, 0.0001, r'Fe \Rn{2} $\lambda$ 2374'],
        'FeII_2382': [2382.0373, 0.0001, r'Fe \Rn{2} $\lambda$ 2382'],
        'FeII_2586': [2585.8756, 0.0001, r'Fe \Rn{2} $\lambda$ 2586'],
        'CrII_2026': [2025.6186, 0.0001, r'Cr \Rn{2} $\lambda$ 2026'],
        'CrII_2062': [2061.57673, 0.00007, r'Cr \Rn{2} $\lambda$ 2062'],
        'CrII_2056': [2055.59869, 0.00006, r'Cr \Rn{2} $\lambda$ 2056'],
        'CrII_2066': [2065.50389, 0.00007, r'Cr \Rn{2} $\lambda$ 2066'],
        'MnII_1162': [1162.0150, 0.0001, r'Mn \Rn{2} $\lambda$ 1162'],
        'MnII_1197': [1197.1840, 0.0001, r'Mn \Rn{2} $\lambda$ 1197'],
        'MnII_1199': [1199.3910, 0.0001, r'Mn \Rn{2} $\lambda$ 1199'],
        'MnII_1201': [1201.1180, 0.0001, r'Mn \Rn{2} $\lambda$ 1201'],
        'MnII_2576': [2576.8770, 0.0001, r'Mn \Rn{2} $\lambda$ 2576'],
        'MnII_2594': [2594.4990, 0.0001, r'Mn \Rn{2} $\lambda$ 2594'],
        'MnII_2606': [2606.4630, 0.0001, r'Mn \Rn{2} $\lambda$ 2606'],
        'NiII_1317': [1317.2170, 0.0001, r'Ni \Rn{2} $\lambda$ 1317'],
        'NiII_1345': [1345.8780, 0.0001, r'Ni \Rn{2} $\lambda$ 1345'],
        'NiII_1370': [1370.1320, 0.0001, r'Ni \Rn{2} $\lambda$ 1370'],
        'NiII_1393': [1393.3240, 0.0001, r'Ni \Rn{2} $\lambda$ 1393'],
        'NiII_1454': [1454.8420, 0.0001, r'Ni \Rn{2} $\lambda$ 1454'],
        'NiII_1502': [1502.1480, 0.0001, r'Ni \Rn{2} $\lambda$ 1502'],
        'NiII_1703': [1703.4050, 0.0001, r'Ni \Rn{2} $\lambda$ 1703'],
        'NiII_1709': [1709.6000, 0.0001, r'Ni \Rn{2} $\lambda$ 1709'],
        'NiII_1741': [1741.5490, 0.0001, r'Ni \Rn{2} $\lambda$ 1741'],
        'NiII_1751': [1751.9100, 0.0001, r'Ni \Rn{2} $\lambda$ 1751'],
        'NiII_1773': [1773.9490, 0.0001, r'Ni \Rn{2} $\lambda$ 1773'],
        'NiII_1804': [1804.4730, 0.0001, r'Ni \Rn{2} $\lambda$ 1804'],
        'CrII_1058': [1058.7320, 0.0001, r'Cr \Rn{2} $\lambda$ 1058'],
        'CrII_1059': [1059.7320, 0.0001, r'Cr \Rn{2} $\lambda$ 1059'],
        'CrII_1064': [1064.1240, 0.0001, r'Cr \Rn{2} $\lambda$ 1064'],
        'CrII_1066': [1066.7760, 0.0001, r'Cr \Rn{2} $\lambda$ 1066'],
        'SiII_1020': [1020.6989, 0.1, r'Si \Rn{2} $\lambda$ 1020'],
        'SiIV_1062': [1062.66, 0.1, r'Si \Rn{4} $\lambda$ 1062'],
        'SiII_1190': [1190.4158, 0.1, r'Si \Rn{2} $\lambda$ 1190'],
        'SiII_1193': [1193.2897, 0.1, r'Si \Rn{2} $\lambda$ 1193'],
        'SiIII_1206': [1206.5000, 0.1, r'Si \Rn{3} $\lambda$ 1206'],
        'SiII_1260': [1260.4221, 0.1, r'Si \Rn{2} $\lambda$ 1260'],
        'SiII_1304': [1304.3702, 0.1, r'Si \Rn{2} $\lambda$ 1304'],
        'SiI_1554': [1554.2960, 0.1, r'Si \Rn{1} $\lambda$ 1554'],
        'SiI_1562': [1562.0020, 0.1, r'Si \Rn{1} $\lambda$ 1562'],
        'SiI_1625': [1625.7051, 0.1, r'Si \Rn{1} $\lambda$ 1625'],
        'SiI_1631': [1631.1705, 0.1, r'Si \Rn{1} $\lambda$ 1631'],
        'SiIV_1693': [1693.2935, 0.1, r'Si \Rn{4} $\lambda$ 1693'],
        'SiI_2515': [2515.0725, 0.1, r'Si \Rn{1} $\lambda$ 2515'],
        'SiI_2208': [2208.6665, 0.1, r'Si \Rn{1} $\lambda$ 2208'],
        'SiIII_1892': [1892.0300, 0.1, r'Si \Rn{3} $\lambda$ 1892'],
        'SiI_1845': [1845.5202, 0.1, r'Si \Rn{1} $\lambda$ 1845'],
        'FeII_935': [935.5175, 0.001, r'Fe \Rn{2} $\lambda$ 935'],
        'FeII_937': [937.6520, 0.001, r'Fe \Rn{2} $\lambda$ 937'],
        'FeII_1055': [1055.2617, 0.001, r'Fe \Rn{2} $\lambda$ 1055'],
        'FeII_1062': [1062.1520, 0.001, r'Fe \Rn{2} $\lambda$ 1062'],
        'FeII_1081': [1081.8750, 0.001, r'Fe \Rn{2} $\lambda$ 1081'],
        'FeII_1083': [1083.4200, 0.001, r'Fe \Rn{2} $\lambda$ 1083'],
        'FeII_1096': [1096.8769, 0.001, r'Fe \Rn{2} $\lambda$ 1096'],
        'FeIII_1122': [1122.5360, 0.001, r'Fe \Rn{3} $\lambda$ 1122'],
        'FeII_1144': [1144.9379, 0.001, r'Fe \Rn{2} $\lambda$ 1144'],
        'FeII_1260': [1260.5330, 0.001, r'Fe \Rn{2} $\lambda$ 1260'],
        'FeII_1608': [1608.4511, 0.001, r'Fe \Rn{2} $\lambda$ 1608'],
        'FeII_1611': [1611.2005, 0.001, r'Fe \Rn{2} $\lambda$ 1611'],
        'FeI_1934': [1934.5351, 0.001, r'Fe \Rn{1} $\lambda$ 1934'],
        'FeI_1937': [1937.2682, 0.001, r'Fe \Rn{1} $\lambda$ 1937'],
        'FeI_2167': [2167.4531, 0.001, r'Fe \Rn{1} $\lambda$ 2167'],
        'FeII_2344': [2344.2140, 0.001, r'Fe \Rn{2} $\lambda$ 2344'],
        'FeII_2382': [2382.7650, 0.001, r'Fe \Rn{2} $\lambda$ 2382'],
        'FeII_2484': [2484.0211, 0.001, r'Fe \Rn{2} $\lambda$ 2484'],
        'FeI_2523': [2523.6083, 0.001, r'Fe \Rn{1} $\lambda$ 2523'],
        'FeII_2600': [2600, 0.001, r'Fe \Rn{2} $\lambda$ 2600'],
        'FeI_2719': [2719.8331, 0.001, r'Fe \Rn{1} $\lambda$ 2719'],
        'FeI_3021': [3021.5189, 0.001, r'Fe \Rn{1} $\lambda$ 3021'],
        'AlIII_1854': [1854.7164, 0.1, r'Al \Rn{3} $\lambda$ 1854'],
        'AlIII_1862': [1862.7895, 0.1, r'Al \Rn{3} $\lambda$ 1862'],
        'MgI_2852': [2852.1370, 0.1, r'Mg \Rn{1} $\lambda$ 2852'],
        'MgI_2026': [2026.4768, 0.1, r'Mg \Rn{1} $\lambda$ 2026'],
        'PII_1152': [1152.8180, 0.001, r'P \Rn{2} $\lambda$ 1152'],
        'CuII_1358': [1358.7730, 0.001, r'Cu \Rn{2} $\lambda$ 1358']
    }
    time_signature = datetime.now().strftime("%m%d-%H%M")
    name = name.replace('.txt', '')
    output_name = f'Final_table_{time_signature}_{dirName}.txt'

    numify = lambda x: float(''.join(
        char for char in x if char.isdigit() or char == "." or char == "-"))

    tex_table = string

    tex_document = r"""
\begin{table}[H] 
\begin{tabular}{cccccccc}
Transition & EW$_r$ [Å] & Redshift\\
\hline
"""

    approx_z = float(input('What is the approximate redshift?'))

    lines = tex_table.split(r"\\")[0:-1]

    data = []

    text = []

    # Interactive way of categorising the lines
    for line in lines:
        [_, wave, eq, _] = line.strip().split("&")
        [wave, wave_err] = wave.split(r"\pm")
        [eq, eq_err] = eq.split(r"\pm")

        line_exp = unc.ufloat(numify(wave), numify(wave_err)) / (1 + approx_z)
        ordered_dict = collections.OrderedDict(
            sorted(line_dict.items(), key=lambda v: v[1]))
        line_true = input(
            f'\n What is this line {line_exp}? Please choose from: \n {ordered_dict.keys()}: '
        )

        data.append([
            unc.ufloat(numify(wave), numify(wave_err)),
            unc.ufloat(numify(eq), numify(eq_err)),
            unc.ufloat(line_dict[f'{line_true}'][0],
                       line_dict[f'{line_true}'][1])
        ])

        text.append(line_dict[f'{line_true}'][2])

    data = unumpy.matrix(data)

    z = (data[:, 0] / data[:, 2] - 1)

    # The errors and their contribution to the weighted redshift avarage
    z_avg = np.mean(z)
    var = sum(pow(i - z_avg, 2) for i in z) / len(z)
    var = var[0, 0]
    z_avg_std = math.sqrt(var.nominal_value)

    ew_r = (data[:, 1] / (z_avg + 1))

    # Creating a LaTeX table for the results

    tex_begin = "\\noindent The weighted avarage of the redshift is $z = {:.1uL}$".format(
        z_avg)

    for i in range(len(z)):
        eq_value = ew_r[i, 0]

        z_value = z[i, 0]

        tex_document += " {0} & ${1:.1uL}$ & ${2:.1uL}$ \\\\".format(
            text[i], eq_value, z_value)

    tex_footer = r"""
\hline
\end{tabular}
\end{table}
"""
    output_name = dirName + "/" + output_name
    with open(output_name, "w+") as outfile:
        outfile.write(tex_begin + tex_document + tex_footer)

    # When the file is saved, it is also printed and inserted in the clip board
    print(tex_begin + tex_document + tex_footer)
    copy(tex_begin + tex_document + tex_footer)
import numpy as np
import uncertainties.unumpy as unp
from uncertainties import ufloat
from scipy.stats import sem

print('====================')
print('Widerstand ANFANG')
print('====================')
print('Wert 12 ANFANG')
ra2 = ufloat(1000, 1000 * 0.002)
pot1a = 2.82
pot1b = 10 - pot1a
pot1c = pot1a / pot1b
pota = ufloat(pot1c, pot1c * 0.005)
ra1 = ra2 * pota
print('ra1', ra1)

rb2 = ufloat(664, 664 * 0.002)
pot2a = 3.73
pot2b = 10 - pot2a
pot2c = pot2a / pot2b
potb = ufloat(pot2c, pot2c * 0.005)
rb1 = rb2 * potb
print('rb1', rb1)

rc2 = ufloat(332, 332 * 0.002)
pot3a = 5.42
pot3b = 10 - pot3a
pot3c = pot3a / pot3b
potc = ufloat(pot3c, pot3c * 0.005)
rc1 = rc2 * potc
Пример #49
0
    def __init__(self, identifier, force_download=False, configFile=None,
            query_dace=True, query_tepcat=True, T0=None, P=None, ecosw=None,
            esinw=None, depth=None, width=None, K=None, verbose=True):

        self.identifier = identifier
        self.T0 = T0
        self.P = P
        self.ecosw = ecosw
        self.esinw = esinw
        self.depth = depth
        self.width = width
        self.K = K
        
        config = load_config(configFile)
        _cache_path = config['DEFAULT']['data_cache_path']
        
        if query_dace: 
            f = {"obj_id_planet_catname":{"contains":[identifier]}}
            planet_data = Cheops.query_catalog('planet', filters=f)
            target = planet_data['obj_id_planet_catname']
            if len(target) == 1:
                if verbose: 
                    print('Target ',target[0],' found in DACE-Planets.')
                T0_val = planet_data['obj_trans_t0_bjd'][0]
                T0_err = planet_data['obj_trans_t0_bjd_err'][0]
                P_val = planet_data['obj_trans_period_days'][0]
                P_err = planet_data['obj_trans_period_days_err'][0]
                ecosw_val = planet_data['obj_trans_ecosw'][0]
                ecosw_err = planet_data['obj_trans_ecosw_err'][0]
                esinw_val = planet_data['obj_trans_esinw'][0]
                esinw_err = planet_data['obj_trans_esinw_err'][0]
                depth_val = planet_data['obj_trans_depth_ppm'][0]
                depth_err = planet_data['obj_trans_depth_ppm_err'][0]
                width_val = planet_data['obj_trans_duration_days'][0]
                width_err = planet_data['obj_trans_duration_days_err'][0]
                # 'obj_rv_k_mps' is in km/s so need to convert to m/s
                # Note use of np.float to avoid problems with 'NaN' values
                K_val = np.float(planet_data['obj_rv_k_mps'][0])*1000
                K_err = np.float(planet_data['obj_rv_k_mps_err'][0])*1000
                
                # Still need to get errors on these parameters and replace
                # np.nan with None
                
                try:
                    self.T0 = ufloat(float(T0_val),float(T0_err))
                    self.T0_note = "DACE-Planets"
                except:
                    self.T0 = None
                try:
                    self.P = ufloat(float(P_val),float(P_err))
                    self.P_note = "DACE-Planets"
                except:
                    self.P = None
                try:
                    self.ecosw=ufloat(float(ecosw_val),float(ecosw_err))
                    self.ecosw_note = "DACE-Planets"
                except:
                    self.ecosw = None
                try:
                    self.esinw=ufloat(float(esinw_val),float(esinw_err))
                    self.esinw_note = "DACE-Planets"
                except:
                    self.esinw = None
                try:
                    self.depth=ufloat(float(depth_val),float(depth_err))
                    self.depth_note = "DACE-Planets"
                except:
                    self.depth = None
                try:
                    self.width=ufloat(float(width_val),float(width_err))
                    self.width_note = "DACE-Planets"
                except:
                    self.width = None
                try:
                    self.K=ufloat(float(K_val),float(K_err))
                    self.K_note = "DACE-Planets"
                except:
                    self.K = None

                # Tidy up any missing values stored as NaNs in DACE
        
                if np.isnan(self.depth.n): 
                    self.depth = None
                if np.isnan(self.width.n): 
                    self.width = None
                if np.isnan(self.ecosw.n): 
                    self.ecosw = None
                if np.isnan(self.esinw.n): 
                    self.esinw = None
                if np.isnan(self.K.n): 
                    self.K = None
    
            elif len(target) < 1:
                print('No matching planet in DACE-Planets.')
                if verbose:
                    print('List of valid planet_id keys:')
                    l = Cheops.query_catalog('planet')['obj_id_planet_catname']
                    print(l)
            else:
                print(r'Target ',identifier,'not defined uniquely: ',target)
            
        if query_tepcat:    
            TEPCatObsPath = Path(_cache_path,'observables.csv')
            download_tepcat = False
            if force_download:
                download_tepcat = True
            elif TEPCatObsPath.is_file():
                file_age = mktime(localtime())-os.path.getmtime(TEPCatObsPath)
                if file_age > int(config['TEPCatObs']['update_interval']):
                    download_tepcat = True
                else:
                    download_tepcat = False
            else:
                download_tepcat = True
            if download_tepcat:
                try:
                    url = config['TEPCatObs']['download_url']
                except:
                    raise KeyError("TEPCatObs table not found in config file."
                            " Run core.setup_config")
                try:
                    req=requests.post(url)
                except:
                    warnings.warn("Failed to update TEPCatObs from server")
                else:
                    with open(TEPCatObsPath, 'wb') as file:
                        file.write(req.content)
                    if verbose:
                        print('TEPCat data downloaded from \n {}'.format(url))
            # Awkward table to deal with because of repeated column names
            T = Table.read(TEPCatObsPath,format='ascii.no_header')
            hdr = list(T[0])
            targets=np.array(T[T.colnames[hdr.index('System')]][1:],
                    dtype=np.str_)
            RAh=np.array(T[T.colnames[hdr.index('RAh')]][1:],
                    dtype=np.str_)
            RAm=np.array(T[T.colnames[hdr.index('RAm')]][1:],
                    dtype=np.str_)
            RAs=np.array(T[T.colnames[hdr.index('RAs')]][1:],
                    dtype=np.str_)
            Decd=np.array(T[T.colnames[hdr.index('Decd')]][1:],
                    dtype=np.str_)
            Decm=np.array(T[T.colnames[hdr.index('Decm')]][1:],
                    dtype=np.str_)
            Decs=np.array(T[T.colnames[hdr.index('Decs')]][1:],
                    dtype=np.str_)
            T0_vals=np.array(T[T.colnames[hdr.index('T0(HJDorBJD)')]][1:],
                    dtype=np.float)
            T0_errs=np.array(T[T.colnames[hdr.index('T0err')]][1:],
                    dtype=np.float)
            periods=np.array(T[T.colnames[hdr.index('Period(day)')]][1:],
                    dtype=np.float)
            perrors=np.array(T[T.colnames[hdr.index('Perioderr')]][1:],
                    dtype=np.float)
            lengths=np.array(T[T.colnames[hdr.index('length')]][1:],
                    dtype=np.float)
            depths =np.array(T[T.colnames[hdr.index('depth')]][1:],
                    dtype=np.float)

            ok = [t.startswith(identifier.replace(' ','_')) for t in targets]
            if sum(ok) > 1:
                print('Matching planet names: ', *targets[ok])
                raise ValueError('More than one planet matches identifier.')
            elif sum(ok) == 1:
                T0_val=T0_vals[ok][0]
                T0_err=T0_errs[ok][0]
                period=periods[ok][0]
                perror=perrors[ok][0]
                length=lengths[ok][0]
                depth_val=depths[ok][0]*10000
            else:
                try:
                    tar_coords = SkyCoord.from_name(identifier) 
                    all_coords = []
                    for index, i in enumerate(RAh):
                        all_coords.append(
                                RAh[index]+":"+RAm[index]+":"+RAs[index]+" "+
                                Decd[index]+":"+Decm[index]+":"+Decs[index])
                    TEPCat_coords = SkyCoord(all_coords, frame="icrs", 
                            unit=(u.hourangle, u.deg))
                    ok = tar_coords.separation(TEPCat_coords) < 5*u.arcsec
                    if sum(ok) > 1:
                        print('Matching planets: ', *targets[ok])
                        raise ValueError(
                                'More than one planet matches coordinates.')
                    elif sum(ok)==1:
                        T0_val=T0_vals[ok][0]
                        T0_err=T0_errs[ok][0]
                        period=periods[ok][0]
                        perror=perrors[ok][0]
                        length=lengths[ok][0]
                        depth_val=depths[ok][0]*10000
            
                    else:
                        print('No matching planet in TEPCat.')   
                except: 
                    print('No coordinate match for planet in TEPCat.')
                
            if sum(ok)==1:        
                if self.T0 == None: 
                    try:
                        self.T0 = ufloat(float(T0_val),float(T0_err))
                        self.T0_note = "TEPCat"
                    except:
                        self.T0 = None
                if self.P == None:
                    try:
                        self.P = ufloat(float(period),float(perror))
                        self.P_note = "TEPCat"
                    except:
                        self.P = None
                if self.depth == None:
                    try:
                        self.depth=ufloat(float(depth_val),1e2)
                        self.depth_note = "TEPCat"
                    except:
                        self.depth = None
                if self.width == None:
                    try:
                        self.width=ufloat(float(length),0.01)
                        self.width_note = "TEPCat"
                    except:
                        self.width = None
                    
        # User defined values
        if T0:
            if  isinstance(T0, UFloat):
                self.T0 = T0
                self.T0_note = "User"
            else:
                raise ValueError("T0 keyword is not ufloat")
        if P:
            if  isinstance(P, UFloat):
                self.P = P
                self.P_note = "User"
            else:
                raise ValueError("P keyword is not ufloat")
        if ecosw:
            if  isinstance(ecosw, UFloat):
                self.ecosw = ecosw
                self.ecosw_note = "User"
            else:
                raise ValueError("ecosw keyword is not ufloat")
        if esinw:
            if  isinstance(esinw, UFloat):
                self.esinw = esinw
                self.esinw_note = "User"
            else:
                raise ValueError("esinw keyword is not ufloat")
        if depth:
            if  isinstance(depth, UFloat):
                self.depth = depth
                self.depth_note = "User"
            else:
                raise ValueError("depth keyword is not ufloat")
        if width:
            if  isinstance(width, UFloat):
                self.width = width
                self.width_note = "User"
            else:
                raise ValueError("width keyword is not ufloat")
        if K:
            if  isinstance(K, UFloat):
                self.K = K
                self.K_note = "User"
            else:
                raise ValueError("K keyword is not ufloat")
            
            
        # Eccentricity and omega from ecosw and esinw
        
        self.ecc = None
        self.omega = None
        self.f_s = None
        self.f_c = None
        if self.ecosw and self.esinw:
            ecosw = self.ecosw
            esinw = self.esinw
            ecc = usqrt(ecosw*ecosw+esinw*esinw)
            if ecc.n != 0:
                omega = uatan2(esinw,ecosw)
                f_s = usqrt(ecc)*usin(omega)
                f_c = usqrt(ecc)*ucos(omega)
            elif ecc.s != 0:
                # Work-around to avoid NaNs for e=0 with finite error. 
                eps = .0001
                ecc = usqrt((ecosw+eps)**2+(esinw+eps)**2)-eps
                omega = None
                f_s = ufloat(0,np.sqrt(esinw.s))
                f_c = ufloat(0,np.sqrt(ecosw.s))
            else:
                ecc = None
                omega = None
                f_s = None
                f_c = None
            self.ecc = ecc
            self.ecc_note = "Derived"
            self.omega = omega
            self.omega_note = "Derived"
            
            self.f_s = f_s
            self.f_s_note = "Derived"
            self.f_c = f_c
            self.f_c_note = "Derived"
Пример #50
0
import numpy as np
import scipy.constants as const
from uncertainties import ufloat
from uncertainties import unumpy as unp
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import scipy.constants as const
import math

a = ufloat(-2.64611770, 0.148322358) * (10**(4))
L = ufloat(10.11, 0.03) * (10**(-3))
C = ufloat(2.098, 0.006) * (10**(-9))
R_1 = ufloat(48.1, 0.1)
R_2 = ufloat(509.5, 0.5)

T_ex = -1 / a
R_eff = -2 * L * a

print("a", a, "T_ex", T_ex, "R_eff", R_eff)
Пример #51
0
pylab.ylabel('I_c (mA)')
pylab.grid(color="gray")

#Fare attenzione che gli errori devono essere sempre sommati con le stesse unita di misura,
#quindi nel coeffiente ci cade anche il fattore per passare da una unita di misura all'altra
error = pylab.sqrt(dIc**2)
init = numpy.array([0.005, 0.005])
par, cov = curve_fit(linear, Vce, Ic, init, error, "true")
#trattazione statistica degli errori
print(par, cov)

#Di nuovo co capisco il chi quadro, non cambia nulla se cambio da true a false
a = par[0]
b = par[1]

a = ufloat(a, cov[0][0]**0.5)
b = ufloat(b, cov[1][1]**0.5)

print(a, b)

print("Early = ", -b / a)
chisq = ((Ic - linear(Vce, a, b)) / error)**2
somma = sum(chisq)
ndof = len(Vce) - 2  #Tolgo due parametri estratti dal fit
p = 1.0 - scipy.stats.chi2.cdf(somma, ndof)
print("Chisquare/ndof = %f/%d" % (somma, ndof))
print("p = ", p)

#Routine per stampare due rette:
div = 1000
bucket = numpy.array([0.0 for i in range(div)])
Пример #52
0
def gcFit(x, y):
    """
    Perform the glow curve deconvolution for a given glow curve.

    Parameters
    ----------

    x
        array-like or string. If array-like, used as x-axis of analysis, should be temperature array from Treco. If string, the call will return a callable to be applied to a data set containing that x column
    y
        array-like or string. If array-like, used as y-axis of analysis, typically photon counts of measurement. If string, the call will return a callable to be applied to a data set containing that y column
    
    Returns
    -------

    GCio object containing the fitted data.
    """

    if isinstance(x, str):
        return gcFitWrapper(
            x, y
        )  #if isinstance(data, pd.DataFrame)  else data.update(gcFitWrapper(data[x], data[y]))
        # return lambda data: gcFit(data[x], data[y]) if isinstance(data, pd.DataFrame)  else data.update(gcFit(data[x], data[y]))

    results = {}
    gcTemp = np.array(x)
    gcPhotons = np.array(y)

    ################################################################################################
    errors_kitis1998 = 0
    errors_kitis2006 = 0
    errors_red_chi2_greater_10 = 0

    # binWidth = 2.5

    #gcTemp = np.linspace(T.min(), T.max(), int((T.max()- T.min())/binWidth))
    #gcPhotons = utils.rebinHistRescale(T , tPhotons, gcTemp)

    upperTCut = 580
    lowerTCut = 350

    indices = np.where([gcTemp > lowerTCut, gcTemp < upperTCut])
    indices = np.intersect1d(indices[1][np.where(indices[0] == 0)],
                             indices[1][np.where(indices[0] == 1)])
    gcTemp = gcTemp[indices]
    gcPhotons = gcPhotons[indices]

    results["gcfit_T"] = gcTemp
    results["gcfit_nPhotons"] = gcPhotons

    # initialize start values
    startT = utils.peakTemps
    startE = np.array([1.25, 1.55, 1.46, 2.4])
    startI = np.array(
        [100,
         gcPhotons.max() / 3,
         gcPhotons.max() / 2, 0.9 * gcPhotons.max()])
    startBg = np.array([100, gcTemp.max() + 1, 1e-15, 1e-2])
    p0 = np.concatenate((startT, startI, startE, startBg))

    bounds = (
        [
            startT[0] - 10, startT[1] - 10, startT[2] - 10, startT[3] - 10, 0,
            0, 0, 0, 0.5, 1, 1, 1, 0,
            gcTemp.max() + 1, 0, 0.0
        ],  #minima
        [
            startT[0] + 10, startT[1] + 10, startT[2] + 10, startT[3] + 10,
            np.inf, np.inf, np.inf, np.inf, 2.3, 3.5, 3.4, 4.5, np.inf, 580,
            10, .1
        ]  #maxima
    )

    # fit marker
    error = False
    prefitVals = None

    # actual fit
    t0 = time.time()

    try:
        params, cov = curve_fit(
            fitmethod_kitis98,
            gcTemp,
            gcPhotons,
            p0=p0,
            bounds=bounds,
        )
        prefitVals = params
    except Exception as e:
        results["gcfit_prefit_error"] = True

        Warning('Fit error kitis 98')

    if isinstance(prefitVals, np.ndarray):
        p0 = prefitVals

    try:
        params, cov = curve_fit(
            fitmethod_kitis06,
            gcTemp,
            gcPhotons,
            p0=p0,
            bounds=bounds,
        )
    except Exception as e:
        Warning('Fit error kitis 06')
        results["gcfit_error"] = True
        return results

    tcpu = round(1000 * (time.time() - t0), 3)

    fitValues = params
    fitErrors = np.sqrt(np.diag(cov))

    I_pred = fitmethod_kitis06(gcTemp, *params)
    results["gcfit_gcd"] = I_pred
    chiSquare = utils.calcRedChisq(gcPhotons, I_pred, np.sqrt(gcPhotons),
                                   len(gcPhotons) - len(params))

    ####################### data extraction #################
    #########################################################
    results["gcfit_cpuTime"] = tcpu
    results["gcfit_redChi2"] = chiSquare
    Nsig = 0  #unc.ufloat(0,0)

    for peak in range(4):
        results["gcfit_Tm%s" % (peak + 2)] = fitValues[peak]
        results["gcfit_Tm%s_std_dev" % (peak + 2)] = fitErrors[peak]

        results["gcfit_Im%s" % (peak + 2)] = fitValues[peak + 4]
        results["gcfit_Im%s_std_dev" % (peak + 2)] = fitErrors[peak + 4]

        results["gcfit_E%s" % (peak + 2)] = fitValues[peak + 8]
        results["gcfit_E%s_std_dev" % (peak + 2)] = fitErrors[peak] + 8

        peakI = utils.ckitis2006(gcTemp, fitValues[peak], fitValues[peak + 4],
                                 fitValues[peak + 8])
        results["gcfit_gcd_peak%s" % (peak + 2)] = peakI

        N_peakI = peakI[1:] * np.diff(gcTemp)
        results["gcfit_N%s" % (peak + 2)] = np.sum(N_peakI)
        Nsig += np.sum(N_peakI)

        results["gcfit_Nsig"] = Nsig

        uA = unc.ufloat(fitValues[-4], fitErrors[-4])
        uB = unc.ufloat(fitValues[-3], fitErrors[-3])
        uC = unc.ufloat(fitValues[-2], fitErrors[-2])
        uD = unc.ufloat(fitValues[-1], fitErrors[-1])
        uIbg = (uA / (uB - gcTemp) + uC * unp.exp((gcTemp - 300) * uD))
        uIbg = np.where(unp.nominal_values(uIbg) < 0, 0, uIbg)

        # uNbg = (uA/(uB-gcTemp[1:])+uC * unp.exp((gcTemp[1:]-300)*uD))*np.diff(gcTemp)
        # uNbg = np.where(unp.nominal_values(uNbg) < 0,0,uNbg)
        results["gcfit_gcd_bg"] = unp.nominal_values(uIbg)
        uNbg = uIbg[1:] * np.diff(gcTemp)

        results["gcfit_a"] = fitValues[-4]
        results["gcfit_a_std_dev"] = fitErrors[-4]
        results["gcfit_b"] = fitValues[-3]
        results["gcfit_b_std_dev"] = fitErrors[-3]
        results["gcfit_c"] = fitValues[-2]
        results["gcfit_c_std_dev"] = fitErrors[-2]
        results["gcfit_d"] = fitValues[-1]
        results["gcfit_d_std_dev"] = fitErrors[-1]

        try:
            results["gcfit_Nbg"] = np.sum(uNbg).nominal_value
            results["gcfit_Nbg_std_dev"] = np.sum(uNbg).std_dev

            results["gcfit_Ntot"] = (Nsig + np.sum(uNbg)).nominal_value
            results["gcfit_Ntot_std_dev"] = (Nsig + np.sum(uNbg)).std_dev

        except AttributeError:
            results["gcfit_Nbg"] = -1
            results["gcfit_Nbg_std_dev"] = -1
            results["gcfit_Ntot"] = -1
            results["gcfit_Ntot_std_dev"] = -1

    return results
Пример #53
0
def wregress(x,y,sy):
    m1=[[np.sum(x**2/sy**2), np.sum(x/sy**2)],[np.sum(x/sy**2),np.sum(1/sy**2)]]
    m2=[[np.sum(x*y/sy**2)],[np.sum(y/sy**2)]]
    [a,b]=linalg.solve(m1,m2)
    return [a,b]

def cerror(x,y,sy):
    d=np.sum(1/sy**2)*np.sum(x**2/sy**2)-(np.sum(x/sy**2))**2
    sa=sa=np.sqrt(1/d*np.sum(1/sy**2))
    sb=np.sqrt(1/d*np.sum(x**2/sy**2))
    return sa, sb


thickness=np.array([0,1,2,3,4,5,6])

Al_width_single=ufloat(10e-3,0.01e-3)
Pb_widthlarge=ufloat(10.03e-3,0.02e-3)
Pb_widthsmall=ufloat(4.98e-3,0.03e-3)

density_Al=ufloat(2.558,0.001)
Al_width=Al_width_single*thickness
Al_thickness=Al_width*100*density_Al
Al_n=unumpy.nominal_values(Al_thickness)
Al_e=unumpy.std_devs(Al_thickness)

Al_1_n=np.array([0.0, 5.116,7.6739999999999995,10.232,12.79, 15.347999999999999])
Al_1_e=np.array([0, 0.005493037047025989, 0.008239555570538983 , 0.010986074094051978, 0.013732592617564975 , 0.016479111141077966])

print(Al_e[1])
Al_5_n=np.array([0.0, 2.558, 5.116,7.6739999999999995,10.232, 15.347999999999999])
Al_5_e=np.array([0,0.0027465185235129945, 0.005493037047025989, 0.008239555570538983 , 0.010986074094051978 , 0.016479111141077966])
Пример #54
0
import numpy as np
from uncertainties import ufloat
from uncertainties.umath import *
#Massendurchsätze
L = ufloat(18830, 190)
T_1 = ufloat(-0.01170, 0.00030)
T_2 = ufloat(-0.00949, 0.00030)
T_3 = ufloat(-0.00729, 0.00030)
T_4 = ufloat(-0.00509, 0.00030)
m_1 = (750 + 16720) * T_1 * 120.9 / L
m_2 = (750 + 16720) * T_2 * 120.9 / L
m_3 = (750 + 16720) * T_3 * 120.9 / L
m_4 = (750 + 16720) * T_4 * 120.9 / L
#print(m_1, m_2, m_3, m_4)

#Kompressorleistung
p_a = np.array([440000, 400000, 380000, 370000])
p_b = np.array([860000, 940000, 1080000, 1150000])
m = np.array([m_1, m_2, m_3, m_4])
r = np.array([23100, 21000, 19900, 19400])
k = 1.14
N = 1 / 0.14 * (p_b * (p_a / p_b)**(1 / k) - p_a) * (1 / r) * m
print(N)
Пример #55
0
def curve_fit(
    func: Callable,
    xdata: np.ndarray,
    ydata: np.ndarray,
    p0: Union[Dict[str, float], np.ndarray],
    sigma: Optional[np.ndarray] = None,
    bounds: Optional[Union[Dict[str, Tuple[float, float]],
                           Tuple[np.ndarray, np.ndarray]]] = None,
    **kwargs,
) -> FitData:
    r"""Perform a non-linear least squares to fit

    This solves the optimization problem

    .. math::
        \Theta_{\mbox{opt}} = \arg\min_\Theta \sum_i
            \sigma_i^{-2} (f(x_i, \Theta) -  y_i)^2

    using :func:`scipy.optimize.curve_fit`.

    Args:
        func: a fit function `f(x, *params)`.
        xdata: a 1D float array of x-data.
        ydata: a 1D float array of y-data.
        p0: initial guess for optimization parameters.
        sigma: Optional, a 1D array of standard deviations in ydata
               in absolute units.
        bounds: Optional, lower and upper bounds for optimization
                parameters.
        kwargs: additional kwargs for :func:`scipy.optimize.curve_fit`.

    Returns:
        result containing ``popt`` the optimal fit parameters,
        ``popt_err`` the standard error estimates popt,
        ``pcov`` the covariance matrix for the fit,
        ``reduced_chisq`` the reduced chi-squared parameter of fit,
        ``dof`` the degrees of freedom of the fit,
        ``xrange`` the range of xdata values used for fit.

    Raises:
        AnalysisError:
            When the number of degrees of freedom of the fit is
            less than 1, or the curve fitting fails.

    .. note::
        ``sigma`` is assumed to be specified in the same units as ``ydata``
        (absolute units). If sigma is instead specified in relative units
        the `absolute_sigma=False` kwarg of scipy
        :func:`~scipy.optimize.curve_fit` must be used. This affects the
        returned covariance ``pcov`` and error ``popt_err`` parameters via
        ``pcov(absolute_sigma=False) = pcov * reduced_chisq``
        ``popt_err(absolute_sigma=False) = popt_err * sqrt(reduced_chisq)``.
    """
    # Format p0 parameters if specified as dictionary
    if isinstance(p0, dict):
        param_keys = list(p0.keys())
        param_p0 = list(p0.values())

        # Convert bounds
        if bounds:
            lower = [bounds[key][0] for key in param_keys]
            upper = [bounds[key][1] for key in param_keys]
            param_bounds = (lower, upper)
        else:
            param_bounds = ([-np.inf] * len(param_keys),
                            [np.inf] * len(param_keys))

        # Convert fit function
        def fit_func(x, *params):
            return func(x, **dict(zip(param_keys, params)))

    else:
        param_keys = [f"p{i}" for i in range(len(p0))]
        param_p0 = p0
        if bounds:
            param_bounds = bounds
        else:
            param_bounds = ([-np.inf] * len(p0), [np.inf] * len(p0))
        fit_func = func

    # Check the degrees of freedom is greater than 0
    dof = len(ydata) - len(param_p0)
    if dof < 1:
        raise AnalysisError(
            "The number of degrees of freedom of the fit data and model "
            " (len(ydata) - len(p0)) is less than 1")

    # Format non-number sigma values
    if sigma is not None:
        if np.all(np.isnan(sigma)):
            sigma = None
        else:
            sigma = np.nan_to_num(sigma)
            if np.count_nonzero(sigma) != len(sigma):
                # Sigma = 0 causes zero division error
                sigma = None

    # Override scipy.curve_fit default for absolute_sigma=True
    # if sigma is specified.
    if sigma is not None and "absolute_sigma" not in kwargs:
        kwargs["absolute_sigma"] = True

    # Run curve fit
    try:
        # pylint: disable = unbalanced-tuple-unpacking
        popt, pcov = opt.curve_fit(fit_func,
                                   xdata,
                                   ydata,
                                   sigma=sigma,
                                   p0=param_p0,
                                   bounds=param_bounds,
                                   **kwargs)
    except Exception as ex:
        raise AnalysisError(
            "scipy.optimize.curve_fit failed with error: {}".format(
                str(ex))) from ex

    if np.isfinite(pcov).all():
        # Keep parameter correlations in following analysis steps
        fit_params = uncertainties.correlated_values(nom_values=popt,
                                                     covariance_mat=pcov,
                                                     tags=param_keys)
    else:
        # Ignore correlations, add standard error if finite.
        fit_params = [
            uncertainties.ufloat(nominal_value=n,
                                 std_dev=s if np.isfinite(s) else np.nan)
            for n, s in zip(popt, np.sqrt(np.diag(pcov)))
        ]

    # Calculate the reduced chi-squared for fit
    yfits = fit_func(xdata, *popt)
    residues = (yfits - ydata)**2
    if sigma is not None:
        residues = residues / (sigma**2)
    reduced_chisq = np.sum(residues) / dof

    return FitData(
        popt=list(fit_params),
        popt_keys=list(param_keys),
        pcov=pcov,
        reduced_chisq=reduced_chisq,
        dof=dof,
        x_data=xdata,
        y_data=ydata,
    )
Пример #56
0
def test_inverse():
    "Tests of the matrix inverse"

    m = unumpy.matrix([[ufloat(10, 1), -3.1], [0, ufloat(3, 0)]])
    m_nominal_values = unumpy.nominal_values(m)

    # "Regular" inverse matrix, when uncertainties are not taken
    # into account:
    m_no_uncert_inv = m_nominal_values.I

    # The matrix inversion should not yield numbers with uncertainties:
    assert m_no_uncert_inv.dtype == numpy.dtype(float)

    # Inverse with uncertainties:
    m_inv_uncert = m.I  # AffineScalarFunc elements
    # The inverse contains uncertainties: it must support custom
    # operations on matrices with uncertainties:
    assert isinstance(m_inv_uncert, unumpy.matrix)
    assert type(m_inv_uncert[0, 0]) == uncert_core.AffineScalarFunc

    # Checks of the numerical values: the diagonal elements of the
    # inverse should be the inverses of the diagonal elements of
    # m (because we started with a triangular matrix):
    assert numbers_close(1 / m_nominal_values[0, 0],
                         m_inv_uncert[0, 0].nominal_value), "Wrong value"

    assert numbers_close(1 / m_nominal_values[1, 1],
                         m_inv_uncert[1, 1].nominal_value), "Wrong value"

    ####################

    # Checks of the covariances between elements:
    x = ufloat(10, 1)
    m = unumpy.matrix([[x, x], [0, 3 + 2 * x]])

    m_inverse = m.I

    # Check of the properties of the inverse:
    m_double_inverse = m_inverse.I
    # The initial matrix should be recovered, including its
    # derivatives, which define covariances:
    assert numbers_close(m_double_inverse[0, 0].nominal_value,
                         m[0, 0].nominal_value)
    assert numbers_close(m_double_inverse[0, 0].std_dev, m[0, 0].std_dev)

    assert arrays_close(m_double_inverse, m)

    # Partial test:
    assert derivatives_close(m_double_inverse[0, 0], m[0, 0])
    assert derivatives_close(m_double_inverse[1, 1], m[1, 1])

    ####################

    # Tests of covariances during the inversion:

    # There are correlations if both the next two derivatives are
    # not zero:
    assert m_inverse[0, 0].derivatives[x]
    assert m_inverse[0, 1].derivatives[x]

    # Correlations between m and m_inverse should create a perfect
    # inversion:
    assert arrays_close(m * m_inverse, numpy.eye(m.shape[0]))
Пример #57
0
import uncertainties
from uncertainties import ufloat
import math
import numpy
import numpy
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import uncertainties
from uncertainties import unumpy

INPUT = "datiGuadagno.txt"
OUTPUT = "datiGuadagnoEstesi.txt"

Vin, dVin, Vout, dVout = pylab.loadtxt(INPUT, unpack=True)

f = ufloat(5.00, 5.00 / 100.0)

VIN = unumpy.uarray(Vin, dVin) / 1000
VIN3 = unumpy.uarray(Vin, ((dVin)**2 + (0.03 * Vin)**2)**0.5) / 1000
VOUT = unumpy.uarray(Vout, dVout)
VOUT3 = unumpy.uarray(Vout, ((dVout)**2 + (0.03 * Vout)**2)**0.5)
A = VOUT3 / VIN3
mediaA = A.mean()
print(A)
Пример #58
0
plt.plot(Iq, Uh, 'ro', label='Hall-Spannung bei Variation von Iq')

# Achsenbeschriftung
plt.xlabel(r'$I_Q \:/\: \si{\ampere}$')
plt.ylabel(r'$U_H \:/\: \si{\volt}$')

# in matplotlibrc leider (noch) nicht möglich
plt.legend()
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)

#print("a: ", a)
#print("Fehler von a: ", a_err)
#print("b: ", b)
#print("Fehler von b: ", b_err)

a_neu = ufloat(a, a_err)
n_neu = ufloat(3.27 * 10**29, 0.09 * 10**29)  # 1/meter^3
tau_neu = ufloat(1.72 * 10**-14, 0.05 * 10**-14)
vd_neu = ufloat(1.91 * 10**-5, 0.05 * 10**-5)
vtotal_neu = ufloat(2.469 * 10**6, 0.023 * 10**6)

m_atom = 63.5 * 1.67 * 10**-27  #kilogram
rho = 8.96 * 1000  #kilogram pro m^3
print("z1 und z Fehler: ", z(rho, n_neu, m_atom))

#print("n und n error: ", n(B_neu,e_neu,d_neu,a_neu))
#print("Tau und Tau error: ", T(m_neu,L_neu,e_neu,n_neu,R_neu,Q_neu))
#print("Vdrift und Error: ", V(j_neu,e_neu,n_neu))
#print("Mü und Mü Fehler: ", M(e_neu,n_neu,tau_neu,vd_neu,m_neu,j_neu))
#print("Vtotal und Fehler: ", VT(h_neu,m_neu,n_neu))
#print("L und L Fehler: ", L(tau_neu, vtotal_neu))
Пример #59
0
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from uncertainties import unumpy as unp
from uncertainties import ufloat
from astropy.io import ascii
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)

plt.rcParams['figure.figsize'] = (10, 8)
plt.rcParams['font.size'] = 16
plt.rcParams['lines.linewidth'] = 2

N = 80
E = ufloat(210 * 10**9, 0.5 * 10**9)  # in Pascal
R = 72 * 10**-3  # Spulenradius in m
D_KH = 22.5 * 10**-7  # Trägheitsmoment Halterung in kg/m^2
R_k = ufloat(51.03 * 10**-3, 0.020412 * 10**-3) / 2  # Kugelradius in m
m_k = ufloat(588.3, 0.23532) * 10**-3  # Kugelmasse in kg
L = (61.7 + 4.2) * 10**-2  # Länge des Drahtes in m
I = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])  # Strom in A
Anzahl1, T = np.genfromtxt('rohdaten/Schubmodul.txt', unpack=True)
Anzahl2, d1 = np.genfromtxt('rohdaten/Drahtdurchmesser.txt', unpack=True)
Anzahl3, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 = np.genfromtxt(
    'rohdaten/MagnetischerMoment.txt', unpack=True)
Anzahl4, Te = np.genfromtxt('rohdaten/Erdmagnetfeld.txt', unpack=True)

# a)
print('A')
r = ufloat(np.mean(d1), np.std(d1)) / 2 * 10**-3
print('R = ', r * 10**3, 'in mm')
print('RK =', R_k * 10**3, 'in mm')
Пример #60
0
@uncertainties.wrap
def integratehigh(al=None,be=None,ls=None,l=None):
	if al==None:
		al=-1.59
	if l==None:
		l=50
	if be==None:
		be=-4.1
	if ls==None:
		ls=43.06
	def integrand(X):
		return np.power(10,((al+1)*np.log10(10**X/10**ls)+be))*np.e**(-10**X/10**ls)
	integral,abserr=sp.integrate.quad(integrand,42,l)
	return integral

OIINumberDens1=integratelow(al=uncertainties.ufloat(-2.21,0.06),be=uncertainties.ufloat(46.96,2.6))+integratehigh(al=uncertainties.ufloat(-1.59,0.15),be=uncertainties.ufloat(-4.1,0.22),ls=uncertainties.ufloat(43.060,14),l=44)

def integ(x,al,bl):
    return 10**((al+1)*(x-42)+bl)

def integ2(x,al,bl):
    return 10**((al+1)*(x-41.5)+bl)

x=[40.9,41.1,41.3,41.5,41.7]
y10=np.array([10**-1.97,10**-2.6,10**-2.8])
y06=np.array([10**-2.57,10**-2.88,10**-2.9,10**-2.99,10**-3.35])
y03=np.array([10**-2.6,10**-2.88,10**-2.94,10**-3.1,10**-3.5])
y01=np.array([10**-2.8,10**-2.95,10**-3.2,10**-3.6,10**-3.8])

alph01,beta01=uncertainties.correlated_values(sp.optimize.curve_fit(integ,x,y01,p0=[-2.21,43.6])[0],sp.optimize.curve_fit(integ,x,y01,p0=[-2.21,43.6])[1])
alph03,beta03=uncertainties.correlated_values(sp.optimize.curve_fit(integ,x,y03,p0=[-2.21,43.6])[0],sp.optimize.curve_fit(integ,x,y03,p0=[-2.21,43.6])[1])