def simulateAndPrint(figure1, ax1, ax2, circuit, fc0, fc1=None): simulator = circuit.simulator() enableLtSpice(simulator, spice_command='/Applications/LTspice.app/Contents/MacOS/LTspice') analysis = simulator.ac(start_frequency=10, stop_frequency=kilo(5), number_of_points=500, variation='dec') print('Simulated, Bode plotting...') bode_diagram(axes=(figure1.add_subplot(ax1), figure1.add_subplot(ax2)), frequency=analysis.frequency, gain=20*np.log10(np.absolute(analysis.out1o)), #gain=np.absolute(analysis.out50), phase=np.angle(analysis.out1o, deg=False), marker='', color='blue', linestyle='-', ) bode_diagram(axes=(figure1.add_subplot(ax1), figure1.add_subplot(ax2)), frequency=analysis.frequency, gain=20*np.log10(np.absolute(analysis.out2o)), #gain=np.absolute(analysis.out50), phase=np.angle(analysis.out2o, deg=False), marker='', color='red', linestyle='-', ) figure1.add_subplot(ax1) plt.axvline(x=fc0, linewidth=0.5, color='k') if fc1 != None: plt.axvline(x=fc1, linewidth=0.5, color='k') figure1.add_subplot(ax2) plt.axvline(x=fc0, linewidth=0.5, color='k') if fc1 != None: plt.axvline(x=fc1, linewidth=0.5, color='k')
def plotall(self): real = self.z_data_raw.real imag = self.z_data_raw.imag real2 = self.z_data_sim.real imag2 = self.z_data_sim.imag fig = plt.figure(figsize=(15,5)) fig.canvas.set_window_title("Resonator fit") plt.subplot(131) plt.plot(real,imag,label='rawdata') plt.plot(real2,imag2,label='fit') plt.xlabel('Re(S21)') plt.ylabel('Im(S21)') plt.legend() plt.subplot(132) plt.plot(self.f_data*1e-9,np.absolute(self.z_data_raw),label='rawdata') plt.plot(self.f_data*1e-9,np.absolute(self.z_data_sim),label='fit') plt.xlabel('f (GHz)') plt.ylabel('Amplitude') plt.legend() plt.subplot(133) plt.plot(self.f_data*1e-9,np.unwrap(np.angle(self.z_data_raw)),label='rawdata') plt.plot(self.f_data*1e-9,np.unwrap(np.angle(self.z_data_sim)),label='fit') plt.xlabel('f (GHz)') plt.ylabel('Phase') plt.legend() # plt.gcf().set_size_inches(15,5) plt.tight_layout() plt.show()
def lossless_mismatch(self,s11,db=True, **kwargs): ''' Lossless mismatch defined by its return loss Parameters ---------- s11 : number, array-like the reflection coefficient. if db==True, then phase is ignored db : bool is s11 in db? otherwise assumes linear Returns -------- ntwk : :class:`~skrf.network.Network` object 2-port lossless mismatch ''' result = self.match(nports=2,**kwargs) if db: s11 = mf.db_2_magnitude(s11) result.s[:,0,0] = s11 result.s[:,1,1] = s11 result.s[:,0,1] = npy.sqrt(1- npy.abs(s11)**2)*\ npy.exp(1j*(npy.angle(s11)+npy.pi/2.*(npy.angle(s11)<0) -npy.pi/2*(npy.angle(s11)>0))) result.s[:,1,0] = result.s[:,0,1] return result
def estrampcpx(inData, estData=None): if estData is not None: if np.any(np.iscomplex(estData)): estData=estData.conj() inData=inData*estData else: estData=np.exp(-1.j*estData) inData=inData*estData indx=np.log10(abs(np.fft.fftshift(np.fft.fft2(np.angle(inData))))).argmax() #to display fft you may want to take log10 of the value here subi=np.unravel_index(indx, inData.shape) X,Y=np.meshgrid(np.r_[0:inData.shape[1]], np.r_[0:inData.shape[0]]) fxmax=inData.shape[1]/2. fymax=inData.shape[0]/2. surface=np.pi*( (subi[0]-fymax)*Y/fymax + (subi[1]-fxmax)*X/fxmax ) #print [ subi, fxmax, fymax ] outData=inData*np.exp(-1.j*surface) outVal=[(subi[0]-fymax)/fymax , (subi[1]-fxmax)/fxmax] #test if we get the direction right. indx2=np.log10(abs(np.fft.fftshift(np.fft.fft2(np.angle(outData))))).argmax() subi2=np.unravel_index(indx2, inData.shape) dist1=np.sqrt( (subi[0]-fymax)**2. + (subi[1]-fxmax)**2.) dist2=np.sqrt( (subi2[0]-fymax)**2. + (subi2[1]-fxmax)**2.) #print [dist1, dist2] if dist1<dist2: #we got the direction wrong outVal=[-(subi[0]-fymax)/fymax , -(subi[1]-fxmax)/fxmax] #outData=np.exp(-1.j*surface) return outVal
def main(): sample_rate = 128 N = 128 freq = 10.5 k = np.pi * 2 * freq / sample_rate x = np.sin(np.arange(N, dtype='float64') * k) #x = np.pad(x, (0, N * 3), mode='constant') xfreq = np.arange(N/2) * (float(sample_rate) / len(x)) fv = np.fft.fft(x) amp = np.abs(fv[:N/2]) phase = np.angle(fv[:N/2]) print amp print phase mid = fv[N/2-3:N/2+4] print amp[0], np.abs(mid), mid plt.figure() plt.subplot(2, 1, 1) plt.plot(xfreq, amp) plt.subplot(2, 1, 2) plt.plot(xfreq, phase) N = len(x) fv[:N/2] *= np.exp(np.random.uniform(0, np.pi*2, N/2) * 1j) fv[N/2:] = np.conjugate(fv[:N/2]) recon = np.fft.ifft(fv) plt.figure() plt.subplot(2, 1, 1) plt.plot(xfreq, np.angle(fv[:len(xfreq)])) plt.subplot(2, 1, 2) plt.plot(np.real(recon)) plt.show()
def fft_to_hkl(h, k, l, val, coeffs, fsc_curve, resolution, full_size, flag_frac): '''Reformat fft record as hkl record''' if h or k or l: res = full_size / (np.linalg.norm(np.asarray([h, k, l]))) else: res = 0.0 if res < resolution or not np.isfinite(res): return None, None mag = np.abs(val) angle = np.angle(val, deg = True) if angle < 0: angle += 360.0 fsc = curve_function((1. / res), coeffs, fsc_curve) sig = fsc_to_sigf(mag, fsc) fom = fsc_to_fom(fsc) hla, hlb = fom_to_hl(fom, np.angle(val)) rf = bernoulli.rvs(flag_frac) record = np.array([h, k, l, mag, sig, angle, fom, hla, hlb, 0.0, 0.0, rf], dtype = np.float32) if not np.all(np.isfinite(record)): print("Skipping record %i %i %i - " %(h, k, l)), print(record) return None, None return record, res
def find_correct_sign(z1,z2,z_approx): ''' Create new vector from z1, z2 choosing elements with sign matching z_approx This is used when you have to make a root choice on a complex number. and you know the approximate value of the root. .. math:: z1,z2 = \\pm \\sqrt(z^2) Parameters ------------ z1 : array-like root 1 z2 : array-like root 2 z_approx : array-like approximate answer of z Returns ---------- z3 : npy.array array built from z1 and z2 by z1 where sign(z1) == sign(z_approx), z2 else ''' return npy.where( npy.sign(npy.angle(z1)) == npy.sign(npy.angle(z_approx)),z1, z2)
def compare_binary(pattern,testname): files = glob.glob(pattern) data1 = np.memmap(files[0],dtype=np.complex128) data2 = np.memmap(files[1],dtype=np.complex128) diff = data1 - data2 diff_real = np.abs(np.real(diff)) diff_imag = np.abs(np.imag(diff)) diff_abs = np.abs(data1) - np.abs(data2) diff_phase = np.angle(data1) - np.angle(data2) diff_phase[diff_phase > math.pi] -= (2*math.pi) diff_phase = np.abs(diff_phase) if np.max(diff_real) < 1e-15 and np.max(diff_imag) < 1e-15: print('TEST {}:\tOK'.format(testname)) else: print('TEST {}:\tFAILED'.format(testname)) print('differences between {} and {}'.format(files[0],files[1])) print('max difference real part:\t',np.max(diff_real )) print('max difference imag part:\t',np.max(diff_imag )) print('max difference modulus:\t\t',np.max(diff_abs )) print('max difference phase:\t\t', np.max(diff_phase)) print()
def change_parameterization(g, p_from, p_to): """ """ if p_from == p_to: return g elif p_from == "MAT" and p_to == "C": theta = np.arctan2(g[..., 1, 0], g[..., 0, 0]) return np.exp(1j * theta) elif p_from == "MAT" and p_to == "ANG": return np.arctan2(g[..., 1, 0], g[..., 0, 0]) elif p_from == "C" and p_to == "MAT": theta = np.angle(g) c = np.cos(theta) s = np.sin(theta) return np.array([[c, -s], [s, c]]).transpose(range(2, 2 + c.ndim) + [0, 1]) elif p_from == "C" and p_to == "ANG": return np.angle(g) elif p_from == "ANG" and p_to == "MAT": c = np.cos(g) s = np.sin(g) return np.array([[c, -s], [s, c]]).transpose(range(2, 2 + c.ndim) + [0, 1]) elif p_from == "ANG" and p_to == "C": return np.exp(1j * g) else: raise ValueError("Unsupported conversion:" + str(p_from) + " to " + str(p_to))
def _process_sample (self, ap1, ap2, ap3, triple, tflags): """We have computed one independent phase closure triple in one timeslot. """ # Frequency-resolved: np.divide (triple, np.abs (triple), triple) phase = np.angle (triple) self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap1, phase, tflags + 0.) self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap2, phase, tflags + 0.) self.ap_spec_stats_by_ddid[self.cur_ddid].accum (ap3, phase, tflags + 0.) # Frequency-averaged: triple = np.dot (triple, tflags) / tflags.sum () phase = np.angle (triple) self.global_stats_by_time.accum (self.cur_time, phase) self.ap_stats_by_ddid[self.cur_ddid].accum (ap1, phase) self.ap_stats_by_ddid[self.cur_ddid].accum (ap2, phase) self.ap_stats_by_ddid[self.cur_ddid].accum (ap3, phase) self.bp_stats_by_ddid[self.cur_ddid].accum ((ap1, ap2), phase) self.bp_stats_by_ddid[self.cur_ddid].accum ((ap1, ap3), phase) self.bp_stats_by_ddid[self.cur_ddid].accum ((ap2, ap3), phase) self.ap_time_stats_by_ddid[self.cur_ddid].accum (self.cur_time, ap1, phase) self.ap_time_stats_by_ddid[self.cur_ddid].accum (self.cur_time, ap2, phase) self.ap_time_stats_by_ddid[self.cur_ddid].accum (self.cur_time, ap3, phase)
def acumPassband( nacum=5, outfile=passbandFile ): [mpNameList, tsysNameList] = makeMpNameLists( ) vectorSumPbMatrix = numpy.zeros( [16,15], dtype=complex ) # vector sum of passband values scalarSumPbMatrix = numpy.zeros( [16,15], dtype=float ) # scalar (magnitude) passband sum npts = 0 while (npts < nacum) : waitForNewData( ) visMatrix = getVisMatrix( mpNameList ) vectorSumPbMatrix += visMatrix scalarSumPbMatrix += numpy.abs(visMatrix) npts += 1 print "accumulating passband (%d/%d records)" % (npts,nacum) meritMatrix = numpy.divide( numpy.abs(vectorSumPbMatrix), scalarSumPbMatrix ) # mag(vector) / sum(mags) # ... some values may be nan if data are missing print numpy.array_str( meritMatrix, precision=3, max_line_width=200 ) maskedMeritMatrix = numpy.ma.array( meritMatrix, mask=(numpy.isnan(meritMatrix) ) ) # ... mask off the nans merit = numpy.ma.mean( maskedMeritMatrix ) print "merit = %.3f" % merit # for consistency with mfcal, rotate passband phases to make phase(win1) = 0 for each antenna print "\nbefore rotation:" print numpy.array_str( numpy.angle(vectorSumPbMatrix, deg=True ), precision=0, suppress_small=True, max_line_width=200 ) for n in range(0,15) : Win1 = vectorSumPbMatrix[0][n] if numpy.abs(Win1) > 0. : for m in range(0,16) : vectorSumPbMatrix[m][n] = vectorSumPbMatrix[m][n] * numpy.conj(Win1) # ... don't bother normalizing, as this happens at the very end anyway print "\nafter rotation:" print numpy.array_str( numpy.angle(vectorSumPbMatrix, deg=True ), precision=0, suppress_small=True, max_line_width=200 ) print "\nsaving normalized passband to file %s" % outfile numpy.save(outfile, vectorSumPbMatrix/numpy.abs(vectorSumPbMatrix) )
def subsample(args): """ Rebin / Congrid variant """ arr, shape, mode = args # unpack arguments if mode == 'phase' and np.iscomplexobj(arr): arr = np.angle(arr) if np.iscomplexobj(arr): arr = np.abs(arr) if arr.shape == shape: return arr oshap = arr.shape for d in range(arr.ndim): n1 = shape[d] n2 = oshap[d] if n1 < n2: s = list(arr.shape) s.insert(d + 1, n2 // n1) s[d] = n1 if mode == 'phase': arr = np.angle(np.exp(1j * arr.reshape(s)).mean(d + 1)) elif mode == 'lables': arr = np.take(arr.reshape(s), 0, d + 1) else: arr = arr.reshape(s).mean(d + 1) else: arr = arr.repeat(n1 // n2, axis=d) return arr
def updateFigs(ZarcFitWindow): if ZarcFitWindow.radioButtonSerial.isChecked(): Z = ZarcFitWindow.zarc.Zseries(ZarcFitWindow.frequency) elif ZarcFitWindow.radioButtonParallel.isChecked(): Z = ZarcFitWindow.zarc.Zparallel(ZarcFitWindow.frequency) else: Exception("Not implemented!! choose either series or parallel") ZarcFitWindow.lineCole.set_data(Z.real, Z.imag) ZarcFitWindow.lineColeobs.set_data(ZarcFitWindow.obs.real, ZarcFitWindow.obs.imag) ZarcFitWindow.axCole.draw_artist(ZarcFitWindow.axCole.patch) ZarcFitWindow.axCole.draw_artist(ZarcFitWindow.lineCole) ZarcFitWindow.axCole.draw_artist(ZarcFitWindow.lineColeobs) ZarcFitWindow.lineBodeMagn.set_ydata(abs(Z)) ZarcFitWindow.lineBodeMagnobs.set_ydata(abs(ZarcFitWindow.obs)) ZarcFitWindow.axBodeMagn.draw_artist(ZarcFitWindow.axBodeMagn.patch) ZarcFitWindow.axBodeMagn.draw_artist(ZarcFitWindow.lineBodeMagn) ZarcFitWindow.axBodeMagn.draw_artist(ZarcFitWindow.lineBodeMagnobs) ZarcFitWindow.lineBodePhase.set_ydata(abs(np.angle(Z, deg=True))) ZarcFitWindow.lineBodePhaseobs.set_ydata(abs(np.angle(ZarcFitWindow.obs, deg=True))) ZarcFitWindow.axBodePhase.draw_artist(ZarcFitWindow.axBodePhase.patch) ZarcFitWindow.axBodePhase.draw_artist(ZarcFitWindow.lineBodePhase) ZarcFitWindow.axBodePhase.draw_artist(ZarcFitWindow.lineBodePhaseobs) ZarcFitWindow.figCole.canvas.update()
def update_plots(widget, baselines): try: (corr_time, left, right, current, total, lags, visibility, phase_fit, m, c) = correlator.get_correlation() baseline = left, right logger.debug('received baseline %s' % repr(baseline)) except NoCorrelations: widget.after(1, update_plots, widget, baselines) return # it never comes to this if baseline not in baselines.keys(): corr.axes.grid() #corr.axes.set_xlabel('Lag', size='large') #corr.axes.set_ylabel('Correlation Function', size='large') phase_line = corr.plot(f, angle(visibility), '%so' % colors[current%len(colors)], linewidth=1, label=repr(baseline))[0] fit_line = corr.plot(f, real(phase_fit), '%s-' % colors[current%len(colors)], linewidth=1, label=None)[0] baselines[baseline] = phase_line, fit_line else: corr.axes.legend() phase_line, fit_line = baselines[baseline] corr.update_line(phase_line, f, angle(visibility)) corr.update_line(fit_line, f, real(phase_fit)) if current == total-1: widget.update() logger.info('update in') widget.after_idle(update_plots, widget, baselines)
def makeGnuFig(filename): resultmat = np.zeros([len(squid.xaxis), 9]) S11 = elem.S11 ydat = measdata.ydat resultmat[:, 0] = squid.xaxis resultmat[:, 1] = ydat.real resultmat[:, 2] = S11.real resultmat[:, 3] = ydat.imag resultmat[:, 4] = S11.imag resultmat[:, 5] = abs(ydat) resultmat[:, 6] = abs(S11) resultmat[:, 7] = np.unwrap(np.angle(S11), discont=pi) resultmat[:, 8] = np.unwrap(np.angle(ydat), discont=pi) np.savetxt(filename, resultmat, delimiter='\t') # Plot in Gnuplot g1 = gp.Gnuplot(persist=1, debug=1) g1("plot '" + str(filename) + "' u 1:2 w l t 'Meas.real'") g1("replot '" + str(filename) + "' u 1:3 w l t 'Fit.real'") g1("replot '" + str(filename) + "' u 1:4 w l t 'Meas.imag'") g1("replot '" + str(filename) + "' u 1:5 w l t 'Fit.imag'") g2 = gp.Gnuplot(persist=1, debug=1) g2("plot '" + str(filename) + "' u 1:6 w l t 'Meas.mag'") g2("replot '" + str(filename) + "' u 1:7 w l t 'Fit.mag'") g2("replot '" + str(filename) + "' u 1:8 w l t 'Meas.phase'") g2("replot '" + str(filename) + "' u 1:9 w l t 'Fit.phase'") return
def ARLineSpectra(ar): """ Convert AR coeffs to LSPs From wikipedia: A palindromic polynomial (i.e., P) of odd degree has -1 as a root. An antipalindromic polynomial (i.e., Q) has 1 as a root. An antipalindromic polynomial of even degree has -1 and 1 as roots """ order = ar.shape[-1] ret = np.zeros(ar.shape) for a, o in core.refiter([ar, ret], core.newshape(ar.shape)): p = np.ones((order+2)) q = np.ones((order+2)) q[-1] = -1.0 for i in range(order): p[i+1] = -a[i] - a[order-i-1] q[i+1] = -a[i] + a[order-i-1] pr = np.roots(p) qr = np.roots(q) j = 0 an = np.ndarray((order+2)) for i in range(len(pr)): if np.imag(pr[i]) >= 0.0: an[j] = np.angle(pr[i]) j += 1 if np.imag(qr[i]) >= 0.0: an[j] = np.angle(qr[i]) j += 1 # The angle list (an) will always contain both 0 and pi; they # will move to the ends after the sort o[...] = np.sort(an)[1:-1] return ret;
def plot_vis_3(d1,d2,d3): fig = plt.figure() p1=fig.add_subplot(3,2,1) p1.set_title("data_amp") i1=p1.imshow(np.abs(d1), interpolation='nearest',aspect='auto') fig.colorbar(i1) p1.xaxis.set_ticklabels([]) p2=fig.add_subplot(3,2,2) p2.set_title("data_phs") i2=p2.imshow(np.angle(d1),interpolation='nearest',aspect='auto') fig.colorbar(i2) p2.xaxis.set_ticklabels([]) p3=fig.add_subplot(3,2,3) p3.set_title("model_amp") i3=p3.imshow(np.abs(d2),interpolation='nearest',aspect='auto') fig.colorbar(i3) p3.xaxis.set_ticklabels([]) p4=fig.add_subplot(3,2,4) p4.set_title("model_phs") i4=p4.imshow(np.angle(d2),interpolation='nearest',aspect='auto') fig.colorbar(i4) p4.xaxis.set_ticklabels([]) p5=fig.add_subplot(3,2,5) p5.set_title("sol*model_amp") i5=p5.imshow(np.abs(d3),interpolation='nearest',aspect='auto') fig.colorbar(i5) p6=fig.add_subplot(3,2,6) p6.set_title("sol*model_phs") i6=p6.imshow(np.angle(d3),interpolation='nearest',aspect='auto') fig.colorbar(i6) plt.show()
def ISPC_over_trials_hb(data, channels, faverage=True): """Calculate the ISPC over time. Parameters ---------- data : numpy array The data to be used. It should be trials x channels x frequencies x times. freqs : int A list with the frequencies to be calculates. channels : list List containing two channels. faverage : bool If true the average is returned, If false each frequency is returned. Returns ------- result : numpy array The result is a numpy array with the lengt equal to the number of trials. """ result = np.empty([len(freqs), data.shape[2]]) chan_A, chan_B = channels[0], channels[1] for i in range(result.shape[2]): result[ii, i] = np.abs(np.mean(np.exp( 1j*(np.angle(data[:, chan_A, i, 4]) - np.angle(data[:, chan_B, i, 4]))))) return result
def ISPC_over_time(data, frequencies, channels, faverage=True): """Calculate the ISPC over time. Parameters ---------- data : numpy array The data to be used. It should be trials x channels x times x frequencies. frequencies : list A list with the frequencies to be calculates. channels : list List containing two channels. faverage : bool If true the average is returned, If false each frequency is returned. Returns ------- result : numpy array The result is a numpy array with the length of the length of the epochs. """ result = np.empty([len(frequencies), data.shape[0]]) chan_A, chan_B = channels[0], channels[1] for ii in range(len(frequencies)): for i in range(len(data)): result[ii, i] = np.abs(np.mean(np.exp( 1j*(np.angle(data[i, chan_A, :, ii]) - np.angle(data[i, chan_B, :, ii]))))) if faverage: result = result.mean(axis=0).squeeze() return result
def drawDataCallback(baseline): matplotlib.pyplot.clf() acc_n,interleave_a,interleave_b = get_data(baseline) matplotlib.pyplot.subplot(211) if ifch == True: matplotlib.pyplot.semilogy(numpy.abs(interleave_a)) matplotlib.pyplot.xlim(0,1024) else: matplotlib.pyplot.semilogy(xaxis,numpy.abs(interleave_a)) matplotlib.pyplot.grid() matplotlib.pyplot.title('Integration number %i \n%s'%(acc_n,baseline)) matplotlib.pyplot.ylabel('Power (arbitrary units)') matplotlib.pyplot.subplot(212) if ifch == True: matplotlib.pyplot.plot(numpy.unwrap(numpy.angle(interleave_b))) matplotlib.pyplot.xlim(0,1024) matplotlib.pyplot.xlabel('FFT Channel') else: matplotlib.pyplot.plot(xaxis,(numpy.angle(interleave_b))) matplotlib.pyplot.xlabel('FFT Frequency') matplotlib.pyplot.ylabel('Phase') matplotlib.pyplot.ylim(-numpy.pi,numpy.pi) matplotlib.pyplot.grid() matplotlib.pyplot.draw() fig.canvas.manager.window.after(100, drawDataCallback,baseline)
def resData2(self,xval,yval,yval_sim=None,xlabel='Frequency',xunit='Hz',plottype='amp', ampformat='log',save=False,Dir=None): self.figure.clear() self.figure.subplots_adjust(bottom=0.15,left=0.17) self.axes = self.figure.add_subplot(111) if plottype=='real/imag': self.axes.plot(np.real(yval),np.imag(yval),np.real(yval_sim),np.imag(yval_sim)) self.axes.set_xlabel("Re(S)") self.axes.set_ylabel("Im(S)") else: self.axes.set_xlabel(xlabel+' ['+xunit+']') if plottype=='amp': if ampformat=="log": self.axes.plot(xval,10*np.log(np.absolute(yval)),xval,10*np.log(np.absolute(yval_sim))) self.axes.set_ylabel("Amplitude [dB]") if ampformat=='lin': self.axes.plot(xval,np.absolute(yval),xval,np.absolute(yval_sim)) self.axes.set_ylabel("Amplitude") if plottype=='phase': if yval_sim==None: #this option is needed for lorentz function since we only fit the amplitude self.axes.plot(xval,np.angle(yval)) else: self.axes.plot(xval,np.angle(yval),xval,np.angle(yval_sim)) self.axes.set_ylabel('Phase [rad]') if save: print_fig = self.figure print_fig.savefig(Dir) else: self.draw()
def get_closure_phase(infile='L401323_SB349_uv.dppp.MS',\ triangle = ['TS001','DE601HBA','DE605HBA']): a=inspect.stack() stacklevel=0 for k in range(len(a)): if (string.find(a[k][1],'ipython console')>0): stacklevel=k myf=sys._getframe(stacklevel).f_globals myf['__last_task']='mytask' myf['taskname']='mytask' tb=myf['tb'] oroot = infile.split('uv')[0] for lfile in np.sort(glob.glob(oroot+'*ms')): os.system('ms2uvfits in='+lfile+' out='+lfile.replace('ms','fits')+' writesyscal=F') if lfile == infile: continue tb.open(lfile+'/ANTENNA') names = tb.getcol('NAME') trnum = [] for itr in range(3): trnum.append(np.argwhere(names==triangle[itr])[0][0]) tb.close() trnum.sort() tb.open(lfile) ant1 = tb.getcol('ANTENNA1') ant2 = tb.getcol('ANTENNA2') data = tb.getcol('DATA') ph12 = +np.angle(data[0,0,(ant1==trnum[0])&(ant2==trnum[1])]) ph23 = +np.angle(data[0,0,(ant1==trnum[1])&(ant2==trnum[2])]) ph31 = -np.angle(data[0,0,(ant1==trnum[0])&(ant2==trnum[2])]) clph = ph12+ph23+ph31 np.putmask(clph,clph>np.pi,clph-2.*np.pi) np.putmask(clph,clph<-np.pi,clph+2.*np.pi) # np.savetxt(lfile.replace('ms','txt'),np.unwrap(clph)) np.savetxt(lfile.replace('ms','txt'),clph)
def plot_line_on_signal(self, color ='m', sampling_rate = None, **kargs): if 'ax'in kargs: ax = kargs['ax'] if sampling_rate is None: x = self.time_line v = self.value_line y = np.cos(np.angle(v))*np.abs(v) else : if self.time_line.size>1: old_dt = (self.time_line[1]-self.time_line[0]).rescale('s').magnitude x = np.arange(self.time_start, self.time_stop+old_dt, 1./sampling_rate.rescale('Hz').magnitude) #~ l = int((self.time_stop-self.time_start)*sampling_rate.rescale('Hz').magnitude) #~ x = self.time_start + np.arange(l) / sampling_rate.rescale('Hz').magnitude else: x=self.time_line v = self.value_line y = np.cos(np.angle(v))*np.abs(v) # Before resampling, in order to avoid slow down due the use of ifft in scipy.resample # y is padded with 0 proportionnally to the distance from x.size to the next 2**N # QUESTION: does it lead to some strange edge effects??? N=np.ceil(np.log2(x.size)) yy=np.r_[y,np.zeros(np.floor(y.size*(2**N-x.size)/x.size))] yy = scipy.signal.resample( yy, 2**N) y = yy[:x.size] l = ax.plot(x,y , linewidth = 1, color=color) return l
def plot_parameters(gid, data): print("Plotting transformed wavepacket parameters of group '"+str(gid)+"'") # Grid of mother and first spawned packet grid_m = data[0][0] grid_s = data[1][0] # Parameters of mother and first spawned packet P, Q, S, p, q = data[0][1] B, A, S, b, a = data[1][1] X = P*abs(Q)/Q # Various interesting figures fig = figure() ax = fig.gca() ax.plot(grid_m, real(X), "*", label=r"$\Re \frac{P |Q|}{Q}$") ax.plot(grid_s, real(B), "o", label=r"$\Re B$") ax.legend() ax.grid(True) fig.savefig("test_spawned_PI_realparts_group"+str(gid)+GD.output_format) fig = figure() ax = fig.gca() ax.plot(grid_m, imag(X), "*", label=r"$\Im \frac{P |Q|}{Q}$") ax.plot(grid_s, imag(B), "o", label=r"$\Im B$") ax.legend() ax.grid(True) fig.savefig("test_spawned_PI_imagparts_group"+str(gid)+GD.output_format) fig = figure() ax = fig.gca() ax.plot(real(X), imag(X), "-*", label=r"traject $\frac{P |Q|}{Q}$") ax.plot(real(B), imag(B), "-*", label=r"traject $B$") ax.legend() ax.grid(True) fig.savefig("test_spawned_PI_complex_trajectories_group"+str(gid)+GD.output_format) fig = figure() ax = fig.gca() ax.plot(grid_m, angle(X), label=r"$\arg \frac{P |Q|}{Q}$") ax.plot(grid_s, angle(B), label=r"$\arg B$") ax.legend() ax.grid(True) fig.savefig("test_spawned_PI_angles_group"+str(gid)+GD.output_format)
def stretch_lattice(x, y, fov, stretch, angle): if stretch < 1: raise RunTimeError("Error. Stretch values must be >1. {} entered.".format(stretch)) print "Stretching by a factor of {} at an angle of {} degrees to the x-axis about the image center".format( stretch, angle ) x_new = [] y_new = [] x_shifted, y_shifted = x - fov / 2.0, y - fov / 2.0 x = ( x_shifted + np.sqrt(x_shifted ** 2 + y_shifted ** 2) * np.cos(np.angle(x_shifted + y_shifted * 1j) - np.radians(angle)) * np.cos(np.radians(angle)) * (stretch - 1) + fov / 2.0 ) y = ( y_shifted + np.sqrt(x_shifted ** 2 + y_shifted ** 2) * np.cos(np.angle(x_shifted + y_shifted * 1j) - np.radians(angle)) * np.sin(np.radians(angle)) * (stretch - 1) + fov / 2.0 ) for i in range(len(x)): if x[i] < fov and x[i] >= 0 and y[i] < fov and y[i] >= 0: x_new.append(x[i]) y_new.append(y[i]) print "{} particles discarded".format(len(x) - len(x_new)) return np.array(x_new), np.array(y_new)
def write(self, MA=False): with open(self.filename, 'w') as g: g.write( "! TOUCHSTONE file generated by Touchstone Python Converter\n" ) g.write( "! Date and time: %s\n"%time.strftime("%b %d %Y %H:%M:%S") ) if MA: g.write( "# GHZ S MA R 50\n" ) for row in zip(self.raw['freq'], self.raw['s11'], self.raw['s12'], self.raw['s21'], self.raw['s22']): freq, s11, s12, s21, s22 = row freq *= 1e-9 ms11, as11 = abs(s11), angle(s11,deg=True) ms12, as12 = abs(s12), angle(s12,deg=True) ms21, as21 = abs(s21), angle(s21,deg=True) ms22, as22 = abs(s22), angle(s22,deg=True) pattern = "{:<15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}\n" g.write( pattern.format(freq, ms11, as11, ms21, as21, ms12, as12, ms22, as22) ) else: g.write( "# GHZ S RI R 50\n" ) for row in zip(self.raw['freq'], self.raw['s11'], self.raw['s12'], self.raw['s21'], self.raw['s22']): freq, s11, s12, s21, s22 = row freq *= 1e-9 pattern = "{:<15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}\n" g.write( pattern.format(freq, s11.real, s11.imag, s21.real, s21.imag, s12.real, s12.imag, s22.real, s22.imag) ) g.write( "! noise parameters\n" ) for row in zip(self.raw['freq'], self.raw['nfmin'], self.raw['sopt'], self.raw['rn']): freq, nfmin, sopt, rn = row freq *= 1e-9 msopt, asopt = abs(sopt), angle(sopt,deg=True) rn *= 1./50. pattern = "{:<15.6e}{:>15.6e}{:>15.6e}{:>15.6e}{:>15.6e}\n" #print freq, nfmin, msopt, asopt, rn g.write( pattern.format(freq, nfmin, msopt, asopt, rn) )
def update(attrname,old,new): ori=orientation.value*(numpy.pi/180.0) oriWidth=orientationWidth.value*(numpy.pi/180.0) oband=[ori, ori-oriWidth] #oband=[ori, numpy.pi/8] t1 = numpy.angle(numpy.exp(complex(0,1)*(theta-oband[0]))) # center it t1 = numpy.exp(-(t1**2/(2*oband[1]*oband[1]))) # and put a gaussian around it # make the 2nd lobe on the other side of k-space t2 = numpy.angle(numpy.exp(complex(0,1)*(theta-oband[0]-numpy.pi))) t2 = numpy.exp(-(t2**2/(2*oband[1]*oband[1]))) thisSF=spatialFreq.value sfWidth=spatialFreqWidth.value fband=[thisSF,thisSF-sfWidth] SF = numpy.exp(-((r-fband[0])**2/(2.0*fband[1]*fband[1]))) customFilter = SF*(t1 + t2) source2 = ColumnDataSource(data={'image': [customFilter]}) p2.image(image="image", x=[0], y=[0], dw=[10], dh=[10],source=source2,palette="Spectral11") filteredFFT = imageFFT*customFilter filteredImage = numpy.fft.ifft2(numpy.fft.fftshift(filteredFFT)) filteredImageReal=numpy.real(filteredImage) source3 = ColumnDataSource(data={'image': [filteredImageReal]}) p3.image(image="image", x=[0], y=[0], dw=[10], dh=[10],source=source3) thisTitle="Ori: %2.1f [%2.1f, %2.1f], SF: %2.1f, %2.1f"%(orientation.value,oband[0]*180/numpy.pi, oband[1]*180/numpy.pi,thisSF, sfWidth) p3.title=thisTitle
def write_cube(self, index, fname, repeat=None, real=True): """Dump specified Wannier function to a cube file""" from ase.io.cube import write_cube # Default size of plotting cell is the one corresponding to k-points. if repeat is None: repeat = self.kptgrid atoms = self.calc.get_atoms() * repeat func = self.get_function(index, repeat) # Handle separation of complex wave into real parts if real: if self.Nk == 1: func *= np.exp(-1.0j * np.angle(func.max())) if 0: assert max(abs(func.imag).flat) < 1e-4 func = func.real else: func = abs(func) else: phase_fname = fname.split(".") phase_fname.insert(1, "phase") phase_fname = ".".join(phase_fname) write_cube(phase_fname, atoms, data=np.angle(func)) func = abs(func) write_cube(fname, atoms, data=func)
def istft(spec, hop): """ :param spec: The result of an stft, spectra at different times :param hop: number of smaples to move forward between windows :return: time domain signal which is related to the original by a constant coefficient. fftlen inferred from shape of input vector. """ fftlen = 2 * (spec.shape[1] - 1) xs = np.empty((spec.shape[0], fftlen)) w = np.hanning(fftlen) out = np.empty(spec.shape[0] * hop + fftlen, dtype=complex) # Need a quick calc to find the length of the output array phase = np.zeros(spec.shape[1]) adj = np.zeros(spec.shape[1], dtype=complex) for t in range(spec.shape[0]): if t > 0: phase += np.angle(spec[t]) - np.angle(spec[t - 1]) phase %= 2 * np.pi adj.real, adj.imag = np.cos(phase), np.sin(phase) # xs[t] = np.fft.ifft(Xs[t]) xs[t] = np.fft.irfft(np.abs(spec[t]) * adj) out[t * hop: t * hop + fftlen] += xs[t] * w return out
def getPhaseNoise(self, psi0, psi1): """ Warning: this function considers spin distribution ellipse to be horizontal, which is not always so. """ ensembles = psi0.shape[0] get = self._env.fromDevice reduce = self._reduce creduce = self._creduce i = self._getInteraction(psi0, psi1) i = get(creduce(i, ensembles)) # Complex numbers {S_xj + iS_yj, j = 1..N} phi = numpy.angle(i) # normalizing # Center of the distribution can be shifted to pi or -pi, # making mean() return incorrect values. # The following approximate method will allow us to shift the center to zero # It will work only if the maximum of the distribution is clearly # distinguished; otherwise it can give anything as a result Pperp = numpy.exp(1j * phi) # transforming Pperp to distribution on the unit circle Pmean = Pperp.mean() # Center of masses is supposed to be close to the center of distribution # Normalizing the direction to the center of masses # Now angle(Pmean) ~ proper mean of Pperp Pmean /= numpy.abs(Pmean) # Shifting the distribution Pcent = Pperp * Pmean.conj() phi_centered = numpy.angle(Pcent) return phi_centered.std()
def plot_state_qsphere(rho): """Plot the qsphere representation of a quantum state.""" num = int(np.log2(len(rho))) # get the eigenvectors and egivenvalues we, stateall = linalg.eigh(rho) for k in range(2**num): # start with the max probmix = we.max() prob_location = we.argmax() if probmix > 0.001: print("The " + str(k) + "th eigenvalue = " + str(probmix)) # get the max eigenvalue state = stateall[:, prob_location] loc = np.absolute(state).argmax() # get the element location closes to lowest bin representation. for j in range(2**num): test = np.absolute( np.absolute(state[j]) - np.absolute(state[loc])) if test < 0.001: loc = j break # remove the global phase angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j * angles) # print(state) # print(angles) state = angleset * state # print(state) state.flatten() # start the plotting fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.axes.set_xlim3d(-1.0, 1.0) ax.axes.set_ylim3d(-1.0, 1.0) ax.axes.set_zlim3d(-1.0, 1.0) ax.set_aspect("equal") ax.axes.grid(False) # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 25) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k', alpha=0.05, linewidth=0) # wireframe # Get rid of the panes ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) d = num for i in range(2**num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") zvalue = -2 * weight / d + 1 number_of_divisions = n_choose_k(d, weight) weight_order = bit_string_index(element) # if weight_order >= number_of_divisions / 2: # com_key = compliment(element) # weight_order_temp = bit_string_index(com_key) # weight_order = np.floor( # number_of_divisions / 2) + weight_order_temp + 1 angle = weight_order * 2 * np.pi / number_of_divisions xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle) ax.plot([xvalue], [yvalue], [zvalue], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=10, alpha=1) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) colorstate = phase_to_color_wheel(state[i]) a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20, alpha=prob, arrowstyle="-", color=colorstate, lw=10) ax.add_artist(a) # add weight lines for weight in range(d + 1): theta = np.linspace(-2 * np.pi, 2 * np.pi, 100) z = -2 * weight / d + 1 r = np.sqrt(1 - z**2) x = r * np.cos(theta) y = r * np.sin(theta) ax.plot(x, y, z, color=(.5, .5, .5)) # add center point ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=10, alpha=1) plt.show() we[prob_location] = 0 else: break
m = np.ones((1, 1), dtype = np.complex128) m[0, 0] = n1/nm nptsx = extent*resolution nptsy = extent*resolution scanx = np.linspace(-extent/2, extent/2, nptsx, endpoint=True)*twopi scany = np.linspace(-extent/2, extent/2, nptsy, endpoint=True)*twopi coordX, coordY = np.meshgrid(scanx, scany) coordX.resize(nptsx*nptsy) coordY.resize(nptsx*nptsy) coordZ = np.ones(nptsx*nptsy, dtype=np.float64)*distance*twopi coord = np.vstack((coordX, coordY, coordZ)).transpose() terms, E, H = scattnlay.fieldnlay(x, m, coord) # take the x-component of the electric field Ex = E[:,:,0].reshape(nptsx, nptsy) # normalize by the background field (free space propagation) Ex /= np.exp(1j*2*np.pi*distance*nm) # plot the phase (np.angle) of the x-component of the electric field ax = plt.subplot(111) mapper = plt.imshow(np.angle(Ex)) plt.colorbar(mapper, ax=ax, label="phase [rad]") plt.title("phase retardation introduced by a dielectric sphere") plt.show()
def _phase_mean(phases): return np.angle(np.sum(np.exp(PI2I * phases))) / (2 * np.pi)
def phaseBasedMagnify(vidFname, vidFnameOut, maxFrames, windowSize, factor, fpsForBandPass, lowFreq, highFreq): # initialize the steerable complex pyramid steer = Steerable(5) pyArr = Pyramid2arr(steer) print("Reading: {}".format(vidFname)) # get vid properties vidReader = cv2.VideoCapture(vidFname) if USE_CV2: # OpenCV 2.x interface vidFrames = int(vidReader.get(cv.CV_CAP_PROP_FRAME_COUNT)) width = int(vidReader.get(cv.CV_CAP_PROP_FRAME_WIDTH)) height = int(vidReader.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) fps = int(vidReader.get(cv.CV_CAP_PROP_FPS)) func_fourcc = cv.CV_FOURCC else: # OpenCV 3.x interface vidFrames = int(vidReader.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(vidReader.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vidReader.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(vidReader.get(cv2.CAP_PROP_FPS)) func_fourcc = cv2.VideoWriter_fourcc if np.isnan(fps): fps = 30 print(' {} frames'.format(vidFrames)) print(' (%d x %d)({},{})'.format(width, height)) print(' FPS: {}'.format(fps)) # video Writer fourcc = func_fourcc('M', 'J', 'P', 'G') vidWriter = cv2.VideoWriter(vidFnameOut, fourcc, int(fps), (width, height), 1) print('Writing: {}'.format(vidFnameOut)) # how many frames nrFrames = min(vidFrames, maxFrames) # read video #print steer.height, steer.nbands # setup temporal filter filter = IdealFilterWindowed(windowSize, lowFreq, highFreq, fps=fpsForBandPass, outfun=lambda x: x[0]) #filter = ButterBandpassFilter(1, lowFreq, highFreq, fps=fpsForBandPass) print('FrameNr:') for frameNr in range(nrFrames + windowSize): print(frameNr) sys.stdout.flush() if frameNr < nrFrames: # read frame _, im = vidReader.read() if im is None: # if unexpected, quit break # convert to gray image if len(im.shape) > 2: grayIm = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) else: # already a grayscale image? grayIm = im # get coeffs for pyramid coeff = steer.buildSCFpyr(grayIm) # add image pyramid to video array # NOTE: on first frame, this will init rotating array to store the pyramid coeffs arr = pyArr.p2a(coeff) phases = np.angle(arr) # add to temporal filter filter.update([phases]) # try to get filtered output to continue try: filteredPhases = filter.next() except StopIteration: continue print('*') # motion magnification magnifiedPhases = (phases - filteredPhases) + filteredPhases * factor # create new array newArr = np.abs(arr) * np.exp(magnifiedPhases * 1j) # create pyramid coeffs newCoeff = pyArr.a2p(newArr) # reconstruct pyramid out = steer.reconSCFpyr(newCoeff) # clip values out of range out[out > 255] = 255 out[out < 0] = 0 # make a RGB image rgbIm = np.empty((out.shape[0], out.shape[1], 3)) rgbIm[:, :, 0] = out rgbIm[:, :, 1] = out rgbIm[:, :, 2] = out #write to disk res = cv2.convertScaleAbs(rgbIm) vidWriter.write(res) # free the video reader/writer vidReader.release() vidWriter.release()
def loopFilter(gamma, LoopBW, PM, CPGain, KVCO, Fout, Fcomp, T31): LoopBWRads = 2 * math.pi * LoopBW ####### #Numerical solution of T1 using bisection method ####### def T1est(T1guess): wcT1 = LoopBWRads * T1guess #return wcT1,math.atan(wcT1) return PM - (180 / math.pi) * (math.atan(gamma / wcT1 / (1 + T31)) - math.atan(wcT1) - math.atan(wcT1 * T31)) #Approximate value from Banerjee T1approx = ((1 / math.cos(PM * math.pi / 180)) - math.tan(PM * math.pi / 180)) / LoopBWRads / (1 + T31) #Create a bracket such T1est(a) and T1est(b) have opposite signs. #So that bisection method converges to a solution. #Since T1est(Tapprox) will be small, if it's negative and we double it, we will have a good bracket. #If it's positive and we halve it we'll also have a good bracket. if T1est(T1approx) < 0: a = T1approx b = T1approx * 2.0 # print a, b else: a = T1approx * 0.5 b = T1approx #print a, b tol = 0.01 c = (a + b) / 2.0 #Mid point. First guess #First guess will be worse than T1approx but the algorithm should still converge quickly. while math.fabs(T1est(c)) > tol: # print a,b,c if (T1est(a) < 0 and T1est(c) < 0) or (T1est(a) > 0 and T1est(c) > 0): a = c else: b = c c = (a + b) / 2.0 # print c, T1est(c,gamma,LoopBWRads,T31,PM) T1approx = c ####### #Rest of calculations ####### T3 = T1approx * T31 T2 = gamma / ((LoopBWRads)**2) / (T1approx + T3) #print "T1approx = ",T1approx," T2 = ",T2," T3 = ",T3 N = float(Fout / Fcomp) P = 8.0 Ndig = float(N / P) A0_sqrt = math.sqrt( (1 + (LoopBWRads * T2)**2) / (1 + (LoopBWRads * T1approx)**2) / (1 + (LoopBWRads * T3)**2)) A0_coeff = CPGain * KVCO / ((LoopBWRads)**2) / N A0 = A0_coeff * A0_sqrt A1 = A0 * (T1approx + T3) A2 = A0 * T1approx * T3 #print "A0 = ",A0," A1 = ",A1," A2 = ",A2 C1_sqrt = math.sqrt(1 + T2 * (T2 * A0 - A1) / A2) C1 = A2 * (1 + C1_sqrt) / (T2**2) C3 = (-(T2**2) * (C1**2) + T2 * A1 * C1 - A2 * A0) / ((T2**2) * C1 - A2) C2 = A0 - C1 - C3 R2 = T2 / C2 R3 = A2 / C1 / C3 / T2 #print "C1 = ",C1," C2 = ",C2," C3 = ",C3," R2 = ",R2," R3 = ",R3 #return C1/1e-9,C2/1e-9,C3/1e-9,R2/1e3,R3/1e3,A2,A1,A0,N f = np.logspace(2, 8, 31) f2 = [] for i in range(len(f)): f2.append(f[i] * 2 * math.pi) K = KVCO * CPGain / N num = [] R = [] ROL = [] XOL = [] X = [] den3Real = [] den3Imag = [] den3 = [] den3OLReal = [] den3OLImag = [] den3OL = [] constantCL = K * N magCL = [] phaseCL = [] magOL = [] phaseOL = [] vcoTFNumR = [] vcoTFNumX = [] vcoTFNumReal = [] vcoTFNumImag = [] vcoTFNum = [] magvcoTF = [] magprescalerTF = [] magpfdcpTF = [] denR2 = [] denR2_R = [] denR2_X = [] magR2TF = [] magLFTF_num_R = [] magLFTF_num_X = [] magLFTF_num = [] magLFTF_den_R = [] magLFTF_den_X = [] magLFTF_den = [] magLFTF = [] magLFTFR2 = [] numR3_R = [] numR3_X = [] numR3 = [] denR3 = [] denR3_R = [] denR3_X = [] magR3TF = [] magLFTFR3 = [] for i in range(len(f)): #Expand the denominator of Eq. 16.2 on page 127 to get real and imag components. #A3 = 0 R.append(A2 * ((f2[i])**4) - A0 * ((f2[i])**2) + K) #Real comp. of CL denom X.append(K * T2 * f2[i] - A1 * ((f2[i])**3)) #Imag comp. of CL denom #Expand denominator of Z(s)/s for 3rd order ROL.append(A2 * ((f2[i])**4) - A0 * ((f2[i])**2)) #Real comp. of OL denom XOL.append(-A1 * ((f2[i])**3)) #Imag comp. of OL denom den3Real.append(R[i]) den3Imag.append(X[i]) den3OLReal.append(ROL[i]) den3OLImag.append(XOL[i]) den3.append(complex(den3Real[i], den3Imag[i])) den3OL.append(complex(den3OLReal[i], den3OLImag[i])) #Transfer function for VCO noise vcoTFNumR.append(A2 * ((f2[i])**4) - A0 * ((f2[i])**2)) vcoTFNumX.append(-A1 * ((f2[i])**3)) vcoTFNumReal.append(vcoTFNumR[i]) vcoTFNumImag.append(vcoTFNumX[i]) vcoTFNum.append(complex(vcoTFNumReal[i], vcoTFNumImag[i])) #The denominator is the same as that of the CL transfer function #constant.append(K*N) #num.append(math.sqrt(1.0+((f[i]/(1/T2))**2))) num.append(complex(1.0, f2[i] / (1 / T2))) magCL.append(20 * np.log10(constantCL) + 20 * np.log10(np.abs(num[i])) - 20 * np.log10(np.abs(den3[i]))) phaseCL.append( (180 / math.pi) * (np.angle(num[i]) - np.angle(den3[i]))) magOL.append(20 * np.log10(K) + 20 * np.log10(np.abs(num[i])) - 20 * np.log10(np.abs(den3OL[i]))) phaseOL.append((180 / math.pi) * (np.angle(num[i]) - np.angle(den3OL[i])) - 180) magvcoTF.append(20 * np.log10(np.abs(vcoTFNum[i])) - 20 * np.log10(np.abs(den3[i]))) magprescalerTF.append(magCL[i] + 20 * np.log10(1 / Ndig)) magpfdcpTF.append(magCL[i] + 20 * np.log10(1 / CPGain)) denR2_R.append((C1 + C2 + C3) - ((2 * math.pi * f[i])**2) * C3 * C2 * C1 * R2 * R3) denR2_X.append(2 * math.pi * f[i] * (C3 * R3 * (C1 + C2) + C2 * R2 * (C1 + C3))) denR2.append(complex(denR2_R[i], denR2_X[i])) magR2TF.append(20 * np.log10(C2) - 20 * np.log10(np.abs(denR2[i]))) magLFTF_num_R.append(-KVCO * A1 * (f2[i])**2) magLFTF_num_X.append(A0 * KVCO * f2[i] - A2 * KVCO * (f2[i])**3) magLFTF_num.append(complex(magLFTF_num_R[i], magLFTF_num_X[i])) magLFTF_den_R.append(A2 * (f2[i])**4 - A0 * (f2[i])**2 + K) magLFTF_den_X.append(K * T2 * f2[i] - A1 * (f2[i])**3) magLFTF_den.append(complex(magLFTF_den_R[i], magLFTF_den_X[i])) magLFTF.append(20 * np.log10(np.abs(magLFTF_num[i])) - 20 * np.log10(np.abs(magLFTF_den[i]))) magLFTFR2.append(magLFTF[i] + magR2TF[i]) #adds the R2 TF and the LFTF numR3_R.append(C1 + C2) numR3_X.append(2 * math.pi * f[i] * C1 * C2 * R2) numR3.append(complex(numR3_R[i], numR3_X[i])) denR3_R.append((C1 + C2 + C3) - ((2 * math.pi * f[i])**2) * C3 * C2 * C1 * R2 * R3) denR3_X.append(2 * math.pi * f[i] * (C3 * R3 * (C1 + C2) + C2 * R2 * (C1 + C3))) denR3.append(complex(denR3_R[i], denR3_X[i])) magR3TF.append(20 * np.log10(np.abs(numR3[i])) - 20 * np.log10(np.abs(denR3[i]))) magLFTFR3.append(magLFTF[i] + magR3TF[i]) #adds the R3 TF and the LFTF return C1 / 1e-9, C2 / 1e-9, C3 / 1e-9, R2 / 1e3, R3 / 1e3, f, magCL, magOL, phaseOL, magvcoTF, magprescalerTF, magpfdcpTF, magLFTFR2, magLFTFR3
def angles(self): """Returns a sequence of angles (read-only property).""" return np.angle(self.hs)
# Now, just multiply x1 and the digital complex exponential x2 = x1 * fc1 # Downsample the signal x3 = signal.lfilter(lpf, 1.0, x2) # Decimate the signal dec_rate = int(Fs / f_bw) x4 = x3[0::dec_rate] # Calculate the new sampling rate Fs_y = Fs / dec_rate # Polar discriminator y5 = x4[1:] * np.conj(x4[:-1]) x5 = np.angle(y5) # The de-emphasis filter # Given a signal 'x5' (in a numpy array) with sampling rate Fs_y d = Fs_y * 75e-6 # Calculate the # of samples to hit the -3dB point x = np.exp(-1 / d) # Calculate the decay between each sample b = [1 - x] # Create the filter coefficients a = [1, -x] x6 = signal.lfilter(b, a, x5) # Find a decimation rate to achieve audio sampling rate between 44-48 kHz audio_freq = 44100.0 dec_audio = int(Fs_y / audio_freq) Fs_audio = Fs_y / dec_audio # Decimate to audio
if opts.dt: d = d[:-2]/2 + d[2:]/2 - d[1:-1] if opts.fringe: d = d.filled(0) flags = n.where(d[:,0] != 0, 1., 0.) gain = n.sqrt(n.average(flags**2)) ker = n.fft.ifft(flags) d = n.fft.ifft(d, axis=0) if not opts.clean is None: for chan in range(d.shape[1]): d[:,chan],info = a.deconv.clean(d[:,chan],ker,tol=opts.clean) d[:,chan] += info['res'] / gain d = n.ma.concatenate([d[d.shape[0]/2:], d[:d.shape[0]/2]], axis=0) if opts.sum_chan: d = d.sum(axis=1) is_chan_range = False if opts.mode.startswith('phs'): d = n.angle(d.filled(0)) elif opts.mode.startswith('lin'): d = n.ma.absolute(d.filled(0)) d = n.ma.masked_less_equal(d, 0) elif opts.mode.startswith('real'): d = d.real elif opts.mode.startswith('imag'): d = d.imag elif opts.mode.startswith('log'): d = n.ma.absolute(d.filled(0)) d = n.ma.masked_less_equal(d, 0) d = n.ma.log10(d) else: raise ValueError('Unrecognized plot mode.') if not opts.share and not is_chan_range and not is_time_range: p.subplot(m2, m1, cnt+1) dmin,dmax = None,None label = '' else: label = bl + ' '
def plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=True, show_state_phases=False, use_degrees=False, *, rho=None): """Plot the qsphere representation of a quantum state. Here, the size of the points is proportional to the probability of the corresponding term in the state and the color represents the phase. Args: state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state. figsize (tuple): Figure size in inches. ax (matplotlib.axes.Axes): An optional Axes object to be used for the visualization output. If none is specified a new matplotlib Figure will be created and used. Additionally, if specified there will be no returned Figure since it is redundant. show_state_labels (bool): An optional boolean indicating whether to show labels for each basis state. show_state_phases (bool): An optional boolean indicating whether to show the phase for each basis state. use_degrees (bool): An optional boolean indicating whether to use radians or degrees for the phase values in the plot. Returns: Figure: A matplotlib figure instance if the ``ax`` kwarg is not set Raises: ImportError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. QiskitError: Input statevector does not have valid dimensions. Example: .. jupyter-execute:: from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere %matplotlib inline qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector.from_instruction(qc) plot_state_qsphere(state) """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed. To install, run ' '"pip install matplotlib".') from mpl_toolkits.mplot3d import proj3d from matplotlib.patches import FancyArrowPatch import matplotlib.gridspec as gridspec from matplotlib import pyplot as plt from matplotlib.patches import Circle from matplotlib import get_backend class Arrow3D(FancyArrowPatch): """Standard 3D arrow.""" def __init__(self, xs, ys, zs, *args, **kwargs): """Create arrow.""" FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): """Draw the arrow.""" xs3d, ys3d, zs3d = self._verts3d xs, ys, _ = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) try: import seaborn as sns except ImportError as ex: raise ImportError('Must have seaborn installed to use ' 'plot_state_qsphere. To install, run "pip install seaborn".') from ex rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") # get the eigenvectors and eigenvalues eigvals, eigvecs = linalg.eigh(rho.data) if figsize is None: figsize = (7, 7) if ax is None: return_fig = True fig = plt.figure(figsize=figsize) else: return_fig = False fig = ax.get_figure() gs = gridspec.GridSpec(nrows=3, ncols=3) ax = fig.add_subplot(gs[0:3, 0:3], projection='3d') ax.axes.set_xlim3d(-1.0, 1.0) ax.axes.set_ylim3d(-1.0, 1.0) ax.axes.set_zlim3d(-1.0, 1.0) ax.axes.grid(False) ax.view_init(elev=5, azim=275) # Force aspect ratio # MPL 3.2 or previous do not have set_box_aspect if hasattr(ax.axes, 'set_box_aspect'): ax.axes.set_box_aspect((1, 1, 1)) # start the plotting # Plot semi-transparent sphere u = np.linspace(0, 2 * np.pi, 25) v = np.linspace(0, np.pi, 25) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=1, cstride=1, color=plt.rcParams['grid.color'], alpha=0.2, linewidth=0) # Get rid of the panes ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the spines ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0)) # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) # traversing the eigvals/vecs backward as sorted low->high for idx in range(eigvals.shape[0]-1, -1, -1): if eigvals[idx] > 0.001: # get the max eigenvalue state = eigvecs[:, idx] loc = np.absolute(state).argmax() # remove the global phase from max element angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi) angleset = np.exp(-1j * angles) state = angleset * state d = num for i in range(2 ** num): # get x,y,z points element = bin(i)[2:].zfill(num) weight = element.count("1") zvalue = -2 * weight / d + 1 number_of_divisions = n_choose_k(d, weight) weight_order = bit_string_index(element) angle = (float(weight) / d) * (np.pi * 2) + \ (weight_order * 2 * (np.pi / number_of_divisions)) if (weight > d / 2) or ((weight == d / 2) and (weight_order >= number_of_divisions / 2)): angle = np.pi - angle - (2 * np.pi / number_of_divisions) xvalue = np.sqrt(1 - zvalue ** 2) * np.cos(angle) yvalue = np.sqrt(1 - zvalue ** 2) * np.sin(angle) # get prob and angle - prob will be shade and angle color prob = np.real(np.dot(state[i], state[i].conj())) if prob > 1: # See https://github.com/Qiskit/qiskit-terra/issues/4666 prob = 1 colorstate = phase_to_rgb(state[i]) alfa = 1 if yvalue >= 0.1: alfa = 1.0 - yvalue if not np.isclose(prob, 0) and show_state_labels: rprime = 1.3 angle_theta = np.arctan2(np.sqrt(1 - zvalue ** 2), zvalue) xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle) yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle) zvalue_text = rprime * np.cos(angle_theta) element_text = '$\\vert' + element + '\\rangle$' if show_state_phases: element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2) if use_degrees: element_text += '\n$%.1f^\\circ$' % (element_angle * 180/np.pi) else: element_angle = pi_check(element_angle, ndigits=3).replace('pi', '\\pi') element_text += '\n$%s$' % (element_angle) ax.text(xvalue_text, yvalue_text, zvalue_text, element_text, ha='center', va='center', size=12) ax.plot([xvalue], [yvalue], [zvalue], markerfacecolor=colorstate, markeredgecolor=colorstate, marker='o', markersize=np.sqrt(prob) * 30, alpha=alfa) a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue], mutation_scale=20, alpha=prob, arrowstyle="-", color=colorstate, lw=2) ax.add_artist(a) # add weight lines for weight in range(d + 1): theta = np.linspace(-2 * np.pi, 2 * np.pi, 100) z = -2 * weight / d + 1 r = np.sqrt(1 - z ** 2) x = r * np.cos(theta) y = r * np.sin(theta) ax.plot(x, y, z, color=(.5, .5, .5), lw=1, ls=':', alpha=.5) # add center point ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5), markeredgecolor=(.5, .5, .5), marker='o', markersize=3, alpha=1) else: break n = 64 theta = np.ones(n) ax2 = fig.add_subplot(gs[2:, 2:]) ax2.pie(theta, colors=sns.color_palette("hls", n), radius=0.75) ax2.add_artist(Circle((0, 0), 0.5, color=plt.rcParams['figure.facecolor'], zorder=1)) offset = 0.95 # since radius of sphere is one. if use_degrees: labels = ['Phase\n(Deg)', '0', '90', '180 ', '270'] else: labels = ['Phase', '$0$', '$\\pi/2$', '$\\pi$', '$3\\pi/2$'] ax2.text(0, 0, labels[0], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(offset, 0, labels[1], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(0, offset, labels[2], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(-offset, 0, labels[3], horizontalalignment='center', verticalalignment='center', fontsize=14) ax2.text(0, -offset, labels[4], horizontalalignment='center', verticalalignment='center', fontsize=14) if return_fig: if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(fig) return fig
import numpy as np from matplotlib import pyplot as plt import cmath as c x = np.array(input('enter seq1:')) n1 = len(x) j = c.sqrt(-1) p = np.pi N = 10000 y = [] w = np.linspace(0, 2 * p, N) for i in range(0, N): sum = 0 for n in range(0, n1, 1): sum = sum + x[n] * (np.exp(-j * w[i] * n)) y = np.append(y, sum) plt.subplot(2, 1, 1) plt.plot(w, np.abs(y)) plt.title("plot of magnitude vs w") plt.subplot(2, 1, 2) plt.title("plot of phase vs w") plt.plot(w, np.angle(y)) plt.show()
size = os.path.getsize(filepath) #获得文件大小 num = int(size / 2) print("size = ", size / 2) y = struct.unpack('h' * num, binfile.read(2 * num)) binfile.close() fft_y = fft(y) # 快速傅里叶变换 print("type(fft_y) = ", type(fft_y)) N = num x = np.arange(N) # 频率个数 half_x = x[range(int(N / 2))] # 取一半区间 abs_y = np.abs(fft_y) # 取复数的绝对值,即复数的模(双边频谱) angle_y = np.angle(fft_y) # 取复数的角度 print("angle_y = ", angle_y) normalization_y = abs_y / N # 归一化处理(双边频谱) normalization_half_y = normalization_y[range(int(N / 2))] # 由于对称性,只取一半区间(单边频谱) # plt.subplot(231) # plt.plot(x, y) # plt.title('原始波形') # # plt.subplot(232) # plt.plot(x, fft_y, 'black') # plt.title('双边振幅谱(未求振幅绝对值)', fontsize=9, color='black') # # plt.subplot(233) # plt.plot(x, abs_y, 'r') # plt.title('双边振幅谱(未归一化)', fontsize=9, color='red')
def plot_chirp_redo(results, chirpnum, spec, fittype='RealImag'): A, Ph, Res, Q = results[6:10] chirpData = signal.detrend(spec.xs(chirpnum)) amp = np.abs(chirpData) phase = np.angle(chirpData) freq = spec.xs(chirpnum).index.values if fittype is 'RealImag': fitted = complexGaus(freq, A, Ph, Res, Q) fitted_amp = np.abs(fitted) fitted_angle = np.angle(fitted) fig, ax1 = plt.subplots(figsize=(8, 8)) color = 'tab:red' ax1.set_xlabel('Freq (Hz)') ax1.set_ylabel('Amp (V)', color=color) ax1.plot(freq, amp, '-', color=color) ax1.plot(freq, fitted_amp / 1e6, '--k') ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx( ) # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('Phase', color=color) # we already handled the x-label with ax1 ax2.plot(freq, phase, '-', color=color) ax2.plot(freq, fitted_angle, '--k') fig.tight_layout( pad=3.0) # otherwise the right y-label is slightly clipped plt.show() fig, ax1 = plt.subplots(figsize=(8, 8)) color = 'tab:red' ax1.set_xlabel('Freq (Hz)') ax1.set_ylabel('Acos(Phi) AKA Real', color=color) #ax1.plot(freq, signal.detrend(amp*np.cos(phase)), '.',color=color) ax1.plot(freq, chirpData, '.', color=color) ax1.plot(freq, (np.abs(fitted) / 1e6) * np.cos(fitted_angle), '--', color='orange') ax1.tick_params(axis='y', labelcolor=color) else: fitted_amp = complexGausAmp(freq, A, Res, Q) fig, ax1 = plt.subplots(figsize=(8, 8)) color = 'tab:red' ax1.set_xlabel('Freq (Hz)') ax1.set_ylabel('Amp (V)', color=color) ax1.plot(freq, amp, '-', color=color) ax1.plot(freq, fitted_amp / 1e6, '--k') ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx( ) # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('Phase', color=color) # we already handled the x-label with ax1 ax2.plot(freq, phase, '-', color=color) ax2.plot(freq, np.repeat(Ph, len(freq)), '--k') fig.tight_layout( pad=3.0) # otherwise the right y-label is slightly clipped plt.show()
def find_2w(x_data, dt): nu = cts.cur_nu average = cts.two_w_average bfilter = cts.two_w_bfilter integral = cts.two_w_integral phi_offset = cts.two_w_phioffset ###### Sampling frequency and bandwidth for the butter bandpass filter ######## fs = 1/dt/nu*1e15 BW = 1.2 ############## # N = len(x_data) #### real frequency step of fft(signal)###### dfreal = 1/(dt*N)/nu*1e15 freqnorm,ampl,ang=FFT(x_data,dt) ####### find index corresponding to the 2-omega peak ######### pk_indeces = np.where(abs(freqnorm - 2) < 0.5)[0] peak_index = np.argmax(ampl[pk_indeces]) peak_index_good = pk_indeces[peak_index] fpeak = freqnorm[peak_index_good] #ifmin=ifmax=0 ########### filtered fft ############ if bfilter == True and average == False: #print('Using bandpass filter around 2omega') lowcut = fpeak - BW/2. highcut = fpeak + BW/2. #i_lc = np.argmin(abs(freqnorm - lowcut)) #i_hc = np.argmin(abs(freqnorm - highcut)) n=len(freqnorm) w, h = butter_bandpass(lowcut,highcut, fs, n, 5) ampl_flt = ampl*h # power_spectrum = abs(fourier_flt)**2 ang_flt = ang + phi_offset # ang_flt = np.unwrap(ang_flt) peak_phase = ang_flt[peak_index_good] peak = ampl_flt[peak_index_good] elif bfilter == False and average == True: #print('Averaging phase over the real frequency step') # ########### average phase over dfreal ######### fmin = fpeak - dfreal/2 fmax = fpeak + dfreal/2 ifmin = np.argmin(abs(freqnorm-fmin)) ifmax = np.argmin(abs(freqnorm-fmax)) if(ifmin<ifmax): peak = ampl[ifmin:ifmax].mean() peak_phase = np.mean(np.unwrap(ang[ifmin:ifmax])) + phi_offset else: peak = ampl[ifmin] peak_phase = ang[ifmin] + phi_offset elif bfilter == True and average == True: #print('Using bandpass filter and averaging over the real frequency step') lowcut = fpeak - BW/2. highcut = fpeak + BW/2. n=len(freqnorm) w, h = butter_bandpass(lowcut,highcut, fs, n, 5) ampl_flt = ampl*h ang_flt = ang + phi_offset fmin = fpeak - dfreal/2 fmax = fpeak + dfreal/2 ifmin = np.argmin(abs(freqnorm-fmin)) ifmax = np.argmin(abs(freqnorm-fmax)) if(ifmin<ifmax): peak = ampl[ifmin:ifmax].mean() peak_phase = np.mean(np.unwrap(ang[ifmin:ifmax])) + phi_offset else: peak = ampl[ifmin] peak_phase = ang[ifmin] + phi_offset else: #print('Taking the peak phase') peak = ampl[peak_index_good] peak_phase = ang[peak_index_good] + phi_offset if integral == True and average == True: print('Error! either average or integral, not both!') elif integral == True and bfilter == True: fourier_flt = ampl_flt*np.exp(1j*ang_flt) fourier_flt_int = np.trapz(fourier_flt,freqnorm) peak_phase = np.angle(fourier_flt_int) + phi_offset peak = abs(fourier_flt_int) #print(ifmin,ifmax) #print(fpeak,peak,peak_phase) return fpeak,peak,peak_phase
import matplotlib.pyplot as plt import numpy as np import math # Komplexe Zahl definieren: z = 2 + 3j z = complex(2, 3) # Real-, Imaginärteil, Komplex-Konjugierte, Betrag / Länge, Winkel print("z = " + str(z)) print("Realteil von z: Re(z) = " + str(z.real)) print("Imaginärteil von z: Im(z) = " + str(z.imag)) print("Komplex-konjugierte von z: z* = " + str(z.conjugate())) print("Länge / Radius von z: r = " + str(np.sqrt(z * z.conjugate()).real)) print("Winkel von z in Radian: φ = " + str(np.angle(z))) print("Winkel von z in Grad: φ = " + str(np.angle(z, deg=True))) print("Winkel von z als Vielfaches von π: φ = " + str(np.angle(z) / math.pi) + "π") # Darstellungsformen z = 3 + 4j # Normalform z = 2 * (math.cos(2 / 3 * math.pi) + math.cos(2 / 3 * math.pi) * 1j ) # Trigonometrische Form (Winkel in Radian) z = 2 * (math.cos(120 * math.pi / 180) + math.cos(120 * math.pi / 180) * 1j ) # Trigonometrische Form (Winkel in Grad) z = 2 * np.exp(2 / 3 * math.pi * 1j) # Exponentialform / Polarform print("z = " + str(z)) # Normalform r = np.sqrt(z * z.conjugate()).real
def magphase(x,arr): mag = np.abs(arr) phase = np.angle(arr) fig1 = plt.subplot(2,1,1) plt.plot(x,phase/np.pi)
def apply(self, data): magnitudes = np.absolute(data) phases = np.angle(data) return np.concatenate((magnitudes, phases), axis=1)
ms[indx, :] = qmf.PQMFAnalysis.complex_analysis_realtime( x[indx * N:(indx + 1) * N, 0], N) # Magnitude plt.figure(1) plt.imshow(np.abs((ms[:500, :].T)), aspect='auto', interpolation='nearest', origin='lower', cmap='jet') plt.draw() plt.show() # Phase plt.figure(2) plt.imshow((np.angle(ms[:500, :].T)), aspect='auto', interpolation='nearest', origin='lower', cmap='jet') plt.draw() plt.show() # Complex synthesis, from internal variable yrec = np.empty((timeSlots * N, 1)) for indx in xrange(timeSlots): yrec[indx * N:(indx + 1) * N, 0] = qmf.PQMFSynthesis.complex_synthesis_realtime(ms[indx, :], N) # Reset Internal buffers!!! qmf.reset_rt()
def FFT(x_data, dt): nu = cts.cur_nu zero_order = cts.FT_zero_order window = cts.FT_window padding = cts.FT_padding npad = cts.FT_npad nu = nu*1e-15 ############## N = len(x_data) # number of vector points # n = npad # number of points for padding pad = np.zeros(n) # use only even number of points for the signal if N % 2 == 0: N = N else: N = N-1 x_data = x_data[1:] # window for limiting spectral leakage and avoid sidelobes in fft amplitude Hm = hamming(N) signal = x_data if zero_order == False: signal = signal - signal.mean() if window == True: #print('Using Hamming window') signal = signal*Hm else: signal = signal if padding == True: signal = signal ###### NAL 000 SIG ### pad[:N//2] = signal[N//2:] pad[-N//2:] = signal[:N//2] ###### 000 SIGNAL 000 ### # a = n - N # pad[a//2:-a//2] = F1 signal=pad fourier = np.fft.fft(signal) fourier = fourier[:n//2] freq = np.fft.fftfreq(n, d=dt) freqpos = freq[:n//2] freqnorm = freqpos/nu else: signal = signal fourier = np.fft.fft(signal) fourier = fourier[:N//2] freq = np.fft.fftfreq(N, d=dt) freqpos = freq[:N//2] freqnorm = freqpos/nu ampl= abs(fourier) phicorr = -np.pi*freqpos*dt ang = np.angle(fourier) + phicorr ang=wrap2pmpi(ang) return freqnorm,ampl,ang
def OverLayFFT(img1,img2): global ang1, ang2, img1DFT, img2DFT, DFTShift1, DFTShift2, img1_magnitudeSpectrum, img2_magnitudeSpectrum, overlayFFT_mag, img1_LPF_iFFT_mag,img2_LPF_iFFT_mag, img1_HPF_iFFT_mag, img2_HPF_iFFT_mag, overlayFFT_phase, overlayFFT_phase2, CartDiff, overlayFFT, overlayiFFT_mag,overlayiFFT,img2Corrected, img2PhaseCorrected row1, col1 = img1.shape row2, col2 = img2.shape centerRow1, centerCol1 = row1/2, col1/2 centerRow2, centerCol2 = row2/2, col2/2 centerRectangle = 15 # Calculating 2D FFT img1FFT2 = np.fft.fft2(img1) img2FFT2 = np.fft.fft2(img2) # WORK IN PROGRESS: CartDiff = img2FFT2 - img1FFT2 print ("Cart Diff: ", CartDiff) img2FFT2 = img1FFT2 - CartDiff # shifting the DC component to the center of the image FFT2Shift1 = np.fft.fftshift(img1FFT2) FFT2Shift2 = np.fft.fftshift(img2FFT2) # Need to verify DFTShift1[:,:,1] is angle or DFTShift1[:,:,0]? DFTShift1[:,:,1] is the angle ang1 = np.angle(img1FFT2) ang2 = np.angle(img2FFT2) overlayFFT_phase = np.angle(FFT2Shift1)-np.angle(FFT2Shift2) print("overlay FFT phase shift", overlayFFT_phase) img2PhaseCorrected = np.angle(FFT2Shift2) - overlayFFT_phase # ang1 = cv2.phase(img1DFT[:,:,0], img1DFT[:,:,1]) # ang2 = cv2.phase(img2DFT[:,:,0], img2DFT[:,:,1]) # overlayFFT_phase2 # m,n = overlayFFT_phase2.shape # print(m,n) # calculating the magnitute of the complex numbers of DFTShift img1_magnitudeSpectrum = 20*np.log(np.abs(FFT2Shift1)) img2_magnitudeSpectrum = 20*np.log(np.abs(FFT2Shift2)) #TODO: try adding the manitudes of the two image in freq domain for overlay FFT overlayFFT_mag = img2_magnitudeSpectrum - img1_magnitudeSpectrum # img2MagCorrected = img1_magnitudeSpectrum + overlayFFT_mag # print(overlayFFT_phase) # Convert back to space domain and then graph the overlay diff # cv2.determinant(ang1) - cv2.determinant(ang2) overlayFFT = [img2_magnitudeSpectrum+img2PhaseCorrected*j] print("overlay FFT: ", overlayFFT) overlayFFT_ishift = np.fft.ifftshift(overlayFFT) # overlayiFFT = np.fft.ifft2(overlayFFT_ishift) overlayiFFT = np.fft.ifft2(img2FFT2) img2Corrected = np.abs(overlayiFFT) print("image 2 corrected: ", img2Corrected.shape, img2Corrected[:,:]) # x,y = cv2.polarToCart(overlayFFT_ishift[0,:,:],overlayFFT_ishift[1,:,:]) # overlayiFFT_mag = np.abs(overlayiFFT[0,:,:]) # row4, col4 =overlayiFFT_mag.shape # print(row4, col4) # print("overlay iFFT Mag: ", overlayiFFT_mag) # print (overlayFFT_phase) # END OF WORK IN PROGRESS # ------------------------------------------------------------------------------ # Low pass filtering: creating a mask with high value of 1 at low freq and # 0 at high freq freqMask1_LPF = np.zeros((row1,col1,2),np.float32) freqMask2_LPF = np.zeros((row2,col2,2),np.float32) freqMask1_LPF[centerRow1-centerRectangle:centerRow1+centerRectangle, centerCol1-centerRectangle:centerCol1+centerRectangle]=1 freqMask2_LPF[centerRow2-centerRectangle:centerRow2+centerRectangle, centerCol2-centerRectangle:centerCol2+centerRectangle]=1 img1DFT = cv2.dft(np.float32(img1), flags=cv2.DFT_COMPLEX_OUTPUT) img2DFT = cv2.dft(np.float32(img2), flags=cv2.DFT_COMPLEX_OUTPUT) DFTShift1 = np.fft.fftshift(img1DFT) DFTShift2 = np.fft.fftshift(img2DFT) #applying the mask for LPF DFTShift1_LPF_Masked = DFTShift1*freqMask1_LPF DFTShift2_LPF_Masked = DFTShift2*freqMask2_LPF #Inverse FFT img1_LPF_iFFT_shift = np.fft.ifftshift(DFTShift1_LPF_Masked) img2_LPF_iFFT_shift = np.fft.ifftshift(DFTShift2_LPF_Masked) img1_LPF_iFFT = cv2.idft(img1_LPF_iFFT_shift) img2_LPF_iFFT = cv2.idft(img2_LPF_iFFT_shift) img1_LPF_iFFT_mag = cv2.magnitude(img1_LPF_iFFT[:,:,0],img1_LPF_iFFT[:,:,1]) img2_LPF_iFFT_mag = cv2.magnitude(img2_LPF_iFFT[:,:,0],img2_LPF_iFFT[:,:,1]) # High Pass filtering: setting a 15x15 center rectangle to block low freq DFTShift1[centerRow1-centerRectangle:centerRow1+centerRectangle, centerCol1-centerRectangle:centerCol1+centerRectangle]=0 DFTShift2[centerRow2-centerRectangle:centerRow2+centerRectangle, centerCol2-centerRectangle:centerCol2+centerRectangle]=0 #inverse FFT img1_HPF_iFFT_shift = np.fft.ifftshift(DFTShift1) img2_HPF_iFFT_shift = np.fft.ifftshift(DFTShift2) img1_HPF_iFFT = cv2.idft(img1_HPF_iFFT_shift) img2_HPF_iFFT = cv2.idft(img2_HPF_iFFT_shift) img1_HPF_iFFT_mag = cv2.magnitude(img1_HPF_iFFT[:,:,0], img1_HPF_iFFT[:,:,1]) img2_HPF_iFFT_mag = cv2.magnitude(img2_HPF_iFFT[:,:,0], img2_HPF_iFFT[:,:,1]) return ang1, ang2, img1DFT, img2DFT, DFTShift1, DFTShift2, img1_magnitudeSpectrum, img2_magnitudeSpectrum, overlayFFT_mag, img1_LPF_iFFT_mag,img2_LPF_iFFT_mag, img1_HPF_iFFT_mag, img2_HPF_iFFT_mag, overlayFFT_phase, CartDiff, overlayFFT,overlayiFFT, img2Corrected, img2PhaseCorrected;
def monte_carlo( measurement_system, random_number_generator, sampling_freq, freqs, complex_freq_resp, reference_array_path, ): udelta = 0.1 * measurement_system["delta"] uS0 = 0.001 * measurement_system["S0"] uf0 = 0.01 * measurement_system["f0"] runs = 10000 MCS0 = random_number_generator.normal( loc=measurement_system["S0"], scale=uS0, size=runs ) MCd = random_number_generator.normal( loc=measurement_system["delta"], scale=udelta, size=runs ) MCf0 = random_number_generator.normal( loc=measurement_system["f0"], scale=uf0, size=runs ) HMC = np.empty((runs, len(freqs)), dtype=complex) for index, mcs0_mcd_mcf0 in enumerate(zip(MCS0, MCd, MCf0)): bc_, ac_ = sos_phys2filter(mcs0_mcd_mcf0[0], mcs0_mcd_mcf0[1], mcs0_mcd_mcf0[2]) b_, a_ = dsp.bilinear(bc_, ac_, sampling_freq) HMC[index, :] = dsp.freqz(b_, a_, 2 * np.pi * freqs / sampling_freq)[1] H = complex_2_real_imag(complex_freq_resp) assert_allclose( H, np.load( os.path.join(reference_array_path, "test_LSFIR_H.npz"), )["H"], ) uAbs = np.std(np.abs(HMC), axis=0) assert_allclose( uAbs, np.load( os.path.join(reference_array_path, "test_LSFIR_uAbs.npz"), )["uAbs"], rtol=3.5e-2, ) uPhas = np.std(np.angle(HMC), axis=0) assert_allclose( uPhas, np.load( os.path.join(reference_array_path, "test_LSFIR_uPhas.npz"), )["uPhas"], rtol=4.3e-2, ) UH = np.cov(np.hstack((np.real(HMC), np.imag(HMC))), rowvar=False) UH = make_semiposdef(UH) assert_allclose( UH, np.load( os.path.join(reference_array_path, "test_LSFIR_UH.npz"), )["UH"], atol=1, ) return {"H": H, "uAbs": uAbs, "uPhas": uPhas, "UH": UH}
def compress(self, audio_data, f): print('Compressing (STFT)...') f.write(b'ANMFS') f.write( struct.pack('<HI', len(audio_data.channels), audio_data.sample_rate)) for i, channel in enumerate(audio_data.channels): stft = scipy.signal.stft(channel.samples, fs=audio_data.sample_rate, window='hann', noverlap=self.FRAME_SIZE // 2, nperseg=self.FRAME_SIZE, padded=True)[2] # transpose for consistency with other methods stft = numpy.transpose(stft) # find phase and magnitude matrices phases = numpy.angle(stft) magnitudes = numpy.absolute(stft) # split the magnitude matrix into chunks submatrices = matrix_split(magnitudes, self.NMF_CHUNK_SIZE) # write the magnitude chunk count into the file f.write(struct.pack('<I', len(submatrices))) # compress phases using Huffman Pq = self.Pquantize_vec(phases) Pout, Prows = self.Phuffman.encode_int_matrix(Pq) # write quantized phase matrix f.write(struct.pack('<II', Prows, len(Pout))) f.write(Pout) # run NMF on the magnitude submatrices, getting their weights and coefficients for submatrix in submatrices: # run NMF on the matrix W, H, min_val = nmf_matrix(submatrix, self.NMF_MAX_ITER, self.NMF_RANK) # scale values to [0,1] using the maximum range of both matrices matrix_min = min(numpy.amin(W), numpy.amin(H)) matrix_max = max(numpy.amax(W), numpy.amax(H)) Ws = self.scale_matrix(W, matrix_min, matrix_max, 0, 1) Hs = self.scale_matrix(H, matrix_min, matrix_max, 0, 1) # compand the scaled matrices using mu-law Wsc = self.compand(Ws, self.MU_LAW_W) Hsc = self.compand(Hs, self.MU_LAW_H) # uniformly quantize the mu-law scaled matrix H (coefficients) # 32 levels of quantization between <0,1> Hscq = self.Hquantize_vec(Hsc) # debug # for val in numpy.nditer(Wscq): # increment_frequency(int(val)) # for val in numpy.nditer(Hscq): # increment_frequency(int(val)) # freq_done() # Huffman encode the matrix Hout, Hrows = self.Hhuffman.encode_int_matrix(Hscq) # for W, we scale it to 32-bit unsigned int Wscs = self.scale_matrix(Wsc, 0, 1, 0, 2**32).astype(numpy.uint32) # now write everything to file # write minimum value to be subtracted later f.write(struct.pack('<d', min_val)) # write the min and max to be re-scaled later f.write(struct.pack('<dd', matrix_min, matrix_max)) # write companded scaled W matrix serialize_matrix(f, Wscs, 'I') # write the quantized matrix H and number of rows f.write(struct.pack('<II', Hrows, len(Hout))) f.write(Hout)
def spectralDiversity(referenceSwath, interferogramDir, interferogramPrefix, outputList, numberLooksScanSAR=None, numberRangeLooks=20, numberAzimuthLooks=10, coherenceThreshold=0.85, keep=False, filt=False, filtWinSizeRange=5, filtWinSizeAzimuth=5): ''' numberLooksScanSAR: number of looks of the ScanSAR system numberRangeLooks: number of range looks to take numberAzimuthLooks: number of azimuth looks to take keep: whether keep intermediate files ''' import os import numpy as np from isceobj.Alos2Proc.Alos2ProcPublic import create_multi_index from isceobj.Alos2Proc.Alos2ProcPublic import create_xml from isceobj.Alos2Proc.Alos2ProcPublic import multilook from isceobj.Alos2Proc.Alos2ProcPublic import cal_coherence_1 width = referenceSwath.numberOfSamples length = referenceSwath.numberOfLines lengthBurst = referenceSwath.burstSlcNumberOfLines nBurst = referenceSwath.numberOfBursts azsi = referenceSwath.azimuthLineInterval tc = referenceSwath.burstCycleLength / referenceSwath.prf bursts = [ os.path.join(interferogramDir, interferogramPrefix + '_%02d.int' % (i + 1)) for i in range(referenceSwath.numberOfBursts) ] #################################################### #input parameters rgl = numberRangeLooks azl = numberAzimuthLooks cor_th = coherenceThreshold nls0 = lengthBurst / (referenceSwath.burstSlcFirstLineOffsets[nBurst - 1] / (nBurst - 1.0)) print('number of looks of the ScanSAR system: {}'.format(nls0)) if numberLooksScanSAR != None: nls = numberLooksScanSAR else: nls = int(nls0) print('number of looks to be used: {}'.format(nls)) #################################################### #read burst interferograms inf = np.zeros((length, width, nls), dtype=np.complex64) cnt = np.zeros((length, width), dtype=np.int8) for i in range(nBurst): if (i + 1) % 5 == 0 or (i + 1) == nBurst: print('reading burst %02d' % (i + 1)) burst = np.fromfile(bursts[i], dtype=np.complex64).reshape(lengthBurst, width) #subset for the burst cntBurst = cnt[0 + referenceSwath.burstSlcFirstLineOffsets[i]:lengthBurst + referenceSwath.burstSlcFirstLineOffsets[i], :] infBurst = inf[0 + referenceSwath.burstSlcFirstLineOffsets[i]:lengthBurst + referenceSwath.burstSlcFirstLineOffsets[i], :, :] #set number of non-zero pixels cntBurst[np.nonzero(burst)] += 1 #get index index1 = np.nonzero(np.logical_and(burst != 0, cntBurst <= nls)) index2 = index1 + (cntBurst[index1] - 1, ) #set values infBurst[index2] = burst[index1] #number of looks for each sample if keep: nlFile = 'number_of_looks.nl' cnt.astype(np.int8).tofile(nlFile) create_xml(nlFile, width, length, 'byte') if filt: import scipy.signal as ss filterKernel = np.ones((filtWinSizeAzimuth, filtWinSizeRange), dtype=np.float64) for i in range(nls): print('filtering look {}'.format(i + 1)) flag = (inf[:, :, i] != 0) #scale = ss.fftconvolve(flag, filterKernel, mode='same') #inf[:,:,i] = flag*ss.fftconvolve(inf[:,:,i], filterKernel, mode='same') / (scale + (scale==0)) #this should be faster? scale = ss.convolve2d(flag, filterKernel, mode='same') inf[:, :, i] = flag * ss.convolve2d( inf[:, :, i], filterKernel, mode='same') / (scale + (scale == 0)) #width and length after multilooking widthm = int(width / rgl) lengthm = int(length / azl) #use the convention that ka > 0 ka = -np.polyval(referenceSwath.azimuthFmrateVsPixel[::-1], create_multi_index(width, rgl)) #get spectral diversity inteferogram offset_sd = [] for i in range(1, nls): print('output spectral diversity inteferogram %d' % i) #original spectral diversity inteferogram sd = inf[:, :, 0] * np.conj(inf[:, :, i]) #replace original amplitude with its square root index = np.nonzero(sd != 0) sd[index] /= np.sqrt(np.absolute(sd[index])) sdFile = outputList[i - 1] sd.astype(np.complex64).tofile(sdFile) create_xml(sdFile, width, length, 'int') #multi look sdm = multilook(sd, azl, rgl) cor = cal_coherence_1(sdm) #convert phase to offset offset = np.angle(sdm) / (2.0 * np.pi * ka * tc * i)[None, :] / azsi #compute offset using good samples point_index = np.nonzero( np.logical_and(cor >= cor_th, np.angle(sdm) != 0)) npoint = round(np.size(point_index) / 2) if npoint < 20: print( 'WARNING: too few good samples for spectral diversity at look {}: {}' .format(i, npoint)) offset_sd.append(0) else: offset_sd.append( np.sum(offset[point_index] * cor[point_index]) / np.sum(cor[point_index])) if keep: sdmFile = 'sd_%d_%drlks_%dalks.int' % (i, rgl, azl) sdm.astype(np.complex64).tofile(sdmFile) create_xml(sdmFile, widthm, lengthm, 'int') corFile = 'sd_%d_%drlks_%dalks.cor' % (i, rgl, azl) cor.astype(np.float32).tofile(corFile) create_xml(corFile, widthm, lengthm, 'float') offsetFile = 'sd_%d_%drlks_%dalks.off' % (i, rgl, azl) offset.astype(np.float32).tofile(offsetFile) create_xml(offsetFile, widthm, lengthm, 'float') offset_mean = np.sum(np.array(offset_sd) * np.arange(1, nls)) / np.sum( np.arange(1, nls)) return offset_mean
# constants for the signal A1 = 4. t1 = 2. f1 = 2. phi1 = 0. # amplitude and phase error phase_shift = 0.8 amp_fac = 3. # generate the signal H1 = (np.sign(t - t1) + 1) / 2 st1 = A1 * (t - t1) * np.exp(-2 * (t - t1)) * \ np.cos(2. * np.pi * f1 * (t - t1) + phi1 * np.pi) * H1 # reference signal st2 = st1.copy() # generate analytical signal (hilbert transform) and add phase shift st1p = hilbert(st1) st1p = np.real( np.abs(st1p) * np.exp((np.angle(st1p) + phase_shift * np.pi) * 1j)) # signal with amplitude error st1a = st1 * amp_fac plotTfGofs(st1a, st2, dt=dt, fmin=fmin, fmax=fmax, show=False) plotTfGofs(st1p, st2, dt=dt, fmin=fmin, fmax=fmax, show=False) plt.show()
def _assert_sinusoid(data, t, freq, amp, msg): __tracebackhide__ = True sinusoid = np.exp(2j * np.pi * freq * t) * amp phase = np.angle(np.dot(data, sinusoid)) sinusoid = np.cos(2 * np.pi * freq * t - phase) * amp assert_allclose(data, sinusoid, rtol=0.05, atol=amp * 1e-3, err_msg=msg)
noise_tx3 = np.random.normal(0, noise_sigma / np.sqrt(2), num_chirps_tx3) + 1j * np.random.normal( 0, noise_sigma / np.sqrt(2), num_chirps_tx3) signal_tx3 = signal_tx1[0:num_chirps_tx3] signal_noise_tx3 = signal_tx3 + noise_tx3 signal_noise_tx3_fft = np.fft.fft(signal_noise_tx3, n=num_fft) / num_chirps_tx3 signal_noise_tx3_spectrum = 20 * np.log10(np.abs(signal_noise_tx3_fft)) est_freq_ind_tx3 = compute_Twolargest_localpeaks( signal_noise_tx3_spectrum[None, :])[0] est_dig_freq_tx3 = (2 * np.pi * est_freq_ind_tx3) / num_fft est_complex_weights_tx3_fft = signal_noise_tx3_fft[est_freq_ind] print('True amplitude (dB)', 20 * np.log10(np.abs(true_complex_weights)), 'True phase (deg)', np.angle(true_complex_weights) * 180 / np.pi) print('Tx1 FFT based Est amplitude (dB)', 20 * np.log10(np.abs(est_complex_weights_tx1_fft)), 'Tx1 FFT based Est phase (deg)', np.angle(est_complex_weights_tx1_fft) * 180 / np.pi) print('Tx2 LS based Est amplitude(dB)', 20 * np.log10(np.abs(est_complex_weights_tx2)), 'Tx2 LS based Est phase (deg)', np.angle(est_complex_weights_tx2) * 180 / np.pi) print('Tx3 FFT based Est amplitude(dB)', 20 * np.log10(np.abs(est_complex_weights_tx3_fft)), 'Tx3 FFT based Est phase (deg)', np.angle(est_complex_weights_tx3_fft) * 180 / np.pi) plt.figure(1, figsize=(16, 9)) plt.plot(signal_noise_tx1_spectrum, '-o', label='Tx1 spectrum')
def run(self, dag): """Run the DynamicalDecoupling pass on dag. Args: dag (DAGCircuit): a scheduled DAG. Returns: DAGCircuit: equivalent circuit with delays interrupted by DD, where possible. Raises: TranspilerError: if the circuit is not mapped on physical qubits. """ if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None: raise TranspilerError("DD runs on physical circuits only.") if dag.duration is None: raise TranspilerError("DD runs after circuit is scheduled.") num_pulses = len(self._dd_sequence) sequence_gphase = 0 if num_pulses != 1: if num_pulses % 2 != 0: raise TranspilerError( "DD sequence must contain an even number of gates (or 1).") noop = np.eye(2) for gate in self._dd_sequence: noop = noop.dot(gate.to_matrix()) if not matrix_equal(noop, IGate().to_matrix(), ignore_phase=True): raise TranspilerError( "The DD sequence does not make an identity operation.") sequence_gphase = np.angle(noop[0][0]) if self._qubits is None: self._qubits = set(range(dag.num_qubits())) else: self._qubits = set(self._qubits) if self._spacing: if sum(self._spacing) != 1 or any(a < 0 for a in self._spacing): raise TranspilerError( "The spacings must be given in terms of fractions " "of the slack period and sum to 1.") else: # default to balanced spacing mid = 1 / num_pulses end = mid / 2 self._spacing = [end] + [mid] * (num_pulses - 1) + [end] new_dag = dag._copy_circuit_metadata() qubit_index_map = { qubit: index for index, qubit in enumerate(new_dag.qubits) } index_sequence_duration_map = {} for qubit in new_dag.qubits: physical_qubit = qubit_index_map[qubit] dd_sequence_duration = 0 for gate in self._dd_sequence: gate.duration = self._durations.get(gate, physical_qubit) dd_sequence_duration += gate.duration index_sequence_duration_map[physical_qubit] = dd_sequence_duration for nd in dag.topological_op_nodes(): if not isinstance(nd.op, Delay): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs) continue dag_qubit = nd.qargs[0] physical_qubit = qubit_index_map[dag_qubit] if physical_qubit not in self._qubits: # skip unwanted qubits new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs) continue pred = next(dag.predecessors(nd)) succ = next(dag.successors(nd)) if self._skip_reset_qubits: # discount initial delays if isinstance(pred, DAGInNode) or isinstance(pred.op, Reset): new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs) continue dd_sequence_duration = index_sequence_duration_map[physical_qubit] slack = nd.op.duration - dd_sequence_duration if slack <= 0: # dd doesn't fit new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs) continue if num_pulses == 1: # special case of using a single gate for DD u_inv = self._dd_sequence[0].inverse().to_matrix() theta, phi, lam, phase = OneQubitEulerDecomposer( ).angles_and_phase(u_inv) # absorb the inverse into the successor (from left in circuit) if isinstance(succ, DAGOpNode) and isinstance( succ.op, (UGate, U3Gate)): theta_r, phi_r, lam_r = succ.op.params succ.op.params = Optimize1qGates.compose_u3( theta_r, phi_r, lam_r, theta, phi, lam) sequence_gphase += phase # absorb the inverse into the predecessor (from right in circuit) elif isinstance(pred, DAGOpNode) and isinstance( pred.op, (UGate, U3Gate)): theta_l, phi_l, lam_l = pred.op.params pred.op.params = Optimize1qGates.compose_u3( theta, phi, lam, theta_l, phi_l, lam_l) sequence_gphase += phase # don't do anything if there's no single-qubit gate to absorb the inverse else: new_dag.apply_operation_back(nd.op, nd.qargs, nd.cargs) continue # insert the actual DD sequence taus = [int(slack * a) for a in self._spacing] unused_slack = slack - sum( taus) # unused, due to rounding to int multiples of dt middle_index = int( (len(taus) - 1) / 2) # arbitrary: redistribute to middle taus[ middle_index] += unused_slack # now we add up to original delay duration for tau, gate in itertools.zip_longest(taus, self._dd_sequence): if tau > 0: new_dag.apply_operation_back(Delay(tau), [dag_qubit]) if gate is not None: new_dag.apply_operation_back(gate, [dag_qubit]) new_dag.global_phase = _mod_2pi(new_dag.global_phase + sequence_gphase) return new_dag
'lines.linewidth':'0.5', 'pdf.fonttype':42, 'ps.fonttype':42, 'font.sans-serif':'Arial'} pylab.rcParams.update(params) """ Plot time series and phases """ fig = plt.figure() for i in range(len(parcels)): ax = fig.add_subplot(1, 3, i+1) ax.plot(np.real(parcelSeries[parcels[i],:].T)+2.2, color=colors[i], label='Parcel ' + str(parcels[i])) ax.plot(np.real(sourceSeries[sources[i],:].T), color=colors[i], label='Source ' + str(sources[i])) ax.plot(np.angle(parcelSeries[parcels[i],:].T)/3.14 -2.8, color=colors[i]) ax.plot(np.angle(sourceSeries[sources[i],:].T)/3.14 -5, color=colors[i]) ax.plot(np.ravel(np.angle(np.exp(1j*(np.angle(parcelSeries[parcels[i],:]) - np.angle(sourceSeries[sources[i],:])))))/3.14 -7.2, color=colors[i]) # Angle difference ax.set_ylabel('Real or Phase') ax.set_xlabel('Time') # plt.axis('off') ax.spines['top'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) legend = ax.legend(loc='best', shadow=False)
def inverse_phase(x, y, gen, val): return np.exp(-I * np.angle((herm(x).dot(gen).dot(y))[0, 0] / val))
def Phi(self): return np.angle(self.A1 + 1j * self.A2)
import numpy as np from scipy.signal import triang from scipy.fftpack import fft x = triang(15) X = fft(x) mX = abs(X) pX = np.angle(X)