def test_LeastSquares(loss, verbose): rng = np.random.default_rng(1) x = np.linspace(0, 1, 1000) ye = 0.1 y = rng.normal(2 * x + 1, ye) def model(x, a, b): return a + b * x cost = LeastSquares(x, y, ye, model, loss=loss, verbose=verbose) assert cost.ndata == len(x) m = Minuit(cost, a=0, b=0) m.migrad() assert_allclose(m.values, (1, 2), rtol=0.05) assert cost.loss == loss if loss != "linear": cost.loss = "linear" assert cost.loss != loss m.migrad() assert_allclose(m.values, (1, 2), rtol=0.05) assert m.ndof == len(x) - 2 assert_allclose(m.fmin.reduced_chi2, 1, atol=5e-2)
def test_LeastSquares_bad_input(): with pytest.raises(ValueError): LeastSquares([1, 2], [1], [1], lambda x, a: 0) with pytest.raises(ValueError): LeastSquares([1, 2], [1, 2], [1], lambda x, a: 0) with pytest.raises(ValueError): LeastSquares([1], [1], [1], lambda x, a: 0, loss="foo")
def test_addable_cost_1(): def model1(x, a): return a + x def model2(x, b, a): return a + b * x def model3(x, c): return c lsq1 = LeastSquares(1, 2, 3, model1) assert lsq1.func_code.co_varnames == ("a", ) lsq2 = LeastSquares(1, 3, 4, model2) assert lsq2.func_code.co_varnames == ("b", "a") lsq3 = LeastSquares(1, 1, 1, model3) assert lsq3.func_code.co_varnames == ("c", ) lsq12 = lsq1 + lsq2 assert lsq12._items == [lsq1, lsq2] assert isinstance(lsq12, CostSum) assert isinstance(lsq1, LeastSquares) assert isinstance(lsq2, LeastSquares) assert lsq12.func_code.co_varnames == ("a", "b") assert lsq12.ndata == 2 assert lsq12(1, 2) == lsq1(1) + lsq2(2, 1) m = Minuit(lsq12, a=0, b=0) m.migrad() assert m.parameters == ("a", "b") assert_allclose(m.values, (1, 2)) assert_allclose(m.errors, (3, 5)) assert_allclose(m.covariance, ((9, -9), (-9, 25)), atol=1e-10) lsq121 = lsq12 + lsq1 assert lsq121._items == [lsq1, lsq2, lsq1] assert lsq121.func_code.co_varnames == ("a", "b") assert lsq121.ndata == 3 lsq312 = lsq3 + lsq12 assert lsq312._items == [lsq3, lsq1, lsq2] assert lsq312.func_code.co_varnames == ("c", "a", "b") assert lsq312.ndata == 3 lsq31212 = lsq312 + lsq12 assert lsq31212._items == [lsq3, lsq1, lsq2, lsq1, lsq2] assert lsq31212.func_code.co_varnames == ("c", "a", "b") assert lsq31212.ndata == 5 lsq31212 += lsq1 assert lsq31212._items == [lsq3, lsq1, lsq2, lsq1, lsq2, lsq1] assert lsq31212.func_code.co_varnames == ("c", "a", "b") assert lsq31212.ndata == 6
def test_LeastSquares_mask(): c = LeastSquares([1, 2, 3], [3, np.nan, 4], [1, 1, 1], lambda x, a: x + a) assert c.ndata == 3 assert np.isnan(c(0)) == True m = Minuit(c, 1) assert m.ndof == 2 m.migrad() assert not m.valid c.mask = np.arange(3) != 1 assert np.isnan(c(0)) == False assert c.ndata == 2 assert m.ndof == 1 m.migrad() assert m.valid assert_equal(m.values, [1.5])
def test_addable_cost_3(): def line_np(x, par): return par[0] + par[1] * x lsq = LeastSquares([1, 2, 3], [3, 4, 5], 1, line_np) con = NormalConstraint("par", (1, 1), (1, 1)) cs = sum([lsq, con]) assert cs((1, 1)) == pytest.approx(3) cs = 1.5 + lsq + con assert cs((1, 1)) == pytest.approx(4.5)
def test_LeastSquares(loss, verbose): np.random.seed(1) x = np.random.rand(20) y = 2 * x + 1 ye = 0.1 y += ye * np.random.randn(len(y)) def model(x, a, b): return a + b * x cost = LeastSquares(x, y, ye, model, loss=loss, verbose=verbose) m = Minuit(cost, a=0, b=0) m.migrad() assert_allclose(m.values, (1, 2), rtol=0.03) assert cost.loss == loss if loss != "linear": cost.loss = "linear" assert cost.loss != loss m.migrad() assert_allclose(m.values, (1, 2), rtol=0.02)
def fit(self, index, n_bins=100, data_color=None, fit_color=None, box_color=None): data, data_errs, bins = self.get_histogram_by_index(index, n_bins) parameters = { 'mu':0.02, 's':1/250, 'c':0.004, 'N':0.35, } parameters_options = { 'mu' : ([0, 1], 0.01), 's' : ([0,1], 1/25), 'c' : ([0,1], 0.01), 'N' : ([0,1], 0.05), } m = Minuit(LeastSquares(bins, data, data_errs, RegEff.sigFunc), **parameters) for par in m.parameters: m.limits[par], m.errors[par] = parameters_options[par] m.migrad() if not(m.accurate): warnings.warn('Minuit troubles') if self.fit_results is None: columns = [] columns += m.parameters columns += ( tuple(map(lambda x: f'{x}_err', m.parameters)) + ('eff0', 'eff0_err') ) self.fit_results = pd.DataFrame(columns=columns) eff0 = RegEff.sigFunc(0, *m.values) eff0_err = RegEff.sigFunc(0, *(np.array(m.values)+np.array(m.errors))) - eff0 temp_ser = pd.Series(list(m.values) + list(m.errors) + [eff0, eff0_err], index=self.fit_results.columns, name=self.index2energy(index)) if temp_ser.name in self.fit_results.index: self.fit_results.drop(temp_ser.name, axis=0, inplace=True) self.fit_results = self.fit_results.append(temp_ser) fig, ax = plt.subplots() xx = np.linspace(0, np.max(bins), 100) ax.errorbar(bins, data, yerr=data_errs, fmt='.', color=data_color) ax.plot(xx, RegEff.sigFunc(xx, *m.values), color=fit_color) my_style(title=f'Registration eff. vs rad. photon energy ($\sqrt{{s}}$ = {self.index2energy(index)*2e-3:.3f} GeV)', xlim=(0, np.max(bins)), ylim=(0, None), xtitle='$E_{\\gamma}$, GeV', ytitle='$\\varepsilon_{reg}$') values_dict = dict(zip(m.parameters, m.values)) chi2, ndf = m.fval, len(bins)-len(m.parameters)-1 s = f'$\\chi^2$ / ndf = {chi2:.2f} / {ndf}\n' s += f'p-value: {1-stats.chi2.cdf(chi2, ndf):.2f}\n' for var, val, err, fixed in zip(m.parameters, m.values, m.errors, m.fixed): if fixed: s += f'{var} = {val:1.3f}\n' else: s += f'{var} = {val:1.3f}$\\pm${err:.4f}\n' props = dict(boxstyle='square', facecolor=box_color, alpha=0.5) ax.text(0.65, 0.95, s.strip(), transform=ax.transAxes, verticalalignment='top', bbox=props) return
def test_NormalConstraint_1(): def model(x, a): return a lsq1 = LeastSquares(0, 1, 1, model) lsq2 = lsq1 + NormalConstraint("a", 1, 0.1) assert lsq1.func_code.co_varnames == ("a",) assert lsq2.func_code.co_varnames == ("a",) m = Minuit(lsq1, 0) m.migrad() assert_allclose(m.values, (1,), atol=1e-2) assert_allclose(m.errors, (1,), rtol=1e-2) m = Minuit(lsq2, 0) m.migrad() assert_allclose(m.values, (1,), atol=1e-2) assert_allclose(m.errors, (0.1,), rtol=1e-2)
def test_LeastSquares_properties(): def model(x, a): return a c = LeastSquares(1, 2, 3, model) assert_equal(c.x, [1]) assert_equal(c.y, [2]) assert_equal(c.yerror, [3]) assert c.model is model with pytest.raises(AttributeError): c.model = model with pytest.raises(ValueError): c.x = [1, 2] with pytest.raises(ValueError): c.y = [1, 2] with pytest.raises(ValueError): c.yerror = [1, 2]
TCR2 = 1 / ((1 / TCS2) + (1 / TAUR)) JTOT1 = TCR1 / (1 + numpy.power((freq1 * TCR1), 2)) JTOT2 = TCR2 / (1 + numpy.power((freq2 * TCR2), 2)) RR1 = CMR * ( (3 * JTOT1) + (7 * JTOT2)) + (CMS * TCS2) / (1 + numpy.power(freq2 * TCS2, 2)) T1M = 1 / RR1 # T1m R1rotSS = PROPR * ( (CONC / 55.55) * SOLV) / (T1M + TAUM) #PROPR # Y de R1 # return x # print(R1trans + R1rot) return R1trans + R1rotSS data_yerr = 0.000001 least_squares = LeastSquares(rawdata_x, rawdata_y, data_yerr, line) # pass starting values for a and b # print("coucou1") m = Minuit( least_squares, CONC=float(params["CONC"]["value"]), SOLV=float(params["SOLV"]["value"]), PROPR=float(params["PROPR"]["value"]), SPIN=float(params["SPIN"]["value"]), B=float(params["B"]["value"]), DIF=float(params["DIF"]["value"]), TAUS0=float(params["TAUS0"]["value"]), TAUV=float(params["TAUV"]["value"]), PROPT=float(params["PROPT"]["value"]), gl=float(params["gl"]["value"]), TAUM=float(params["TAUM"]["value"]),
plt.xlabel('$t_{decay}$ (s)') plt.ylabel('Entries') plt.title('Decay time distribution') centers = bins[:-1] + np.diff(bins) / 2 gamma_init = 100. n0_init = n[0] #l = 1./gamma def special_exp(x, n0, gamma): y = n0 * np.exp(-centers / (gamma * piCnst.lifetime())) return y #plt.plot(centers, y, '-', color='b') least_squares = LeastSquares(centers, n, yerror=np.sqrt(n), model=special_exp) m = Minuit(least_squares, n0=n0_init, gamma=gamma_init) m.migrad() print(m.hesse()) plt.plot(centers, special_exp(centers, m.values[0], m.values[1]), color='b', label='fit') #plt.show() plt.savefig('Scratch/nuSTORMTrfLine/nuSTORMTrfLineTst_4_tdec.pdf') plt.close() n, bins, patches = plt.hist(s_dcy_pi, bins=50, color='y') plt.xlabel('s decay (m)') plt.ylabel('Entries') plt.title('Decay point distribution')
print(error) errbar = np.array(error) err = sem(avg) x_data = len y = avg f = plt.figure() f.set_figwidth(10) f.set_figheight(10) def line(x, a, b): return a + b * x least_squares = LeastSquares(x_data, y, error, line) m = Minuit(least_squares, a=0, b=0) m.migrad() # finds minimum of least_squares function m.hesse() plt.plot(np.linspace(0.35, 2.00), line(np.linspace(0.35, 2.00), *m.values), label="fit") plt.errorbar(x_data, y, yerr=error, fmt="o", label="data") print(x_data) print(m.nfit) print(m.fval) length = 7 r = m.fval / (length - m.nfit) fit_info = [
eid_other.append(i[0]) P = pd.DataFrame(eid_p) if not P.empty: P.columns = ['EventID'] P_DFRONT = pd.merge(P,DATA_FRONT, on='EventID') P_DBACK = pd.merge(P,DATA_BACK, on='EventID') P_DDIFF = pd.merge(P,DATA_DIFFERENCE, on='EventID') P_DDIFF = P_DDIFF.dropna() P_DBACK = P_DBACK.dropna() doiList = P_DBACK.gammaxpos.tolist() backCountsList = P_DBACK.Back_Counts.tolist() diffCountsList = P_DDIFF.Difference_Counts.tolist() k = Minuit(LeastSquares(diffCountsList, doiList, 10.0, Line), m = 0.02, b = 0) k.migrad() k.hesse() fig, axs = plt.subplots() crystalLength = 30 nChoices = [5] refractiveIndex = 1.82 for index in range(len(nChoices)): nthPhotonTimes = [] backTriggers = [] frontTriggers = [] doiList = [] doiTruthList = []
variancesOverEnergy.append(varianceOverEnergy) photopeakEnergies = [i for i in eventEnergies if i > 7500] numBins = 50 fig, ax = plt.subplots() hist, xedges = np.histogram(eventEnergies, bins=100) photoPeak = xedges[hist.argmax()] (binCounts, bins, patches) = ax.hist(photopeakEnergies, bins=numBins, range=[photoPeak - 1000, photoPeak + 1000]) binCenters = np.linspace(min(bins), max(bins), numBins) k = Minuit(LeastSquares(binCenters, binCounts, 10.0, gauss), a=100, mu=photoPeak, sigma=100, c=0) k.migrad() k.hesse() energyResolution = k.values[2] / k.values[1] * 100 fitPoints = np.linspace(min(bins), max(bins), 1000) ax.plot(fitPoints, gauss(fitPoints, *k.values[0:4]), color='k') ax.text(0.7, 0.9, "Data Stats:", weight='bold', transform=ax.transAxes) ax.text(0.7, 0.85, "mean: " + format(np.mean(photopeakEnergies), "5.4f"), transform=ax.transAxes)
new_mag = [] for i in range(len(x_chunk)): if np.abs(x_chunk[i] - np.median(x_chunk) ) < 2 * 1.428 * stats.median_absolute_deviation( x_chunk - np.median(x_chunk)): new_chunk.append(x_chunk[i]) newt_chunk.append(t_chunk[i]) new_chunk1.append(ra_chunk[i]) new_chunk2.append(dec_chunk[i]) new_mag.append(mag_chunk[i]) new_chunk3.append(raerr_chunk[i]) new_chunk4.append(decerr_chunk[i]) #Run Minuit on outlier-free ra and dec chunks least_squares = LeastSquares(newt_chunk, new_chunk1, new_chunk3, line) m = Minuit(least_squares, a=0, b=0) m.migrad() m.hesse() least_squares1 = LeastSquares(newt_chunk, new_chunk2, new_chunk4, line) m1 = Minuit(least_squares1, a=0, b=0) m1.migrad() m1.hesse() #Run linear regression with scipy.stats slope, intercept, r_value, p_value, std_err = stats.linregress(
def fit_freezeout(dict_yield,**kwargs): """ Extract freeze out parameters by fitting final heavy ion data (dN/dy) given in dict_yield. Construct ratios of different particles. """ # additional plots of chi^2 (takes time) try: chi2_plot = kwargs['chi2_plot'] except: chi2_plot = False # default # consider decay from unstable particles in the calculation of densities? try: freezeout_decay = kwargs['freezeout_decay'] except: freezeout_decay = True # apply fit to both yields and ratios? try: method = kwargs['method'] except: method = 'all' # consider integration over mass? try: offshell = kwargs['offshell'] except: offshell = False # default # evaluate freeze out parameters for which EoS? full or strangeness neutrality ns0 ? try: EoS = kwargs['EoS'] except: EoS = 'all' # default # we fit the HRG EoS to the ratios of particle yields as list_part1/list_part2 # as in BES STAR paper: PHYSICAL REVIEW C 96, 044904 (2017) list_part1 = ['pi-','K-','p~','Lambda~','Xi~+','K-','p~','Lambda','Xi~+'] list_part2 = ['pi+','K+','p','Lambda','Xi-','pi-','pi-','pi-','pi-'] # unique list of particles (for the yields) list_part = ['pi+','pi-','K+','K-','p','p~','Lambda','Lambda~','Xi-','Xi~+'] # construct yields from input data_yields = [] err_yields = [] final_part = [] for part in list_part: try: # check if the particles are given in dict_yield if(dict_yield[part]!=None and dict_yield[part]>0.): data_yields.append(dict_yield[part]) err_yields.append(dict_yield[part+'_err']) final_part.append(part) except: pass # construct ratios from input yields data_ratios = [] err_ratios = [] final_part1 = [] final_part2 = [] # loop over particles in list_part1 and list_part2 for part1,part2 in zip(list_part1,list_part2): try: # check if the particles are given in dict_yield if(dict_yield[part1]!=None and dict_yield[part1]>0. and dict_yield[part2]!=None and dict_yield[part2]>0.): ratio = dict_yield[part1]/dict_yield[part2] data_ratios.append(ratio) err_ratios.append(abs(ratio)*np.sqrt((dict_yield[part1+'_err']/dict_yield[part1])**2.+(dict_yield[part2+'_err']/dict_yield[part2])**2.)) final_part1.append(part1) final_part2.append(part2) except: pass def f_yields(x,T,muB,muQ,muS,gammaS,dVdy): """ Calculate the particle yields for fixed T,muB,muQ,muS,gammaS,volume x is a dummy argument """ result = np.zeros(len(final_part)) # calculate all densities result_HRG = HRG_freezout(T,muB,muQ,muS,gammaS,EoS='full',**kwargs) # loop over particles for i,part in enumerate(final_part): yval = result_HRG[part] #print('part,yval=',part,yval) # if no decays, then Sigma0 should be added to Lambda # if decays are activated, then Sigma0 decays to Lambda if(not(freezeout_decay)): # include Sigma0 with Lambda if(part=='Lambda'): yval += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part=='Lambda~'): yval += result_HRG['Sigma~0'] # number of particles result[i] = yval*T**3.*dVdy/(0.197**3.) # return the list of yields return result def f_yields_nS0(x,T,muB,gammaS,dVdy): """ Calculate the particle yields for fixed T,muB,gammaS,volume x is a dummy argument """ result = np.zeros(len(final_part)) # calculate all densities result_HRG = HRG_freezout(T,muB,0.,0.,gammaS,EoS='nS0',**kwargs) # loop over particles for i,part in enumerate(final_part): yval = result_HRG[part] #print('part,yval=',part,yval) # if no decays, then Sigma0 should be added to Lambda # if decays are activated, then Sigma0 decays to Lambda if(not(freezeout_decay)): # include Sigma0 with Lambda if(part=='Lambda'): yval += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part=='Lambda~'): yval += result_HRG['Sigma~0'] # number of particles result[i] = yval*T**3.*dVdy/(0.197**3.) # return the list of yields return result def f_ratios(x,T,muB,muQ,muS,gammaS): """ Calculate the ratios of particle yields for fixed T,muB,muQ,muS,gammaS x is a dummy argument """ result = np.zeros(len(data_ratios)) # calculate all densities result_HRG = HRG_freezout(T,muB,muQ,muS,gammaS,EoS='full',**kwargs) # loop over different ratios for i,(part1,part2) in enumerate(zip(final_part1,final_part2)): yval1 = result_HRG[part1] yval2 = result_HRG[part2] #print('part,yval1=',part1,yval1) #print('part,yval2=',part2,yval2) # if no decays, then Sigma0 should be added to Lambda # if decays are activated, then Sigma0 decays to Lambda if(not(freezeout_decay)): # include Sigma0 with Lambda if(part1=='Lambda'): yval1 += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part1=='Lambda~'): yval1 += result_HRG['Sigma~0'] # include Sigma0 with Lambda if(part2=='Lambda'): yval2 += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part2=='Lambda~'): yval2 += result_HRG['Sigma~0'] # ratio of particle1/particle2 result[i] = yval1/yval2 # return the list of ratios return result def f_ratios_nS0(x,T,muB,gammaS): """ Calculate the ratios of particle yields for fixed T,muB,gammaS x is a dummy argument """ result = np.zeros(len(data_ratios)) # calculate all densities result_HRG = HRG_freezout(T,muB,0.,0.,gammaS,EoS='nS0',**kwargs) # loop over different ratios for i,(part1,part2) in enumerate(zip(final_part1,final_part2)): yval1 = result_HRG[part1] yval2 = result_HRG[part2] #print('part,yval1=',part1,yval1) #print('part,yval2=',part2,yval2) # if no decays, then Sigma0 should be added to Lambda # if decays are activated, then Sigma0 decays to Lambda if(not(freezeout_decay)): # include Sigma0 with Lambda if(part1=='Lambda'): yval1 += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part1=='Lambda~'): yval1 += result_HRG['Sigma~0'] # include Sigma0 with Lambda if(part2=='Lambda'): yval2 += result_HRG['Sigma0'] # include Sigma~0 with Lambda~ elif(part2=='Lambda~'): yval2 += result_HRG['Sigma~0'] # ratio of particle1/particle2 result[i] = yval1/yval2 # return the list of ratios return result # initialize the parameters # which parameters to be fixed? fix_T=False fix_muB=False fix_muQ=False fix_muS=False fix_gammaS=False fix_dVdy=False # first guesses for T,muB,muQ,muS,gammaS,dVdy guess = (0.150, 0.05, 0., 0.05, 1., 2000.) # bounds bounds = ((0.100, 0.200), (0, 0.6), (-0.2,0.2), (0,0.2), (0.0,1.2), (100.,10000.)) # fit with yields if((EoS=='all' or EoS=='full') and (method=='all' or method=='yields')): # x-values, just the indexes of ratios [1,2,...,N_particles] xyields = np.arange(len(final_part)) # initialize Minuit least_squares class least_squares = LeastSquares(xyields, data_yields, err_yields, f_yields) m = Minuit(least_squares, T=guess[0], muB=guess[1], muQ=guess[2], muS=guess[3], gammaS=guess[4], dVdy=guess[5], limit_T=bounds[0],limit_muB=bounds[1],limit_muQ=bounds[2],limit_muS=bounds[3],limit_gammaS=bounds[4],limit_dVdy=bounds[5], fix_T=fix_T,fix_muB=fix_muB,fix_muQ=fix_muQ,fix_muS=fix_muS,fix_gammaS=fix_gammaS,fix_dVdy=fix_dVdy) m.migrad() # finds minimum of least_squares function m.hesse() # computes errors #print(m.params) # minuit output # display values and errors popt1 = m.values.values() perr1 = m.errors.values() print('\nfit from yields, full EoS:') fit_string1 = f'$T_{{ch}}={popt1[0]:.4f} \pm {perr1[0]:.4f}\ GeV$\ \n$\mu_{{B}}={popt1[1]:.4f} \pm {perr1[1]:.4f}\ GeV$\ \n$\mu_{{Q}}={popt1[2]:.4f} \pm {perr1[2]:.4f}\ GeV$\ \n$\mu_{{S}}={popt1[3]:.4f} \pm {perr1[3]:.4f}\ GeV$\ \n$\gamma_{{S}}={popt1[4]:.2f} \pm {perr1[4]:.2f}$\ \n$dV/dy={popt1[5]:.1f} \pm {perr1[5]:.1f} \ fm^3$' print(fit_string1) thermo = HRG(popt1[0],popt1[1],popt1[2],popt1[3],gammaS=popt1[4],offshell=offshell) snB1 = thermo['s']/thermo['n_B'] snB1_err = 0. # derivative wrt T thermoT1 = HRG(popt1[0]+perr1[0]/2.,popt1[1],popt1[2],popt1[3],gammaS=popt1[4],offshell=offshell) thermoT2 = HRG(popt1[0]-perr1[0]/2.,popt1[1],popt1[2],popt1[3],gammaS=popt1[4],offshell=offshell) if(thermoT1['n_B']!=0. and thermoT2['n_B']!=0.): snB1_err += (thermoT1['s']/thermoT1['n_B']-thermoT2['s']/thermoT2['n_B'])**2. # derivative wrt mu_B thermomuB1 = HRG(popt1[0],popt1[1]+perr1[1]/2.,popt1[2],popt1[3],gammaS=popt1[4],offshell=offshell) thermomuB2 = HRG(popt1[0],popt1[1]-perr1[1]/2.,popt1[2],popt1[3],gammaS=popt1[4],offshell=offshell) if(thermomuB1['n_B']!=0. and thermomuB2['n_B']!=0.): snB1_err += (thermomuB1['s']/thermomuB1['n_B']-thermomuB2['s']/thermomuB2['n_B'])**2. # derivative wrt mu_Q thermomuQ1 = HRG(popt1[0],popt1[1],popt1[2]+perr1[2]/2.,popt1[3],gammaS=popt1[4],offshell=offshell) thermomuQ2 = HRG(popt1[0],popt1[1],popt1[2]-perr1[2]/2.,popt1[3],gammaS=popt1[4],offshell=offshell) if(thermomuQ1['n_B']!=0. and thermomuQ2['n_B']!=0.): snB1_err += (thermomuQ1['s']/thermomuQ1['n_B']-thermomuQ2['s']/thermomuQ2['n_B'])**2. # derivative wrt mu_S thermomuS1 = HRG(popt1[0],popt1[1],popt1[2],popt1[3]+perr1[3]/2.,gammaS=popt1[4],offshell=offshell) thermomuS2 = HRG(popt1[0],popt1[1],popt1[2],popt1[3]-perr1[3]/2.,gammaS=popt1[4],offshell=offshell) if(thermomuS1['n_B']!=0. and thermomuS2['n_B']!=0.): snB1_err += (thermomuS1['s']/thermomuS1['n_B']-thermomuS2['s']/thermomuS2['n_B'])**2. # derivative wrt gamma_S thermogammaS1 = HRG(popt1[0],popt1[1],popt1[2],popt1[3],gammaS=popt1[4]+perr1[4]/2.,offshell=offshell) thermogammaS2 = HRG(popt1[0],popt1[1],popt1[2],popt1[3],gammaS=popt1[4]-perr1[4]/2.,offshell=offshell) if(thermogammaS1['n_B']!=0. and thermogammaS2['n_B']!=0.): snB1_err += (thermogammaS1['s']/thermogammaS1['n_B']-thermogammaS2['s']/thermogammaS2['n_B'])**2. # error as sqrt((df/dT)**2. dT+(df/dmuB)**2.+...) with f = s/n_B snB1_err = np.sqrt(snB1_err) print(f's/n_B = {snB1} \pm {snB1_err}') # evaluate the chi^2 values for each parameter if(chi2_plot): dT, fT = m.profile('T') dmuB, fmuB = m.profile('muB') dmuQ, fmuQ = m.profile('muQ') dmuS, fmuS = m.profile('muS') dgammaS, fgammaS = m.profile('gammaS') ddVdy, fdVdy = m.profile('dVdy') output_chi21 = [[dT,fT],[dmuB,fmuB],[dmuQ,fmuQ],[dmuS,fmuS],[dgammaS,fgammaS],[ddVdy,fdVdy]] else: output_chi21 = None output_yields = {'fit_yields':np.array(list(zip(popt1,perr1))),\ 'fit_string_yields':fit_string1,\ 'result_yields':f_yields(xyields,*popt1),\ 'data_yields':np.array(list(zip(data_yields,err_yields))),\ 'particle_yields':list(latex(final_part)),\ 'chi2_yields':output_chi21,\ 'snB_yields':np.array([snB1,snB1_err])} else: output_yields = {} # fit with yields # strangeness neutrality if((EoS=='all' or EoS=='nS0') and (method=='all' or method=='yields')): # x-values, just the indexes of ratios [1,2,...,N_particles] xyields = np.arange(len(final_part)) # initialize Minuit least_squares class least_squares = LeastSquares(xyields, data_yields, err_yields, f_yields_nS0) m = Minuit(least_squares, T=guess[0], muB=guess[1], gammaS=guess[4], dVdy=guess[5], limit_T=bounds[0],limit_muB=bounds[1],limit_gammaS=bounds[4],limit_dVdy=bounds[5], fix_T=fix_T,fix_muB=fix_muB,fix_gammaS=fix_gammaS,fix_dVdy=fix_dVdy) m.migrad() # finds minimum of least_squares function m.hesse() # computes errors #print(m.params) # minuit output # display values and errors popt1 = m.values.values() perr1 = m.errors.values() thermo = EoS_nS0(HRG,popt1[0],popt1[1],gammaS=popt1[2],offshell=offshell) print('\nfit from yields, nS0 EoS:') fit_string1 = f'$T_{{ch}}={popt1[0]:.4f} \pm {perr1[0]:.4f}\ GeV$\ \n$\mu_{{B}}={popt1[1]:.4f} \pm {perr1[1]:.4f}\ GeV$\ \n$\gamma_{{S}}={popt1[2]:.2f} \pm {perr1[2]:.2f}$\ \n$dV/dy={popt1[3]:.1f} \pm {perr1[3]:.1f} \ fm^3$\ \n$\mu_{{Q}}={thermo["muQ"]:.4f}\ GeV$\ \n$\mu_{{S}}={thermo["muS"]:.4f}\ GeV$' print(fit_string1) snB1 = thermo['s']/thermo['n_B'] snB1_err = 0. # derivative wrt T thermoT1 = EoS_nS0(HRG,popt1[0]+perr1[0]/2.,popt1[1],gammaS=popt1[2],offshell=offshell) thermoT2 = EoS_nS0(HRG,popt1[0]-perr1[0]/2.,popt1[1],gammaS=popt1[2],offshell=offshell) if(thermoT1['n_B']!=0. and thermoT2['n_B']!=0.): snB1_err += (thermoT1['s']/thermoT1['n_B']-thermoT2['s']/thermoT2['n_B'])**2. # derivative wrt mu_B thermomuB1 = EoS_nS0(HRG,popt1[0],popt1[1]+perr1[1]/2.,gammaS=popt1[2],offshell=offshell) thermomuB2 = EoS_nS0(HRG,popt1[0],popt1[1]-perr1[1]/2.,gammaS=popt1[2],offshell=offshell) if(thermomuB1['n_B']!=0. and thermomuB2['n_B']!=0.): snB1_err += (thermomuB1['s']/thermomuB1['n_B']-thermomuB2['s']/thermomuB2['n_B'])**2. # derivative wrt gamma_S thermogammaS1 = EoS_nS0(HRG,popt1[0],popt1[1],gammaS=popt1[2]+perr1[2]/2.,offshell=offshell) thermogammaS2 = EoS_nS0(HRG,popt1[0],popt1[1],gammaS=popt1[2]-perr1[2]/2.,offshell=offshell) if(thermogammaS1['n_B']!=0. and thermogammaS2['n_B']!=0.): snB1_err += (thermogammaS1['s']/thermogammaS1['n_B']-thermogammaS2['s']/thermogammaS2['n_B'])**2. # error as sqrt((df/dT)**2. dT+(df/dmuB)**2.+...) with f = s/n_B snB1_err = np.sqrt(snB1_err) print(f's/n_B = {snB1} \pm {snB1_err}') # evaluate the chi^2 values for each parameter if(chi2_plot): dT, fT = m.profile('T') dmuB, fmuB = m.profile('muB') dgammaS, fgammaS = m.profile('gammaS') ddVdy, fdVdy = m.profile('dVdy') output_chi21 = [[dT,fT],[dmuB,fmuB],[dgammaS,fgammaS],[ddVdy,fdVdy]] else: output_chi21 = None result_yields_nS0 = f_yields_nS0(xyields,*popt1) Tch,muB,gammaS,dVdy = popt1 Tch_err,muB_err,gammaS_err,dVdy_err = perr1 popt1 = np.array([Tch,muB,thermo['muQ'],thermo['muS'],gammaS,dVdy]) perr1 = np.array([Tch_err,muB_err,0.,0.,gammaS_err,dVdy_err]) output_yields_nS0 = {'fit_yields_nS0':np.array(list(zip(popt1,perr1))),\ 'fit_string_yields_nS0':fit_string1,\ 'result_yields_nS0':result_yields_nS0,\ 'data_yields':np.array(list(zip(data_yields,err_yields))),\ 'particle_yields':list(latex(final_part)),\ 'chi2_yields_nS0':output_chi21,\ 'snB_yields_nS0':np.array([snB1,snB1_err])} else: output_yields_nS0 = {} # fit with ratios if((EoS=='all' or EoS=='full') and (method=='all' or method=='ratios')): # x-values, just the indexes of ratios [1,2,...,N_ratios] xratios = np.arange(len(data_ratios)) # initialize Minuit least_squares class least_squares = LeastSquares(xratios, data_ratios, err_ratios, f_ratios) m = Minuit(least_squares, T=guess[0], muB=guess[1], muQ=guess[2], muS=guess[3], gammaS=guess[4], limit_T=bounds[0],limit_muB=bounds[1],limit_muQ=bounds[2],limit_muS=bounds[3],limit_gammaS=bounds[4], fix_T=fix_T,fix_muB=fix_muB,fix_muQ=fix_muQ,fix_muS=fix_muS,fix_gammaS=fix_gammaS) m.migrad() # finds minimum of least_squares function m.hesse() # computes errors #print(m.params) # minuit output # display values and errors popt2 = m.values.values() perr2 = m.errors.values() print('\nfit from ratios, full EoS:') fit_string2 = f'$T_{{ch}}={popt2[0]:.4f} \pm {perr2[0]:.4f}\ GeV$\ \n$\mu_{{B}}={popt2[1]:.4f} \pm {perr2[1]:.4f}\ GeV$\ \n$\mu_{{Q}}={popt2[2]:.4f} \pm {perr2[2]:.4f}\ GeV$\ \n$\mu_{{S}}={popt2[3]:.4f} \pm {perr2[3]:.4f}\ GeV$\ \n$\gamma_{{S}}={popt2[4]:.2f} \pm {perr2[4]:.2f}$' print(fit_string2) thermo = HRG(popt2[0],popt2[1],popt2[2],popt2[3],gammaS=popt2[4],offshell=offshell) snB2 = thermo['s']/thermo['n_B'] snB2_err = 0. # derivative wrt T thermoT1 = HRG(popt2[0]+perr2[0]/2.,popt2[1],popt2[2],popt2[3],gammaS=popt2[4],offshell=offshell) thermoT2 = HRG(popt2[0]-perr2[0]/2.,popt2[1],popt2[2],popt2[3],gammaS=popt2[4],offshell=offshell) if(thermoT1['n_B']!=0. and thermoT2['n_B']!=0.): snB2_err += (thermoT1['s']/thermoT1['n_B']-thermoT2['s']/thermoT2['n_B'])**2. # derivative wrt mu_B thermomuB1 = HRG(popt2[0],popt2[1]+perr2[1]/2.,popt2[2],popt2[3],gammaS=popt2[4],offshell=offshell) thermomuB2 = HRG(popt2[0],popt2[1]-perr2[1]/2.,popt2[2],popt2[3],gammaS=popt2[4],offshell=offshell) if(thermomuB1['n_B']!=0. and thermomuB2['n_B']!=0.): snB2_err += (thermomuB1['s']/thermomuB1['n_B']-thermomuB2['s']/thermomuB2['n_B'])**2. # derivative wrt mu_Q thermomuQ1 = HRG(popt2[0],popt2[1],popt2[2]+perr2[2]/2.,popt2[3],gammaS=popt2[4],offshell=offshell) thermomuQ2 = HRG(popt2[0],popt2[1],popt2[2]-perr2[2]/2.,popt2[3],gammaS=popt2[4],offshell=offshell) if(thermomuQ1['n_B']!=0. and thermomuQ2['n_B']!=0.): snB2_err += (thermomuQ1['s']/thermomuQ1['n_B']-thermomuQ2['s']/thermomuQ2['n_B'])**2. # derivative wrt mu_S thermomuS1 = HRG(popt2[0],popt2[1],popt2[2],popt2[3]+perr2[3]/2.,gammaS=popt2[4],offshell=offshell) thermomuS2 = HRG(popt2[0],popt2[1],popt2[2],popt2[3]-perr2[3]/2.,gammaS=popt2[4],offshell=offshell) if(thermomuS1['n_B']!=0. and thermomuS2['n_B']!=0.): snB2_err += (thermomuS1['s']/thermomuS1['n_B']-thermomuS2['s']/thermomuS2['n_B'])**2. # derivative wrt gamma_S thermogammaS1 = HRG(popt2[0],popt2[1],popt2[2],popt2[3],gammaS=popt2[4]+perr2[4]/2.,offshell=offshell) thermogammaS2 = HRG(popt2[0],popt2[1],popt2[2],popt2[3],gammaS=popt2[4]-perr2[4]/2.,offshell=offshell) if(thermogammaS1['n_B']!=0. and thermogammaS2['n_B']!=0.): snB2_err += (thermogammaS1['s']/thermogammaS1['n_B']-thermogammaS2['s']/thermogammaS2['n_B'])**2. # error as sqrt((df/dT)**2. dT+(df/dmuB)**2.+...) with f = s/n_B snB2_err = np.sqrt(snB2_err) print(f's/n_B = {snB2} \pm {snB2_err}') # evaluate the chi^2 values for each parameter if(chi2_plot): dT, fT = m.profile('T') dmuB, fmuB = m.profile('muB') dmuQ, fmuQ = m.profile('muQ') dmuS, fmuS = m.profile('muS') dgammaS, fgammaS = m.profile('gammaS') output_chi22 = [[dT,fT],[dmuB,fmuB],[dmuQ,fmuQ],[dmuS,fmuS],[dgammaS,fgammaS]] else: output_chi22 = None output_ratios = {'fit_ratios':np.array(list(zip(popt2,perr2))),\ 'fit_string_ratios':fit_string2,\ 'result_ratios':f_ratios(xratios,*popt2),\ 'data_ratios':np.array(list(zip(data_ratios,err_ratios))),\ 'particle_ratios':list(zip(latex(final_part1),latex(final_part2))),\ 'chi2_ratios':output_chi22,\ 'snB_ratios':np.array([snB2,snB2_err])} else: output_ratios = {} # fit with ratios if((EoS=='all' or EoS=='nS0') and (method=='all' or method=='ratios')): # x-values, just the indexes of ratios [1,2,...,N_ratios] xratios = np.arange(len(data_ratios)) # initialize Minuit least_squares class least_squares = LeastSquares(xratios, data_ratios, err_ratios, f_ratios_nS0) m = Minuit(least_squares, T=guess[0], muB=guess[1], gammaS=guess[4], limit_T=bounds[0],limit_muB=bounds[1],limit_gammaS=bounds[4], fix_T=fix_T,fix_muB=fix_muB,fix_gammaS=fix_gammaS) m.migrad() # finds minimum of least_squares function m.hesse() # computes errors #print(m.params) # minuit output # display values and errors popt2 = m.values.values() perr2 = m.errors.values() thermo = EoS_nS0(HRG,popt2[0],popt2[1],gammaS=popt2[2],offshell=offshell) print('\nfit from ratios, nS0 EoS:') fit_string2 = f'$T_{{ch}}={popt2[0]:.4f} \pm {perr2[0]:.4f}\ GeV$\ \n$\mu_{{B}}={popt2[1]:.4f} \pm {perr2[1]:.4f}\ GeV$\ \n$\gamma_{{S}}={popt2[2]:.2f} \pm {perr2[2]:.2f}$\ \n$\mu_{{Q}}={thermo["muQ"]:.4f}\ GeV$\ \n$\mu_{{S}}={thermo["muS"]:.4f}\ GeV$' print(fit_string2) snB2 = thermo['s']/thermo['n_B'] snB2_err = 0. # derivative wrt T thermoT1 = EoS_nS0(HRG,popt2[0]+perr2[0]/2.,popt2[1],gammaS=popt2[2],offshell=offshell) thermoT2 = EoS_nS0(HRG,popt2[0]-perr2[0]/2.,popt2[1],gammaS=popt2[2],offshell=offshell) if(thermoT1['n_B']!=0. and thermoT2['n_B']!=0.): snB2_err += (thermoT1['s']/thermoT1['n_B']-thermoT2['s']/thermoT2['n_B'])**2. # derivative wrt mu_B thermomuB1 = EoS_nS0(HRG,popt2[0],popt2[1]+perr2[1]/2.,gammaS=popt2[2],offshell=offshell) thermomuB2 = EoS_nS0(HRG,popt2[0],popt2[1]-perr2[1]/2.,gammaS=popt2[2],offshell=offshell) if(thermomuB1['n_B']!=0. and thermomuB2['n_B']!=0.): snB2_err += (thermomuB1['s']/thermomuB1['n_B']-thermomuB2['s']/thermomuB2['n_B'])**2. # derivative wrt gamma_S thermogammaS1 = EoS_nS0(HRG,popt2[0],popt2[1],gammaS=popt2[2]+perr2[2]/2.,offshell=offshell) thermogammaS2 = EoS_nS0(HRG,popt2[0],popt2[1],gammaS=popt2[2]-perr2[2]/2.,offshell=offshell) if(thermogammaS1['n_B']!=0. and thermogammaS2['n_B']!=0.): snB2_err += (thermogammaS1['s']/thermogammaS1['n_B']-thermogammaS2['s']/thermogammaS2['n_B'])**2. # error as sqrt((df/dT)**2. dT+(df/dmuB)**2.+...) with f = s/n_B snB2_err = np.sqrt(snB2_err) print(f's/n_B = {snB2} \pm {snB2_err}') # evaluate the chi^2 values for each parameter if(chi2_plot): dT, fT = m.profile('T') dmuB, fmuB = m.profile('muB') dgammaS, fgammaS = m.profile('gammaS') output_chi22 = [[dT,fT],[dmuB,fmuB],[dgammaS,fgammaS]] else: output_chi22 = None result_ratios_nS0 = f_ratios_nS0(xratios,*popt2) Tch,muB,gammaS = popt2 Tch_err,muB_err,gammaS_err = perr2 popt2 = np.array([Tch,muB,thermo['muQ'],thermo['muS'],gammaS]) perr2 = np.array([Tch_err,muB_err,0.,0.,gammaS_err]) output_ratios_nS0 = {'fit_ratios_nS0':np.array(list(zip(popt2,perr2))),\ 'fit_string_ratios_nS0':fit_string2,\ 'result_ratios_nS0':result_ratios_nS0,\ 'data_ratios':np.array(list(zip(data_ratios,err_ratios))),\ 'particle_ratios':list(zip(latex(final_part1),latex(final_part2))),\ 'chi2_ratios_nS0':output_chi22,\ 'snB_ratios_nS0':np.array([snB2,snB2_err])} else: output_ratios_nS0 = {} output = {} output.update(output_yields) output.update(output_ratios) output.update(output_yields_nS0) output.update(output_ratios_nS0) return output
cache = [] # initilize model model = Quarks(boundary_type=boundary_type) chi_squared_threshold = 10. N = 100 # number of trials x = np.array([None]) # 2-step optimization process # fit masses then fit full for i in tqdm(range(N)): # Step 1: fitting the masses only params = model.generate_random_inputs(c_min=1., c_max=5.) least_squares = LeastSquares(x, model.output_values[:, :6], model.output_errors[:, :6], model.get_output_masses) optimizer = Minuit(least_squares, params, name=model.input_names) optimizer.limits = model.input_limits optimizer.fixed[:36] = True try: optimizer.migrad() optimizer.hesse() except ValueError: pass # Step 2: fitting all at once # Only run if step 1 is error-free if optimizer.fval: params_2 = np.array(optimizer.values) # feed forward y_2 = model.get_output_full(x, params_2)
def test_LeastSquares_mask(): c = LeastSquares([1, 2, 3], [3, np.nan, 4], [1, 1, 1], lambda x, a: x + a) assert np.isnan(c(0)) == True c.mask = np.arange(3) != 1 assert np.isnan(c(0)) == False
# elif whatDetector == 'Back': # ax1 = P_DBACK.plot(kind='scatter', y ='gammaxpos', x='Back_Counts', label = 'phot',color='b') # elif whatDetector == 'Difference': # ax1 = P_DDIFF.plot(kind='scatter', y ='gammaxpos', x='Difference_Counts', label = 'phot',color='b') # elif whatDetector == 'Aug': # ax1 = P_DAUG.plot(kind='scatter', y ='gammaxpos', x='Augmented_Difference_Counts', label = 'phot',color='b') P_DDIFF = P_DDIFF.dropna() doiListPhot = P_DDIFF.gammaxpos.tolist() differenceCountsPhot = P_DDIFF.Difference_Counts.tolist() DATA_DIFFERENCE = DATA_DIFFERENCE.dropna() doiList = DATA_DIFFERENCE.gammaxpos.tolist() differenceCounts = DATA_DIFFERENCE.Difference_Counts.tolist() m = Minuit(LeastSquares(differenceCountsPhot, doiListPhot, 10.0, Line), m=-500, b=3000) m.migrad() m.hesse() # print(m.values) # x = range(int(min(differenceCounts)), int(max(differenceCounts))) # y = [Line(k, *m.values[0:2]) for k in x] # ax1.plot(x, y, color = 'k') # C = pd.DataFrame(eid_c) # if not C.empty: # C.columns = ['EventID'] # C_DFRONT = pd.merge(C,DATA_FRONT, on='EventID') # C_DBACK = pd.merge(C,DATA_BACK, on='EventID') # C_DDIFF = pd.merge(C,DATA_DIFFERENCE, on='EventID') # C_DDIFF = pd.merge(C,DATA_DIFFERENCE, on='EventID')
dppLg = np.zeros_like(dppHg) pedestalLg = np.zeros_like(pedestalHg) if GUI: fig, ax = plt.subplots() for r in range(row): for c in range(col): channelHgPe = matrixHg[r, c, :] channelLgADC = matrixLg[r, c, :] x = channelHgPe[(channelHgPe > INF) & (channelHgPe < SUP)] y = channelLgADC[(channelHgPe > INF) & (channelHgPe < SUP)] lsq = LeastSquares(x, y, np.ones_like(y), line) fit = Minuit(lsq, m=1, q=60) fit.migrad() fit.hesse() dppLg[r, c] = fit.values["m"] pedestalLg[r, c] = fit.values["q"] print( f"Channel {r} - {c} ADC/pe: {fit.values[0]:.2f} +/- {fit.errors[0]:.2f} Pedestal: {fit.values[1]:.2f} +/- {fit.errors[1]:.2f}" ) if GUI: xFit = np.arange(channelHgPe.min(), channelHgPe.max(), 0.1) yFit = line(xFit, *fit.values) par_b = np.random.multivariate_normal(fit.values, fit.covariance,