real和imag在python_Python numpy.imag() 使用实例

这篇博客展示了如何在Python中使用numpy库的imag()函数处理复数的虚部。通过多个示例,包括计算傅里叶变换、频率响应、相位、幅度等,解释了imag()函数在处理信号处理、数据可视化和傅里叶变换中的应用。
摘要由CSDN通过智能技术生成

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def phormants(x, Fs):

N = len(x)

w = numpy.hamming(N)

# Apply window and high pass filter.

x1 = x * w

x1 = lfilter([1], [1., 0.63], x1)

# Get LPC.

ncoeff = 2 + Fs / 1000

A, e, k = lpc(x1, ncoeff)

#A, e, k = lpc(x1, 8)

# Get roots.

rts = numpy.roots(A)

rts = [r for r in rts if numpy.imag(r) >= 0]

# Get angles.

angz = numpy.arctan2(numpy.imag(rts), numpy.real(rts))

# Get frequencies.

frqs = sorted(angz * (Fs / (2 * math.pi)))

return frqs

Example 2

def mdst(x, odd=True):

""" Calculate modified discrete sine transform of input signal

Parameters

----------

X : array_like

The input signal

odd : boolean, optional

Switch to oddly stacked transform. Defaults to :code:`True`.

Returns

-------

out : array_like

The output signal

"""

return -1 * numpy.imag(cmdct(x, odd=odd)) * numpy.sqrt(2)

Example 3

def get_phases(self):

sizeimg = np.real(self.imgfft).shape

mag = np.zeros(sizeimg)

for x in range(sizeimg[0]):

for y in range(sizeimg[1]):

mag[x][y] = np.arctan2(np.real(self.imgfft[x][y]), np.imag(self.imgfft[x][y]))

rpic = MyImage(mag)

rpic.limit(1)

return rpic

# int my = y-output.height/2;

# int mx = x-output.width/2;

# float angle = atan2(my, mx) - HALF_PI ;

# float radius = sqrt(mx*mx+my*my) / factor;

# float ix = map(angle,-PI,PI,input.width,0);

# float iy = map(radius,0,height,0,input.height);

# int inputIndex = int(ix) + int(iy) * input.width;

# int outputIndex = x + y * output.width;

# if (inputIndex <= input.pixels.length-1) {

# output.pixels[outputIndex] = input.pixels[inputIndex];

Example 4

def fftDf( df , part = "abs") :

#Handle series or DataFrame

if type(df) == pd.Series :

df = pd.DataFrame(df)

ise = True

else :

ise = False

res = pd.DataFrame( index = np.fft.rfftfreq( df.index.size, d = dx( df ) ) )

for col in df.columns :

if part == "abs" :

res["FFT_"+col] = np.abs( np.fft.rfft(df[col]) ) / (0.5*df.index.size)

elif part == "real" :

res["FFT_"+col] = np.real( np.fft.rfft(df[col]) ) / (0.5*df.index.size)

elif part == "imag" :

res["FFT_"+col] = np.imag( np.fft.rfft(df[col]) ) / (0.5*df.index.size)

if ise :

return res.iloc[:,0]

else :

return res

Example 5

def test_psi(adjcube):

"""Tests retrieval of the wave functions and eigenvalues.

"""

from pydft.bases.fourier import psi, O, H

cell = adjcube

V = QHO(cell)

W = W4(cell)

Ns = W.shape[1]

Psi, epsilon = psi(V, W, cell, forceR=False)

#Make sure that the eigenvalues are real.

assert np.sum(np.imag(epsilon)) < 1e-13

checkI = np.dot(Psi.conjugate().T, O(Psi, cell))

assert abs(np.sum(np.diag(checkI))-Ns) < 1e-13 # Should be the identity

assert np.abs(np.sum(checkI)-Ns) < 1e-13

checkD = np.dot(Psi.conjugate().T, H(V, Psi, cell))

diagsum = np.sum(np.diag(checkD))

assert np.abs(np.sum(checkD)-diagsum) < 1e-12 # Should be diagonal

# Should match the diagonal elements of previous matrix

assert np.allclose(np.diag(checkD), epsilon)

Example 6

def fcn_ComputeFrequencyResponse(self,f,sig,mur,a,x0,y0,z0,X,Y,Z):

"""Compute Single Frequency Response at (X,Y,Z)"""

m = self.m

orient = self.orient

xtx = self.xtx

ytx = self.ytx

ztx = self.ztx

chi = fcn_ComputeExcitation_FEM(f,sig,mur,a)

Hpx,Hpy,Hpz = fcn_ComputePrimary(m,orient,xtx,ytx,ztx,x0,y0,z0)

mx = 4*np.pi*a**3*chi*Hpx/3

my = 4*np.pi*a**3*chi*Hpy/3

mz = 4*np.pi*a**3*chi*Hpz/3

R = np.sqrt((X-x0)**2 + (Y-y0)**2 + (Z-z0)**2)

Hx = (1/(4*np.pi))*(3*(X-x0)*(mx*(X-x0) + my*(Y-y0) + mz*(Z-z0))/R**5 - mx/R**3)

Hy = (1/(4*np.pi))*(3*(Y-y0)*(mx*(X-x0) + my*(Y-y0) + mz*(Z-z0))/R**5 - my/R**3)

Hz = (1/(4*np.pi))*(3*(Z-z0)*(mx*(X-x0) + my*(Y-y0) + mz*(Z-z0))/R**5 - mz/R**3)

Habs = np.sqrt(np.real(Hx)**2 + np.real(Hy)**2 + np.real(Hz)**2) + 1j*np.sqrt(np.imag(Hx)**2 + np.imag(Hy)**2 + np.imag(Hz)**2)

return Hx, Hy, Hz, Habs

Example 7

def genSpectra(time,dipole,signal):

fw, frequency = pade(time,dipole)

fw_sig, frequency = pade(time,signal,alternate=True)

fw_re = np.real(fw)

fw_im = np.imag(fw)

fw_abs = fw_re**2 + fw_im**2

#spectra = (fw_re*17.32)/(np.pi*field*damp_const)

#spectra = (fw_re*17.32*514.220652)/(np.pi*field*damp_const)

#numerator = np.imag((fw*np.conjugate(fw_sig)))

numerator = np.imag(fw_abs*np.conjugate(fw_sig))

#numerator = np.abs((fw*np.conjugate(fw_sig)))

#numerator = np.abs(fw)

denominator = np.real(np.conjugate(fw_sig)*fw_sig)

#denominator = 1.0

spectra = ((4.0*27.21138602*2*frequency*np.pi*(numerator))/(3.0*137.036*denominator))

spectra *= 1.0/100.0

#plt.plot(frequency*27.2114,fourier)

#plt.show()

return frequency, spectra

Example 8

def histogram_plot(data, sfreq, toffset, bins, log_scale, title):

"""Plot a histogram of the data for a given bin size."""

print("histogram")

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1)

ax.hist(numpy.real(data), bins,

log=log_scale, histtype='bar', color=['green'])

ax.hold(True)

ax.hist(numpy.imag(data), bins,

log=log_scale, histtype='bar', color=['blue'])

ax.grid(True)

ax.set_xlabel('adc value')

ax.set_ylabel('frequency')

ax.set_title(title)

ax.hold(False)

return fig

Example 9

def __init__(self,jet,kernels,k,x,y,pt,subpixel):

self.jet = jet

self.kernels = kernels

self.k = k

self.x = x

self.y = y

re = np.real(jet)

im = np.imag(jet)

self.mag = np.sqrt(re*re + im*im)

self.phase = np.arctan2(re,im)

if subpixel:

d = np.array([[pt.X()-x],[pt.Y()-y]])

comp = np.dot(self.k,d)

self.phase -= comp.flatten()

self.jet = self.mag*np.exp(1.0j*self.phase)

Example 10

def __init__(self, qubit_names, quad="real"):

super(PulseCalibration, self).__init__()

self.qubit_names = qubit_names if isinstance(qubit_names, list) else [qubit_names]

self.qubit = [QubitFactory(qubit_name) for qubit_name in qubit_names] if isinstance(qubit_names, list) else QubitFactory(qubit_names)

self.filename = 'None'

self.exp = None

self.axis_descriptor = None

self.cw_mode = False

self.saved_settings = config.load_meas_file(config.meas_file)

self.settings = deepcopy(self.saved_settings) #make a copy for used during calibration

self.quad = quad

if quad == "real":

self.quad_fun = np.real

elif quad == "imag":

self.quad_fun = np.imag

elif quad == "amp":

self.quad_fun = np.abs

elif quad == "phase":

self.quad_fun = np.angle

else:

raise ValueError('Quadrature to calibrate must be one of ("real", "imag", "amp", "phase").')

self.plot = self.init_plot()

Example 11

def fit_photon_number(xdata, ydata, params):



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值