def plot_compare_ogp(self, new_ogp, old_ogp, freq, pts=50): """ This function plots a comparison between a snap and a fitted sine for two different sets of ogp Inputs: - 'new_ogp' is an array containing measured ogp values, - 'old_ogp' is an array containing current ogp values loaded on ADC5g (if old_ogp = None, will use 0 ogp for all 4 cores), - 'freq' is frequency of input CW tone (in MHz) - 'pts' is for how many points in snap to plot (max 8192) Outputs: - - - """ tot_pts = 8192 del_phi = 2*math.pi*freq/self.clk #freq in MHz x = [del_phi*i for i in range(tot_pts)] r = np.arange(0, tot_pts*del_phi, del_phi/10.) p0 = [128., 90., 90.] self.syn.set_freq(freq*1e6) self.clear_ogp() time.sleep(0.5) raw_u = adc5g.get_snapshot(self.roach, 'scope_raw_a0_snap') params_u = curve_fit(syn_func, x, raw_u, p0) self.set_ogp(new_ogp, 0, cores=[1,2]) time.sleep(0.5) raw_c = adc5g.get_snapshot(self.roach, 'scope_raw_a0_snap') params_c = curve_fit(syn_func, x, raw_c, p0) f_u = syn_func(r, params_u[0][0], params_u[0][1], params_u[0][2]) f_c = syn_func(r, params_c[0][0], params_c[0][1], params_c[0][2]) fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.plot(r[:(pts*10)], f_u[:(pts*10)]) ax1.plot(x[:pts], raw_u[:pts], 'o', color='r') ax1.set_title('OGP Uncorrected Fit, freq = %d MHz' %freq) ax2.plot(r[:(pts*10)], f_c[:(pts*10)]) ax2.plot(x[:pts], raw_c[:pts], 'o', color='r') ax2.set_title('OGP Corrected Fit, freq = %d MHz' %freq) plt.tight_layout() plt.show()
def plot_compare_ogp(self, new_ogp, old_ogp, freq, pts=50): """ This function plots a comparison between a snap and a fitted sine for two different sets of ogp Inputs: - 'new_ogp' is an array containing measured ogp values, - 'old_ogp' is an array containing current ogp values loaded on ADC5g (if old_ogp = None, will use 0 ogp for all 4 cores), - 'freq' is frequency of input CW tone (in MHz) - 'pts' is for how many points in snap to plot (max 8192) Outputs: - - - """ tot_pts = 8192 del_phi = 2 * math.pi * freq / self.clk #freq in MHz x = [del_phi * i for i in range(tot_pts)] r = np.arange(0, tot_pts * del_phi, del_phi / 10.) p0 = [128., 90., 90.] self.syn.set_freq(freq * 1e6) self.clear_ogp() time.sleep(0.5) raw_u = adc5g.get_snapshot(self.roach, 'scope_raw_a0_snap') params_u = curve_fit(syn_func, x, raw_u, p0) self.set_ogp(new_ogp, 0, cores=[1, 2]) time.sleep(0.5) raw_c = adc5g.get_snapshot(self.roach, 'scope_raw_a0_snap') params_c = curve_fit(syn_func, x, raw_c, p0) f_u = syn_func(r, params_u[0][0], params_u[0][1], params_u[0][2]) f_c = syn_func(r, params_c[0][0], params_c[0][1], params_c[0][2]) fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) ax1.plot(r[:(pts * 10)], f_u[:(pts * 10)]) ax1.plot(x[:pts], raw_u[:pts], 'o', color='r') ax1.set_title('OGP Uncorrected Fit, freq = %d MHz' % freq) ax2.plot(r[:(pts * 10)], f_c[:(pts * 10)]) ax2.plot(x[:pts], raw_c[:pts], 'o', color='r') ax2.set_title('OGP Corrected Fit, freq = %d MHz' % freq) plt.tight_layout() plt.show()
def dosnap(fr=0, name="t", rpt = 1, donot_clear=False): """ Takes a snapshot and uses fit_cores to fit a sine function to each core separately assuming a CW signal is connected to the input. The offset, gain and phase differences are reoprted for each core as well as the average of all four. The parameters are: fr The frequency of the signal generator. It will default to the last frequency set by set_freq() name the name of the file into which the snapshot is written. 5 other files are written. Name.c1 .. name.c4 contain themeasurements from cores a, b, c and d. Note that data is taken from cores in the order a, c, b, d. A line is appended to the file name.fit containing signal freq, average zero, average amplitude followed by triplets of zero, amplitude and phase differences for cores a, b, c and d rpt The number of repeats. Defaults to 1. The c1 .. c4 files mentioned above are overwritten with each repeat, but new rows of data are added to the .fit file for each pass. """ global freq avg_pwr_sinad = 0 if fr == 0: fr = freq for i in range(rpt): snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) np.savetxt(name, snap,fmt='%d') ogp, pwr_sinad = fit_cores.fit_snap(fr, samp_freq, name,\ clear_avgs = i == 0 and not donot_clear, prnt = i == rpt-1) avg_pwr_sinad += pwr_sinad return ogp, avg_pwr_sinad/rpt
def og_from_noise(fname="ogp.noise", rpt=100): """ Take a number of snapshots of noise. Analyze for offset and gain for each core separately. """ sum_result = np.zeros((15), dtype=float) sum_cnt = 0 for n in range(rpt): result = np.zeros((15), dtype=float) snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) if(rpt == 1): np.savetxt("t.og_noise", snap,fmt='%d') l=float(len(snap)) snap_off=np.sum(snap)/l snap_amp=np.sum(abs(snap-snap_off))/l result[0]=snap_off*(-500.0/256.0) result[1]=snap_amp for core in range(4): # This will actually sample the cores in the order A,C,B,D # index will fix this up when data is put in the result array index=(3,9,6,12)[core] c=snap[core::4] l=float(len(c)) off=np.sum(c)/l result[index] = off*(-500.0/256.0) amp=np.sum(abs(c-off))/l result[index+1]= 100.0*(snap_amp-amp)/snap_amp sum_result += result sum_cnt += 1 print "%.4f "*15 % tuple(result) sum_result /= sum_cnt print "%.4f "*15 % tuple(sum_result) np.savetxt(fname, sum_result[3:], fmt="%8.4f")
def dosnap(fr=0, name="t", rpt=1, donot_clear=False): """ Takes a snapshot and uses fit_cores to fit a sine function to each core separately assuming a CW signal is connected to the input. The offset, gain and phase differences are reoprted for each core as well as the average of all four. The parameters are: fr The frequency of the signal generator. It will default to the last frequency set by set_freq() name the name of the file into which the snapshot is written. 5 other files are written. Name.c1 .. name.c4 contain themeasurements from cores a, b, c and d. Note that data is taken from cores in the order a, c, b, d. A line is appended to the file name.fit containing signal freq, average zero, average amplitude followed by triplets of zero, amplitude and phase differences for cores a, b, c and d rpt The number of repeats. Defaults to 1. The c1 .. c4 files mentioned above are overwritten with each repeat, but new rows of data are added to the .fit file for each pass. """ global freq avg_pwr_sinad = 0 if fr == 0: fr = freq for i in range(rpt): snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) np.savetxt(name, snap, fmt='%d') ogp, pwr_sinad = fit_cores.fit_snap(fr, samp_freq, name,\ clear_avgs = i == 0 and not donot_clear, prnt = i == rpt-1) avg_pwr_sinad += pwr_sinad return ogp, avg_pwr_sinad / rpt
def hist_from_snapshots(rpt=10): # hist_all = np.zeros(256,dtype=int) hist1 = np.zeros(256, dtype=int) hist2 = np.zeros(256, dtype=int) hist3 = np.zeros(256, dtype=int) hist4 = np.zeros(256, dtype=int) for i in range(rpt): snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) snap = 128 + np.array(snap) # hist = np.bincount(snap, minlength=256) # hist_all += hist hist = np.bincount(snap[0::4], minlength=256) hist1 += hist hist = np.bincount(snap[1::4], minlength=256) hist2 += hist hist = np.bincount(snap[2::4], minlength=256) hist3 += hist hist = np.bincount(snap[3::4], minlength=256) hist4 += hist data = np.column_stack((np.arange(-128., 128, dtype=int), hist1, hist2, hist3, hist4)) np.savetxt("hist_cores", data, fmt=("%d")) # print "all ",np.sum(hist_all[0:128]), np.sum(hist_all[128:256]) print "core a ", np.sum(hist1[0:128]), np.sum(hist1[129:256]) print "core b ", np.sum(hist3[0:128]), np.sum(hist3[129:256]) print "core c ", np.sum(hist2[0:128]), np.sum(hist2[129:256]) print "core d ", np.sum(hist4[0:128]), np.sum(hist4[129:256])
def get_rms(): global zdok save_zdok = zdok set_zdok(0) snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) rmsSnap = np.std(snap) loadingFactor = -20.0 * math.log10(128 / rmsSnap) print "If0 Rms = %f, loading factor = %f" % (rmsSnap, loadingFactor) set_zdok(1) snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) rmsSnap = np.std(snap) loadingFactor = -20.0 * math.log10(128 / rmsSnap) print "If1 Rms = %f, loading factor = %f" % (rmsSnap, loadingFactor) if zdok != save_zdok: set_zdok(save_zdok)
def og_from_noise(fname="ogp.noise", rpt=100): """ Take a number of snapshots of noise. Analyze for offset and gain for each core separately. """ sum_result = np.zeros((15), dtype=float) sum_cnt = 0 for n in range(rpt): result = np.zeros((15), dtype=float) snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) l = float(len(snap)) snap_off = np.sum(snap) / l snap_amp = np.sum(abs(snap - snap_off)) / l result[0] = snap_off result[1] = snap_amp for core in range(4): # This will actually sample the cores in the order A,C,B,D # index will fix this up when data is put in the result array index = (3, 9, 6, 12)[core] c = snap[core::4] l = float(len(c)) off = np.sum(c) / l result[index] = (-off) * 500.0 / 256.0 #result[index] = (snap_off-off)*500.0/256.0 amp = np.sum(abs(c - off)) / l result[index + 1] = 100.0 * (snap_amp - amp) / snap_amp sum_result += result sum_cnt += 1 sum_result /= sum_cnt print "%.4f " * 15 % tuple(sum_result) np.savetxt(fname, sum_result[3:], fmt="%8.4f")
def levels_hist(self, raw): raw = np.array(adc5g.get_snapshot(self.roach, 'scope_raw_a0_snap'), np.int32) bins = np.arange(-128.5, 128.5, 1) th = 32 lim1 = -th-0.5 lim2 = -0.5 lim3 = th-0.5 ideal_gauss = mlab.normpdf(bins, 0, th) plt.subplot(111) plt.plot((lim1,lim1), (0,1), 'k--') plt.plot((lim2,lim2), (0,1), 'k--') plt.plot((lim3,lim3), (0,1), 'k--') plt.plot(bins, ideal_gauss, 'gray', linewidth=1) plt.hist(raw, bins, normed=1, facecolor='blue', alpha=0.9, histtype='stepfilled') plt.xlim(-129, 128) plt.ylim(0, 0.06) plt.xlabel('ADC Value') plt.ylabel('Normalized Count') plt.title('zdok0 levels') plt.grid() plt.show()
def get_rms(): global zdok save_zdok = zdok set_zdok(0) snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) rmsSnap = np.std(snap) loadingFactor = -20.0*math.log10(128/rmsSnap) print "If0 Rms = %f, loading factor = %f" % (rmsSnap,loadingFactor) set_zdok(1) snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) rmsSnap = np.std(snap) loadingFactor = -20.0*math.log10(128/rmsSnap) print "If1 Rms = %f, loading factor = %f" % (rmsSnap,loadingFactor) if zdok != save_zdok: set_zdok(save_zdok)
def hist_from_snapshots(rpt = 10): # hist_all = np.zeros(256,dtype=int) hist1 = np.zeros(256,dtype=int) hist2 = np.zeros(256,dtype=int) hist3 = np.zeros(256,dtype=int) hist4 = np.zeros(256,dtype=int) for i in range(rpt): snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) snap = 128 + np.array(snap) # hist = np.bincount(snap, minlength=256) # hist_all += hist hist = np.bincount(snap[0:: 4], minlength=256) hist1 += hist hist = np.bincount(snap[1:: 4], minlength=256) hist2 += hist hist = np.bincount(snap[2:: 4], minlength=256) hist3 += hist hist = np.bincount(snap[3:: 4], minlength=256) hist4 += hist data=np.column_stack((np.arange(-128., 128, dtype=int), hist1, hist2, hist3, hist4)) np.savetxt("hist_cores", data, fmt=("%d")) # print "all ",np.sum(hist_all[0:128]), np.sum(hist_all[128:256]) print "core a ",np.sum(hist1[0:128]), np.sum(hist1[129:256]) print "core b ",np.sum(hist3[0:128]), np.sum(hist3[129:256]) print "core c ",np.sum(hist2[0:128]), np.sum(hist2[129:256]) print "core d ",np.sum(hist4[0:128]), np.sum(hist4[129:256])
def setUpClass(cls): TestBase.setUpClass() cls._sample_rate = cls._clk_rate * 2. cls._tone_per = int(round(cls._sample_rate / cls._tone_freq)) cls._raw = adc5g.get_snapshot(cls._roach, 'scope_raw_%d_snap' % cls._zdok_n) cls._raw = list(samp/128. for samp in cls._raw) cls._bias = (cls._raw[0] + cls._raw[cls._tone_per/2])/2. cls._amp = sqrt((cls._raw[0]-cls._bias)**2 + (cls._raw[cls._tone_per/4]-cls._bias)**2) cls._phase = atan2((cls._raw[0]-cls._bias)/cls._amp, (cls._raw[125]-cls._bias)/cls._amp) cls._fit = list(cls._amp*sin(t*2*pi/cls._tone_per + cls._phase) + cls._bias \ for t in range(len(cls._raw)))
def setUpClass(cls): TestBase.setUpClass() cls._sample_rate = cls._clk_rate * 2.0 cls._tone_per = int(round(cls._sample_rate / cls._tone_freq)) cls._raw = adc5g.get_snapshot(cls._roach, "raw_%d" % cls._zdok_n) cls._raw = list(samp - 128 for samp in cls._raw) cls._bias = (cls._raw[0] + cls._raw[cls._tone_per / 2]) / 2.0 cls._amp = sqrt((cls._raw[0] - cls._bias) ** 2 + (cls._raw[cls._tone_per / 4] - cls._bias) ** 2) cls._phase = atan2((cls._raw[0] - cls._bias) / cls._amp, (cls._raw[125] - cls._bias) / cls._amp) cls._fit = list( cls._amp * sin(t * 2 * pi / cls._tone_per + cls._phase) + cls._bias for t in range(len(cls._raw)) )
def get_snap(self, chan, freq): #MHz """ Takes a snap shot on channel 'chan' of a cw tone of frequency 'freq' (MHz) """ if freq != None: # self.syn.output_on() self.syn.set_freq(freq * 1e6) time.sleep(1) # reg = self.get_channel_snap_reg(chan) raw = array(adc5g.get_snapshot(self.roach, 'snap%i' % (chan))) return raw
def dosnap(fr=0, name=None, rpt=1, donot_clear=False, plot=True): """ Takes a snapshot and uses fit_cores to fit a sine function to each core separately assuming a CW signal is connected to the input. The offset, gain and phase differences are reoprted for each core as well as the average of all four. The parameters are: fr The frequency of the signal generator. It will default to the last frequency set by set_freq() name the name of the file into which the snapshot is written. 5 other files are written. Name.c1 .. name.c4 contain themeasurements from cores a, b, c and d. Note that data is taken from cores in the order a, c, b, d. A line is appended to the file name.fit containing signal freq, average zero, average amplitude followed by triplets of zero, amplitude and phase differences for cores a, b, c and d name defaults to if0 or if1, depending on the current zdok rpt The number of repeats. Defaults to 1. The c1 .. c4 files mentioned above are overwritten with each repeat, but new rows of data are added to the .fit file for each pass. """ global freq if name == None: name = "if%d" % (zdok) avg_pwr_sinad = 0 if fr == 0: fr = freq for i in range(rpt): snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) if (plot): plt.clf() plt.plot(snap) plt.show(block=False) rmsSnap = np.std(snap) loadingFactor = -20.0 * math.log10(128 / rmsSnap) print "Rms = %f, loading factor = %f" % (rmsSnap, loadingFactor) if i == rpt - 1: np.savetxt(name, snap, fmt='%d') ogp, pwr_sinad = fit_cores.fit_snap(snap, fr, samp_freq, name,\ clear_avgs = ((i == 0) and not donot_clear), prnt = (i == rpt-1)) avg_pwr_sinad += pwr_sinad return ogp, avg_pwr_sinad / rpt
def get_snap(self, chan, freq): #MHz """ Takes a snap shot on channel 'chan' of a cw tone of frequency 'freq' (MHz) """ # if freq != None: # self.syn.output_on() # self.syn.set_freq(freq*1e6) # time.sleep(1) reg = self.get_channel_snap_reg(chan) raw = array(adc5g.get_snapshot(self.roach, reg)) return raw, freq
def dosnap(fr=0, name=None, rpt = 1, donot_clear=False, plot=True): """ Takes a snapshot and uses fit_cores to fit a sine function to each core separately assuming a CW signal is connected to the input. The offset, gain and phase differences are reoprted for each core as well as the average of all four. The parameters are: fr The frequency of the signal generator. It will default to the last frequency set by set_freq() name the name of the file into which the snapshot is written. 5 other files are written. Name.c1 .. name.c4 contain themeasurements from cores a, b, c and d. Note that data is taken from cores in the order a, c, b, d. A line is appended to the file name.fit containing signal freq, average zero, average amplitude followed by triplets of zero, amplitude and phase differences for cores a, b, c and d name defaults to if0 or if1, depending on the current zdok rpt The number of repeats. Defaults to 1. The c1 .. c4 files mentioned above are overwritten with each repeat, but new rows of data are added to the .fit file for each pass. """ global freq if name == None: name = "if%d" % (zdok) avg_pwr_sinad = 0 if fr == 0: fr = freq for i in range(rpt): snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) if(plot): plt.clf() plt.plot(snap) plt.show(block = False) rmsSnap = np.std(snap) loadingFactor = -20.0*math.log10(128/rmsSnap) print "Rms = %f, loading factor = %f" % (rmsSnap,loadingFactor) if i == rpt-1: np.savetxt(name, snap,fmt='%d') ogp, pwr_sinad = fit_cores.fit_snap(snap, fr, samp_freq, name,\ clear_avgs = ((i == 0) and not donot_clear), prnt = (i == rpt-1)) avg_pwr_sinad += pwr_sinad return ogp, avg_pwr_sinad/rpt
def dopsdcores(nfft=None, rpt=10): if nfft == None: nfft = numpoints / 4 for i in range(rpt): snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) power, freqs = mlab.psd(snap, nfft*4, Fs=samp_freq*1e6, detrend=mlab.detrend_mean, \ scale_by_freq=False) if i == 0: psd_all = power[:1 + nfft / 2] else: psd_all += power[:1 + nfft / 2] power, freqs = mlab.psd(snap[0:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd1 = power else: psd1 += power power, freqs = mlab.psd(snap[1:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd2 = power else: psd2 += power power, freqs = mlab.psd(snap[2:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd3 = power else: psd3 += power power, freqs = mlab.psd(snap[3:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd4 = power else: psd4 += power data = np.column_stack((freqs*1e-6, 10*np.log10(psd_all/rpt), \ 10*np.log10(psd1/rpt), \ 10*np.log10(psd2/rpt), 10*np.log10(psd3/rpt), 10*np.log10(psd4/rpt))) np.savetxt("psd_cores", data, fmt=('%7.2f'))
def setUpClass(cls): TestBase.setUpClass() cls._sample_rate = cls._clk_rate * 2. cls._tone_per = int(round(cls._sample_rate / cls._tone_freq)) #cls._raw = adc5g.get_snapshot(cls._roach, 'delay_fifo_snap', False, 0 ) cls._raw2 = adc5g.get_snapshot(cls._roach, 'snap', False, 0) #cls._raw = list(samp for samp in cls._raw) cls._raw2 = list(samp for samp in cls._raw2) #print "THE AMPLITUDE: ", cls._raw print "THE AMPLITUDE2: ", cls._raw2 #cls._bias = (cls._raw[0] + cls._raw[cls._tone_per/2])/2. #cls._amp = sqrt((cls._raw[0]-cls._bias)**2 + (cls._raw[cls._tone_per/4]-cls._bias)**2) #cls._phase = atan2((cls._raw[0]-cls._bias)/cls._amp, (cls._raw[125]-cls._bias)/cls._amp) #cls._fit = list(cls._amp*sin(t*2*pi/cls._tone_per + cls._phase) + cls._bias \ #for t in range(len(cls._raw))) cls._roach.write_int('delay_fifo_enable', 0) """cls._roach.write_int('en_tri', 1)
def og_from_noise(fname=None, rpt=100, printEach=False): """ Take a number of snapshots of noise. Analyze for offset and gain for each core separately. """ global ogp_name if fname == None: fname = ogp_name + ".meas" sum_result = np.zeros((15), dtype=float) sum_cnt = 0 for n in range(rpt): result = np.zeros((15), dtype=float) snap = adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) if (rpt == 1): np.savetxt("t.og_noise", snap, fmt='%d') l = float(len(snap)) snap_off = np.sum(snap) / l snap_amp = np.sum(abs(snap - snap_off)) / l result[0] = snap_off * (-500.0 / 256.0) result[1] = snap_amp for core in range(4): # This will actually sample the cores in the order A,C,B,D # index will fix this up when data is put in the result array index = (3, 9, 6, 12)[core] c = snap[core::4] l = float(len(c)) off = np.sum(c) / l result[index] = off * (-500.0 / 256.0) amp = np.sum(abs(c - off)) / l result[index + 1] = 100.0 * (snap_amp - amp) / snap_amp sum_result += result sum_cnt += 1 if printEach: print "%.4f " * 15 % tuple(result) sum_result /= sum_cnt print "%.4f " * 15 % tuple(sum_result) np.savetxt(fname, sum_result[3:], fmt="%8.4f")
def dopsdcores(nfft = None, rpt = 10): if nfft == None: nfft = numpoints/4 for i in range(rpt): snap=adc5g.get_snapshot(roach2, snap_name, man_trig=True, wait_period=2) power, freqs = mlab.psd(snap, nfft*4, Fs=samp_freq*1e6, detrend=mlab.detrend_mean, \ scale_by_freq=False) if i == 0: psd_all = power[:1+nfft/2] else: psd_all += power[:1+nfft/2] power, freqs = mlab.psd(snap[0:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd1 = power else: psd1 += power power, freqs = mlab.psd(snap[1:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd2 = power else: psd2 += power power, freqs = mlab.psd(snap[2:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd3 = power else: psd3 += power power, freqs = mlab.psd(snap[3:: 4], nfft, Fs=samp_freq*.25e6, detrend=mlab.detrend_mean,\ scale_by_freq=True) if i == 0: psd4 = power else: psd4 += power data = np.column_stack((freqs*1e-6, 10*np.log10(psd_all/rpt), \ 10*np.log10(psd1/rpt), \ 10*np.log10(psd2/rpt), 10*np.log10(psd3/rpt), 10*np.log10(psd4/rpt))) np.savetxt("psd_cores", data, fmt=('%7.2f'))
raise RuntimeError(msg) Fs = 2*2048e6 # R2DBE sampling freq Nif = 2 # R2DBE typically 2 IFs Ninteg = 1 # integrate this many ADC snapshots if len(sys.argv)==2: Ninteg = int(sys.argv[1]) Nsamp = [0]*Nif Lfft = [0]*Nif data = [None]*Nif for ii in range(Ninteg): for ifnr in range(Nif): data8 = adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_%d_data' % (ifnr)) Lfft[ifnr] = len(data8) Nsamp[ifnr] = Nsamp[ifnr] + Lfft[ifnr] if data[ifnr]==None: data[ifnr] = data8 else: # data[ifnr] = data[ifnr] + data8 data[ifnr] = [data[ifnr][n]+data8[n] for n in range(len(data8))] print ' Int %d/%d : ADC %d snapshot of 8-bit data, got %d samples' % (ii+1,Ninteg,ifnr,len(data8)) for ifnr in range(Nif): subplot(Nif,1,(ifnr+1)) plotSpectrum(data[ifnr], Fs, 'ADC %d' % (ifnr)) gcf().set_facecolor('white') show()
def get_data(): #get the data... hola = numpy.array(adc5g.get_snapshot(fpga, "snapshot0")) hola1 = numpy.array(adc5g.get_snapshot(fpga, "snapshot1")) # raw_1 = numpy.array(adc5g.get_snapshot(fpga, "raw_1")) return hola, hola1
parser.add_argument('-v','--verbose',action='count', help="control verbosity, use multiple times for more detailed output") parser.add_argument('host',metavar='R2DBE',type=str,nargs='?',default='r2dbe-1', help="hostname or ip address of r2dbe (default is 'r2dbe-1')") args = parser.parse_args() # connect to roach2 roach2 = corr.katcp_wrapper.FpgaClient(args.host) if not roach2.wait_connected(timeout=args.timeout): msg = "Could not establish connection to '{0}' within {1} seconds, aborting".format( args.host,args.timeout) raise RuntimeError(msg) if args.verbose > 1: print "connected to '{0}'".format(args.host) for ii in ['0','1']: # grab snapshot of 8 bit data from each input if args.verbose > 2: print "get snapshot form 'r2dbe_snap_8bit_{0}_data'".format(ii) x8 = adc5g.get_snapshot(roach2,'r2dbe_snap_8bit_'+ii+'_data') th = get_th_16_84(x8) if args.verbose > 0: print "threshold {0} = {1}".format(ii,th) # write threshold to FPGA if args.verbose > 2: print "write threshold to 'r2dbe_quantize_{0}_thresh'".format(ii) roach2.write_int('r2dbe_quantize_'+ii+'_thresh', th)
def cplanecmd(cmd): af, socktype, proto, canonname, sa = socket_res s = socket.socket(af,socktype, proto) s.connect(sa) s.sendall(cmd + ';') # extra ';' will not matter ret = s.recv(8192).strip() s.close() return ret recstate = cplanecmd('record?;') if "recording" in recstate: sys.exit('currently recording do not run!') if hascorr: roach2 = corr.katcp_wrapper.FpgaClient(r2_hostname) roach2.wait_connected() x0 = np.array(adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_0_data')) x1 = np.array(adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_1_data')) th0 = roach2.read_int('r2dbe_quantize_0_thresh') th1 = roach2.read_int('r2dbe_quantize_1_thresh') class R2EpochIsCorrect(unittest.TestCase): def test(self): utcnow = datetime.utcnow() epoch = 2*(utcnow.year - 2000) + (utcnow.month > 6) self.assertEqual(epoch, roach2.read_int('r2dbe_vdif_0_hdr_w1_ref_ep'), "epoch set in R2DBE startup script") self.assertEqual(epoch, roach2.read_int('r2dbe_vdif_1_hdr_w1_ref_ep'), "epoch set in R2DBE startup script") # class R2SecondsAreCorrect(unittest.TestCase): # def test(self): # utcnow = datetime.utcnow() # wait = (1500000 - utcnow.microsecond) % 1e6 # get to 0.5s boundary
# OFFSET - GAIN - PHASE Calibration print 'Doing OGP calibration...' #ogp, sinad = rww_tools.dosnap(fr=opts.testfreq,name=FNAME,rpt=opts.n_trials,donot_clear=False) # calibration parameters rpt = 30 # repetitions until set of offset, ganancia y fase snap_name = 'snapshot1' # ADC snapshot name samp_freq = frec_samp # ADC interleave mode sample rate FNAME = 'snapshot_adc1_raw.dat' avg_pwr_sinad = 0 fr = opts.testfreq donot_clear = False for i in range(rpt): snap = adc.get_snapshot(fpga, snap_name, man_trig=True, wait_period=2) np.savetxt(FNAME, snap, fmt='%d') ogp, pwr_sinad = fit_cores.fit_snap(fr, samp_freq, FNAME,\ clear_avgs = i == 0 and not donot_clear, prnt = i == rpt-1) avg_pwr_sinad += pwr_sinad sinad = avg_pwr_sinad / rpt ogp = ogp[3:] np.savetxt('ogp', ogp, fmt='%8.4f') # print registers print 'OGP registers: ' rww_tools.get_ogp()
help ='Interleave data from pairs of ADC cores (even the cores not used in the downstream firmware') args = parser.parse_args() print "Connecting to %s" % args.host snap = casperfpga.CasperFpga(args.host) print "Interpretting design data for %s with %s" % (args.host, args.fpgfile) snap.get_system_information(args.fpgfile) chani = [] chanq = [] speci = [] specq = [] for i in range(args.numsnaps): print "Grabbing ADC data (%d of %d)" % (i+1, args.numsnaps) all_chan_data = adc5g.get_snapshot(snap, 'ss_adc') # Separate data into multiple channels if args.interleave: chani = [all_chan_data[0::2]] chanq = [all_chan_data[1::2]] else: chani = [all_chan_data[0::2][0::2]] chanq = [all_chan_data[1::2][0::2]] speci += [np.abs(np.fft.rfft(chani[-1]))**2] specq += [np.abs(np.fft.rfft(chanq[-1]))**2] time.sleep(0.2) chani = np.array(chani) chanq = np.array(chanq) speci = np.array(speci)
type=str, nargs='?', default='r2dbe-1', help="hostname or ip address of r2dbe (default is 'r2dbe-1')") args = parser.parse_args() # connect to roach2 roach2 = corr.katcp_wrapper.FpgaClient(args.host) if not roach2.wait_connected(timeout=args.timeout): msg = "Could not establish connection to '{0}' within {1} seconds, aborting".format( args.host, args.timeout) raise RuntimeError(msg) if args.verbose > 1: print "connected to '{0}'".format(args.host) for ii in ['0', '1']: # grab snapshot of 8 bit data from each input if args.verbose > 2: print "get snapshot form 'r2dbe_snap_8bit_{0}_data'".format(ii) x8 = adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_' + ii + '_data') th = get_th_16_84(x8) if args.verbose > 0: print "threshold {0} = {1}".format(ii, th) # write threshold to FPGA if args.verbose > 2: print "write threshold to 'r2dbe_quantize_{0}_thresh'".format(ii) roach2.write_int('r2dbe_quantize_' + ii + '_thresh', th)
# reverse time order (per vdif spec) roach2.write_int('r2dbe_vdif_0_reorder_2b_samps', 1) roach2.write_int('r2dbe_vdif_1_reorder_2b_samps', 1) # set to test-vector noise mode roach2.write_int('r2dbe_quantize_0_thresh', 12) roach2.write_int('r2dbe_quantize_1_thresh', 12) # JanW: -7 dBm over 0-1.5 GHz band input to R2DBE # thresh=16 produces 10%:41%:41%:8% # thresh=12 produces 16%:35%:35%:14% # set threshold automatically # get snapshot of 8-bit data print 'Setting 8-bit -> 2-bit quantization threshold levels...' x8_0 = adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_0_data') L = len(x8_0) print 'Auto-thresholding input 0 using %d samples' % (L) y = sorted(x8_0) Lt = int(L * 0.16) th1 = abs(y[Lt - 1]) Lt2 = int(L * 0.84) th2 = abs(y[Lt2 - 1]) th = (th1 + th2) / 2 roach2.write_int('r2dbe_quantize_0_thresh', th) print 'r2dbe_quantize_0_thresh : %d' % (th) x8_1 = adc5g.get_snapshot(roach2, 'r2dbe_snap_8bit_1_data') L = len(x8_1) print 'Auto-thresholding input 1 using %d samples' % (L) y = sorted(x8_1)
# OFFSET - GAIN - PHASE Calibration print "Doing OGP calibration..." # ogp, sinad = rww_tools.dosnap(fr=opts.testfreq,name=FNAME,rpt=opts.n_trials,donot_clear=False) # calibration parameters rpt = 30 # repetitions until set of offset, ganancia y fase snap_name = "snapshot1" # ADC snapshot name samp_freq = frec_samp # ADC interleave mode sample rate FNAME = "snapshot_adc1_raw.dat" avg_pwr_sinad = 0 fr = opts.testfreq donot_clear = False for i in range(rpt): snap = adc.get_snapshot(fpga, snap_name, man_trig=True, wait_period=2) np.savetxt(FNAME, snap, fmt="%d") ogp, pwr_sinad = fit_cores.fit_snap( fr, samp_freq, FNAME, clear_avgs=i == 0 and not donot_clear, prnt=i == rpt - 1 ) avg_pwr_sinad += pwr_sinad sinad = avg_pwr_sinad / rpt ogp = ogp[3:] np.savetxt("ogp", ogp, fmt="%8.4f") # print registers print "OGP registers: " rww_tools.get_ogp()