def dynamic_axis(zero,pole,K): if list(zero)+list(pole)==[]: x_min,x_max,y_min,y_max = -1,1,-1,1 else: x_min = min(list(np.real(zero))+list(np.real(pole))) x_max = max(list(np.real(zero))+list(np.real(pole))) if x_min == x_max: x_min -= 1 x_max += 1 else: x_min,x_max = (x_min- 0.75*(x_max-x_min)),(x_max + 0.75*(x_max-x_min)) y_min = min(list(np.imag(zero))+list(np.imag(pole))) y_max = max(list(np.imag(zero))+list(np.imag(pole))) if y_min == y_max: y_min -= 1 y_max += 1 else: y_min,y_max = (y_min- 0.75*(y_max-y_min)),(y_max + 0.75*(y_max-y_min)) if K == 0: z_min,z_max = -1,1 else: K = abs(K) print K z_min,z_max = K*0.1,K*10.0 return x_min,x_max,y_min,y_max,z_min,z_max
def zplane(self, title="", fontsize=18): """ Display filter in the complex plane Parameters ---------- """ rb = self.z ra = self.p t = np.arange(0, 2 * np.pi + 0.1, 0.1) plt.plot(np.cos(t), np.sin(t), "k") plt.plot(np.real(ra), np.imag(ra), "x", color="r") plt.plot(np.real(rb), np.imag(rb), "o", color="b") M1 = -10000 M2 = -10000 if len(ra) > 0: M1 = np.max([np.abs(np.real(ra)), np.abs(np.imag(ra))]) if len(rb) > 0: M2 = np.max([np.abs(np.real(rb)), np.abs(np.imag(rb))]) M = 1.6 * max(1.2, M1, M2) plt.axis([-M, M, -0.7 * M, 0.7 * M]) plt.title(title, fontsize=fontsize) plt.show()
def solveBlockGlasso(signal): start = int(signal[0]) # include S_Matrix = S_Matrix_bc.value W_matrix = W_Matrix_bc.value old_W = np.copy(W_matrix) end = min(int(signal[1]),S_Matrix.shape[0]) # non-inclusive deltamatrix = np.zeros(S_Matrix.shape) NN = S_Matrix.shape[0] for n in range(start,end): W11 = np.delete(W_matrix,n,0) W11 = np.delete(W11,n,1) Z = linalg.sqrtm(W11) s11 = S_Matrix[:,n] s11 = np.delete(s11,n) Y = np.dot(nplinalg.inv(linalg.sqrtm(W11)),s11) Y = np.real(Y) Z = np.real(Z) B = lasso(Z,Y,beta_value) updated_column = np.dot(W11,B) matrix_ind = np.array(range(0,NN)) matrix_ind = np.delete(matrix_ind,n) column_ind = 0 for k in matrix_ind: deltamatrix[k,n]=updated_column[column_ind] - W_matrix[k,n] deltamatrix[n,k]=updated_column[column_ind] - W_matrix[k,n] W_matrix[k,n] = updated_column[column_ind] W_matrix[n,k] = updated_column[column_ind] column_ind = column_ind+1
def invert(self, estimate): """Invert the estimate to produce slopes. Parameters ---------- estimate : array_like Phase estimate to invert. Returns ------- xs : array_like Estimate of the x slopes. ys : array_like Estimate of the y slopes. """ if self.manage_tt: estimate, ttx, tty = remove_tiptilt(self.ap, estimate) est_ft = fftpack.fftn(estimate) / 2.0 xs_ft = self.gx * est_ft ys_ft = self.gy * est_ft xs = np.real(fftpack.ifftn(xs_ft)) ys = np.real(fftpack.ifftn(ys_ft)) if self.manage_tt and not self.suppress_tt: xs += ttx ys += tty return (xs, ys)
def FFT_Correlation(x,y): """ FFT-based correlation, much faster than numpy autocorr. x and y are row-based vectors of arbitrary lengths. This is a vectorized implementation of O(N*log(N)) flops. """ lengthx = x.shape[0] lengthy = y.shape[0] x = np.reshape(x,(1,lengthx)) y = np.reshape(y,(1,lengthy)) length = np.array([lengthx, lengthy]).min() x = x[:length] y = y[:length] fftx = fft(x, 2 * length - 1, axis=1) #pad with zeros ffty = fft(y, 2 * length - 1, axis=1) corr_xy = fft.ifft(fftx * np.conjugate(ffty), axis=1) corr_xy = np.real(fft.fftshift(corr_xy, axes=1)) #should be no imaginary part corr_yx = fft.ifft(ffty * np.conjugate(fftx), axis=1) corr_yx = np.real(fft.fftshift(corr_yx, axes=1)) corr = 0.5 * (corr_xy[:,length:] + corr_yx[:,length:]) / range(1,length)[::-1] return np.reshape(corr,corr.shape[1])
def fourier(self): """ Generate a profile of fourier coefficients, amplitudes and phases """ if pynbody.config['verbose'] : print 'Profile: fourier()' f = {'c': np.zeros((7, self.nbins),dtype=complex), 'amp': np.zeros((7, self.nbins)), 'phi': np.zeros((7, self.nbins))} for i in range(self.nbins): if self._profiles['n'][i] > 100: phi = np.arctan2(self.sim['y'][self.binind[i]], self.sim['x'][self.binind[i]]) mass = self.sim['mass'][self.binind[i]] hist, binphi = np.histogram(phi,weights=mass,bins=100) binphi = .5*(binphi[1:]+binphi[:-1]) for m in range(7) : f['c'][m,i] = np.sum(hist*np.exp(-1j*m*binphi)) f['c'][:,self['mass']>0] /= self['mass'][self['mass']>0] f['amp'] = np.sqrt(np.imag(f['c'])**2 + np.real(f['c'])**2) f['phi'] = np.arctan2(np.imag(f['c']), np.real(f['c'])) return f
def SaveData (self, fname, verbose = True): if (verbose): print (" Saving measurement to %s ... " % fname) start = time.clock() f = h5py.File(fname, 'w') f['data_r'] = np.squeeze(np.real(self.data).transpose()) f['data_i'] = np.squeeze(np.imag(self.data).transpose()) if (self.noise != 0): f['noise_r'] = np.squeeze(np.real(self.noise).transpose()) f['noise_i'] = np.squeeze(np.imag(self.noise).transpose()) if (self.acs != 0): f['acs_r'] = np.squeeze(np.real(self.acs).transpose()) f['acs_i'] = np.squeeze(np.imag(self.acs).transpose()) if (self.sync.any() != 0): f['sync'] = self.sync.transpose() f.close() if (verbose): print ' ... saved in %(time).1f s.\n' % {"time": time.clock()-start} return
def fbm(n, hurst): """Generate Fractional brownian motion noise. http://www.maths.uq.edu.au/~kroese/ps/MCSpatial.pdf Args: n (int): Length of the time series. H (float): Hurst parameter. Kwargs: seed (int): Random generator number seed. Returns: Time series array. """ r = np.empty((n + 1,)) * np.NaN r[0] = 1 for k in range(1, n + 1): a = 2.0 * hurst r[k] = 0.5 * ((k + 1)**a - 2 * k**a + (k - 1)**a) r = np.append(r, r[-2:0:-1]) # first row of circulant matrix lambda_ = np.real(np.fft.fft(r)) / (2 * n) # Eigenvalues W = np.fft.fft(np.sqrt(lambda_) * (np.random.randn(2 * n) + 1j * np.random.randn(2 * n))) W = n**(-hurst) * np.cumsum(np.real(W[0:n + 1])) # Rescale return W
def _exportDataToText(self, file): """Saves textual data to a file """ Nt = self.data.shape[0] N = self.data.shape[1] # all elements [real] + (all elements - diagonal) [imaginary] + time Na = N + 1 + N*(N-1) out = numpy.zeros((Nt, Na), dtype=numpy.float64) for i in range(Nt): #print("%%%%") # time out[i,0] = self.TimeAxis.data[i] #print(0) # populations for j in range(N): out[i,j+1] = numpy.real(self.data[i,j,j]) #print(j+1) # coherences l = 0 for j in range(N): for k in range(j+1,N): out[i,N+1+l] = numpy.real(self.data[i,j,k]) #print(N+1+l) l += 1 out[i,N+1+l] = numpy.imag(self.data[i,j,k]) #print(N+1+l) l += 1 numpy.savetxt(file, out)
def childGeneration(N, particles, tree, i): maxInCell = 3 p, t = noOfParticlesInside(particles, N[i]) N[i].particleIndex = t if p > maxInCell: t = len(N) tree[i] = [t, t + 1, t + 2, t + 3] c = N[i].center v = N[i].vertex N.append(Node((c - (v - c) / 2), c, t)) N.append(Node((c + (v - c) / 2), v, t + 1)) N.append(Node(c + (conj(v - c) / 2), real(v) + 1j * imag(c), t + 2)) N.append(Node(c - (conj(v - c) / 2), real(c) + 1j * imag(v), t + 3)) tree.append([]) tree.append([]) tree.append([]) tree.append([]) for ch in tree[i]: childGeneration(N, particles, tree, ch) N[i].aj = zeros(noOfTerms) * 1j for j in range(1, noOfTerms + 1): for k in range(1, j + 1): for chi in tree[i]: N[i].aj[j - 1] += ( N[chi].aj[k - 1] * combitorial(j - 1, k - 1) * pow((-N[i].center + N[chi].center), j - k) ) else: N[i].aj = zeros(noOfTerms) * 1j for j in range(1, noOfTerms + 1): for tempIdx in t: N[i].aj[j - 1] += particles[tempIdx].strength * pow((particles[tempIdx].xy - N[i].center), (j - 1))
def update_all_baseline_plots(i, fig, crawler, lines, norm_cross=False, forward=True): if forward: try: crawler.forward() except EOFError as err: print err raw_input("End of File. Press enter to quit.") sys.exit() burst = crawler for k in range(len(BASELINES)): if k < 4: #autos lines[k].set_data(FREQS, 10*np.log10(burst.autos[BASELINES[k]])) #overlays lines[-(k+1)].set_data(FREQS,10*np.log10(burst.autos[BASELINES[k]])) elif norm_cross: norm_val = np.array(burst.cross[BASELINES[k]])/np.sqrt(np.array(burst.autos[BASELINES[k][0]*2])*np.array(burst.autos[BASELINES[k][1]*2])) lines[k]['real'].set_data(FREQS, np.real(norm_val)) lines[k]['imag'].set_data(FREQS, np.imag(norm_val)) else: lines[k].set_data(FREQS, 10*np.log10(np.abs(np.real(burst.cross[BASELINES[k]])))) return lines
def _default_response_frequencies(A, n): """Compute a reasonable set of frequency points for bode plot. This function is used by `bode` to compute the frequency points (in rad/s) when the `w` argument to the function is None. Parameters ---------- A : ndarray The system matrix, which is square. n : int The number of time samples to generate. Returns ------- w : ndarray The 1-D array of length `n` of frequency samples (in rad/s) at which the response is to be computed. """ vals = linalg.eigvals(A) # Remove poles at 0 because they don't help us determine an interesting # frequency range. (And if we pass a 0 to log10() below we will crash.) poles = [pole for pole in vals if pole != 0] # If there are no non-zero poles, just hardcode something. if len(poles) == 0: minpole = 1 maxpole = 1 else: minpole = min(abs(real(poles))) maxpole = max(abs(real(poles))) # A reasonable frequency range is two orders of magnitude before the # minimum pole (slowest) and two orders of magnitude after the maximum pole # (fastest). w = numpy.logspace(numpy.log10(minpole) - 2, numpy.log10(maxpole) + 2, n) return w
def window_fn_matrix(Q,N,num_remov=None,save_tag=None,lms=None): Q = n.matrix(Q); N = n.matrix(N) Ninv = uf.pseudo_inverse(N,num_remov=None) # XXX want to remove dynamically #print Ninv info = n.dot(Q.H,n.dot(Ninv,Q)) M = uf.pseudo_inverse(info,num_remov=num_remov) W = n.dot(M,info) if save_tag!=None: foo = W[0,:] foo = n.real(n.array(foo)) foo.shape = (foo.shape[1]), print foo.shape p.scatter(lms[:,0],foo,c=lms[:,1],cmap=mpl.cm.PiYG,s=50) p.xlabel('l (color is m)') p.ylabel('W_0,lm') p.title('First Row of Window Function Matrix') p.colorbar() p.savefig('{0}/{1}_W.pdf'.format(fig_loc,save_tag)) p.clf() print 'W ',W.shape p.imshow(n.real(W)) p.title('Window Function Matrix') p.colorbar() p.savefig('{0}/{1}_W_im.pdf'.format(fig_loc,save_tag)) p.clf() return W
def p_sector5(MSA=[], C="seq", klist=[0, 1, 2, 3], Niter=20000, r=0.0001): if MSA.__class__ != msa: print "The function needs a msa as input" return False if C not in ["seq", "pos"]: print "gotta pick seq or pos" return False print "Calculating the SCA matrices" Cp, Cs = SCA5(MSA) print "Computing eigenmodes with numpy/LAPACK" if C == "seq": lbd, ev = numpy.linalg.eig(Cs) elif C == "pos": lbd, ev = numpy.linalg.eig(Cp) # ordering print "Sorting eigenmodes" idx = lbd.argsort() lbdsort = numpy.real(lbd[idx[::-1]]) evsort = numpy.real(ev[:, idx[::-1]]) print "top 10 eigenvalues" print lbdsort[:10] print "Calculating Independent Component Analysis" W, c = ICA(evsort, klist, Niter, r) return lbdsort, evsort, W, numpy.dot(W, evsort[:, klist].T).T
def eta_fil(self, x, V_app, apprx=(0, 0, 0, 0)): m_eff = self.m_r * const.electron_mass mpmath.mp.dps = 20 x0 = Symbol('x0') # eta_fil x1 = Symbol('x1') # eta_ac x2 = Symbol('x2') # eta_hop x3 = Symbol('x3') # V_tunnel f0 = const.Boltzmann * self.T / (1 - self.alpha) / const.elementary_charge / self.z * \ ln(self.A_fil/self.A_ac*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1) + 1) - x1# eta_ac = f(eta_fil) x1 = f(x0) f1 = x*2*const.Boltzmann*self.T/self.a/self.z/const.elementary_charge*\ asinh(self.j_0et/self.j_0hop*(exp(- self.alpha * const.elementary_charge * self.z / const.Boltzmann / self.T * x0) - 1)) - x2# eta_hop = f(eta_fil) f2 = x1 - x0 + x2 - x3 f3 = -V_app + ((self.C * 3 * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \ exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+x3/2)*const.elementary_charge))) * self.A_fil*x3) + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*x0/const.Boltzmann/self.T) - 1))) * (self.R_el + self.R_S + self.rho_fil*(self.L - x) / self.A_fil) \ + x3 eta_fil, eta_ac, eta_hop, V_tunnel = nsolve((f0, f1, f2, f3), [x0, x1, x2, x3], apprx) eta_fil = np.real(np.complex128(eta_fil)) eta_ac = np.real(np.complex128(eta_ac)) eta_hop = np.real(np.complex128(eta_hop)) V_tunnel = np.real(np.complex128(V_tunnel)) current = ((self.C * 3 * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge)) / 2 / x * (const.elementary_charge / const.Planck)**2 * \ exp(- 4 * const.pi * x / const.Planck * sqrt(2 * m_eff * ((4+V_tunnel)*const.elementary_charge))) * self.A_fil*V_tunnel) + (self.j_0et*self.A_fil*(exp(-self.alpha*const.elementary_charge*self.z*eta_fil/const.Boltzmann/self.T) - 1))) print(eta_fil, eta_ac, eta_hop, V_tunnel) # print(eta_ac - eta_fil + eta_hop - V_tunnel) return eta_fil, eta_ac, eta_hop, V_tunnel, current
def _coherence_bavg(fxy, fxx, fyy): r""" Compute the band-averaged coherency between the spectra of two time series. input to this function is in the frequency domain Parameters ---------- fxy : float array The cross-spectrum of the time series fyy,fxx : float array The spectra of the signals Returns ------- float : the band-averaged coherence """ if not np.isrealobj(fxx): fxx = np.real(fxx) if not np.isrealobj(fyy): fyy = np.real(fyy) return (np.abs(fxy.sum()) ** 2) / (fxx.sum() * fyy.sum())
def _select_function(sort, typ): if typ in ['F','D']: if callable(sort): # assume the user knows what they're doing sfunction = sort elif sort == 'lhp': sfunction = lambda x,y: (np.real(x/y) < 0.0) elif sort == 'rhp': sfunction = lambda x,y: (np.real(x/y) >= 0.0) elif sort == 'iuc': sfunction = lambda x,y: (abs(x/y) <= 1.0) elif sort == 'ouc': sfunction = lambda x,y: (abs(x/y) > 1.0) else: raise ValueError("sort parameter must be None, a callable, or " "one of ('lhp','rhp','iuc','ouc')") elif typ in ['f','d']: if callable(sort): # assume the user knows what they're doing sfunction = sort elif sort == 'lhp': sfunction = lambda x,y,z: (np.real((x+y*1j)/z) < 0.0) elif sort == 'rhp': sfunction = lambda x,y,z: (np.real((x+y*1j)/z) >= 0.0) elif sort == 'iuc': sfunction = lambda x,y,z: (abs((x+y*1j)/z) <= 1.0) elif sort == 'ouc': sfunction = lambda x,y,z: (abs((x+y*1j)/z) > 1.0) else: raise ValueError("sort parameter must be None, a callable, or " "one of ('lhp','rhp','iuc','ouc')") else: # to avoid an error later raise ValueError("dtype %s not understood" % typ) return sfunction
def plot_potential(grid, potential, view=None, size=(12, 9), path="."): # The Grid u = grid.get_nodes(split=True) u = real(u[0]) # Create potential and evaluate eigenvalues potew = potential.evaluate_eigenvalues_at(grid) potew = [real(level).reshape(-1) for level in potew] # View if view[0] is None: view[0] = u.min() if view[1] is None: view[1] = u.max() # Plot the energy surfaces of the potential fig = figure(figsize=size) ax = fig.gca() for index, ew in enumerate(potew): ax.plot(u, ew, label=r"$\lambda_{%d}$" % index) ax.ticklabel_format(style="sci", scilimits=(0, 0), axis="y") ax.grid(True) ax.set_xlim(view[:2]) ax.set_ylim(view[2:]) ax.set_xlabel(r"$x$") ax.set_ylabel(r"$\lambda_i\left(x\right)$") legend(loc="outer right") ax.set_title(r"The eigenvalues $\lambda_i$ of the potential $V\left(x\right)$") fig.savefig(os.path.join(path, "potential" + GD.output_format)) close(fig)
def coherence_spec(fxy, fxx, fyy): r""" Compute the coherence between the spectra of two time series. Parameters of this function are in the frequency domain. Parameters ---------- fxy : array The cross-spectrum of the time series fyy, fxx : array The spectra of the signals Returns ------- float : a frequency-band-dependent measure of the linear association between the two time series See also -------- :func:`coherence` """ if not np.isrealobj(fxx): fxx = np.real(fxx) if not np.isrealobj(fyy): fyy = np.real(fyy) c = np.abs(fxy) ** 2 / (fxx * fyy) return c
def filters_bank(M, N, J, L=8): filters = {} filters['psi'] = [] offset_unpad = 0 for j in range(J): for theta in range(L): psi = {} psi['j'] = j psi['theta'] = theta psi_signal = morlet_2d(M, N, 0.8 * 2**j, (int(L - L / 2 - 1) - theta) * np.pi / L, 3.0 / 4.0 * np.pi / 2**j,offset=offset_unpad) # The 5 is here just to match the LUA implementation :) psi_signal_fourier = fft.fft2(psi_signal) for res in range(j + 1): psi_signal_fourier_res = crop_freq(psi_signal_fourier, res) psi[res] = torch.FloatTensor(np.stack((np.real(psi_signal_fourier_res), np.imag(psi_signal_fourier_res)), axis=2)) # Normalization to avoid doing it with the FFT! psi[res].div_(M * N // 2**(2 * j)) filters['psi'].append(psi) filters['phi'] = {} phi_signal = gabor_2d(M, N, 0.8 * 2**(J - 1), 0, 0, offset=offset_unpad) phi_signal_fourier = fft.fft2(phi_signal) filters['phi']['j'] = J for res in range(J): phi_signal_fourier_res = crop_freq(phi_signal_fourier, res) filters['phi'][res] = torch.FloatTensor(np.stack((np.real(phi_signal_fourier_res), np.imag(phi_signal_fourier_res)), axis=2)) filters['phi'][res].div_(M * N // 2 ** (2 * J)) return filters
def writeToAscii(self, directory): """ This function writes the values of the normalization integral to a text file. Make sure to run execute method first. """ outfile = open(os.path.join(directory, "normint.txt"), "w") outfile.write(str(len(self.waves)) + "\n") outfile.write(str(len(self.alphaList)) + "\n") for eps1 in range(2): for eps2 in range(2): outfile.write( str(len(self.waves)) + " " + str(len(self.waves)) + " " + str(eps1) + " " + str(eps2) + "\n" ) for index1 in range(len(self.waves)): for index2 in range(len(self.waves) - 1): tempcomplex = self.ret[eps1, eps2, index1, index2] tempreal = numpy.real(tempcomplex) tempim = numpy.imag(tempcomplex) outfile.write(" (" + str(tempreal) + " + i " + str(tempim) + ") , ") tempcomplex = self.ret[eps1, eps2, index1, int(len(self.waves) - 1)] tempreal = numpy.real(tempcomplex) tempim = numpy.imag(tempcomplex) outfile.write(" (" + str(tempreal) + " + i " + str(tempim) + ")") outfile.write("\n") outfile.write("\n") outfile.write(str(len(self.waves)) + "\n") for wave in self.waves: outfile.write(wave.filename + " " + str(self.waves.index(wave)) + "\n") outfile.close()
def writeToDatFile(data, file, field="E", punits="mm", funits="V/m", pscale=1.0, fscale=1.0): """ Write to field map to DAT data file. """ nx = data.nx ny = data.ny nz = data.nz file.write(" x [{0}] y [{0}] z [{0}] {1}xRe [{2}] {1}yRe [{2}] {1}zRe [{2}] {1}xIm [{2}] {1}yIm [{2}] {1}zIm [{2}] \r\n".format(punits, field, funits)) file.write("------------------------------------------------------------------------------------------------------------------------------------------\r\n") for x in xrange(nx): px = pscale * data.px[x] for y in xrange(ny): py = pscale * data.py[y] for z in xrange(nz): pz = pscale * data.pz[z] fxre = fscale * numpy.real(data.fx[x,y,z]) fyre = fscale * numpy.real(data.fy[x,y,z]) fzre = fscale * numpy.real(data.fz[x,y,z]) fxim = fscale * numpy.imag(data.fx[x,y,z]) fyim = fscale * numpy.imag(data.fy[x,y,z]) fzim = fscale * numpy.imag(data.fz[x,y,z]) file.write("%13.1f %13.1f %13.1f %13.6g %13.6g %13.6g %13.6g %13.6g %13.6g\r\n" % (px, py, pz, fxre, fyre, fzre, fxim, fyim, fzim))
def _test_random(test_case,inarr,outarr,tol): tc = test_case # Test that applying a transform and its inverse to reasonably long, random # input gives back the (appropriately scaled) input. We must allow for numerical # error, and it seems more reliable to check using normwise error (than elementwise). # # First test IFFT(FFT(random)) # The numpy randn(n) provides an array of n numbers drawn from standard normal if dtype(inarr).kind == 'c': inarr._data[:] = randn(len(inarr)) +1j*randn(len(inarr)) # If we're going to do a HC2R transform we must worry about DC/Nyquist imaginary if dtype(outarr).kind == 'f': inarr._data[0] = real(inarr[0]) if (len(outarr)%2)==0: inarr._data[len(inarr)-1] = real(inarr[len(inarr)-1]) else: inarr._data[:] = randn(len(inarr)) incopy = type(inarr)(inarr) outarr.clear() # An FFT followed by IFFT gives Array scaled by len(Array), but for # Time/FrequencySeries there should be no scaling. if type(inarr) == pycbc.types.Array: incopy *= len(inarr) with tc.context: pycbc.fft.fft(inarr, outarr) pycbc.fft.ifft(outarr, inarr) emsg="IFFT(FFT(random)) did not reproduce original array to within tolerance {0}".format(tol) if isinstance(incopy,ts) or isinstance(incopy,fs): tc.assertTrue(incopy.almost_equal_norm(inarr,tol=tol,dtol=tol), msg=emsg) else: tc.assertTrue(incopy.almost_equal_norm(inarr,tol=tol), msg=emsg) # Perform arithmetic on outarr and inarr to pull them off of the GPU: outarr *= 1.0 inarr *= 1.0 # Now the same for FFT(IFFT(random)) if dtype(outarr).kind == 'c': outarr._data[:] = randn(len(outarr))+1j*randn(len(outarr)) # If we're going to do a HC2R transform we must worry about DC/Nyquist imaginary if dtype(inarr).kind == 'f': outarr._data[0] = real(outarr[0]) if (len(inarr)%2)==0: outarr._data[len(outarr)-1] = real(outarr[len(outarr)-1]) else: outarr._data[:] = randn(len(outarr)) inarr.clear() outcopy = type(outarr)(outarr) if type(outarr) == pycbc.types.Array: outcopy *= len(inarr) with tc.context: pycbc.fft.ifft(outarr, inarr) pycbc.fft.fft(inarr, outarr) emsg="FFT(IFFT(random)) did not reproduce original array to within tolerance {0}".format(tol) if isinstance(outcopy,ts) or isinstance(outcopy,fs): tc.assertTrue(outcopy.almost_equal_norm(outarr,tol=tol,dtol=tol), msg=emsg) else: tc.assertTrue(outcopy.almost_equal_norm(outarr,tol=tol), msg=emsg)
def closest_point_on_the_parabola(a, px, py): thingy1 = 2. * a * py thingy2 = np.sqrt(-3 + 0j) thingy3 = 2 ** (1 / 3.) thingy4 = 2 ** (2 / 3.) thingy = (-108. * a ** 4 * px + np.sqrt(11664. * a ** 8 * px ** 2 - 864. * a ** 6 * (-1 + thingy1) ** 3 + 0j)) ** ( 1 / 3.) Aone = (thingy3 * (-1. + thingy1)) Atwo = thingy Athree = thingy Afour = (6. * thingy3 * a ** 2) Bone = ((1. + thingy2) * (-1. + thingy1)) Btwo = (thingy4 * thingy) Bthree = ((1. - thingy2) * thingy) Bfour = (12. * thingy3 * a ** 2) Cone = (1. - thingy2) * (-1 + thingy1) Ctwo = thingy4 * thingy Cthree = (1. + thingy2) * thingy Cfour = 12. * thingy3 * a ** 2 A = -np.real(Aone / Atwo + Athree / Afour) B = np.real(Bone / Btwo + Bthree / Bfour) C = np.real(Cone / Ctwo + Cthree / Cfour) solns = [A, B, C] solns_temp = [] for soln in solns: solns_temp.append(np.abs(soln - px)) val, idx = min((val, idx) for (idx, val) in enumerate(solns_temp)) return solns[idx]
def simulate(self, steps, time, collect_dynamic = False): """! @brief Performs static simulation of oscillatory network. @param[in] steps (uint): Number simulation steps. @param[in] time (double): Time of simulation. @param[in] collect_dynamic (bool): If True - returns whole dynamic of oscillatory network, otherwise returns only last values of dynamics. @return (list) Dynamic of oscillatory network. If argument 'collect_dynamic' is True, than return dynamic for the whole simulation time, otherwise returns only last values (last step of simulation) of output dynamic. @see simulate() @see simulate_dynamic() """ dynamic_amplitude, dynamic_time = ([], []) if collect_dynamic is False else ([self.__amplitude], [0]); step = time / steps; int_step = step / 10.0; for t in numpy.arange(step, time + step, step): self.__amplitude = self.__calculate(t, step, int_step); if collect_dynamic is True: dynamic_amplitude.append([ numpy.real(amplitude)[0] for amplitude in self.__amplitude ]); dynamic_time.append(t); if collect_dynamic is False: dynamic_amplitude.append([ numpy.real(amplitude)[0] for amplitude in self.__amplitude ]); dynamic_time.append(time); output_sync_dynamic = fsync_dynamic(dynamic_amplitude, dynamic_time); return output_sync_dynamic;
def getArgumentVariable(_ComplexVariable): #Debug ''' print('l 31 Numscipier') print('_ComplexVariable is ') print(_ComplexVariable) print('') ''' #import import numpy as np #return return 2.*np.arctan( np.imag(_ComplexVariable)/( np.sqrt( np.imag( _ComplexVariable )**2+np.real( _ComplexVariable )**2)+np.real( _ComplexVariable ) ) );
def instantaneous_frequency(data, fs, fk): """ Instantaneous frequency of a signal. Computes the instantaneous frequency of the given data which can be windowed or not. The instantaneous frequency is determined by the time derivative of the analytic signal of the input data. :type data: :class:`~numpy.ndarray` :param data: Data to determine instantaneous frequency of. :param fs: Sampling frequency. :param fk: Coefficients for calculating time derivatives (calculated via central difference). :return: **omega[, domega]** - Instantaneous frequency of input data, Time derivative of instantaneous frequency (windowed only). """ x = envelope(data) if len(x[0].shape) > 1: omega = np.zeros(x[0].shape[0], dtype=np.float64) i = 0 for row in x[0]: f = np.real(row) h = np.imag(row) # faster alternative to calculate f_add f_add = np.hstack(([f[0]] * (np.size(fk) // 2), f, [f[np.size(f) - 1]] * (np.size(fk) // 2))) fd = signal.lfilter(fk, 1, f_add) # correct start and end values of time derivative fd = fd[np.size(fk) - 1 : np.size(fd)] # faster alternative to calculate h_add h_add = np.hstack(([h[0]] * (np.size(fk) // 2), h, [h[np.size(h) - 1]] * (np.size(fk) // 2))) hd = signal.lfilter(fk, 1, h_add) # correct start and end values of time derivative hd = hd[np.size(fk) - 1 : np.size(hd)] omega_win = abs(((f * hd - fd * h) / (f * f + h * h)) * fs / 2 / np.pi) omega[i] = np.median(omega_win) i = i + 1 # faster alternative to calculate omega_add omega_add = np.hstack( ([omega[0]] * (np.size(fk) // 2), omega, [omega[np.size(omega) - 1]] * (np.size(fk) // 2)) ) domega = signal.lfilter(fk, 1, omega_add) # correct start and end values of time derivative domega = domega[np.size(fk) - 1 : np.size(domega)] return omega, domega else: omega = np.zeros(np.size(x[0]), dtype=np.float64) f = np.real(x[0]) h = np.imag(x[0]) # faster alternative to calculate f_add f_add = np.hstack(([f[0]] * (np.size(fk) // 2), f, [f[np.size(f) - 1]] * (np.size(fk) // 2))) fd = signal.lfilter(fk, 1, f_add) # correct start and end values of time derivative fd = fd[np.size(fk) - 1 : np.size(fd)] # faster alternative to calculate h_add h_add = np.hstack(([h[0]] * (np.size(fk) // 2), h, [h[np.size(h) - 1]] * (np.size(fk) // 2))) hd = signal.lfilter(fk, 1, h_add) # correct start and end values of time derivative hd = hd[np.size(fk) - 1 : np.size(hd)] omega = abs(((f * hd - fd * h) / (f * f + h * h)) * fs / 2 / np.pi) return omega
def icd(self, G1, G2): """Incomplete Cholesky decomposition """ # remove mean. avoid standard calculation N0 = eye(N)-1/N*ones(N); G1 = G1 - numpy.array(numpy.mean(G1, 0), ndmin=2, copy=False) G2 = G2 - numpy.array(numpy.mean(G2, 0), ndmin=2, copy=False) R, D = self.method(G1, G2, self.reg) #solve generalized eigenvalues problem betas, alphas = scipy.linalg.eig(R,D) ind = numpy.argsort(numpy.real(betas)) max_ind = ind[-1] alpha = alphas[:, max_ind] alpha = alpha/numpy.linalg.norm(alpha) beta = numpy.real(betas[max_ind]) N1 = G1.shape[1] alpha1 = alpha[:N1] alpha2 = alpha[N1:] y1 = dot(G1, alpha1) y2 = dot(G2, alpha2) self.alpha1 = alpha1 self.alpha2 = alpha2 return (y1, y2, beta)
def test_morlet(): """Test morlet with and without zero mean""" Wz = morlet(1000, [10], 2., zero_mean=True) W = morlet(1000, [10], 2., zero_mean=False) assert_true(np.abs(np.mean(np.real(Wz[0]))) < 1e-5) assert_true(np.abs(np.mean(np.real(W[0]))) > 1e-3)
def compress_data(X, k): Xtemp = X.dot(X.T) if len(Xtemp) == 0: return None e_vals, e_vecs = np.linalg.eig(Xtemp) e_vals = np.maximum(0.0, np.real(e_vals)) e_vecs = np.real(e_vecs) idx = np.argsort(e_vals)[::-1] e_vals = e_vals[idx] e_vecs = e_vecs[:, idx] # Truncate to k dimensions if k < len(e_vals): e_vals = e_vals[:k] e_vecs = e_vecs[:, :k] # Normalize by the leading singular value of X Z = np.sqrt(e_vals.max()) if Z > 0: e_vecs = e_vecs / Z return e_vecs.T.dot(X)
def build_initial_condition(rossby, froude, nx, outfilename, csvFlag): """ Main method to compute initially-balanced turbulent flow field. Creates initially-balanced randomised flow field plus height field for use in rotating shallow water equations. Follows the procedure implemented in Polvani et al (1994). Relies on the methods contained in the TurbulentICs class as well as those in the spectral_toolbox. **Parameters** - `rossby` : the desired Rossby number, defined as :math: `R = U/(f_{0}L)` - `froude` : the Froude number, defined as :math: `F = U/\\sqrt{gH}` - `nx` : the number of points to use, such that the domain is n x n - `outfilename` : the stem to be used for creating outfiles - `csvFlag` : optional flag to create MATLAB-syle output **Returns** - `outfilename.bin` : data file for use by RSWE code - `outfilename_u.txt` : CSV file with v1 - `outfilename_v.txt` : CSV file with v2 - `outfilename_h.txt` : CSV file with h - `outfilename_data.txt` : CSV file with other data **See Also** TurbulentICs, SpectralToolbox """ control = dict() np.set_printoptions(precision=2, linewidth=200) # Set control parameters: control['Rossby'] = rossby control['Froude'] = froude control['Nx'] = nx control['Lx'] = 2.0 * np.pi * 14.0 control['outname'] = outfilename # Compute the Burger number control['Burger'] = (control['Rossby'] / control['Froude'])**2 # Hardcode tolerance for iterative solver control['tolerance'] = 1e-6 logging.info('Control Structure Created Successfully') # Create spectral toolbox object for use in TurbulentICs st = SpectralToolbox(control['Nx'], control['Lx']) # Create turbulence handler turb_cond = TurbulentICs(control, st) logging.info('Turbulence Handler Created Successfully') # Create streamfunction field, store in turb_cond turb_cond.construct_streamfunction() logging.info('Streamfunction Created Successfully') # Create height field, store in turb_cond turb_cond.create_height(control) logging.info('Height Computed Successfully') # Create velocity potential field, store in turb_cond logging.info('Beginning Computation of Velocity Potential') turb_cond.create_velocity_potential(control) logging.info('Potential Created Successfully') # Compute velocities turb_cond.compute_velocities(control) # Save ICs to File if csvFlag: h = np.real(turb_cond.st.inverse_fft(turb_cond.h)) h = 1.0 + control['Rossby'] * h / control['Burger'] v1 = np.real(turb_cond.st.inverse_fft(turb_cond.vx)) v2 = np.real(turb_cond.st.inverse_fft(turb_cond.vy)) np.savetxt(str(outfilename) + "_u.txt", v1, delimiter="\t") np.savetxt(str(outfilename) + "_v.txt", v2, delimiter="\t") np.savetxt(str(outfilename) + "_h.txt", h, delimiter="\t") with open(str(outfilename) + '_data.txt', 'w') as f: f.write("Rossby {}\n".format(control['Rossby'])) f.write("Froude {}\n".format(control['Froude'])) f.write("Burger {}\n".format(control['Burger'])) f.write("Nx {}\n".format(control['Nx'])) logging.info("Initial Condition saved to successfully") else: with open(str(outfilename) + '.bin', 'wb') as f: np.save(f, control['Nx']) # Compute total nondimensional height height = 1.0 + (control['Rossby'] / control['Burger']) * st.inverse_fft(turb_cond.h) np.save(f, st.forward_fft(height)) np.save(f, turb_cond.vx) np.save(f, turb_cond.vy) logging.info("Initial Condition saved to {}".format( str(outfilename) + '.bin'))
def tsp_signal(self, impulse, real_num=7, app=None): # tsp = TSP('../config_tf.ini') recode_data_directory = self.data_search(self.date, self.sound_kind, self.geometric, app, plane_wave=self.plane_wave) wave_path = self.recode_data_path + recode_data_directory print(wave_path) print("Making data set....") # impulse = Trueでインパルス応答計算用に平均したデータを作成 if impulse: data_set = np.empty((0, self.data_set_freq_len), dtype=np.float) for data_dir in self.DIRECTIONS: sound_data, channel, sampling, frames = self.wave_read_func( wave_path + str(data_dir) + '.wav') if self.mic_name == 'Respeaker': sound_data = np.delete(sound_data, [0, 5], 0) elif self.mic_name == 'Matrix': sound_data = sound_data start_time = self.zero_cross(sound_data, 128, sampling, 512, self.origin_frames, up=True) if start_time < 0: if real_num != self.data_num: start_time = start_time + self.origin_frames else: start_time = 0 cut_data = sound_data[:, start_time:int(start_time + self.origin_frames * self.data_num)] fft_data = np.fft.rfft(cut_data)[0] fft_data = fft_data[self.freq_min_id:self.freq_max_id] smooth_data = np.convolve(fft_data, np.ones(self.smooth_step) / float(self.smooth_step), mode='valid') smooth_data = np.reshape(smooth_data, (1, -1)) # print(smooth_data.shape) data_set = np.append(data_set, smooth_data, axis=0) print('finish: ', data_dir + 50 + 1, '/', len(self.DIRECTIONS)) print('Made data set: ', data_set.shape) return np.real(data_set) # impluse = FalseでSVRやPCA用の一個一個のデータに分割 else: data_set = np.zeros((len(self.DIRECTIONS), self.mic_num, self.data_num, self.data_set_freq_len), dtype=np.float) print('Need Number', self.origin_frames) for data_dir in self.DIRECTIONS: sound_data, channel, sampling, frames = self.wave_read_func( wave_path + str(data_dir) + '.wav') if self.mic_name == 'Respeaker': sound_data = np.delete(sound_data, [0, 5], 0) elif self.mic_name == 'Matrix': sound_data = sound_data start_time = self.zero_cross(sound_data, 128, sampling, 512, int(self.origin_frames), up=True) if start_time < 0: if real_num != self.data_num: start_time = start_time + self.origin_frames else: start_time = 0 cut_data = sound_data[:, start_time:int(start_time + self.origin_frames * self.data_num)] cut_data = np.reshape(cut_data, (self.mic_num, self.data_num, -1)) fft_data = np.fft.rfft(cut_data) if data_dir == self.DIRECTIONS[0]: print("#######################") print("This mic is ", self.mic_name) print("Channel ", channel) print("Frames ", frames) print("Data Set ", fft_data.shape) # print("0Cross point ", start_time) print("Object ", self.target) print("Rate ", sampling) print("#######################") plt.figure() plt.specgram(cut_data[0, 0, :], Fs=sampling) plt.title("cut_data check") plt.show() for data_id in range(cut_data.shape[1]): for mic in range(cut_data.shape[0]): smooth_data = np.convolve(np.abs( fft_data[mic, data_id, self.freq_min_id:self.freq_max_id]), np.ones(self.smooth_step) / float(self.smooth_step), mode='valid') smooth_data = np.real(np.reshape(smooth_data, (1, -1)))[0] normalize_data = stats.zscore(smooth_data, axis=0) # normalize_data = (smooth_data - smooth_data.mean()) / smooth_data.std() # normalize_data = (smooth_data - min(smooth_data))/(max(smooth_data) - min(smooth_data)) data_set[data_dir, mic, data_id, :] = normalize_data # print(normalize_data) print('finish: ', data_dir + self.label_max + 1, '/', len(self.DIRECTIONS)) print('Made data set: ', data_set.shape) output_path = self.make_dir_path(array=True) np.save(output_path + recode_data_directory.strip('/'), data_set)
def tsp_signal_individually(self, app=None): recode_path = self.data_search(self.date, self.sound_kind, self.geometric, app, plane_wave=self.plane_wave) wave_path = self.recode_data_path + recode_path print(wave_path) if self.beam: data_set = np.zeros((len(self.DIRECTIONS), len( self.ms.ss_list), self.data_num, self.data_set_freq_len), dtype=np.float) else: data_set = np.zeros((len(self.DIRECTIONS), self.mic_num, self.data_num, self.data_set_freq_len), dtype=np.float) for data_id in range(self.data_num): for data_dir in self.DIRECTIONS: sound_data, channel, sampling, frames = \ self.wave_read_func(wave_path + self.target + '_' + str(data_id + 1) + '/' + str(data_dir) + '.wav') if self.mic_name == 'Respeaker': sound_data = np.delete(sound_data, [0, 5], 0) elif self.mic_name == 'Matrix': sound_data = np.delete(sound_data, 0, 0) else: print("Error") sys.exit() start_time = self.zero_cross(sound_data, 128, sampling, 512, self.origin_frames, up=True) if start_time < 0: start_time = 0 sound_data = sound_data[:, start_time:int(start_time + self.origin_frames)] if data_dir == self.DIRECTIONS[0]: print("#######################") print("This mic is ", self.mic_name) print("Channel ", channel) print("Frames ", frames) print("Data Set ", sound_data.shape) print("0Cross point ", start_time) print("Object ", self.target) print("Rate ", sampling) print("#######################") fft_data = np.fft.rfft(sound_data) if self.beam: bmp = self.ms.beam_forming_localization( fft_data[:, self.freq_min_id:self.freq_max_id], self.tf, self.fft_list) for dir in range(bmp.shape[0]): smooth_data = np.convolve(np.abs(bmp[dir, :]), np.ones(self.smooth_step) / float(self.smooth_step), mode='valid') smooth_data = np.real(np.reshape(smooth_data, (1, -1)))[0] normalize_data = stats.zscore(smooth_data, axis=0) # 平均0 分散1 data_set[data_dir, dir, data_id, :] = normalize_data else: for mic in range(fft_data.shape[0]): smooth_data = np.convolve(np.abs( fft_data[mic, self.freq_min_id:self.freq_max_id]), np.ones(self.smooth_step) / float(self.smooth_step), mode='valid') smooth_data = np.real(np.reshape(smooth_data, (1, -1)))[0] normalize_data = stats.zscore(smooth_data, axis=0) # 平均0 分散1 # normalize_data = (smooth_data - smooth_data.mean()) / smooth_data.std() # normalize_data = (smooth_data - min(smooth_data))/(max(smooth_data) - min(smooth_data)) data_set[data_dir, mic, data_id, :] = normalize_data # print('finish: ', data_dir + 50 + 1, '/', len(self.DIRECTIONS)) print('finish: ', data_id + 1, '/', self.data_num) print('***********************************************') print('Made data set: ', data_set.shape) output_path = self.make_dir_path(array=True) np.save(output_path + recode_path.strip('/'), data_set)
# calculating and sorting eigenvalues and eigenvectors for Gam_up in Gam_up_array: j = 0 # Calculating rates gamma_i^{\mu} (requires Lindblad parameters) gam_mu_i = rates(Gam_up, Gam_down, Gam_z, gam_phon, lam, N, T, om_v, S) # calculating zeta, xi and psi (requires Hamiltonian and Lindblad parameters) zeta, xi, psi, phi, eta = equat_coeff(gam_mu_i, f, g, A, N) # normal state specification A_vec = -(2j / N) * np.einsum('mj, mk, ijk -> i', gam_mu_i, np.conjugate(gam_mu_i), f) xi_inv_matr = inv(xi) lam_ns = np.real(np.dot(xi_inv_matr, A_vec)) for om_c in phot_freq: # build stability matrix with A^2 term M = M_stability_with_A_squared(om_c, kappa, B, f, xi, lam_ns, N_m, g_light_mat, eps) # build stability matrix without A^2 term #M = M_stability(om_c, kappa, B, f, xi, lam_ns, N_m) # get eigenvalues and assosiated eigenvectors eigenValues, eigenVectors = linalg.eig(M) # sort the according to eigenvalues' real parts from smallest to largest idx_real_sort = eigenValues.argsort()
import numpy as np import matplotlib.pyplot as plt from scipy.fft import fft n = 52 F = np.zeros((n, n), dtype="complex") w = np.exp(-2 * np.pi * np.complex(0, 1) / n) for i in range(n): for k in range(n): m = (i) * (k) # (j - 1)*(k - 1), but python is 0 indexed F[i, k] = w**m fig, ax = plt.subplots(1, 3) ax[0].imshow(np.real(F)) ax[1].imshow(np.imag(F)) ax[2].imshow(np.abs(F)) #x = np.random.randn(n, 1) x = np.random.randn(n) x1 = np.matmul(F, x) x2 = fft(x) fig, ax2 = plt.subplots(1, 1) ax2.plot(range(n), np.abs(x1)) ax2.scatter(range(n), np.abs(x2), s=50, marker='o', facecolors='none',
def real(self): """Returns the real part of the hs (read-only property).""" return np.real(self.hs)
def FID(m0, c0, m1, c1): ret = 0 ret += np.sum((m0 - m1) ** 2) ret += np.trace(c0 + c1 - 2.0 * scipy.linalg.sqrtm(np.dot(c0, c1))) return np.real(ret)
def _extract_emd(mat, **kwargs): """Extract the data from the EMD substruct, given a medusa-created MNU0-mat file Parameters ---------- mat: matlab-imported struct """ emd = mat['EMD'].squeeze() # Labview epoch epoch = datetime.datetime(1904, 1, 1) def convert_epoch(x): timestamp = epoch + datetime.timedelta(seconds=x.astype(float)) return timestamp dfl = [] # loop over frequencies for f_id in range(0, emd.size): # print('Frequency: ', emd[f_id]['fm']) fdata = emd[f_id] # some consistency checks if len(fdata['nu']) == 2 and fdata['nu'].shape[1] == 2: raise Exception('Need MNU0 file, not a quadpole .mat file:') timestamp = np.atleast_2d( [convert_epoch(x) for x in fdata['Time'].squeeze()]).T df = pd.DataFrame( np.hstack(( timestamp, fdata['ni'], fdata['nu'][:, np.newaxis], fdata['Zt3'], fdata['Is3'], fdata['Il3'], fdata['Zg3'], fdata['As3'][:, 0, :].squeeze(), fdata['As3'][:, 1, :].squeeze(), fdata['As3'][:, 2, :].squeeze(), fdata['As3'][:, 3, :].squeeze(), fdata['Yg13'], fdata['Yg23'], )), ) df.columns = ( 'datetime', 'a', 'b', 'p', 'Z1', 'Z2', 'Z3', 'Is1', 'Is2', 'Is3', 'Il1', 'Il2', 'Il3', 'Zg1', 'Zg2', 'Zg3', 'ShuntVoltage1_1', 'ShuntVoltage1_2', 'ShuntVoltage1_3', 'ShuntVoltage2_1', 'ShuntVoltage2_2', 'ShuntVoltage2_3', 'ShuntVoltage3_1', 'ShuntVoltage3_2', 'ShuntVoltage3_3', 'ShuntVoltage4_1', 'ShuntVoltage4_2', 'ShuntVoltage4_3', 'Yg13_1', 'Yg13_2', 'Yg13_3', 'Yg23_1', 'Yg23_2', 'Yg23_3', ) df['frequency'] = np.ones(df.shape[0]) * fdata['fm'] # cast to correct type df['datetime'] = pd.to_datetime(df['datetime']) df['a'] = df['a'].astype(int) df['b'] = df['b'].astype(int) df['p'] = df['p'].astype(int) df['Z1'] = df['Z1'].astype(complex) df['Z2'] = df['Z2'].astype(complex) df['Z3'] = df['Z3'].astype(complex) df['Zg1'] = df['Zg1'].astype(complex) df['Zg2'] = df['Zg2'].astype(complex) df['Zg3'] = df['Zg3'].astype(complex) df['Is1'] = df['Is1'].astype(complex) df['Is2'] = df['Is2'].astype(complex) df['Is3'] = df['Is3'].astype(complex) df['Il1'] = df['Il1'].astype(complex) df['Il2'] = df['Il2'].astype(complex) df['Il3'] = df['Il3'].astype(complex) df['ShuntVoltage1_1'] = df['ShuntVoltage1_1'].astype(complex) df['ShuntVoltage1_2'] = df['ShuntVoltage1_2'].astype(complex) df['ShuntVoltage1_3'] = df['ShuntVoltage1_3'].astype(complex) df['ShuntVoltage2_1'] = df['ShuntVoltage2_1'].astype(complex) df['ShuntVoltage2_2'] = df['ShuntVoltage2_2'].astype(complex) df['ShuntVoltage2_3'] = df['ShuntVoltage2_3'].astype(complex) df['ShuntVoltage3_1'] = df['ShuntVoltage3_1'].astype(complex) df['ShuntVoltage3_2'] = df['ShuntVoltage3_2'].astype(complex) df['ShuntVoltage3_3'] = df['ShuntVoltage3_3'].astype(complex) df['ShuntVoltage4_1'] = df['ShuntVoltage4_1'].astype(complex) df['ShuntVoltage4_2'] = df['ShuntVoltage4_2'].astype(complex) df['ShuntVoltage4_3'] = df['ShuntVoltage4_3'].astype(complex) dfl.append(df) if len(dfl) == 0: return None df = pd.concat(dfl) # average swapped current injections here! # TODO # sort current injections condition = df['a'] > df['b'] df.loc[condition, ['a', 'b']] = df.loc[condition, ['b', 'a']].values # for some reason we lose the integer casting of a and b here df['a'] = df['a'].astype(int) df['b'] = df['b'].astype(int) # change sign because we changed A and B df.loc[condition, ['Z1', 'Z2', 'Z3']] *= -1 # average of Z1-Z3 df['Zt'] = np.mean(df[['Z1', 'Z2', 'Z3']].values, axis=1) # we need to keep the sign of the real part sign_re = np.real(df['Zt']) / np.abs(np.real(df['Zt'])) df['r'] = np.abs(df['Zt']) * sign_re # df['Zt_std'] = np.std(df[['Z1', 'Z2', 'Z3']].values, axis=1) df['Is'] = np.mean(df[['Is1', 'Is2', 'Is3']].values, axis=1) df['Il'] = np.mean(df[['Il1', 'Il2', 'Il3']].values, axis=1) df['Zg'] = np.mean(df[['Zg1', 'Zg2', 'Zg3']].values, axis=1) # "standard" injected current, in [mA] df['Iab'] = np.abs(df['Is']) * 1e3 df['Iab'] = df['Iab'].astype(float) # df['Is_std'] = np.std(df[['Is1', 'Is2', 'Is3']].values, axis=1) # take absolute value and convert to mA df['Ileakage'] = np.abs(df['Il']) * 1e3 df['Ileakage'] = df['Ileakage'].astype(float) return df
def mcm_to_m2(m1,mc): c = [m1**3 , 0 , -mc**5 , -mc**5*m1] m2 = np.real(np.roots(c)) return float(m2[np.where(m2>=0)])
def construct_streamfunction(self): """ Construct the initially-balanced streamfunction. Sets the attribute psi with the streamfunction computed according to .. math:: 1/2 k^{2}|\\psi_{k}|^{2} = E_{K}(k) Proceeds by creating a vorticity field with initially random phases in Fourier space and moduli of 1. This field is then integrated to find the corresponding streamfunction which is 'tuned' to have the desired kinetic energy spectrum. The spectrum is tuned such that the desired spectrum occurs in shells. """ # Initialise the random phases, e^{i*theta} N = self.N phases = np.random.uniform(0.0, 2 * np.pi, (N - 1, N - 1)) vorticity_hat = np.zeros((N, N), dtype=complex) vorticity_buffer = np.exp(1j * phases) Nyquist_1 = np.exp(1j * np.random.uniform(0.0, 2 * np.pi, (N // 2 - 1))) Nyquist_2 = np.exp(1j * np.random.uniform(0.0, 2 * np.pi, (N // 2 - 1))) # Ensure that the initial vorticity field has a Hermitian # spectrum in Fourier space for a real-valued solution. mid = (N - 1) // 2 mid2 = 2 * mid for k1 in range(N - 1): for k2 in range(k1 + 1, N - 1): vorticity_buffer[k1, k2] = np.conj(vorticity_buffer[mid2 - k1, mid2 - k2]) for k in range(mid): vorticity_buffer[k, k] = np.conj(vorticity_buffer[mid2 - k, mid2 - k]) vorticity_hat[1:, 1:] = vorticity_buffer # Set up the Nyqusist frequencies to yield a real-valued, # C_{inf} vorticity field in realspace. vorticity_hat[0, 1:N // 2] = Nyquist_1 vorticity_hat[0, N // 2 + 1:N] = np.conj(Nyquist_1[::-1]) vorticity_hat[1:N // 2, 0] = Nyquist_2 vorticity_hat[N // 2 + 1:N, 0] = np.conj(Nyquist_2[::-1]) vorticity_hat[N // 2, N // 2] = 0.0 vorticity_hat[0, 0] = 0.0 vorticity_hat[0, N // 2] = 0.0 vorticity_hat[N // 2, 0] = 0.0 vorticity = self.st.inverse_fft(vorticity_hat) vorticity /= np.amax(np.real(vorticity)) vorticity_hat = self.st.forward_fft(-vorticity) # Find the associated streamfunction via inverse Helmholtz self.psi = self.st.solve_inverse_laplacian(vorticity_hat, 0.0) # Calculate the total kinetic energy in each wavenumber shell E_k = dict() for k1 in range(-N // 2, N // 2): for k2 in range(-N // 2, N // 2): k = np.sqrt(k1**2 + k2**2) k_ctr = int(round(k)) psi_value = self.psi[k1 + N // 2, k2 + N // 2] local_energy = np.real(0.5 * ((2 * np.pi)**2) * k**2 * psi_value * np.conj(psi_value)) try: E_k[k_ctr] += local_energy except KeyError: E_k[k_ctr] = local_energy for k1 in range(-N // 2, N // 2): for k2 in range(-N // 2, N // 2): k = np.sqrt(k1**2 + k2**2) k_ctr = int(round(k)) # Compute the desired kinetic energy level for the # current shell E_target = self.energy_spectrum(k1, k2) # `Tune' the kinetic energy spectrum, shell by shell if k_ctr > 0 and E_k[k_ctr] > 1e-12: self.psi[k1 + N // 2, k2 + N // 2] *= np.sqrt(E_target / E_k[k_ctr]) else: self.psi[k1 + N // 2, k2 + N // 2] = 0.0
def grad(self,complex_im,axis=0): g_r = np.gradient(np.real(complex_im),edge_order=2,axis=axis) g_i = np.gradient(np.imag(complex_im),edge_order=2,axis=axis) return(g_r,g_i)
x_bottom = np.array([np.linspace(0.0, 2.0, int(N_b/4))]) y_bottom = np.zeros((int(N_b/4),1),dtype = np.float32) X_b_bottom = np.concatenate((x_bottom.T, y_bottom), axis=1) u_y_b_bottom = np.zeros((int(N_b/4),1),dtype = np.float32) x_top = np.array([np.linspace(0.0, 2.0, int(N_b/4))]) y_top = np.ones((int(N_b/4),1),dtype = np.float32) X_b_top = np.concatenate((x_top.T, y_top), axis=1) u_y_b_top = np.zeros((int(N_b/4),1),dtype = np.float32) x_right = 2*np.ones((int(N_b/4),1),dtype = np.float32) y_right = np.array([np.linspace(0.0,1.0,int(N_b/4))]) X_b_right = np.concatenate((x_right, y_right.T), axis=1) x_right_scal = 2; u_x_b_right = np.float32(np.real(np.cos(m*np.pi*y_right)*(A[0]*(-1j)*kx*np.exp(-1j*kx*x_right_scal)+A[1]*1j*kx*np.exp(1j*kx*x_right_scal)))) u_x_b_right = u_x_b_right.T nPred = 160 xPred = np.linspace(0.0, 2.0, nPred) yPred = np.linspace(0.0, 1.0, nPred) xGrid, yGrid = np.meshgrid(xPred, yPred) xGrid = np.array([xGrid.flatten()]) yGrid = np.array([yGrid.flatten()]) Grid = np.concatenate((xGrid.T,yGrid.T),axis=1) np.savetxt('Grid.out', Grid, delimiter=',') print('Defining model...') model = PhysicsInformedNN(X_b_left, u_x_b_left, X_b_bottom, u_y_b_bottom, X_b_top, u_y_b_top, X_b_right, u_x_b_right, X_f, layers, LB_Plate, UB_Plate, m, k)
def plot_one_testcase_panels(preds_dd, solns, show_n_timesteps=10, alpha=0.7, title=None, fp=None): """Plots a single test case solutions/predictions by producing a series of panels. The rows of panels each correspond to one time step, and the three columns are the real part, the imaginary part, and the errors. Args: preds_dd (dict): Dictionary of 2d numpy arrays. Each array corresponds to the predictions on a single test-case, and has time on the 0th axis and space on the 1st axis. The arrays should have matching shape (n_time_steps, n_grid_points). Time step 0 (assumed to be the initial conditions) will not be shown. solns (numpy array): The true solutions. 2d array with time on the 0th axis and space on the 1st axis. Should have shape (n_time_steps, n_grid_points). Time step 0 (assumed to be the initial conditions) will not be shown. show_n_timesteps (int, optional): min(show_n_timesteps, n_time_steps-1) will be shown. Defaults to 10. alpha (float, optional): Constrols satuation value. Defaults to 0.7. title (string, optional): Figure title. Defaults to None. fp (string, optional): Filepath to save the plot. If not specified, the plot will be shown via `plt.show`. Defaults to None. """ # Checking that the time axes are the same size to avoid silly off-by-one # plotting errors n_tsteps, grid_size = solns.shape for k,v in preds_dd.items: assert v.shape[0] == n_tsteps N_TSTEPS = min(n_tsteps - 1, show_n_timesteps) fig, ax = plt.subplots(N_TSTEPS, 3, sharex='col', sharey=False) # This sets the figure to an image with aspect ratio 1.5x2 fig.set_size_inches(1.5 * N_TSTEPS ,2 * N_TSTEPS) fig.patch.set_facecolor('white') ax[0,0].set_title("$Re(u)$", size=20) ax[0,1].set_title("$Im(u)$", size=20) ax[0,2].set_title("$| u - \\hat u|$", size=20) for i in range(1, N_TSTEPS+1): # First column has Re(prediction), Re(solution) ax[i,0].plot(np.real(solns[i]), '--', alpha=alpha, label='solution') # Second column has Im(predictions), Im(solution) ax[i,1].plot(np.imag(solns[i]), '--', alpha=alpha, label='solutions') for k,v in preds_dd.items(): ax[i,0].plot(np.real(v[i]), alpha=alpha, label=k) ax[i,1].plot(np.imag(v[i]), alpha=alpha, label=k) # Third column has errors Abs(solns - predictions) ax[i,2].plot(np.abs(solns[i] - v[i]), alpha=alpha, label=k) ax[i,0].set_ylabel("t = {}".format(i), size=15) ax[i,2].hlines(0, xmin=0, xmax=grid_size, linestyles='dashed') ax[0,0].legend(fontsize=13, markerscale=2) ax[0,1].legend(fontsize=13, markerscale=2) ax[0,2].legend(fontsize=13, markerscale=2) if title is not None: fig.suptitle(title) fig.tight_layout(rect=[0, 0.03, 1, 0.95]) if fp is not None: plt.savefig(fp) else: plt.show() plt.close(fig)
def get_q_values(freqs, cplx, filename_wo_ext): # find resonant frequency idx_res = np.argmin(np.abs(cplx)) f_res = freqs[idx_res] # determine the rotation angle from the offset for detuned short location idx_max = np.argmin(np.abs(cplx)) + 100 idx_min = np.argmin(np.abs(cplx)) - 100 rotation = (np.angle(cplx[idx_min]) + np.angle(cplx[idx_max])) / 2 # find the detuned short position real_shifted = np.abs(cplx) * np.cos(np.angle(cplx) - rotation) imag_shifted = np.abs(cplx) * np.sin(np.angle(cplx) - rotation) cplx_shifted = np.vectorize(complex)(real_shifted, imag_shifted) # without multiplication with 50 ohm. so it is normalized impz_shifted = (1 + cplx_shifted) / (1 - cplx_shifted) * 50 # find detuned open position real_dop = np.abs(cplx_shifted) * np.cos(np.angle(cplx_shifted) - np.pi) imag_dop = np.abs(cplx_shifted) * np.sin(np.angle(cplx_shifted) - np.pi) cplx_dop = np.vectorize(complex)(real_dop, imag_dop) impz_dop = (1 + cplx_dop) / (1 - cplx_dop) * 50 # find the index of the point where Re(Z) = |Im(Z)| left of the resonance and call it f5 f5 = freqs[np.argmin(np.abs(np.real(impz_shifted)[:idx_res] - np.abs(np.imag(impz_shifted)[:idx_res])))] # find the index of the point where Re(Z) = |Im(Z)| right of the resonance and call it f6 f6 = freqs[np.argmin(np.abs(np.real(impz_shifted)[idx_res:] - np.abs(np.imag(impz_shifted)[idx_res:]))) + idx_res] # These are the point needed for the unloaded Q delta_f_u = np.abs(f5 - f6) Qu = f_res / delta_f_u print('Qu: ', Qu, '∆fu: ', delta_f_u, 'MHz') # These are the point needed for the loaded Q f1 = freqs[np.argmax(np.imag(cplx_shifted))] f2 = freqs[np.argmin(np.imag(cplx_shifted))] delta_f_l = np.abs(f1 - f2) Ql = f_res / delta_f_l print('Ql: ', Ql, '∆fl: ', delta_f_l, 'MHz') # Calculate the external Q from the other two Qs Qext = 1 / (1 / Ql - 1 / Qu) print('Qext: ', Qext) # Calculate the coupling factor beta = Qu / Qext print('beta', beta) # Calculate the external Q using the impedance ~ ±j # cnt = 0 # for z in impz_shifted: # if 0.9 < np.imag(z) < 1.1: # print(z, cnt, freqs[cnt]) # cnt += 1 # # cnt = 0 # for z in impz_shifted: # if -0.9 > np.imag(z) > -1.1: # print(z, cnt, freqs[cnt]) # cnt += 1 # f2 = freqs[np.argmin( # np.abs(np.imag(impz_shifted) - np.ones(len(impz_shifted))))] # f3 = freqs[np.argmin(np.abs(np.imag(impz_shifted) - # (np.ones(len(impz_shifted)) * -1)))] # print(f2, f3) # Qext = f_res / (np.abs(f2 - f3)) # print('Qext: ', Qext) # Plot section plt.figure() # figsize=(6, 6)) ax = plt.subplot(1, 1, 1, projection='smith', grid_minor_enable=False) plt.plot(cplx, markevery=10, label='Measurement data', datatype=SmithAxes.S_PARAMETER) plt.plot(cplx_shifted, markevery=10, label='Detuned short position', datatype=SmithAxes.S_PARAMETER) plt.plot(cplx_dop, markevery=10, label='Detuned open position', datatype=SmithAxes.S_PARAMETER) plt.legend(loc="lower right", fontsize=8) plt.title("File: {}".format(filename_wo_ext)) print('Plotting to file.') txt = 'Qu={:0.0f}, Ql={:0.0f}\n∆fu={:0.3f} [MHz]\nf_res={:0.3f} [MHz]\nbeta={:.3f}'.format( Qu, Ql, delta_f_u, f_res, beta) plt.text(0, 0.6, txt, size=9, rotation=0, ha="left", va="top", bbox=dict(boxstyle="square", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), ) ) plt.savefig("{}.png".format(filename_wo_ext), format="png", dpi=1200, bbox_inches="tight",)
def cs_decomp(unitary_mats): """ This function does a CS (cosine-sine) decomposition (by calling the LAPACK function cuncsd.f. The old C++ Qubiter called zggsvd.f instead) of each unitary matrix in the list of arrays unitary_mats. This function is called by the constructor of the class Node and is fundamental for decomposing a unitary matrix into multiplexors and diagonal unitaries. Parameters ---------- unitary_mats : list(np.ndarray) Returns ------- list(np.ndarray), list(np.ndarray), list(np.ndarray) """ block_size = unitary_mats[0].shape[0] num_mats = len(unitary_mats) for mat in unitary_mats: assert mat.shape == (block_size, block_size) if block_size == 1: left_mats = None right_mats = None vec = np.array([unitary_mats[k][0, 0] for k in range(0, num_mats)]) vec1 = vec[0]*np.ones((num_mats,)) if np.linalg.norm(vec-vec1) < 1e-6: central_mats = None else: c_vec = np.real(vec) s_vec = np.imag(vec) central_mats = np.arctan2(s_vec, c_vec) else: # Henning Dekant constructed a python wrapper for LAPACK's cuncsd.f # via the python application f2py. Thanks Henning! # In[2]: import cuncsd # In[3]: print(cuncsd.cuncsd.__doc__) # x11,x12,x21,x22,theta,u1,u2,v1t,v2t,work,rwork,iwork,info = # cuncsd(p,x11,x12,x21,x22,lwork,lrwork, # [jobu1,jobu2,jobv1t,jobv2t,trans,signs,m,q, # ldx11,ldx12,ldx21,ldx22,ldu1,ldu2,ldv1t,ldv2t,credit]) # # Wrapper for ``cuncsd``. # # Parameters # ---------- # p : input int # x11 : input rank-2 array('F') with bounds (p,p) # x12 : input rank-2 array('F') with bounds (p,p) # x21 : input rank-2 array('F') with bounds (p,p) # x22 : input rank-2 array('F') with bounds (p,p) # lwork : input int # lrwork : input int # # Other Parameters # ---------------- # jobu1 : input string(len=1), optional # Default: 'Y' # jobu2 : input string(len=1), optional # Default: 'Y' # jobv1t : input string(len=1), optional # Default: 'Y' # jobv2t : input string(len=1), optional # Default: 'Y' # trans : input string(len=1), optional # Default: 'T' # signs : input string(len=1), optional # Default: 'O' # m : input int, optional # Default: 2*p # q : input int, optional # Default: p # ldx11 : input int, optional # Default: p # ldx12 : input int, optional # Default: p # ldx21 : input int, optional # Default: p # ldx22 : input int, optional # Default: p # ldu1 : input int, optional # Default: p # ldu2 : input int, optional # Default: p # ldv1t : input int, optional # Default: p # ldv2t : input int, optional # Default: p # credit : input int, optional # Default: 0 # # Returns # ------- # x11 : rank-2 array('F') with bounds (p,p) # x12 : rank-2 array('F') with bounds (p,p) # x21 : rank-2 array('F') with bounds (p,p) # x22 : rank-2 array('F') with bounds (p,p) # theta : rank-1 array('f') with bounds (p) # u1 : rank-2 array('F') with bounds (p,p) # u2 : rank-2 array('F') with bounds (p,p) # v1t : rank-2 array('F') with bounds (p,p) # v2t : rank-2 array('F') with bounds (p,p) # work : rank-1 array('F') with bounds (abs(lwork)) # rwork : rank-1 array('f') with bounds (abs(lrwork)) # iwork : rank-1 array('i') with bounds (p) # info : int left_mats = [] central_mats = [] right_mats = [] for mat in unitary_mats: dim = mat.shape[0] assert dim % 2 == 0 hdim = dim >> 1 # half dimension p = hdim # x11 = np.copy(mat[0:hdim, 0:hdim], 'C') # x12 = np.copy(mat[0:hdim, hdim:dim], 'C') # x21 = np.copy(mat[hdim:dim, 0:hdim], 'C') # x22 = np.copy(mat[hdim:dim, hdim:dim], 'C') x11 = mat[0:hdim, 0:hdim] x12 = mat[0:hdim, hdim:dim] x21 = mat[hdim:dim, 0:hdim] x22 = mat[hdim:dim, hdim:dim] # print('mat\n', mat) # print('x11\n', x11) # print('x12\n', x12) # print('x21\n', x21) # print('x22\n', x22) x11, x12, x21, x22, theta, u1, u2, v1t, v2t,\ work, rwork, iwork, info =\ csd.cuncsd(p, x11, x12, x21, x22, lwork=-1, lrwork=-1, trans='F') # print('x11\n', x11) # print('x12\n', x12) # print('x21\n', x21) # print('x22\n', x22) lw = math.ceil(work[0].real) lrw = math.ceil(rwork[0].real) # print("work query:", lw) # print("rwork query:", lrw) x11, x12, x21, x22, theta, u1, u2, v1t, v2t,\ work, rwork, iwork, info =\ csd.cuncsd(p, x11, x12, x21, x22, lwork=lw, lrwork=lrw, trans='F') # print('info', info) # print('u1 continguous', u1.flags.contiguous) # u1 = np.ascontiguousarray(u1) # u2 = np.ascontiguousarray(u2) # v1t = np.ascontiguousarray(v1t) # v2t = np.ascontiguousarray(v2t) # print('u1 continguous', u1.flags.contiguous) left_mats.append(u1) left_mats.append(u2) central_mats.append(theta) right_mats.append(v1t) right_mats.append(v2t) return left_mats, central_mats, right_mats
def sort_complex_by_order(self,complex_im,sorter): ii,jj = self.sort_by_order(np.real(sorter)) real = np.real(complex_im)[ii,jj] ii,jj = self.sort_by_order(np.imag(sorter)) imag = np.imag(complex_im)[ii,jj] return(real + 1j*imag)
def mu_fun_r(r,n,domain_index,result): result[0]=np.real((self.mu[domain_index][fi]))
def main(): n = 3 # complex channel use per message rate = 3 # bit per complex channel use Pa = 0.005 # avewrage power constraint iter_length = 100 sequence_l = 1000000 snr = 50 #dB k = rate * n #number of bits per complex symbol file_name = 'analytic_code_pp_nx_' + str(2**k) + '_0p005_L' + str( 2 * n) + '.pickle' M = 2**k * n # total Code_book_name = 'Codebook_0p' + str(Pa - int(Pa))[2:] + '_' + str( 2**k) + '_' + str(2 * n) + '.pickle' p_on = Pa / 0.31 # probability of the on signal for the flash signalling "Power delivery" "Open the EH model" file_name_EH = 'Sys_params.pickle' with open(file_name_EH, 'rb') as f: EH_Model = pickle.load(f) "Codebook" with open(Code_book_name, 'rb') as f: CB = pickle.load(f) Number_of_Flashes = np.argmin( np.abs(p_on - np.arange(1, M + 1, 1) / M)) + 1 Cb_r, Cb_i = CB[0], CB[1] Code_r, Code_i = Cb_r.reshape(1, -1), Cb_i.reshape(1, -1) Yr = tf.placeholder(tf.float32, [2, None]) P_del_tf = Fs.compute_delivery_power(Yr, EH_Model) ind_sorted_symbols = np.argsort(Code_r**2 + Code_i**2)[0, ::-1][0:Number_of_Flashes] Phi_t = np.zeros((Number_of_Flashes)) for i in range(Number_of_Flashes): t1 = ind_sorted_symbols[i] Phi_t[i] = np.pi * (1 - np.sign(Code_r[0, t1])) / 2 + np.arctan( Code_i[0, t1] / Code_r[0, t1]) t2 = np.argsort(Phi_t) delta_vector = np.zeros((2, Number_of_Flashes)) for i in range(Number_of_Flashes): t1 = ind_sorted_symbols[t2[i]] Phi = np.pi * (1 - np.sign(Code_r[0, t1])) / 2 + np.arctan( Code_i[0, t1] / Code_r[0, t1]) radius = np.sqrt(Code_r[0, t1]**2 + Code_i[0, t1]**2) Phi_t1 = (2 * np.pi * i / Number_of_Flashes - Phi) / iter_length temp = (np.sqrt(M * Pa / Number_of_Flashes - 1e-10) - radius) / iter_length delta_vector[0, t2[i]], delta_vector[1, t2[i]] = temp, Phi_t1 params = [] for j in range(iter_length + 1): if j != 0: for i in range(Number_of_Flashes): c1, c2 = Code_r[0, ind_sorted_symbols[i]], Code_i[ 0, ind_sorted_symbols[i]] ra, th = np.sqrt( c1**2 + c2**2), np.pi * (1 - np.sign(c1)) / 2 + np.arctan(c2 / c1) Tz = (ra + delta_vector[0, i]) * np.exp( 1j * (th + delta_vector[1, i])) Code_r[0, ind_sorted_symbols[i]] = np.real(Tz) Code_i[0, ind_sorted_symbols[i]] = np.imag(Tz) t0 = list( set(np.arange(Code_r.shape[1])) - set(ind_sorted_symbols)) t1 = Code_r[0, t0] t2 = Code_i[0, t0] t3 = np.sum(Code_r[0, ind_sorted_symbols]**2 + Code_i[0, ind_sorted_symbols]**2) Code_r[0, t0] *= np.sqrt( (M * Pa - np.sum(t3)) / np.sum(t1**2 + t2**2)) Code_i[0, t0] *= np.sqrt( (M * Pa - np.sum(t3)) / np.sum(t1**2 + t2**2)) "Each row is a codeword for a message index and real and imaginary symbols ordered alternativel" Codebook = (np.concatenate((Code_r, Code_i), axis=0).transpose()).reshape(-1, 2 * n) # print(np.sum(Codebook**2)/M) Codebook_norm = np.sum(Codebook**2, axis=1).reshape(1, -1) Codebook_tran = Codebook.transpose() #plt.plot(Code_r,Code_i,'.') err_rate, P_delivery = Fs.SER_Pdel_calculator(k, snr, Pa, sequence_l, Codebook, Codebook_tran, Codebook_norm, 101, Yr, P_del_tf, EH_Model) print(err_rate, P_delivery) params += [[n, k, p_on, Pa, snr, err_rate, P_delivery, Codebook]] "Save the file" with open(file_name, 'wb') as f: pickle.dump(params, f)
def retorna_sinal(X, x): return np.real(ifft(X) * len(x))
# Heff = Heff -complex(0,1)* 1/2*L[i].dag()*L[i] e_ops = [a1.dag()*a2, a1.dag()*a3, a2.dag()*a3, a1.dag()*a1, a2.dag()*a2, a3.dag()*a3, (a1+a1.dag())/np.sqrt(2), (a2+a2.dag())/np.sqrt(2),(a3+a3.dag())/np.sqrt(2)] final_state = steadystate(Htot,c_op) qsave(final_state,'3QVdPallssindi') ssevals = [expect(a1.dag()*a2,final_state), expect(a1.dag()*a3,final_state), expect(a2.dag()*a3,final_state), expect(a1.dag()*a1,final_state), expect(a2.dag()*a2,final_state),expect(a3.dag()*a3,final_state) ] Cpi12 = ssevals[0]/np.sqrt(ssevals[3]*ssevals[4]) Cpimod12 = np.abs(Cpi12)*np.ones(len(times)) Cpiphi12 = np.angle(Cpi12)*np.ones(len(times)) Cpi13 = ssevals[1]/np.sqrt(ssevals[3]*ssevals[5]) Cpimod13 = np.abs(Cpi13)*np.ones(len(times)) Cpiphi13 = np.angle(Cpi13)*np.ones(len(times)) Cpi23 = ssevals[2]/np.sqrt(ssevals[4]*ssevals[5]) Cpimod23 = np.abs(Cpi23)*np.ones(len(times)) Cpiphi23 = np.angle(Cpi23)*np.ones(len(times)) pnarr,pinarr = np.linalg.eig(final_state) pnarr = np.real(pnarr) pinlist =[] for j in range(len(pinarr)): pinlist.append(Qobj(pinarr[:,j])) pick = np.random.choice(len(pnarr),p=pnarr) #picking the initial state vector, this starts the Monte Carlo part psi0 = pinlist[pick] data = ssesolve(Htot,psi0,times2,sc_ops=c_op, e_ops = e_ops, method="homodyne") qsave(data.expect,'3QVdPallexpvalsindi') Cphi12 = data.expect[0][1:len(times)]/np.sqrt(data.expect[3][1:len(times)]*data.expect[4][1:len(times)]) Cphimod12 = np.abs(Cphi12) Cphiphase12 = np.angle(Cphi12) Cphi13 = data.expect[1][1:len(times)]/np.sqrt(data.expect[3][1:len(times)]*data.expect[5][1:len(times)]) Cphimod13 = np.abs(Cphi13) Cphiphase13 = np.angle(Cphi13) Cphi23 = data.expect[2][1:len(times)]/np.sqrt(data.expect[4][1:len(times)]*data.expect[5][1:len(times)]) Cphimod23 = np.abs(Cphi23)
def compute_diff( self, filename_a, filename_b, params, ): # Load first file_b, to avoid wasting time for filename_a if filename_b doesn't exist file_b = PlaneDataPhysical(filename_b) file_a = PlaneDataPhysical(filename_a) self.norm_l1_value = 0.0 self.norm_l2_value = 0.0 self.norm_linf_value = 0.0 self.norm_rms_value = 0.0 self.N = 0 size_ref_j = len(file_a.data) size_ref_i = len(file_a.data[0]) size_cmp_j = len(file_b.data) size_cmp_i = len(file_b.data[0]) if size_ref_j == size_cmp_j and size_ref_i == size_cmp_i:# and False: self.info("Using 'default' method (matching resolutions)") data_ref = file_a.data data_cmp = file_b.data elif 'reduce_ref_to_cmp' in params: self.info("Using 'ref_reduce' method") # # Reduce reference solution, assuming that the # resolution is integer multiples of the one to compare with # data_ref = file_a.data data_cmp = file_b.data multiplier_j = size_ref_j/size_cmp_j multiplier_i = size_ref_i/size_cmp_i print("Dimensions of reference solution: ", size_ref_i, size_ref_j) print("Dimensions of method under analysis: ", size_cmp_i, size_cmp_j) if not float(multiplier_i).is_integer() or not float(multiplier_j).is_integer() : print("Grids are not aligned") print("Try to use (TODO) interpolation script") print("Dimensions of method under analysis: ", size_cmp_i, size_cmp_j) print("Multipliers: ", multiplier_i, multiplier_j) raise Exception("Grids not properly aligned") multiplier_j = int(multiplier_j) multiplier_i = int(multiplier_i) print("Using multipliers (int): ", multiplier_i, multiplier_j) data_ref_new = np.zeros(shape=data_cmp.shape) for j in range(0, size_cmp_j): for i in range(0, size_cmp_i): data_ref_new[j,i] = 0.0 for sj in range(0, multiplier_j): for si in range(0, multiplier_i): data_ref_new[j,i] += data_ref[j*multiplier_j+sj, i*multiplier_i+si] data_ref_new[j,i] /= multiplier_i*multiplier_j data_ref = data_ref_new elif ('interpolate' in params and size_ref_j > size_cmp_j and size_ref_i > size_cmp_i) or ('interpolate_cmp_to_ref' in params): self.info("Using 'interpolate_cmp_to_ref' method") # # Interpolate solution to resolution of reference solution. # Note, that this can also lead to a reduction in case of a lower resolution of the reference # # This is the code written by Pedro which uses spline interpolation # Comparison via interpolation # print("Interpolation") # A-grid REFERENCE (file1) - sweet outputs only A grids physical space data_ref = file_a.data data_cmp = file_b.data ny_ref = len(file_a.data) nx_ref = len(file_a.data[0]) print("REF resolution: "+str(nx_ref)+", "+str(ny_ref)) ny_cmp = len(file_b.data) nx_cmp = len(file_b.data[0]) print("CMP resolution: "+str(nx_cmp)+", "+str(ny_cmp)) dx_ref = 1.0/(nx_ref) dy_ref = 1.0/(ny_ref) x_ref = np.linspace(0, 1, nx_ref, endpoint=False) y_ref = np.linspace(0, 1, ny_ref, endpoint=False) x_ref += dx_ref/2 # Make it cell-centered y_ref += dy_ref/2 X_ref, Y_ref = np.meshgrid(x_ref, y_ref) # A-grid cmp file (file2) dx_cmp=1.0/nx_cmp dy_cmp=1.0/ny_cmp x_cmp = np.linspace(0, 1, nx_cmp, endpoint=False) y_cmp = np.linspace(0, 1, ny_cmp, endpoint=False) x_cmp += dx_cmp/2 y_cmp += dy_cmp/2 X_cmp, Y_cmp = np.meshgrid(x_cmp, y_cmp) # Create cubic interpolation of comparison # Data to be interpolated interp_spline = RectBivariateSpline(x_cmp, y_cmp, data_cmp) # Compute reduced reference resolution # Target grid data_cmp_high = interp_spline(x_ref, y_ref) data_cmp = data_cmp_high data_ref = data_ref elif ('interpolate' in params and size_ref_j < size_cmp_j and size_ref_i < size_cmp_i) or ('interpolate_ref_to_cmp' in params): self.info("Using 'interpolate_ref_to_cmp' method") # # Interpolate: REF => resolution(CMP) # # # Interpolate solution to resolution of reference solution. # Note, that this can also lead to a reduction in case of a lower resolution of the reference # # This is the code written by Pedro which uses spline interpolation # Comparison via interpolation # print("Interpolation") # A-grid REFERENCE (file1) - sweet outputs only A grids physical space data_ref = file_a.data data_cmp = file_b.data ny_ref = len(file_a.data) nx_ref = len(file_a.data[0]) print("REF resolution: "+str(nx_ref)+", "+str(ny_ref)) ny_cmp = len(file_b.data) nx_cmp = len(file_b.data[0]) print("CMP resolution: "+str(nx_cmp)+", "+str(ny_cmp)) dx_ref = 1.0/nx_ref dy_ref = 1.0/ny_ref x_ref = np.linspace(0, 1, nx_ref, endpoint=False) y_ref = np.linspace(0, 1, ny_ref, endpoint=False) x_ref += dx_ref/2 # Make it cell-centered, this significantly reduces the errors y_ref += dy_ref/2 X_ref, Y_ref = np.meshgrid(x_ref, y_ref) # A-grid cmp file (file2) dx_cmp=1.0/nx_cmp dy_cmp=1.0/ny_cmp x_cmp = np.linspace(0, 1, nx_cmp, endpoint=False) y_cmp = np.linspace(0, 1, ny_cmp, endpoint=False) x_cmp += dx_cmp/2 y_cmp += dy_cmp/2 X_cmp, Y_cmp = np.meshgrid(x_cmp, y_cmp) # Create cubic interpolation of reference file interp_spline = RectBivariateSpline(x_ref, y_ref, data_ref) # Compute reduced reference resolution data_ref_low = interp_spline(x_cmp, y_cmp) data_ref = data_ref_low #elif 'spectral_ref_to_cmp' in params: elif 'spectral_ref_to_cmp' in params or 'spectral' in params: self.info("Using 'spectral_ref_to_cmp' method") # This is the code written by Pedro which uses spline interpolation # Comparison via interpolation # print("Interpolation") # A-grid REFERENCE (file1) - sweet outputs only A grids physical space data_ref = file_a.data data_cmp = file_b.data """ #if True: if False: data_ref = np.zeros((8, 8)) data_cmp = np.zeros((6, 6)) for i in range(len(data_ref[0])): for j in range(len(data_ref)): data_ref[j,i] = 1.0 a = 1.0 a *= math.sin(2.0*i*math.pi*2.0/len(data_ref[0])) a *= math.cos(2.0*j*math.pi*2.0/len(data_ref)) data_ref[j,i] += a a = 1.0 a *= math.sin(i*math.pi*2.0/len(data_ref[0])) a *= math.cos(j*math.pi*2.0/len(data_ref)) data_ref[j,i] += a for i in range(len(data_cmp[0])): for j in range(len(data_cmp)): data_cmp[j,i] = 1.0 a = 1.0 a *= math.sin(2.0*i*math.pi*2.0/len(data_cmp[0])) a *= math.cos(2.0*j*math.pi*2.0/len(data_cmp)) data_cmp[j,i] += a a = 1.0 a *= math.sin(i*math.pi*2.0/len(data_cmp[0])) a *= math.cos(j*math.pi*2.0/len(data_cmp)) data_cmp[j,i] += a """ ny_ref = len(data_ref) nx_ref = len(data_ref[0]) res_ref = nx_ref*ny_ref print("REF resolution: "+str(nx_ref)+", "+str(ny_ref)) ny_cmp = len(data_cmp) nx_cmp = len(data_cmp[0]) res_cmp = nx_cmp*ny_cmp print("CMP resolution: "+str(nx_cmp)+", "+str(ny_cmp)) if nx_cmp & 1 or ny_cmp & 1: raise Exception("Only even resolutions allowed") # # Spectral rescaling # shift_ref_i = -1.0/size_ref_i*0.5 shift_ref_j = -1.0/size_ref_j*0.5 shift_cmp_j = 1.0/size_cmp_j*0.5 shift_cmp_i = 1.0/size_cmp_i*0.5 #if False: if True: # # RFFT # # Convert reference data to spectrum data_ref_spec = np.fft.rfft2(data_ref) # Dummy transformation to get matching spectral size data_ref_new_spec = np.fft.rfft2(np.zeros(shape=data_cmp.shape)) specx = data_ref_spec.shape[1] specy = data_ref_spec.shape[0] newspecx = data_ref_new_spec.shape[1] newspecy = data_ref_new_spec.shape[0] data_ref_new_spec[0:newspecy//2, 0:newspecx] = data_ref_spec[0:newspecy//2, 0:newspecx] d = specy - newspecy//2 nd = newspecy - newspecy//2 data_ref_new_spec[nd:nd+newspecy//2, 0:newspecx] = data_ref_spec[d:d+newspecy//2, 0:newspecx] """ print("*"*80) print(data_ref_spec) print("*"*80) print(data_ref_new_spec) print("*"*80) """ def shift( spec_data, # spectral data sh_x, # shift in x direction within domain [0;1] sh_y, # shift in y direction within domain [0;1] ): # return data ret_data = np.zeros(spec_data.shape, dtype=complex) for iy in range(spec_data.shape[0]): # compute mode if iy < spec_data.shape[0]//2: ky = iy else: ky = iy-spec_data.shape[0] for ix in range(spec_data.shape[1]): # compute mode kx = ix ret_data[iy,ix] = spec_data[iy,ix] #ret_data[iy,ix] *= np.exp(1j*2.0*math.pi*kx*sh_x) #ret_data[iy,ix] *= np.exp(1j*2.0*math.pi*ky*sh_y) ret_data[iy,ix] *= np.exp(1j*2.0*math.pi*(kx*sh_x + ky*sh_y)) return ret_data # Shift high res reference data to 0,0 data_ref_new_spec = shift(data_ref_new_spec, shift_ref_i+shift_cmp_i, shift_ref_j+shift_cmp_j) data_ref_new = np.fft.irfft2(data_ref_new_spec) data_ref_new *= res_cmp/res_ref else: # # FFT # # Convert reference data to spectrum data_ref_spec = np.fft.fft2(data_ref) # Dummy transformation to get matching spectral size data_ref_new_spec = np.fft.fft2(np.zeros(shape=data_cmp.shape)) specx = data_ref_spec.shape[1] specy = data_ref_spec.shape[0] newspecx = data_ref_new_spec.shape[1] newspecy = data_ref_new_spec.shape[0] dy = specy - newspecy//2 ndy = newspecy - newspecy//2 dx = specx - newspecx//2 ndx = newspecx - newspecx//2 data_ref_new_spec[ 0:newspecy//2, 0:newspecx//2 ] = data_ref_spec[ 0:newspecy//2, 0:newspecx//2 ] data_ref_new_spec[ ndy:ndy+newspecy//2, 0:newspecx//2 ] = data_ref_spec[ dy:dy+newspecy//2, 0:newspecx//2 ] data_ref_new_spec[ 0:newspecy//2, ndx:ndx+newspecx//2 ] = data_ref_spec[ 0:newspecy//2, dx:dx+newspecx//2 ] data_ref_new_spec[ ndy:ndy+newspecy//2, ndx:ndx+newspecx//2 ] = data_ref_spec[ dy:dy+newspecy//2, dx:dx+newspecx//2 ] if False: print("*"*80) print(data_ref_spec) print("*"*80) print(data_ref_new_spec) print("*"*80) def shift( spec_data, # spectral data sh_x, # shift in x direction within domain [0;1] sh_y, # shift in y direction within domain [0;1] ): # return data ret_data = np.zeros(spec_data.shape, dtype=complex) for iy in range(spec_data.shape[0]): # compute mode if iy < spec_data.shape[0]//2: ky = iy else: ky = iy-spec_data.shape[0] for ix in range(spec_data.shape[1]): # compute mode if ix < spec_data.shape[1]//2: kx = ix else: kx = ix-spec_data.shape[1] ret_data[iy,ix] = spec_data[iy,ix] ret_data[iy,ix] *= np.exp(1j*2.0*math.pi*kx*sh_x) ret_data[iy,ix] *= np.exp(1j*2.0*math.pi*ky*sh_y) return ret_data # Shift high res reference data to 0,0 data_ref_new_spec = shift(data_ref_new_spec, shift_ref_i+shift_cmp_i, shift_ref_j+shift_cmp_j) data_ref_new = np.fft.ifft2(data_ref_new_spec) data_ref_new *= res_cmp/res_ref # Restrict to real data data_ref_new = np.real(data_ref_new) # The axes might be wrong. # # Swap axis=1 and axis=0 if there are some errors. # #f = signal.resample(data_ref, nx_cmp, t=None, axis=0) #data_ref_new = signal.resample(f, ny_cmp, t=None, axis=1) data_ref = data_ref_new else: print("") print("No supported method provided in '"+(','.join(params))+"'") print("") raise Exception("No supported method provided in '"+(','.join(params))+"'") # # Grids have same resolution # for j in range(0, data_cmp.shape[0]): for i in range(0, data_cmp.shape[1]): value = data_cmp[j,i] - data_ref[j,i] # http://mathworld.wolfram.com/L1-Norm.html self.norm_l1_value += abs(value) # http://mathworld.wolfram.com/L2-Norm.html self.norm_l2_value += value*value # http://mathworld.wolfram.com/L-Infinity-Norm.html self.norm_linf_value = max(abs(value), self.norm_linf_value) # http://mathworld.wolfram.com/Root-Mean-Square.html self.norm_rms_value += value*value self.N += 1 # Compute sqrt() for Euklidian L2 norm self.norm_l2_value = math.sqrt(self.norm_l2_value) # RMS final sqrt(N) computation self.norm_rms_value = math.sqrt(self.norm_rms_value/float(self.N)) # resolution normalized L1 value self.res_norm_l1_value = self.norm_l1_value/float(self.N)
bottom=0.13, right=0.99, top=0.95, wspace=0.14, hspace=0.37) subs = [] for i in range(4): subs.append(fig.add_subplot(int("22" + str(i + 1)))) p.title(ondas_n[i]) n4 = ondas[i] p.plot(n4, "bo") ff = f(n4) # Primeiro componente, 0Hz a0 = n.real(ff[0]) b0 = n.imag(ff[0]) # sempre zero # Segundo componente, t_a/N Hz ab1 = n.abs(ff[1]) # (a**2+b**2)**0.5 a1 = n.real(ff[1]) b1 = n.imag(ff[1]) fas = n.arctan(b1 / a1) # fase fas=n.angle(f[1]) if a1 < 0: fas += n.pi # segundo e terceiro quadrantes somam pi print("abs: %s, a1: %s, b1: %s, fas: %s" % (ab1, a1, b1, fas)) # Segundo componente, t_a/N Hz ab2 = n.abs(ff[2]) # (a**2+b**2)**0.5 a2 = n.real(ff[2]) b2 = n.imag(ff[2]) if a2: fas2 = n.arctan(b2 / a2) # fase fas=n.angle(f[1])
def aux(c, eta0, la0): v = np.roots(poly(eta0, la0, c)) m = max(np.real(v[np.isreal(v)])) if m < 0: print("error ") return (eta0 * m / (m + ra * c), m)
def demapping(x): condlist = [(np.real(x)>0.0)&(np.imag(x)>0.0),(np.real(x)<=0.0)&(np.imag(x)>0.0),(np.real(x)>0.0)&(np.imag(x)<=0.0),(np.real(x)<=0.0)&(np.imag(x)<=0.0)] funclist = [lambda x: 0,lambda x: 1,lambda x: 2,lambda x: 3] return np.piecewise(x.astype(dtype=np.complex), condlist, funclist)
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
def se_2D_v0_RP(): sample_nr = 1100 # number of (I,Q) samples to acquire during a shot of the experiment pe_step_nr = 32 # number of phase encoding steps tx_dt = 0.1 # RF TX sampling time in microseconds; will be rounded to a multiple of system clocks (122.88 MHz) rx_dt = 1 # desired sampling dt rx_dt_corr = rx_dt * 0.5 # correction factor till the bug is fixed sample_nr_echo = 32 ##### Times in "<instruction_file>.txt" ##### TR = 0.02e6 # Repetition time (us) TE = 0.001e6 # Echo time (us) T_tx_Rf = 10 # RF pulse length (us) T_G_pe_trig = 50 # Phase encoding gradient starting time (us) T_G_pe_dur = 200 # Phase encoding gradient ON time length (us) T_G_ramp_dur = 50 # Gradient ramp time T_G_fe_dur = 2 * T_G_pe_dur # Frequency encoding gradient ON time length (us) t = np.linspace(0, TR, math.ceil(TR / tx_dt) + 1) # 90 TX instruction length seq = np.array([[0, T_tx_Rf], # 90 Rf pulse [T_G_pe_trig, T_G_pe_trig + T_G_pe_dur], # Phase encoding gradient [TE / 2, TE / 2 + T_tx_Rf], # 180 Rf pulse [TE + T_tx_Rf / 2 - T_G_fe_dur / 2, TE + T_tx_Rf / 2 + T_G_fe_dur / 2]]) # Frequency encoding gradient idx_tmp = np.zeros([np.size(seq, 1), np.size(seq, 0)]) for idx in range(np.size(seq, 0)): idx_tmp[0, idx] = np.argmin(t <= seq[idx, 0]) # Instruction Start times idx_tmp[1, idx] = np.argmin(t <= seq[idx, 1]) # Instruction Stop times ##### RF pulses ##### ### 90 RF pulse ### # Time vector t_Rf_90 = np.linspace(0, T_tx_Rf, math.ceil(T_tx_Rf / tx_dt) + 1) # Actual TX RF pulse length # sinc pulse alpha = 0.46 # alpha=0.46 for Hamming window, alpha=0.5 for Hanning window Nlobes = 1 Rf_ampl = 0.125 # sinc pulse with Hamming window tx90 = Rf_ampl * sinc(math.pi*(t_Rf_90 - T_tx_Rf/2),T_tx_Rf,Nlobes,alpha) # tx90 = Rf_ampl * np.ones(np.size(t_Rf_90)) ### 180 RF pulse ### # sinc pulse tx180 = tx90 * 2 tx180 =np.concatenate((tx180, np.zeros(1000-np.size(tx180)-np.size(tx90)))) # For testing ONLY: echo centering acq_shift = 0 tx90_echo_cent = np.hstack(( np.zeros(np.floor(T_G_fe_dur/(2*tx_dt)).astype('int')- np.floor(np.size(tx90)/2).astype('int')-acq_shift), tx90 , np.zeros(np.floor(T_G_fe_dur/(2*tx_dt)).astype('int')- np.floor(np.size(tx90)/2).astype('int')+acq_shift))) # tx90_echo_cent = tx90_echo_cent * 0 ##### Gradients ##### # Phase encoding gradient shape grad_pe_samp_nr = math.ceil(T_G_pe_dur / 10) grad_ramp_samp_nr = math.ceil(T_G_ramp_dur / 10) grad_pe = np.hstack([np.linspace(0, 1, grad_ramp_samp_nr), # Ramp up np.ones(grad_pe_samp_nr - 2 * grad_ramp_samp_nr), # Top np.linspace(1, 0, grad_ramp_samp_nr)]) # Ramp down grad_pe = np.hstack([grad_pe, np.zeros(100 - np.size(grad_pe))]) # Frequency encoding gradient shape grad_fe_samp_nr = math.ceil(T_G_fe_dur / 10) grad_fe = np.hstack([np.linspace(0, 1, grad_ramp_samp_nr), # Ramp up np.ones(grad_fe_samp_nr - 2 * grad_ramp_samp_nr), # Top np.linspace(1, 0, grad_ramp_samp_nr)]) # Ramp down grad_fe = np.hstack([grad_fe, np.zeros(100 - np.size(grad_fe))]) # Correct for DC offset and scaling scale_G_x = 0.1 scale_G_y = 0.1 scale_G_z = 0.1 offset_G_x = 0.05 offset_G_y = 0.05 offset_G_z = 0.0 # Loop repeating TR and updating the gradients waveforms # data = np.zeros([np.size(grad_fe_corr),pe_step_nr]) data = np.zeros([sample_nr, pe_step_nr], dtype=complex) exp = Experiment(samples=sample_nr, # number of (I,Q) samples to acquire during a shot of the experiment lo_freq=5, # local oscillator frequency, MHz tx_t=tx_dt, # RF TX sampling time in microseconds; will be rounded to a multiple of system clocks (122.88 MHz) rx_t=rx_dt_corr, # RF RX sampling time in microseconds; as above instruction_file="ocra_lib/se_default_vn.txt") exp.initialize_DAC() for idx2 in range(pe_step_nr): exp = Experiment(samples=sample_nr, # number of (I,Q) samples to acquire during a shot of the experiment lo_freq=5, # local oscillator frequency, MHz tx_t=tx_dt, # RF TX sampling time in microseconds; will be rounded to a multiple of system clocks (122.88 MHz) rx_t=rx_dt_corr, # RF RX sampling time in microseconds; as above instruction_file="se_2D_v0_RP.txt") ###### Send waveforms to RP memory ########### # Load the RF waveforms tx_idx = exp.add_tx(tx90) # add the data to the ocra TX memory tx_idx = exp.add_tx(tx180) # add the data to the ocra TX memory tx_idx = exp.add_tx(tx90_echo_cent) scale_G_pe_sweep = 2 * (idx2 / (pe_step_nr - 1) - 0.5) grad_x_pe_corr = grad_pe * scale_G_x + offset_G_x grad_y_pe_corr = grad_pe * scale_G_y * scale_G_pe_sweep + offset_G_y grad_z_pe_corr = np.zeros(np.size(grad_x_pe_corr))+ offset_G_z grad_x_fe_corr = grad_fe * scale_G_x + offset_G_x grad_y_fe_corr = np.zeros(np.size(grad_x_fe_corr)) + offset_G_y grad_z_fe_corr = np.zeros(np.size(grad_x_fe_corr)) + offset_G_z grad_idx = exp.add_grad(grad_x_pe_corr , grad_y_pe_corr , grad_z_pe_corr) grad_idx = exp.add_grad(grad_x_fe_corr , grad_y_fe_corr , grad_z_fe_corr) # grad_idx = exp.add_grad(np.zeros(np.size(grad_fe_corr)), grad_fe_corr, np.zeros(np.size(grad_fe_corr))) data[:, idx2] = exp.run() # data = exp.run() data_mV = data * 1000 # data = np.zeros([sample_nr, pe_step_nr]) # time vector for representing the received data samples_data = len(data) t_rx = np.linspace(0, rx_dt * samples_data, samples_data) # us plt.plot(t_rx, np.real(data_mV)) # plt.plot(t_rx, np.imag(data_mV)) plt.plot(t_rx, np.abs(data_mV)) plt.legend(['real', 'imag', 'abs']) plt.xlabel('time (us)') plt.ylabel('signal received (mV)') plt.title('sampled data = %i' % samples_data) plt.grid() echo_delay = 96.5 # ms echo_shift_idx = np.floor(echo_delay/rx_dt).astype('int') echo_idx = np.floor(T_G_fe_dur / (2 * rx_dt)).astype('int') - np.floor(sample_nr_echo/ 2).astype('int') kspace = data[echo_idx+echo_shift_idx:echo_idx+echo_shift_idx+sample_nr_echo, : ] # Y = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(kspace))) plt.figure(2) plt.plot(t_rx[echo_idx+echo_shift_idx:echo_idx+echo_shift_idx+sample_nr_echo], np.real(kspace)) # plt.plot(t_rx, np.imag(data_mV)) plt.plot(t_rx[echo_idx+echo_shift_idx:echo_idx+echo_shift_idx+sample_nr_echo], np.abs(kspace)) plt.legend(['real', 'imag', 'abs']) plt.xlabel('time (us)') plt.ylabel('signal received (mV)') plt.title('sampled data = %i' % samples_data) plt.grid() Y = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(kspace))) img = np.abs(Y) plt.figure(3) plt.imshow(img, cmap='gray') plt.title('image') plt.show()
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
def plot_wigner_function(state, res=100): """Plot the equal angle slice spin Wigner function of an arbitrary quantum state. Args: state (np.matrix[[complex]]): - Matrix of 2**n x 2**n complex numbers - State Vector of 2**n x 1 complex numbers res (int) : number of theta and phi values in meshgrid on sphere (creates a res x res grid of points) References: [1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro, and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016). [2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and M. J. Everitt, Phys. Rev. A 96, 022117 (2017). """ state = np.array(state) if state.ndim == 1: state = np.outer(state, state) # turns state vector to a density matrix state = np.matrix(state) num = int(np.log2(len(state))) # number of qubits phi_vals = np.linspace(0, np.pi, num=res, dtype=np.complex_) theta_vals = np.linspace(0, 0.5 * np.pi, num=res, dtype=np.complex_) # phi and theta values for WF w = np.empty([res, res]) harr = np.sqrt(3) delta_su2 = np.zeros((2, 2), dtype=np.complex_) # create the spin Wigner function for theta in range(res): costheta = harr * np.cos(2 * theta_vals[theta]) sintheta = harr * np.sin(2 * theta_vals[theta]) for phi in range(res): delta_su2[0, 0] = 0.5 * (1 + costheta) delta_su2[0, 1] = -0.5 * (np.exp(2j * phi_vals[phi]) * sintheta) delta_su2[1, 0] = -0.5 * (np.exp(-2j * phi_vals[phi]) * sintheta) delta_su2[1, 1] = 0.5 * (1 - costheta) kernel = 1 for _ in range(num): kernel = np.kron(kernel, delta_su2) # creates phase point kernel w[phi, theta] = np.real(np.trace(state * kernel)) # Wigner function # Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc fig = plt.figure(figsize=(11, 9)) ax = fig.gca(projection='3d') w_max = np.amax(w) # Color data for plotting w_c = cm.seismic_r((w + w_max) / (2 * w_max)) # color data for sphere w_c2 = cm.seismic_r( (w[0:res, int(res / 2):res] + w_max) / (2 * w_max)) # bottom w_c3 = cm.seismic_r((w[int(res / 4):int(3 * res / 4), 0:res] + w_max) / (2 * w_max)) # side w_c4 = cm.seismic_r( (w[int(res / 2):res, 0:res] + w_max) / (2 * w_max)) # back u = np.linspace(0, 2 * np.pi, res) v = np.linspace(0, np.pi, res) 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)) # creates a sphere mesh ax.plot_surface(x, y, z, facecolors=w_c, vmin=-w_max, vmax=w_max, rcount=res, ccount=res, linewidth=0, zorder=0.5, antialiased=False) # plots Wigner Bloch sphere ax.plot_surface(x[0:res, int(res / 2):res], y[0:res, int(res / 2):res], -1.5 * np.ones((res, int(res / 2))), facecolors=w_c2, vmin=-w_max, vmax=w_max, rcount=res / 2, ccount=res / 2, linewidth=0, zorder=0.5, antialiased=False) # plots bottom reflection ax.plot_surface(-1.5 * np.ones((int(res / 2), res)), y[int(res / 4):int(3 * res / 4), 0:res], z[int(res / 4):int(3 * res / 4), 0:res], facecolors=w_c3, vmin=-w_max, vmax=w_max, rcount=res / 2, ccount=res / 2, linewidth=0, zorder=0.5, antialiased=False) # plots side reflection ax.plot_surface(x[int(res / 2):res, 0:res], 1.5 * np.ones((int(res / 2), res)), z[int(res / 2):res, 0:res], facecolors=w_c4, vmin=-w_max, vmax=w_max, rcount=res / 2, ccount=res / 2, linewidth=0, zorder=0.5, antialiased=False) # plots back reflection ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0)) ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0)) ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0)) ax.set_xticks([], []) ax.set_yticks([], []) ax.set_zticks([], []) ax.grid(False) ax.xaxis.pane.set_edgecolor('black') ax.yaxis.pane.set_edgecolor('black') ax.zaxis.pane.set_edgecolor('black') ax.set_xlim(-1.5, 1.5) ax.set_ylim(-1.5, 1.5) ax.set_zlim(-1.5, 1.5) m = cm.ScalarMappable(cmap=cm.seismic_r) m.set_array([-w_max, w_max]) plt.colorbar(m, shrink=0.5, aspect=10) plt.show()
def plot_state_hinton(state, title='', figsize=None, ax_real=None, ax_imag=None, *, rho=None): """Plot a hinton diagram for the density matrix of a quantum state. Args: state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state. title (str): a string that represents the plot title figsize (tuple): Figure size in inches. ax_real (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. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. ax_imag (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. If this is specified without an ax_imag only the real component plot will be generated. Additionally, if specified there will be no returned Figure since it is redundant. Returns: matplotlib.Figure: The matplotlib.Figure of the visualization if neither ax_real or ax_imag is set. Raises: ImportError: Requires matplotlib. VisualizationError: if input is not a valid N-qubit state. Example: .. jupyter-execute:: from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_hinton %matplotlib inline qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix.from_instruction(qc) plot_state_hinton(state, title="New Hinton Plot") """ if not HAS_MATPLOTLIB: raise ImportError('Must have Matplotlib installed. To install, run ' '"pip install matplotlib".') from matplotlib import pyplot as plt from matplotlib import get_backend # Figure data rho = DensityMatrix(state) num = rho.num_qubits if num is None: raise VisualizationError("Input is not a multi-qubit quantum state.") max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2)) datareal = np.real(rho.data) dataimag = np.imag(rho.data) if figsize is None: figsize = (8, 5) if not ax_real and not ax_imag: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize) else: if ax_real: fig = ax_real.get_figure() else: fig = ax_imag.get_figure() ax1 = ax_real ax2 = ax_imag column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] ly, lx = datareal.shape # Real if ax1: ax1.patch.set_facecolor('gray') ax1.set_aspect('equal', 'box') ax1.xaxis.set_major_locator(plt.NullLocator()) ax1.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(datareal): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([0.5 + x - size / 2, 0.5 + y - size / 2], size, size, facecolor=color, edgecolor=color) ax1.add_patch(rect) ax1.set_xticks(0.5 + np.arange(lx)) ax1.set_yticks(0.5 + np.arange(ly)) ax1.set_xlim([0, lx]) ax1.set_ylim([ly, 0]) ax1.set_yticklabels(row_names, fontsize=14) ax1.set_xticklabels(column_names, fontsize=14, rotation=90) ax1.invert_yaxis() ax1.set_title('Re[$\\rho$]', fontsize=14) # Imaginary if ax2: ax2.patch.set_facecolor('gray') ax2.set_aspect('equal', 'box') ax2.xaxis.set_major_locator(plt.NullLocator()) ax2.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(dataimag): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w) / max_weight) rect = plt.Rectangle([0.5 + x - size / 2, 0.5 + y - size / 2], size, size, facecolor=color, edgecolor=color) ax2.add_patch(rect) ax2.set_xticks(0.5 + np.arange(lx)) ax2.set_yticks(0.5 + np.arange(ly)) ax1.set_xlim([0, lx]) ax1.set_ylim([ly, 0]) ax2.set_yticklabels(row_names, fontsize=14) ax2.set_xticklabels(column_names, fontsize=14, rotation=90) ax2.invert_yaxis() ax2.set_title('Im[$\\rho$]', fontsize=14) if title: fig.suptitle(title, fontsize=16) if ax_real is None and ax_imag is None: if get_backend() in ['module://ipykernel.pylab.backend_inline', 'nbAgg']: plt.close(fig) return fig
def plot_state_city(rho, title=""): """Plot the cityscape of quantum state. Plot two 3d bargraphs (two dimenstional) of the mixed state rho Args: rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex numbers title (str): a string that represents the plot title """ num = int(np.log2(len(rho))) # get the real and imag parts of rho datareal = np.real(rho) dataimag = np.imag(rho) # get the labels column_names = [bin(i)[2:].zfill(num) for i in range(2**num)] row_names = [bin(i)[2:].zfill(num) for i in range(2**num)] lx = len(datareal[0]) # Work out matrix dimensions ly = len(datareal[:, 0]) xpos = np.arange(0, lx, 1) # Set up a mesh of positions ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx * ly) dx = 0.5 * np.ones_like(zpos) # width of bars dy = dx.copy() dzr = datareal.flatten() dzi = dataimag.flatten() fig = plt.figure(figsize=(8, 8)) ax1 = fig.add_subplot(2, 1, 1, projection='3d') ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color="g", alpha=0.5) ax2 = fig.add_subplot(2, 1, 2, projection='3d') ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color="g", alpha=0.5) ax1.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax1.set_yticks(np.arange(0.5, ly + 0.5, 1)) ax1.axes.set_zlim3d(-1.0, 1.0001) ax1.set_zticks(np.arange(-1, 1, 0.5)) ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45) ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5) # ax1.set_xlabel('basis state', fontsize=12) # ax1.set_ylabel('basis state', fontsize=12) ax1.set_zlabel("Real[rho]") ax2.set_xticks(np.arange(0.5, lx + 0.5, 1)) ax2.set_yticks(np.arange(0.5, ly + 0.5, 1)) ax2.axes.set_zlim3d(-1.0, 1.0001) ax2.set_zticks(np.arange(-1, 1, 0.5)) ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45) ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5) # ax2.set_xlabel('basis state', fontsize=12) # ax2.set_ylabel('basis state', fontsize=12) ax2.set_zlabel("Imag[rho]") plt.title(title) plt.show()