def coremeasurement(self): # needed_param.path+'/Shift_parameters/shift_param'+self.freq1name+'and'+self.freq2name+'.p','wb') xshifttemp = [] yshifttemp = [] #change the int round , do not forget, the name of the files changed after last update %'%1.2f' %(self.freq2) for i in xrange(0, len(needed_param.freq) - 1): if needed_param.freq[i + 1] < 0.5: self.freq2name = str('%1.0f' % (needed_param.freq[i + 1] * 1000)) self.freq2unit = 'MHz' else: self.freq2name = str('%1.2f' % (needed_param.freq[i + 1])) self.freq2unit = 'GHz' if needed_param.freq[i] < 0.5: self.freq1name = str('%1.0f' % (needed_param.freq[i] * 1000)) self.freq1unit = 'MHz' else: self.freq1name = str('%1.2f' % (needed_param.freq[i])) self.freq1unit = 'GHz' for filename in sorted( glob.glob('Shift_parameters/shift_param' + str(self.freq1name) + 'and' + str(self.freq2name) + '.p')): print filename res = open(filename, 'rb') pick = pickle.load(res) res.close() xshifttemp.append(pick[0]) yshifttemp.append(pick[1]) #self.noise.append(pick[2]) self.xshift = [] self.yshift = [] self.coreshift = [0.] self.coreshift2 = [0.] a = -1 for i in xrange(len(needed_param.freq) - 2, -1, -1): if i == len(needed_param.freq) - 2: #tempx2 = 0. + xshifttemp[i] tempx = -0.05 + xshifttemp[i] tempy = 0 + yshifttemp[i] else: tempx = self.xshift[a] + xshifttemp[i] tempy = self.yshift[a] + yshifttemp[i] self.xshift.append(tempx) self.yshift.append(tempy) self.coreshift2.append(np.sqrt(tempx**2 + tempy**2)) #self.coreshift2.append(np.sqrt(tempx2**2+tempy**2)) a = a + 1 self.coreshift2 = np.asarray(self.coreshift2) #self.coreshift2[len(self.coreshift2)-1] = 0.7 self.coreshift = self.coreshift2.copy() for i in xrange(len(self.coreshift) - 2, 0, -1): self.coreshift[i] = self.coreshift[i] - 0.05 res = open(needed_param.path + '/coreshiftValuesAll.p', 'wb') pickle.dump(self.coreshift, res) res.close() errCoreshift = np.asarray([0.1, 0.07, 0.05, 0.01])[::-1] errCoreshift = None n = len(needed_param.freq) freqs = needed_param.freq[0:n] #-1] self.freqs = freqs[::-1] chi2rcore = probfit.Chi2Regression(rcoreFunct, self.freqs, self.coreshift2, error=errCoreshift, weights=errCoreshift) try: PLFit = iminuit.Minuit(chi2rcore, A=1., kr=1.) PLFit.migrad() PLFit.hesse() print PLFit.values print PLFit.errors errCoreshift = np.asarray([0.1, 0.07, 0.05, 0.01])[::-1] plt.figure(1) plt.errorbar(self.freqs, self.coreshift, yerr=errCoreshift, marker='.', color='r', markersize=8, linestyle='', linewidth=2) #plt.errorbar(self.freqs,self.coreshift2,yerr=errCoreshift,marker='.',color='g',markersize=8,linestyle='',linewidth=2) xaxis = np.linspace(self.freqs[0] + 0.2 * self.freqs[0], self.freqs[n - 1] - 0.2 * self.freqs[n - 1], 1000) plt.plot(xaxis, rcoreFunct(xaxis, PLFit.values.get('A'), 1.), 'b--', label='kr=1') #plt.plot(xaxis,rcoreFunct(xaxis,PLFit.values.get('A'), 0.8),'g--',label='kr=0.8') plt.plot(xaxis, rcoreFunct(xaxis, PLFit.values.get('A'), PLFit.values.get('kr')), 'r-', label='kr= ' + str(('%1.2f' % (PLFit.values.get('kr'))))) ax = plt.gca() ax.minorticks_on() ax.tick_params('both', length=10, width=2, which='major') ax.tick_params('both', length=5, width=1, which='minor') ax.set_xticks(ticks=freqs) ax.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) plt.legend(loc='upper right', numpoints=1, frameon=True, handletextpad=0, markerscale=1, fontsize=12) plt.ylabel('offset [mas]') plt.xlabel(r'$\nu$ [GHz]') plt.ylim(-0.1, 0.8) #plt.xlim(0,30) plt.show() print PLFit.values.get('kr') except RuntimeError: print 'Covariance is not valid. May be the last Hesse call failed?' self.kr = PLFit.values.get('kr') self.krerr = PLFit.errors.get('kr') freqsv1v2 = [] itemp = [] for i in xrange(0, len(self.checksv1v2)): if self.checksv1v2[i].isChecked(): itemp.append(i) freqsv1v2.append(needed_param.freq[i]) self.freqv1 = freqsv1v2[0] self.freqv2 = freqsv1v2[1] self.DLvalue = float(self.DL.text()) self.zvalue = float(self.z.text()) self.scalevalue = float(self.scale.text()) if self.approx.isChecked(): self.csMeas = CoreShiftMeasure(self.coreshift2[::-1][itemp[0]], self.freqv1, self.freqv2, 1., self.zvalue, self.DLvalue) if self.noapprox.isChecked(): self.csMeas = CoreShiftMeasure(self.coreshift2[::-1][itemp[0]], self.freqv1, self.freqv2, self.kr, self.zvalue, self.DLvalue) self.krscreen.setText(("%s " % ('%1.3f' % (self.kr)))) self.krerrscreen.setText((u" \u00b1 %s" % ('%1.3f' % (self.krerr)))) self.csmeasscreen.setText( (u"%s \u00b1 %s" % ('%1.3f' % (self.csMeas), '%1.3f' % (self.krerr))))
def remake_arrays(input_arr_): w_r_bins = 0.01 # need z-binning corresponding to 1 roc w_z_bins = 52 # # of pixels in a roc n_z_bins = int(3328 / w_z_bins) # 3328 is number of pixels in a ladder row inner_array = np.array([row for row in input_arr_ if not np.all(row==None)]) cleaned_array = np.array([[x if x is not None else [0, np.nan, np.nan, np.nan] for x in row] for row in inner_array]) r_min = np.nanmin(cleaned_array[:, :, 1]) r_max = np.nanmax(cleaned_array[:, :, 1]) n_r_bins = int((r_max - r_min) / w_r_bins) array_by_rocs = np.array([cleaned_array[:, i*w_z_bins:(i+1)*w_z_bins] for i in range(n_z_bins)]) #roc_index = [0, 1] roc_index = range(0, n_z_bins) # fig, axs = plt.subplots(8, 8, sharex=False, sharey=False, figsize=(160, 160), tight_layout=True) #all rocs and modules fig, axs = plt.subplots(1, sharex=True, sharey=True, figsize=(20, 20), tight_layout=True) # fraction of rocs and modules x, y = 0, 0 occ = [] r_sph = [] z_array = [] phi_array = [] for roc in roc_index: true_roc = roc_map(roc) # if 23 < roc < 40: continue # if true_roc == 7: continue # if true_roc == 15: continue # if true_roc == 23: continue # if true_roc == 39: continue # if true_roc == 47: continue # if true_roc == 55: continue occ_tmp = np.concatenate(array_by_rocs[roc, :, :, 0]) r = np.concatenate(array_by_rocs[roc, :, :, 1]) phi = np.concatenate(array_by_rocs[roc, :, :, 2]) z = np.concatenate(array_by_rocs[roc, :, :, 3]) z_avg = np.nanmean(z) r_sph_tmp = np.sqrt(r**2 + z**2) z_array.append(np.average(z[~np.isnan(r_sph_tmp)], weights=occ_tmp[~np.isnan(r_sph_tmp)])) phi_array.append(np.average(phi[~np.isnan(r_sph_tmp)], weights=occ_tmp[~np.isnan(r_sph_tmp)])) r_sph.append(np.average(r_sph_tmp[~np.isnan(r_sph_tmp)], weights=occ_tmp[~np.isnan(r_sph_tmp)])) occ.append(np.nansum(occ_tmp)) z_array = np.array(z_array) phi_array = np.array(phi_array) r_sph = np.array(r_sph) occ = np.array(occ) sort = np.argsort(r_sph) z_array = z_array[sort] phi_array = phi_array[sort] r_sph = r_sph[sort] occ = occ[sort] # for roc selection # removing outermost and innermost rocs remove_z = (z_array > -25) * (z_array < 25) #remove_z = ((z_array > 1) + (z_array < -1)) * (z_array > -25) * (z_array < 25) #remove_z = (z_array > -22) * (z_array < 22) #remove_z *= (z_array < 14) + (z_array > 20) #remove_z *= (z_array > -14) + (z_array < -20) # remove_z = ((z_array > 11.5) + z_array < 8.5)) * (z_array > -25) * (z_array < 25) # remove_z = ((z_array > -8.5) + (z_array < -11.5)) * (z_array > -25) * (z_array < 25) remove_blips = (z_array < -21) + (z_array > -20) remove_blips *= (z_array < -14.5) + (z_array > -13.5) remove_blips *= (z_array < -7.5) + (z_array > -6.5) remove_blips *= (z_array < -1) + (z_array > 1) remove_blips *= (z_array < 5.75) + (z_array > 6.5) remove_blips *= (z_array < 12.5) + (z_array > 13.5) remove_blips *= (z_array < 19) + (z_array > 20) remove_hl = (phi_array < -2.3) + (phi_array > -2) remove_hl *= (phi_array < -1.3) + (phi_array > -1) remove_hl *= (phi_array < -0.25) + (phi_array > 0) remove_hl *= (phi_array < 0.8) + (phi_array > 1.1) remove_hl *= (phi_array < 1.8) + (phi_array > 2.2) remove_hl *= (phi_array < 2.4) + (phi_array > 2.7) #remove_hl = (phi_array > -2.3) * (phi_array < -2) #remove_hl += (phi_array > -1.3) * (phi_array < -1) #remove_hl += (phi_array > -0.25) * (phi_array < 0) #remove_hl += (phi_array > 0.8) * (phi_array < 1.1) #remove_hl += (phi_array > 1.8) * (phi_array < 2.2) #remove_hl += (phi_array > 2.4) * (phi_array < 2.7) #z_array = z_array[remove_z*remove_blips*remove_hl] #r_sph = r_sph[remove_z*remove_blips*remove_hl] #occ = occ[remove_z*remove_blips*remove_hl] z_array = z_array[remove_z*remove_blips] r_sph = r_sph[remove_z*remove_blips] occ = occ[remove_z*remove_blips] # removing rocs at the edge of the modules #mask = np.array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], dtype=bool) #r_sph = r_sph[mask] #occ = occ[mask] r_sph_condense = [] occ_condense = [] for ir, r in enumerate(r_sph): if ir % 2 == 0: r_sph_condense.append((r+r_sph[ir+1])/2) occ_condense.append(occ[ir]+occ[ir+1]) #r_sph_condense.append(r) #occ_condense.append(occ[ir]) else: continue occ_z = occ r_sph = np.array(r_sph_condense) occ = np.array(occ_condense) #axs.plot(r_sph, occ, 'b*', label='all z') axs.plot(z_array, occ_z, 'b*', label='all z') #bin_centers = np.array([(bins[i] + bins[i+1]) / 2. for i, b in enumerate(bins) if b != bins[-1]]) # bin_chi2 = pf.costfunc.BinnedChi2(func, np.concatenate(r), weights=np.concatenate(occ), # bins=n_r_bins, bound=(r_min_roc, r_max_roc)) #def chi2(a, b, c, d, e, f): # func_array = (func(r_sph, z_array, a, b, c, d, e, f) - occ)**2 # return np.sum(func_array) chi2 = pf.Chi2Regression(func, z_array, occ_z) minuit = im.Minuit(chi2, a=10000, b=2, c=20000, ga=-10000, gb=-0.015, gc=1, error_a=0.01, error_b=0.01, error_c=0.1, error_ga=0.01, error_gb=0.01, error_gc=0.01, fix_b=False, limit_a=(None, None), limit_b=(None, None), limit_c=(None, None), limit_ga=(None, None), limit_gb=(None, None), limit_gc=(0.00001, None), errordef=1) #minuit = im.Minuit(chi2, a=10000, b=2, c=20000, ga=-10000, gb=-0.015, gc=1, # error_a=0.01, error_b=0.01, error_c=0.1, error_ga=0.01, error_gb=0.01, error_gc=0.01, # fix_b=False, # limit_a=(None, None), limit_b=(None, None), limit_c=(None, None), limit_ga=(None, None), # limit_gb=(None, None), limit_gc=(0.00001, None), # errordef=1) #minuit = im.Minuit(chi2, a=2300000, b=2, c=20000, # error_a=1, error_b=0.01, error_c=1, # fix_b=False, # limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), # errordef=1) minuit.migrad() print(minuit.get_param_states()) print(minuit.get_fmin()) chi2.draw(minuit, axs) param_string = '' #for p in minuit.parameters: # param_string += '{}: {} +/- {}\n'.format(p, np.format_float_scientific(minuit.values[p], precision=3), # np.format_float_scientific(minuit.errors[p], precision=1)) #axs.text(15, 5000, param_string, fontsize='xx-small') #axs.plot(r_sph, func(r_sph, z_array, *minuit.values.values()), color='red', label='fit') axs.legend() plt.show()
def plotAeffVsAngle(files, comparison=False, save=False, doFit=False, rcir=None): energy, aeff, ang, aeff_eres, aeff_eres_modfrac = getAeff(files, 10000., rcir, sortAngle=True) #print ang angle = [] for i in range(len(ang)): angle.append(round(numpy.degrees(numpy.arccos(ang[i])))) aeff_err = [x * 0.01 for x in aeff] if doFit: #print iminuit.describe(cosFun) #print angle chi2 = probfit.Chi2Regression(cosFun, numpy.asarray(angle), numpy.asarray(aeff), numpy.asarray(aeff_err)) #print iminuit.describe(chi2) minuit = iminuit.Minuit(chi2, a=80., b=1., error_a=1, error_b=0.01, limit_a=(60., 100.), limit_b=(0.2, 1.0)) minuit.migrad() print(minuit.values) print(minuit.errors) ((data_edges, datay), err, (total_pdf_x, total_pdf_y), parts) = chi2.draw(minuit) if not doFit: chi2Cos = probfit.Chi2Regression(cosNorm, numpy.asarray(angle), numpy.asarray(aeff), numpy.asarray(aeff_err)) minuitCos = iminuit.Minuit(chi2Cos, a=80., error_a=1, limit_a=(60., 100.)) minuitCos.migrad() print(minuitCos.values) print(minuitCos.errors) ((data_edges_cos, datay_cos), err_cos, (total_pdf_x_cos, total_pdf_y_cos), parts_cos) = chi2Cos.draw(minuitCos) plot.figure(figsize=(8, 6)) #plot.errorbar(angle, aeff, yerr=aeff_err, color='black',fmt='o',label='BurstCube') plot.errorbar(angle, aeff, yerr=aeff_err, color='black', fmt='o') if comparison: energy2, aeff2, ang2, aeff_eres2, aeff_eres_modfrac2 = getAeff( 'sim/thin/FarFieldPointSource_100.000keV_Cos*.sim', 10000., rcir) angle2 = [] for i in range(len(ang2)): angle2.append(round(numpy.degrees(numpy.arccos(ang2[i])))) aeff_err2 = [x * 0.01 for x in aeff2] #plot.scatter(angle2, aeff2, color='blue', label='thin') #plot.errorbar(angle2, aeff2, yerr=aeff_err2, color='blue',fmt='o',label='thin') plot.errorbar(angle2, aeff2, yerr=aeff_err2, color='blue', fmt='o') if doFit: chi2_thin = probfit.Chi2Regression(cosFun, numpy.asarray(angle2), numpy.asarray(aeff2), numpy.asarray(aeff_err2)) minuit_thin = iminuit.Minuit(chi2_thin, a=80., b=1., error_a=1, error_b=0.01, limit_a=(60., 100.), limit_b=(0.2, 1.0)) minuit_thin.migrad() print(minuit_thin.values) print(minuit_thin.errors) ((data_edges_thin, datay_thin), err_thin, (total_pdf_x_thin, total_pdf_y_thin), parts_thin) = chi2.draw(minuit_thin) energy3, aeff3, ang3, aeff_eres3, aeff_eres_modfrac3 = getAeff( 'sim/thick/FarFieldPointSource_100.000keV_Cos*.sim', 10000., rcir) angle3 = [] for i in range(len(ang3)): angle3.append(round(numpy.degrees(numpy.arccos(ang2[i])))) aeff_err3 = [x * 0.01 for x in aeff3] #plot.scatter(angle3, aeff3, color='red', label='thick') #plot.errorbar(angle3, aeff3, yerr=aeff_err3, color='red',fmt='o',label='thick') plot.errorbar(angle3, aeff3, yerr=aeff_err3, color='red', fmt='o') if doFit: chi2_thick = probfit.Chi2Regression(cosFun, numpy.asarray(angle3), numpy.asarray(aeff3), numpy.asarray(aeff_err3)) minuit_thick = iminuit.Minuit(chi2_thick, a=80., b=1., error_a=1, error_b=0.01, limit_a=(60., 100.), limit_b=(0.2, 1.0)) minuit_thick.migrad() print(minuit_thick.values) print(minuit_thick.errors) ((data_edges_thick, datay_thick), err_thick, (total_pdf_x_thick, total_pdf_y_thick), parts_thick) = chi2.draw(minuit_thick) if doFit: plot.figure(figsize=(8, 6)) plot.errorbar(angle, aeff, yerr=aeff_err, color='black', fmt='o') function = r"Nominal fit: %.1f * cos($\theta$)$^{%.2f}$" % ( minuit.values['a'], minuit.values['b']) plot.plot(total_pdf_x, total_pdf_y, color='black', lw=2, label=function) if comparison: plot.errorbar(angle2, aeff2, yerr=aeff_err2, color='blue', fmt='o') function2 = r"Thin fit: %.1f * cos($\theta$)$^{%.2f}$" % ( minuit_thin.values['a'], minuit_thin.values['b']) plot.plot(total_pdf_x_thin, total_pdf_y_thin, color='blue', lw=2, label=function2) plot.errorbar(angle3, aeff3, yerr=aeff_err3, color='red', fmt='o') function3 = r"Thick fit: %.1f * cos($\theta$)$^{%.2f}$" % ( minuit_thick.values['a'], minuit_thick.values['b']) plot.plot(total_pdf_x_thick, total_pdf_y_thick, color='red', lw=2, label=function3) plot.gca().set_xlim([0., 80.]) plot.xlabel('Incident Angle (deg)', fontsize=16) plot.gca().set_ylim([20., 100.]) plot.ylabel('Effective Area (cm$^2$)', fontsize=16) legend = plot.legend(loc='lower center', scatterpoints=1, prop={'size': 16}, frameon=False) plot.grid(True) if save: plot.savefig('EffectiveArea_vs_Ang.png') plot.savefig('EffectiveArea_vs_Ang.pdf') plot.show()
def remake_arrays(input_arr_): w_r_bins = 0.01 # need z-binning corresponding to 1 roc w_z_bins = 52 # # of pixels in a roc # need phi-binning corresponding to 1 roc (maybe 2?) w_phi_bins = 80 n_z_bins = int(3328 / w_z_bins) # 3328 is number of pixels in a ladder row n_phi_bins = int( 960 / w_phi_bins ) # 1440 is number of pixels around phi for all ladders, 960 for inner ladders #n_phi_bins = int(1440 / w_phi_bins) # 1440 is number of pixels around phi for all ladders, 960 for inner ladders inner_array = np.array( [row for row in input_arr_ if not np.all(row == None)]) cleaned_array = np.array( [[x if x is not None else [0, np.nan, np.nan, np.nan] for x in row] for row in inner_array]) r_min = np.nanmin(cleaned_array[:, :, 1]) r_max = np.nanmax(cleaned_array[:, :, 1]) # separate pixels into groups corresponding to rocs in phi and z array_by_rocs = np.array([ cleaned_array[j * w_phi_bins:(j + 1) * w_phi_bins, i * w_z_bins:(i + 1) * w_z_bins] for i in range(n_z_bins) for j in range(n_phi_bins) ]) #roc_index = [0, 1] roc_index = range(0, n_z_bins * n_phi_bins) # fig, axs = plt.subplots(8, 8, sharex=False, sharey=False, figsize=(160, 160), tight_layout=True) #all rocs and modules #fig, axs = plt.subplots(12, 2, sharex=True, sharey=True, figsize=(20, 20), tight_layout=False) # fraction of rocs and modules fig, axs = plt.subplots(12, sharex=True, sharey=True, figsize=(20, 20), tight_layout=False) # fraction of rocs and modules #fig, axs = plt.subplots(3, sharex=True, sharey=True, figsize=(20, 20), tight_layout=True) # fraction of rocs and modules # minus - 0-383 # plus - 384-767 occ_plus = [] occ_minus = [] r_sph_plus = [] r_sph_minus = [] phi_plus = [] phi_minus = [] z_plus = [] z_minus = [] # section off rocs into roc ladders (12 'ladders'), each true ladder is split in half 6 * 2 = 12 n_ladders = 12 for x in range(n_ladders): occ_plus.append([]) occ_minus.append([]) r_sph_plus.append([]) r_sph_minus.append([]) phi_plus.append([]) phi_minus.append([]) z_plus.append([]) z_minus.append([]) i_ladder = 0 for roc in roc_index: occ_tmp = np.concatenate(array_by_rocs[roc, :, :, 0]) r = np.concatenate(array_by_rocs[roc, :, :, 1]) phi = np.concatenate(array_by_rocs[roc, :, :, 2]) z = np.concatenate(array_by_rocs[roc, :, :, 3]) z_avg = np.nanmean(z) r_sph_tmp = np.sqrt(r**2 + z**2) r_sph_minus[i_ladder].append(np.nanmean(r_sph_tmp)) occ_minus[i_ladder].append(np.sum(occ_tmp[~np.isnan(occ_tmp)])) phi_minus[i_ladder].append(np.nanmean(phi)) z_minus[i_ladder].append(np.nanmean(z)) #if roc < 384: # r_sph_minus[i_ladder].append(np.nanmean(r_sph_tmp)) # occ_minus[i_ladder].append(np.sum(occ_tmp[~np.isnan(occ_tmp)])) # phi_minus[i_ladder].append(np.nanmean(phi)) # z_minus[i_ladder].append(np.nanmean(z)) #else: # r_sph_plus[i_ladder].append(np.nanmean(r_sph_tmp)) # occ_plus[i_ladder].append(np.sum(occ_tmp[~np.isnan(occ_tmp)])) # phi_plus[i_ladder].append(np.nanmean(phi)) # z_plus[i_ladder].append(np.nanmean(z)) i_ladder += 1 if i_ladder == n_ladders: i_ladder = 0 #avg_phi_plus = np.array([np.mean(iphi) for iphi in phi_plus]) avg_phi_minus = np.array([np.mean(iphi) for iphi in phi_minus]) #phi_sort_plus = np.argsort(avg_phi_plus) phi_sort_minus = np.argsort(avg_phi_minus) # sort ladders by phi #r_sph_plus_tmp = np.array(r_sph_plus) r_sph_minus_tmp = np.array(r_sph_minus) #occ_plus_tmp = np.array(occ_plus) occ_minus_tmp = np.array(occ_minus) #z_plus_tmp = np.array(z_plus) z_minus_tmp = np.array(z_minus) #r_sph_plus_tmp = r_sph_plus_tmp[phi_sort_plus] r_sph_minus_tmp = r_sph_minus_tmp[phi_sort_minus] #occ_plus_tmp = occ_plus_tmp[phi_sort_plus] occ_minus_tmp = occ_minus_tmp[phi_sort_minus] #z_plus_tmp = z_plus_tmp[phi_sort_plus] z_minus_tmp = z_minus_tmp[phi_sort_minus] #print(avg_phi_plus[phi_sort_plus]) print(avg_phi_minus[phi_sort_minus]) #n_ladders = 6 # for running over modules in a ring instead of rocs for x in range(n_ladders): #fig, axs = plt.subplots(3, sharex=True, sharey=True, figsize=(20, 20), # tight_layout=True) # fraction of rocs and modules r_sph_minus[x] = np.array(r_sph_minus_tmp[x]) occ_minus[x] = np.array(occ_minus_tmp[x]) z_minus[x] = np.array(z_minus_tmp[x]) sort_minus = np.argsort(r_sph_minus[x]) r_sph_minus[x] = r_sph_minus[x][sort_minus] occ_minus[x] = occ_minus[x][sort_minus] #r_sph_plus[x] = np.array(r_sph_plus_tmp[x]) #occ_plus[x] = np.array(occ_plus_tmp[x]) #z_plus[x] = np.array(z_plus_tmp[x]) #sort_plus = np.argsort(r_sph_plus[x]) #r_sph_plus[x] = r_sph_plus[x][sort_plus] #occ_plus[x] = occ_plus[x][sort_plus] #z_plus[x] = z_plus[x][sort_plus] # removing rocs remove_z = (z_minus[x] > -25) * (z_minus[x] < 25) remove_blips = (z_minus[x] < -21) + (z_minus[x] > -20) remove_blips *= (z_minus[x] < -14.5) + (z_minus[x] > -13.5) remove_blips *= (z_minus[x] < -7.5) + (z_minus[x] > -6.5) remove_blips *= (z_minus[x] < 5.75) + (z_minus[x] > 6.5) remove_blips *= (z_minus[x] < 12.5) + (z_minus[x] > 13.5) remove_blips *= (z_minus[x] < 19) + (z_minus[x] > 20) #r_sph_plus[x] = r_sph_plus[x][remove_z_plus*remove_blips_plus] r_sph_minus[x] = r_sph_minus[x][remove_z * remove_blips] #r_sph_minus[x] = r_sph_minus[x][remove_z_minus] #occ_plus[x] = occ_plus[x][remove_z_plus*remove_blips_plus] occ_minus[x] = occ_minus[x][remove_z * remove_blips] #occ_minus[x] = occ_minus[x][remove_z_minus] z_condense = [] r_sph_condense = [] occ_condense = [] for ir, r in enumerate(r_sph_minus[x]): if ir % 2 == 0 and ir + 1 < len(r_sph_minus[x]): r_sph_condense.append((r + r_sph_minus[x][ir + 1]) / 2) occ_condense.append(occ_minus[x][ir] + occ_minus[x][ir + 1]) z_condense.append((z_minus[x][ir] + z_minus[x][ir + 1]) / 2) else: continue r_sph_minus[x] = np.array(r_sph_condense) occ_minus[x] = np.array(occ_condense) z_minus[x] = np.array(z_condense) axs[x].plot(r_sph_minus[x], occ_minus[x], 'b*', label='full z hl ' + str(x)) #axs[x, 0].plot(r_sph_minus[x], occ_minus[x], 'b*', label='minus z - hl '+str(x)) #axs[x, 1].plot(r_sph_plus[x], occ_plus[x], 'b*', label='plus z - hl '+str(x)) #axs[0].plot(r_sph_minus[x], occ_minus[x], 'b*', label='minus z - hl '+str(x)) #axs[1].plot(r_sph_plus[x], occ_plus[x], 'b*', label='plus z - hl '+str(x)) #axs[2].plot(r_sph_minus[x], occ_minus[x], 'r*', label='occ minus') #axs[2].plot(r_sph_plus[x], occ_plus[x], 'b*', label='occ plus') chi2_minus = pf.Chi2Regression(func, r_sph_minus[x], occ_minus[x]) #chi2_plus = pf.Chi2Regression(func, r_sph_plus[x], occ_plus[x]) #minuit_minus = im.Minuit(chi2_minus, a=0, b=1.16, c=2000, # error_a=1, error_b=0.01, error_c=1, # fix_b=False, # limit_a=(None, None), limit_b=(None, None), limit_c=(None, None), # errordef=1) minuit_minus = im.Minuit(chi2_minus, a=200000, b=-0.4, c=2000, error_a=1, error_b=0.01, error_c=1, fix_b=False, limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), errordef=1) #minuit_minus = im.Minuit(chi2_minus, a=200000, b=0.5989, c=2000, r0=0, # error_a=1, error_b=0.01, error_c=1, error_r0=0.01, # fix_b=True, # limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), limit_r0=(None, None), # errordef=1) #minuit_plus = im.Minuit(chi2_plus, a=200000, b=0.5989, c=2000, r0=0, # error_a=1, error_b=0.01, error_c=1, error_r0=0.01, # fix_b=True, # limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), limit_r0=(None, None), # errordef=1) #print(minuit.get_param_states()) minuit_minus.migrad() #minuit_plus.migrad() #print(minuit_plus.get_param_states()) #print(minuit_plus.get_fmin()) print(minuit_minus.get_param_states()) print(minuit_minus.get_fmin()) # chi2_minus.draw(minuit_minus, axs[x, 0]) # chi2_plus.draw(minuit_plus, axs[x, 1]) # chi2_minus.draw(minuit_minus, axs[0]) # chi2_plus.draw(minuit_plus, axs[1]) param_string = '' for p in minuit_minus.parameters: param_string += '{}: {} +/- {}\n'.format( p, np.format_float_scientific(minuit_minus.values[p], precision=3), np.format_float_scientific(minuit_minus.errors[p], precision=1)) #axs[x, 0].text(15, 550000, param_string, fontsize='xx-small') #axs[x].text(7.5, 20000, param_string, fontsize='xx-small') axs[x].text(22, 6500, param_string, fontsize='xx-small') #param_string = '' #for p in minuit_plus.parameters: # param_string += '{}: {} +/- {}\n'.format(p, np.format_float_scientific(minuit_plus.values[p], precision=3), # np.format_float_scientific(minuit_plus.errors[p], precision=1)) #axs[x, 1].text(15, 550000, param_string, fontsize='xx-small') axs[x].plot(r_sph_minus[x], func(r_sph_minus[x], *minuit_minus.values.values()), color='red', label='fit') #axs[x, 0].plot(r_sph_minus[x], func(r_sph_minus[x], *minuit_minus.values.values()), color='red', label='fit minus') #axs[x, 1].plot(r_sph_plus[x], func(r_sph_plus[x], *minuit_plus.values.values()), color='red', linestyle='solid', label='fit plus') #axs[0].plot(r_sph_minus[x], func(r_sph_minus[x], *minuit_minus.values.values()), color='red', label='fit minus') #axs[1].plot(r_sph_plus[x], func(r_sph_plus[x], *minuit_plus.values.values()), color='red', linestyle='solid', label='fit plus') #axs[2].plot(r_sph_minus[x], func(r_sph_minus[x], *minuit_minus.values.values()), color='red', label='fit minus') #axs[2].plot(r_sph_plus[x], func(r_sph_plus[x], *minuit_plus.values.values()), color='blue', linestyle='dashed', label='fit plus') axs[x].legend(fontsize='xx-small', loc='upper right') #axs[x, 1].legend(fontsize='xx-small', loc='upper right') #axs[x, 0].legend(fontsize='xx-small', loc='upper right') #axs[2].legend() #axs[1].legend(fontsize='xx-small') #axs[0].legend(fontsize='xx-small') #axs[2].grid() #plt.savefig('plots_0_smear/fit_ladders_pm_'+str(x)+'_layer1.png') #plt.clf() plt.show()
ax = plt.gca() ax.minorticks_on() ax.tick_params('both', length=10, width=2, which='major') ax.tick_params('both', length=5, width=1, which='minor') ax.set_xticks(ticks=freqs) ax.get_xaxis().set_major_formatter(ticker.ScalarFormatter()) plt.ylabel('offset [mas]') plt.xlabel(r'$\nu$ [GHz]') plt.ylim(-0.15, 2) plt.xlim(0, 30) plt.savefig('coreshift.png') #plt.show() chi2rcore = probfit.Chi2Regression(rcoreFunct, freqs, coreshift, error=errCoreshift, weights=None) try: PLFit = iminuit.Minuit(chi2rcore, A=3., kr=1.) PLFit.migrad() PLFit.hesse() print PLFit.values print PLFit.errors plt.errorbar(freqs, coreshift,
# <codecell> # Let's define our line. # First argument has to be the independent variable, # arguments after that are shape parameters. def line(x, m, c): # define it to be parabolic or whatever you like return m * x + c # <codecell> iminuit.describe(line) # <codecell> # Define a chi^2 cost function chi2 = probfit.Chi2Regression(line, x, y, err) # <codecell> # Chi2Regression is just a callable object; nothing special about it iminuit.describe(chi2) # <codecell> # minimize it # yes, it gives you a heads up that you didn't give it initial value # we can ignore it for now minuit = iminuit.Minuit(chi2) # see iminuit tutorial on how to give initial value/range/error minuit.migrad(); # MIGRAD is a very stable robust minimization method # you can look at your terminal to see what it is doing;
extname='amp' + str(i)) # Sum those with the special iminut functions if PEAKS == 1: MODEL = peak0 if PEAKS == 2: MODEL = probfit.AddPdf(peak0, peak1) if PEAKS == 3: MODEL = probfit.AddPdf(peak0, peak1, peak2) if PEAKS == 4: MODEL = probfit.AddPdf(peak0, peak1, peak2, peak3) # STEP ONE : fit the first row (or only row) print('Fitting the first peak shape') # Setting up a chi2 function chi2 = probfit.Chi2Regression(MODEL, REF_M, RSLT[0], errs[0]) # Setting up dictionnary of initial values pars = dict() pars['cupwidth'] = cup_guess pars['sigma'] = sigma_guess for i in range(PEAKS): pars['amp' + str(i)] = abund_guess[i] pars['center' + str(i)] = mass_guess[i] pars['error_center' + str(i)] = 0.0001 pars['error_amp' + str(i)] = 0.001 pars['error_cupwidth'] = 0.001 pars['error_sigma'] = 0.001 print(abund_guess) m = iminuit.Minuit(chi2, **pars)
def remake_arrays(input_arr_): w_r_bins = 0.01 # need z-binning corresponding to 1 roc w_z_bins = 52 # # of pixels in a roc n_z_bins = int(3328 / w_z_bins) # 3328 is number of pixels in a ladder row inner_array = np.array([row for row in input_arr_ if not np.all(row==None)]) cleaned_array = np.array([[x if x is not None else [0, np.nan, np.nan, np.nan] for x in row] for row in inner_array]) r_min = np.nanmin(cleaned_array[:, :, 1]) r_max = np.nanmax(cleaned_array[:, :, 1]) n_r_bins = int((r_max - r_min) / w_r_bins) array_by_rocs = np.array([cleaned_array[:, i*w_z_bins:(i+1)*w_z_bins] for i in range(n_z_bins)]) #roc_index = [0, 1] roc_index = range(0, n_z_bins) # fig, axs = plt.subplots(8, 8, sharex=False, sharey=False, figsize=(160, 160), tight_layout=True) #all rocs and modules fig, axs = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(20, 20), tight_layout=True) # fraction of rocs and modules x, y = 0, 0 occ_plus = [] occ_minus = [] r_sph_plus = [] r_sph_minus = [] for roc in roc_index: occ_tmp = np.concatenate(array_by_rocs[roc, :, :, 0]) r = np.concatenate(array_by_rocs[roc, :, :, 1]) z = np.concatenate(array_by_rocs[roc, :, :, 3]) z_avg = np.nanmean(z) r_sph_tmp = np.sqrt(r**2 + z**2) if roc < 32: r_sph_minus.append(np.nanmean(r_sph_tmp)) occ_minus.append(np.nansum(occ_tmp)) else: r_sph_plus.append(np.nanmean(r_sph_tmp)) occ_plus.append(np.nansum(occ_tmp)) r_sph_minus = np.array(r_sph_minus) occ_minus = np.array(occ_minus) sort_minus = np.argsort(r_sph_minus) r_sph_minus = r_sph_minus[sort_minus] occ_minus = occ_minus[sort_minus] r_sph_plus = np.array(r_sph_plus) occ_plus = np.array(occ_plus) sort_plus = np.argsort(r_sph_plus) r_sph_plus = r_sph_plus[sort_plus] occ_plus = occ_plus[sort_plus] # removing rocs r_sph_plus = r_sph_plus[3:-2] occ_plus = occ_plus[3:-2] r_sph_minus = r_sph_minus[3:-2] occ_minus = occ_minus[3:-2] ## removing rocs at the edge of the modules #mask_plus = np.array([1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], dtype=bool) #r_sph_plus = r_sph_plus[mask_plus] #occ_plus = occ_plus[mask_plus] #mask_minus = np.array([1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], dtype=bool) #r_sph_minus = r_sph_minus[mask_minus] #occ_minus = occ_minus[mask_minus] axs[0].plot(r_sph_minus, occ_minus, 'b*', label='minus z') axs[1].plot(r_sph_plus, occ_plus, 'b*', label='plus z') axs[2].plot(r_sph_minus, occ_minus, 'r*', label='occ minus') axs[2].plot(r_sph_plus, occ_plus, 'b*', label='occ plus') #bin_centers = np.array([(bins[i] + bins[i+1]) / 2. for i, b in enumerate(bins) if b != bins[-1]]) # bin_chi2 = pf.costfunc.BinnedChi2(func, np.concatenate(r), weights=np.concatenate(occ), # bins=n_r_bins, bound=(r_min_roc, r_max_roc)) chi2_minus = pf.Chi2Regression(func, r_sph_minus, occ_minus) chi2_plus = pf.Chi2Regression(func, r_sph_plus, occ_plus) minuit_minus = im.Minuit(chi2_minus, a=2300000, b=2, c=20000, error_a=1, error_b=0.01, error_c=1, fix_b=False, limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), errordef=1) minuit_plus = im.Minuit(chi2_plus, a=2300000, b=2, c=20000, error_a=1, error_b=0.01, error_c=1, fix_b=False, limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), errordef=1) #minuit_minus = im.Minuit(chi2_minus, a=2300000, b=0.5939, c=20000, r0=0, # error_a=1, error_b=0.01, error_c=1, error_r0=0.01, # fix_b=True, # limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), limit_r0=(None, None), # errordef=1) #minuit_plus = im.Minuit(chi2_plus, a=2300000, b=0.6025, c=20000, r0=0, # error_a=1, error_b=0.01, error_c=1, error_r0=0.01, # fix_b=True, # limit_a=(None, None), limit_b=(0, 10), limit_c=(None, None), limit_r0=(None, None), # errordef=1) #print(minuit.get_param_states()) minuit_minus.migrad() minuit_plus.migrad() print(minuit_plus.get_param_states()) print(minuit_plus.get_fmin()) print(minuit_minus.get_param_states()) print(minuit_minus.get_fmin()) chi2_minus.draw(minuit_minus, axs[0]) chi2_plus.draw(minuit_plus, axs[1]) axs[2].plot(r_sph_minus, func(r_sph_minus, *minuit_minus.values.values()), color='red', label='fit minus') axs[2].plot(r_sph_plus, func(r_sph_plus, *minuit_plus.values.values()), color='blue', linestyle='dashed', label='fit plus') axs[2].legend() axs[1].legend() axs[0].legend() axs[2].grid() plt.show()
def remake_arrays(input_arr_): w_r_bins = 0.01 # need z-binning corresponding to 1 roc w_z_bins = 52 # # of pixels in a roc n_z_bins = int(3328 / w_z_bins) # 3328 is number of pixels in a ladder row inner_array = np.array([row for row in input_arr_ if not np.all(row==None)]) cleaned_array = np.array([[x if x is not None else [0, np.nan, np.nan, np.nan] for x in row] for row in inner_array]) r_min = np.nanmin(cleaned_array[:, :, 1]) r_max = np.nanmax(cleaned_array[:, :, 1]) n_r_bins = int((r_max - r_min) / w_r_bins) array_by_rocs = np.array([cleaned_array[:, i*w_z_bins:(i+1)*w_z_bins] for i in range(n_z_bins)]) array_by_rocs.argsort() roc_index = range(0, n_z_bins) # fig, axs = plt.subplots(8, 8, sharex=False, sharey=False, figsize=(160, 160), tight_layout=True) #all rocs and modules fig, axs = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(20, 20), tight_layout=True) # fraction of rocs and modules x, y = 0, 0 for roc in roc_index: roc_i = roc roc = roc_map(roc) # if (roc != 16) and (roc != 63) and (roc != 2): continue # looking at a single ROC # if roc != 31: continue # looking at a single ROC print(roc) occ = array_by_rocs[roc, :, :, 0] r = array_by_rocs[roc, :, :, 1] z = array_by_rocs[roc, :, :, 3] z_avg = np.nanmean(np.round(z, 2)) r_sph = np.sqrt(r**2 + z**2) # if z_avg < 0: # r_sph = np.negative(r_sph) r_sph_max = np.nanmax(r_sph) r_sph_min = np.nanmin(r_sph) n_r_sph_bins = int((r_sph_max - r_sph_min) / w_r_bins) r_min_roc = np.nanmin(r) r_max_roc = np.nanmax(r) n_r_bins_roc = int((r_max_roc - r_min_roc) / w_r_bins) r_range_min = (r_min_roc - r_min_roc)*100 r_range_max = (r_max_roc - r_min_roc)*100 r = (r - r_min_roc)*100 # bin_values, bins, patches = axs[x][y].hist(np.concatenate(r), bins=n_r_bins_roc, # range=(r_range_min, r_range_max), # # weights=np.concatenate(occ), density=True) # weights = np.concatenate(occ)) bin_values, bins, patches = axs.hist(np.concatenate(r_sph), bins=n_r_sph_bins, range=(r_sph_min, r_sph_max), # weights=np.concatenate(occ), density=True) weights = np.concatenate(occ)) bin_centers = np.array([(bins[i] + bins[i+1]) / 2. for i, b in enumerate(bins) if b != bins[-1]]) # bin_chi2 = pf.costfunc.BinnedChi2(func, np.concatenate(r), weights=np.concatenate(occ), # bins=n_r_bins, bound=(r_min_roc, r_max_roc)) # chi2 = pf.Chi2Regression(func, bin_centers[1:-5], bin_values[1:-5]) # for r_cyl # chi2 = pf.Chi2Regression(func, bin_centers[14:-12], bin_values[14:-12]) # deltaR = 0.01 chi2 = pf.Chi2Regression(func, bin_centers[17:-16], bin_values[17:-16]) # deltaR = 0.02 minuit = im.Minuit(chi2, a=1, b=0.5, c=1, error_a=1, error_b=0.01, error_c=1, fix_b=False, limit_a=(None, None), limit_b=(0, 4), limit_c=(None, None), errordef=1) print(minuit.get_param_states()) minuit.migrad() print(minuit.get_param_states()) print(minuit.get_fmin()) # chi2.draw(minuit, axs[x][y]) chi2.draw(minuit, axs) #axs[x][y].text(2.8, 15000, round(z_avg, 2)) #axs[x][y].legend(fontsize='xx-small') x += 1 if x == 8: x = 0 y += 1 if y == 8: x = 0 y = 0 plt.axis((None, None, 0, 20000)) plt.show()