def setup_detector(self): timeStepSize = 1 #ns num_steps = np.amax([1200, self.siggen_wf_length * timeStepMult]) det = Detector(self.conf.siggen_conf_file, timeStep=timeStepSize / timeStepMult, numSteps=num_steps, maxWfOutputLength=self.output_wf_length, t0_padding=100) det.LoadFieldsGrad(self.conf.field_file_name) self.detector = det
def setup_detector(self, fieldFileName): timeStepSize = 1 #ns det = Detector(self.det_name, timeStep=timeStepSize, numSteps=self.siggen_wf_length, maxWfOutputLength=self.output_wf_length, t0_padding=100) det.LoadFieldsGrad(fieldFileName) self.detector = det
def MakeSiggenWaveform(samp, r, z, ene, t0, smooth=1, phi=np.pi / 8): """ Use pysiggen to generate a waveform w/ arb. ADC amplitude. Thanks Ben. """ wf_length = samp # in tens of ns. This sets how long a wf you will simulate # r ranges from 0 to detector.detector_radius # phi ranges from 0 to np.pi/4 (Clint: Limit is the pcrad, set below) # z ranges from 0 to detector.detector_length (Clint: Limit is the pclen, set below) # energy sets the waveform amplitude # t0 sets the start point of the waveform # smooth is a gaussian smoothing parameter # default: r, phi, z, energy, t0, smooth = (15, np.pi/8, 15, 80, 10,15) # Probably don't mess around with anything in this block fitSamples = 1000 # ask me if you think you need to change this (you almost definitely don't) timeStepSize = 1 # don't change this, you'll break everything # Create a detector model (don't change any of this) detName = "../data/conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % ( 0.05, 2.5, 1.65) detector = Detector(detName, timeStep=timeStepSize, numSteps=fitSamples * 10. / timeStepSize, maxWfOutputLength=5000) detector.LoadFieldsGrad("../data/fields_impgrad.npz", pcLen=1.6, pcRad=2.5) # Sets the impurity gradient. Don't bother changing this detector.SetFieldsGradIdx(0) # First 3 params control the preamp shaping. # The 4th param is the RC decay, you can change that if you want. # params 5 and 6 are set not to do anything (theyre for the 2 rc constant decay model) rc_decay = 72.6 #us detector.SetTransferFunction(50, -0.814072377576, 0.82162729751, rc_decay, 1, 1) wf_notrap = np.copy( detector.MakeSimWaveform(r, phi, z, ene, t0, wf_length, h_smoothing=smooth)) timesteps = np.arange(0, wf_length) * 10 # makes it so your plot is in ns # Add charge trapping # trap_constants = [8, 28,288] # these are in microseconds # trap_constant_colors = ["red", "blue", "purple"] # for (idx, trap_rc) in enumerate(trap_constants): # detector.trapping_rc = trap_rc # wf = np.copy(detector.MakeSimWaveform(r, phi, z, ene, t0, wf_length, h_smoothing=smooth)) # ax0.plot(timesteps, wf, color = trap_constant_colors[idx], label = "%0.1f us trapping" % trap_rc ) # ax1.plot(timesteps, wf_notrap - wf, color = trap_constant_colors[idx]) # print "amplitude diff: %f" % ( (np.amax(wf_notrap) - np.amax(wf)) / np.amax(wf_notrap) ) return wf_notrap, timesteps
from progressbar import ProgressBar, Percentage, Bar, ETA from multiprocessing import Pool from timeit import default_timer as timer max_sample_idx = 125 #Prepare detector timeStepSize = 1 fitSamples = 200 #Create a detector model timeStepSize = 1 #ns detName = "conf/P42574A_bull.conf" field_file_name = "P42574A_mar28_21by21.npz" det = Detector(detName, timeStep=timeStepSize, numSteps=fitSamples, maxWfOutputLength =fitSamples, t0_padding=100 ) det.LoadFieldsGrad(field_file_name) #fit params fallPercentage = 0.985 out_file_name = "mle_wfs.txt" rad_mult = 10. phi_mult = 0.1 z_mult = 10. scale_mult = 1000. maxt_mult = 100. smooth_mult = 10. #set up the detector w/ trained params h_111_va = 6156919.714510
if doInitPlot: plt.show() exit() siggen_wf_length = (max_sample_idx - np.amin(baselineLengths) + 10) * 10 output_wf_length = np.amax(wfLengths) + 1 #Create a detector model timeStepSize = 1 #ns detName = "conf/P42574A_ben.conf" det = Detector(detName, timeStep=timeStepSize, numSteps=siggen_wf_length, maxWfOutputLength=output_wf_length, t0_padding=100) det.LoadFieldsGrad(fieldFileName) def fit(directory): if reinitializeDetector: initializeDetectorAndWaveforms(det.__getstate__(), wfs, reinit=reinitializeDetector, doInterp=doMaxInterp) else: initializeDetectorAndWaveforms(det, wfs, reinit=reinitializeDetector, doInterp=doMaxInterp) initMultiThreading(numThreads)
if doInitPlot: plt.show() exit() siggen_wf_length = (np.amax(wfMaxes) - t0_padding + 10) * 10 output_wf_length = np.amax(wfLengths) #Create a detector model timeStepSize = 1 #ns detName = "conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % (0.05, 2.5, 1.65) det = Detector(detName, timeStep=timeStepSize, numSteps=siggen_wf_length, maxWfOutputLength=output_wf_length) det.LoadFieldsGrad("fields_impgrad_0-0.02.npz", pcLen=1.6, pcRad=2.5) def fit(directory): initializeDetectorAndWaveforms(det, wfs, results, reinit=False) initMultiThreading(numThreads) # Create a model object and a sampler model = Model() sampler = dnest4.DNest4Sampler(model, backend=dnest4.backends.CSVBackend( basedir="./" + directory, sep=" ")) # Set up the sampler. The first argument is max_num_levels gen = sampler.sample(max_num_levels=500,
def plot(sample_file_name, directory): max_sample_idx = 200 fallPercentage = 0.97 if os.path.isfile(directory + "fit_params.npz"): data = np.load(directory + "fit_params.npz", encoding="latin1") max_sample_idx = data['max_sample_idx'] fallPercentage = data['fallPercentage'] wf_idxs = data['wf_idxs'] wf_file_name = data['wf_file_name'] field_file_name = data['field_file_name'] doMaxInterp = data['doMaxInterp'] # det_name = data['det_name'] wf_file_name = "%s" % wf_file_name field_file_name = "%s" % field_file_name else: print("Saved fit param %s not available" % (directory + "fit_params.npz")) exit(0) if os.path.isfile(wf_file_name): data = np.load(wf_file_name) wfs = data['wfs'] wfs = wfs[wf_idxs] numWaveforms = wfs.size else: print("Saved waveform file %s not available" % wfFileName) exit(0) wfLengths = np.empty(numWaveforms) wfMaxes = np.empty(numWaveforms) if doInitPlot: plt.figure(500) baselineLengths = np.empty(numWaveforms) for (wf_idx, wf) in enumerate(wfs): wf.WindowWaveformAroundMax(fallPercentage=fallPercentage, rmsMult=2, earlySamples=max_sample_idx) baselineLengths[wf_idx] = wf.t0Guess print("wf %d length %d (entry %d from run %d)" % (wf_idx, wf.wfLength, wf.entry_number, wf.runNumber)) wfLengths[wf_idx] = wf.wfLength wfMaxes[wf_idx] = np.argmax(wf.windowedWf) if doInitPlot: if len(colors) < numWaveforms: color = "red" else: color = colors[wf_idx] plt.plot(wf.windowedWf, color=color) if doInitPlot: plt.show() exit() siggen_wf_length = (max_sample_idx - np.amin(baselineLengths) + 10) * 10 output_wf_length = np.amax(wfLengths) + 1 #Create a detector model timeStepSize = 1 #ns detName = "conf/P42574A_bull.conf" det = Detector(detName, timeStep=timeStepSize, numSteps=siggen_wf_length, maxWfOutputLength=output_wf_length, t0_padding=100) det.LoadFieldsGrad(field_file_name) fig1 = plt.figure(0, figsize=(20, 10)) plt.clf() gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) ax1 = plt.subplot(gs[1], sharex=ax0) ax1.set_xlabel("Digitizer Time [ns]") ax0.set_ylabel("Voltage [Arb.]") ax1.set_ylabel("Residual") for wf in wfs: dataLen = wf.wfLength t_data = np.arange(dataLen) * 10 ax0.plot(t_data, wf.windowedWf, color="black") sample_file_name = directory + sample_file_name if sample_file_name == directory + "sample.txt": shutil.copy(directory + "sample.txt", directory + "sample_plot.txt") sample_file_name = directory + "sample_plot.txt" data = np.loadtxt(sample_file_name) num_samples = len(data) data_len = num_samples # data = pd.read_csv("sample_plot.txt", delim_whitespace=True, header=None) # num_samples = len(data.index) print("found %d samples" % num_samples) if sample_file_name == (directory + "sample_plot.txt"): if num_samples > plotNum: num_samples = plotNum if doWaveformPlot: if num_samples > plotNum: num_samples = plotNum print("plotting %d samples" % num_samples) r_arr = np.empty((numWaveforms, num_samples)) z_arr = np.empty((numWaveforms, num_samples)) tf = np.empty((6, num_samples)) velo = np.empty((6, num_samples)) wf_params = np.empty((numWaveforms, 6, num_samples)) det_params = np.empty((4, num_samples)) tf_first_idx, velo_first_idx, grad_idx, trap_idx = global_get_indices() for (idx, params) in enumerate(data[-num_samples:]): # params = data.iloc[-(idx+1)] # print params tf_phi, tf_omega, d, rc1, rc2, rcfrac, aliasrc = params[ tf_first_idx:tf_first_idx + 7] #tf_d = tf_c * tf_dc c = -d * np.cos(tf_omega) b_ov_a = c - np.tan(tf_phi) * np.sqrt(d**2 - c**2) a = 1. / (1 + b_ov_a) tf_b = a * b_ov_a tf_c = c tf_d = d h_111_va, h_111_vmax, h_100_multa, h_100_multmax, h_100_beta, h_111_beta, = params[ velo_first_idx:velo_first_idx + 6] charge_trapping = params[trap_idx] grad = (params[grad_idx]) imp_avg = (params[grad_idx + 1]) # rc1 = -1./np.log(e_rc1) # rc2 = -1./np.log(e_rc2) # charge_trapping = -1./np.log(e_charge_trapping) h_100_va = h_100_multa * h_111_va h_100_vmax = h_100_multmax * h_111_vmax h_100_mu0, h_100_beta, h_100_e0 = get_velo_params( h_100_va, h_100_vmax, h_100_beta) h_111_mu0, h_111_beta, h_111_e0 = get_velo_params( h_111_va, h_111_vmax, h_111_beta) tf[:, idx] = tf_phi, tf_omega, tf_d, rc1, rc2, rcfrac velo[:, idx] = params[velo_first_idx:velo_first_idx + 6] det_params[:, idx] = grad, imp_avg, charge_trapping, aliasrc det.SetTransferFunction(tf_b, tf_c, tf_d, rc1, rc2, rcfrac) det.siggenInst.set_hole_params(h_100_mu0, h_100_beta, h_100_e0, h_111_mu0, h_111_beta, h_111_e0) det.trapping_rc = charge_trapping det.SetGrads(grad, imp_avg) det.SetAntialiasingRC(aliasrc) rad_arr, phi_arr, theta_arr, scale_arr, t0_arr, smooth_arr, = params[ trap_idx + 1:].reshape((6, numWaveforms)) for (wf_idx, wf) in enumerate(wfs): rad, phi, theta = rad_arr[wf_idx], phi_arr[wf_idx], theta_arr[ wf_idx] scale, t0, smooth = scale_arr[wf_idx], t0_arr[wf_idx], smooth_arr[ wf_idx] # m, b = m_arr[wf_idx], b_arr[wf_idx] wf_params[wf_idx, :, idx] = rad, phi, theta, scale, t0, smooth, r = rad * np.cos(theta) z = rad * np.sin(theta) r_arr[wf_idx, idx], z_arr[wf_idx, idx] = r, z if doWaveformPlot: color_idx = wf_idx % len(colors) ml_wf = det.MakeSimWaveform(r, phi, z, scale, t0, np.int(output_wf_length), h_smoothing=smooth, alignPoint="max", doMaxInterp=True) if ml_wf is None: continue dataLen = wf.wfLength t_data = np.arange(dataLen) * 10 ax0.plot(t_data, ml_wf[:dataLen], color=colors[color_idx], alpha=0.1) ax1.plot(t_data, ml_wf[:dataLen] - wf.windowedWf, color=colors[color_idx], alpha=0.1) ax0.set_ylim(-20, wf.wfMax * 1.1) ax1.set_ylim(-20, 20) if not doHists: plt.tight_layout() plt.savefig("waveforms.png") plt.show() exit() vFig = plt.figure(2, figsize=(20, 10)) tfLabels = ['tf_phi', 'tf_omega', 'tf_d', 'rc1', 'rc2', 'rcfrac'] vLabels = [ 'h_111_va', 'h_111_vmax', 'h_100_multa', 'h_100_multmax', 'h_100_beta', 'h_111_beta' ] vmodes, tfmodes = np.empty(6), np.empty(6) num_bins = 100 for i in range(6): idx = (i + 1) * 3 axis = vFig.add_subplot(6, 3, idx - 1) axis.set_ylabel(vLabels[i]) [n, b, p] = axis.hist(velo[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % (vLabels[i], b[max_idx])) axis = vFig.add_subplot(6, 3, idx - 2) axis.set_ylabel(tfLabels[i]) [n, b, p] = axis.hist(tf[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % (tfLabels[i], b[max_idx])) if i == 0: axis = vFig.add_subplot(6, 3, idx) axis.set_ylabel("imp grad") [n, b, p] = axis.hist(det_params[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % ("imp_grad", b[max_idx])) if i == 1: axis = vFig.add_subplot(6, 3, idx) axis.set_ylabel("imp average") [n, b, p] = axis.hist(det_params[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % ("imp_avg", b[max_idx])) if i == 2: axis = vFig.add_subplot(6, 3, idx) axis.set_ylabel("trapping_rc") [n, b, p] = axis.hist(det_params[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % ("trapping_rc", b[max_idx])) if i == 3: axis = vFig.add_subplot(6, 3, idx) axis.set_ylabel("alias_rc") [n, b, p] = axis.hist(det_params[i, :], bins=num_bins) max_idx = np.argmax(n) print("%s mode: %f" % ("alias_rc", b[max_idx])) if doPositionHist: positionFig = plt.figure(3, figsize=(10, 10)) plt.clf() colorbars = [ "Reds", "Blues", "Greens", "Purples", "Oranges", "Greys", "YlOrBr", "PuRd" ] if not doContourHist: for wf_idx in range(numWaveforms): color_idx = wf_idx % len(colorbars) xedges = np.linspace( 0, np.around(det.detector_radius, 1), np.around(det.detector_radius, 1) * 10 + 1) yedges = np.linspace( 0, np.around(det.detector_length, 1), np.around(det.detector_length, 1) * 10 + 1) plt.hist2d(r_arr[wf_idx, :], z_arr[wf_idx, :], bins=[xedges, yedges], cmap=plt.get_cmap(colorbars[color_idx])) #cmin=0.1 rad_mean = np.mean(wf_params[wf_idx, 0, :]) # print "--> guess was at %f" % (np.sqrt(results[wf_idx]['x'][0]**2 + results[wf_idx]['x'][2]**2)) # plt.colorbar() plt.xlabel("r from Point Contact (mm)") plt.ylabel("z from Point Contact (mm)") plt.xlim(0, det.detector_radius) plt.ylim(0, det.detector_length) plt.gca().set_aspect('equal', adjustable='box') else: for wf_idx in range(numWaveforms): xedges = np.linspace( 0, np.around(det.detector_radius, 1), np.around(det.detector_radius, 1) * 10 + 1) yedges = np.linspace( 0, np.around(det.detector_length, 1), np.around(det.detector_length, 1) * 10 + 1) z, xe, ye = np.histogram2d(r_arr[wf_idx, :], z_arr[wf_idx, :], bins=[xedges, yedges]) z /= z.sum() n = 100 t = np.linspace(0, z.max(), n) integral = ((z >= t[:, None, None]) * z).sum(axis=(1, 2)) from scipy import interpolate f = interpolate.interp1d(integral, t) t_contours = f(np.array([0.9, 0.8])) cs = plt.contourf( z.T, t_contours, extent=[0, det.detector_radius, 0, det.detector_length], alpha=1, colors=(colors[wf_idx]), extend='max') # cs.cmap.set_over(colors[wf_idx]) plt.xlabel("r from Point Contact (mm)") plt.ylabel("z from Point Contact (mm)") # plt.axis('equal') plt.xlim(0, det.detector_radius) plt.ylim(0, det.detector_length) plt.gca().set_aspect('equal', adjustable='box') plt.tight_layout() plt.savefig("credible_intervals.pdf") if numWaveforms == 1: #TODO: make this plot work for a bunch of wfs vFig = plt.figure(4, figsize=(20, 10)) wfLabels = ['rad', 'phi', 'theta', 'scale', 't0', 'smooth', 'm', 'b'] num_bins = 100 for i in range(8): axis = vFig.add_subplot(4, 2, i + 1) axis.set_ylabel(wfLabels[i]) [n, b, p] = axis.hist(wf_params[0, i, :], bins=num_bins) # if i == 4: # axis.axvline(x=t0_min, color="r") # axis.axvline(x=t0_max, color="r") # axis.axvline(x=t0_guess, color="g") if False: velo_plot = plt.figure(5) fields_log = np.linspace(np.log(100), np.log(10000), 100) fields = np.exp(fields_log) for idx in range(num_samples): h_111_va, h_111_vmax, h_100_multa, h_100_multmax, h_100_beta, h_111_beta, = velo[:, idx] # print "v params: ", # print mu_0, h_100_lnbeta, h_111_lnbeta, h_111_emu, h_100_mult h_100_va = h_100_multa * h_111_va h_100_vmax = h_100_multmax * h_111_vmax h100 = np.empty_like(fields) h111 = np.empty_like(fields) h_100_mu0, h_100_beta, h_100_e0 = get_velo_params( h_100_va, h_100_vmax, h_100_beta) h_111_mu0, h_111_beta, h_111_e0 = get_velo_params( h_111_va, h_111_vmax, h_111_beta) for (idx, field) in enumerate(fields): h100[idx] = find_drift_velocity_bruyneel( field, h_100_mu0, h_100_beta, h_100_e0) h111[idx] = find_drift_velocity_bruyneel( field, h_111_mu0, h_111_beta, h_111_e0) plt.plot(fields, h100, color="r", alpha=1. / 100) plt.plot(fields, h111, color="b", alpha=1. / 100) h100_reg = np.zeros_like(h100) h111_reg = np.zeros_like(h100) h100_bruy = np.zeros_like(h100) h111_bruy = np.zeros_like(h100) for (idx, field) in enumerate(fields): h100_reg[idx] = find_drift_velocity_bruyneel( field, 66333., 0.744, 181.) h111_reg[idx] = find_drift_velocity_bruyneel( field, 107270., 0.580, 100.) h100_bruy[idx] = find_drift_velocity_bruyneel( field, 61824., 0.942, 185.) h111_bruy[idx] = find_drift_velocity_bruyneel( field, 61215., 0.662, 182.) plt.plot(fields, h100_reg, color="g") plt.plot(fields, h111_reg, color="g", ls="--") plt.plot(fields, h100_bruy, color="orange") plt.plot(fields, h111_bruy, color="orange", ls="--") # plt.axvline(x=250, color="black", ls=":") plt.axvline(x=500, color="black", ls=":") plt.xscale('log') # plt.yscale('log') # plt.xlim(.45, 1E5) # plt.ylim(1E4, 1E8) plt.show()
def plot_waveforms(): #the pysiggen Detector object is a wrapper around siggen that also does all the elctronics processing. Let's set one up. wf_length = 350 #in tens of ns. This sets how long a wf you will simulate (after post-processing for electronics etc) fitSamples = 800 #number of samples siggen will calculate (before post-processing, in 1 ns increments) timeStepSize = 1 #don't change this, you'll break everything detName = "conf/P42574A_ben.conf" detector = Detector(detName, timeStep=timeStepSize, numSteps=fitSamples, maxWfOutputLength=5000) #Load field information detector.LoadFieldsGrad("P42574A_fields_impAndAvg_21by21.npz") #Set a specific impurity gradient, impurity level combo imp_grad =detector.gradList[3]; avg_imp = detector.impAvgList[3]; detector.SetGrads(imp_grad, avg_imp) #hole drift mobilities detector.siggenInst.set_hole_params(66333., 0.744, 181., 107270., 0.580, 100.,) #Electronics transfer function rc_decay = 72.6 #us detector.SetTransferFunction(1, -0.814072377576, 0.82162729751, rc_decay, 1, 1) #position we're gonna simulate r, phi,z = 30, np.pi/8 ,30 #energy just scales the simulated waveform amplitude linearly energy = 10 #align time is where the signal is aligned. If alignPoint="max" is set, this is at the signal max. Else, its at the signal t0 (with flat baseline before t0) align_t = 200 smooth = 10 #sigma of the gaussian charge size convolution #Set up some plotz fig1 = plt.figure(0, figsize=(15,8)) gs = gridspec.GridSpec(2, 2, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) ax1 = plt.subplot(gs[2], sharex=ax0) ax1.set_xlabel("Digitizer Time [ns]") ax0.set_ylabel("Voltage [A.U.]") ax1.set_ylabel("Residual [A.U]") ax0.set_title("Raw hole signal (no processing)") ax2 = plt.subplot(gs[1]) ax3 = plt.subplot(gs[3], sharex=ax2) ax3.set_xlabel("Digitizer Time [ns]") ax2.set_ylabel("Voltage [A.U.]") ax3.set_ylabel("Residual [A.U]") ax2.set_title("After electronics processing") timesteps_raw = np.arange(0, fitSamples) #for raw signal timesteps = np.arange(0, wf_length)*10. #for processed signal #need to do a np.copy because the memory allocated for wf sim gets rewritten with each sim wf_raw = np.copy(detector.MakeRawSiggenWaveform(r, phi, z,1)) #the 1 is to do holes - a -1 would do electrons wf_proc = np.copy(detector.MakeSimWaveform(r, phi, z, energy, align_t, wf_length, h_smoothing=smooth, trapType="fullSignal", alignPoint="max")) ax0.plot(timesteps_raw, wf_raw, color="green") ax2.plot(timesteps, wf_proc, color="green") #take a look at how changing average impurity level changes the signal num = 7 imp_vals = np.linspace(detector.impAvgList[0], detector.impAvgList[-1], num) imp_grads = np.linspace(detector.gradList[0], detector.gradList[-1], num) #just to make sure the residual color is the same as the corresponding wf colorList = ["red", "blue", "purple", "orange", "black", "brown", "magenta", "cyan"] # for (idx, grad) in enumerate(imp_grads): for (idx, avg_imp) in enumerate(imp_vals): detector.SetGrads(imp_grad, avg_imp) new_wf_raw = np.copy(detector.MakeRawSiggenWaveform(r, phi, z, 1)) ax0.plot(timesteps_raw, new_wf_raw, color=colorList[idx]) ax1.plot(timesteps_raw, wf_raw - new_wf_raw, color=colorList[idx]) new_wf_proc= np.copy(detector.MakeSimWaveform(r, phi, z, energy, align_t, wf_length, h_smoothing=smooth, trapType="fullSignal", alignPoint="max")) ax2.plot(timesteps, new_wf_proc, color=colorList[idx]) ax3.plot(timesteps, wf_proc - new_wf_proc, color=colorList[idx]) plt.show()
print "No saved waveforms available. Loading from Data" exit(0) tempGuess = 79.071172 gradGuess = 0.01 pcRadGuess = 2.5 pcLenGuess = 1.6 #Create a detector model detName = "conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % (0.05, 2.5, 1.65) det = Detector(detName, temperature=tempGuess, timeStep=timeStepSize, numSteps=fitSamples * 10) det.LoadFieldsGrad("fields_impgrad_0-0.02.npz", pcLen=pcLenGuess, pcRad=pcRadGuess) det.SetFieldsGradInterp(gradGuess) tf_first_idx = 8 velo_first_idx = 14 trap_idx = 20 grad_idx = 21 wf_idx = 4 wf = wfs[wf_idx] wf.WindowWaveformTimepoint(fallPercentage=.99, rmsMult=2, earlySamples=50) print "wf is %d samples long" % wf.wfLength
from timeit import default_timer as timer max_sample_idx = 150 #Prepare detector timeStepSize = 1 fitSamples = 200 detName = "conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % (0.05, 2.5, 1.65) detector = Detector(detName, timeStep=timeStepSize, numSteps=fitSamples * 10. / timeStepSize, maxWfOutputLength=fitSamples + max_sample_idx + 2) fieldFileName = "P42574A_fields_impgrad_0.00000-0.00100.npz" #sets the impurity gradient. Don't bother changing this detector.LoadFieldsGrad(fieldFileName) detector.SetFieldsGradIdx(33) b = 169.722312 c = -0.805889 d = 0.813206 rc1 = 72.904982 rc2 = 23.900887 rcfrac = 0.996435 fallPercentage = 0.99 detector.SetTransferFunction(b, c, d, rc1, rc2, rcfrac) h_100_mu0, h_100_beta, h_100_e0 = 337372.980584, 0.545879, 30.952525, h_111_mu0, h_111_beta, h_111_e0 = 452053.925755, 0.430484, 23.900887
def plot_waveforms(): wf_length = 200 #in tens of ns. This sets how long a wf you will simulate #Probably don't mess around with anything in this block fitSamples = 1000 #ask me if you think you need to change this (you almost definitely don't) timeStepSize = 1 #don't change this, you'll break everything #Create a detector model (don't change any of this) detName = "conf/P42574A_grad%0.2f_pcrad%0.2f_pclen%0.2f.conf" % (0.05, 2.5, 1.65) detector = Detector(detName, timeStep=timeStepSize, numSteps=fitSamples * 10. / timeStepSize, maxWfOutputLength=5000) detector.LoadFieldsGrad("fields_impgrad.npz", pcLen=1.6, pcRad=2.5) #sets the impurity gradient. Don't bother changing this detector.SetFieldsGradIdx(0) #First 3 params control the preamp shaping. #The 4th param is the RC decay, you can change that if you want. #params 5 and 6 are set not to do anything (theyre for the 2 rc constant decay model) rc_decay = 72.6 #us detector.SetTransferFunction(50, -0.814072377576, 0.82162729751, rc_decay, 1, 1) #r ranges from 0 to detector.detector_radius #phi ranges from 0 to np.pi/4 #z ranges from 0 to detector.detector_length #energy sets the waveform amplitude #t0 sets the start point of the waveform #smooth is a gaussian smoothing parameter r, phi, z, energy, t0, smooth = (15, np.pi / 8, 15, 80, 10, 15) trap_constants = [8, 28, 288] #these are in microseconds trap_constant_colors = ["red", "blue", "purple"] # fig1 = plt.figure(0, figsize=(20,10)) fig1 = plt.figure(0, figsize=(9, 7)) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) ax1 = plt.subplot(gs[1], sharex=ax0) ax1.set_xlabel("Digitizer Time [ns]") ax0.set_ylabel("Voltage [A.U.]") ax1.set_ylabel("Residual [A.U]") timesteps = np.arange(0, wf_length) * 10 #makes it so your plot is in ns wf_notrap = np.copy( detector.MakeSimWaveform(r, phi, z, energy, t0, wf_length, h_smoothing=smooth)) ax0.plot(timesteps, wf_notrap, color="green", label="No trapping") for (idx, trap_rc) in enumerate(trap_constants): detector.trapping_rc = trap_rc wf = np.copy( detector.MakeSimWaveform(r, phi, z, energy, t0, wf_length, h_smoothing=smooth)) ax0.plot(timesteps, wf, color=trap_constant_colors[idx], label="%0.1f us trapping" % trap_rc) ax1.plot(timesteps, wf_notrap - wf, color=trap_constant_colors[idx]) print "amplitude diff: %f" % ( (np.amax(wf_notrap) - np.amax(wf)) / np.amax(wf_notrap)) ax0.legend(loc=4) plt.show() plt.savefig("wf.pdf")
def main(argv): wfFileName = "P42574A_24_spread.npz" if os.path.isfile(wfFileName): data = np.load(wfFileName) wfs = data['wfs'] else: print "No saved waveforms available." exit(0) global wf wf = wfs[20] max_sample_idx = 150 fallPercentage = 0.97 wf.WindowWaveformAroundMax(fallPercentage=fallPercentage, rmsMult=2, earlySamples=max_sample_idx) baseline_length = wf.t0Guess print "wf length %d (entry %d from run %d)" % ( wf.wfLength, wf.entry_number, wf.runNumber) wf_length = wf.wfLength wf_max = np.argmax(wf.windowedWf) baseline_origin_idx = baseline_length - 30 if baseline_origin_idx < 0: print "not enough baseline!!" exit(0) initT0Padding(max_sample_idx, baseline_origin_idx) siggen_wf_length = (max_sample_idx - baseline_length + 10) * 10 global output_wf_length output_wf_length = wf_length + 1 #setup .ector timeStepSize = 1 fitSamples = 200 detName = "conf/P42574A_ben.conf" det = Detector( detName, timeStep=timeStepSize, numSteps=siggen_wf_length, maxWfOutputLength=output_wf_length, ) fieldFileName = "P42574A_fields_impgrad_0.00000-0.00100.npz" #sets the impurity gradient. Don't bother changing this det.LoadFieldsGrad(fieldFileName) det.SetFieldsGradIdx(np.int(imp_grad)) det.siggenInst.set_hole_params(h_100_mu0, h_100_beta, h_100_e0, h_111_mu0, h_111_beta, h_111_e0) det.trapping_rc = trapping_rc det.SetTransferFunction( tf_b, tf_c, tf_d, rc1, rc2, rcfrac, ) global detector detector = det directory = "" if len(argv) == 0: fit(directory) elif argv[0] == "plot": if len(argv) > 1: directory = argv[1] plot("sample.txt", directory) elif argv[0] == "plotpost": if len(argv) > 1: directory = argv[1] plot("posterior_sample.txt", directory) else: fit(argv[0])