def graphPhase(zeroes = [], poles = [], size = 100, isReal = True): graphList = [] for i in range(size): if isReal: p = cmath.exp(cmath.pi * complex(0, 1) * i/size) else: p = cmath.exp(cmath.pi * complex(0, 1) * (i - size/2)/size) B = 0 A = 0 for j in zeroes: B += cmath.polar(p - j.getComplexValue())[1] #print i #print j.getComplexValue() for k in poles: A += cmath.polar(p - k.getComplexValue())[1] phase = B-A """ while phase < -math.pi: phase += math.pi while phase > math.pi: phase -= math.pi """ graphList.append(phase) return graphList
def appl_bondary(h): w = 1.0+h f = A*exp(-1.0j*kt*log(1.0-w)/d) + B*exp(1.0j*kt*log(1.0-w)/d) fp= A*exp(-1.0j*kt*log(1.0-w)/d)*1.0j*kt/(d*(1.0-w)) - B*exp(1.0j*kt*log(1.0-w)/d)*1.0j*kt/(d*(1.0-w)) # f = A*exp(kt*log(1-w)/d) + B*exp(-kt*log(1-w)/d) # fp= - A*exp(kt*log(1.0-w)/d)*kt/(d*(1.0-w)) + B*exp(kt*log(1.0-w)/d)*kt/(d*(1.0-w)) return (f,fp)
def CalcEnergy(conf, kpoints, N): """ E = sum_k S_0(k) + S_1(k) S(k) = 1/N *|rho(k)|^2 = rho_R^2 + rho_I^2 calculates energy E of configuration [conf], where subscripts 0,1 denote two of species k points are specified as (nx,ny) for square lattice """ energy = 0 N = len(conf) l = int(N**0.5) for k in kpoints: kx = k[0] * 2 * np.pi / l ky = k[1] * 2 * np.pi / l rho0 = complex(0,0) rho1 = complex(0,0) for i in range(N): curspin = conf[i] if dict[curspin] == 0: x = i%l y = int(i/l) rho0 += cmath.exp(complex(0,kx * x + ky * y)) elif dict[curspin] == 1: x = i%l y = int(i/l) rho1 += cmath.exp(complex(0,kx * x + ky * y)) energy += (rho0.real**2 + rho0.imag**2) + (rho1.real**2 + rho1.imag**2) return energy/N
def FFT(x): N = len(x) if N <= 1: return x even = FFT(x[0::2]) odd = FFT(x[1::2]) return [(even[k] + cmath.exp(-2j*pi*k/N)*odd[k])/2 for k in xrange(N/2)] + \ [(even[k] - cmath.exp(-2j*pi*k/N)*odd[k])/2 for k in xrange(N/2)]
def _teta1_changed(self,old,new): r1 = self.l*exp(self.teta1*1j) r2 = r1 + self.l*exp(self.teta2*1j) self.top.r_top = r1.imag,-r1.real,0 self.bottom.r_bot = self.top.r_top self.bottom.r_top = r2.imag,-r2.real,0
def Fourier_Trans(x,y,z,field,L,n): # L = max of deltaX or range of X, or Y, or Z n -= 0 n3 = n**3 l = 0 kx = zeros(n3) # kx ky = zeros(n3) # ky kz = zeros(n3) # kz cn = zeros(n3,complex) # Fourier Factor if (mod(n,2) == 0): for i in range(n): for j in range(n): for k in range(n): kx[l] = - pi*n/L + 2.0*pi*i/L ky[l] = - pi*n/L + 2.0*pi*j/L kz[l] = - pi*n/L + 2.0*pi*k/L for m in range(len(x)): cn[l] += exp(- 1.0j*kx[l]*x[m] - 1.0j*ky[l]*y[m] - 1.0j*kz[l]*z[m])*field[m] cn[l] = cn[l] / n3 l += 1 else: for i in range(n): for j in range(n): for k in range(n): kx[l] = - pi*(n+1)/L + 2.0*pi*i/L ky[l] = - pi*(n+1)/L + 2.0*pi*j/L kz[l] = - pi*(n+1)/L + 2.0*pi*k/L for m in range(len(x)): cn[l] += field[m]*exp(- 1.0j*kx[l]*x[m] - 1.0j*ky[l]*y[m] - 1.0j*kz[l]*z[m]) cn[l] = cn[l] / n3 l += 1 return (cn, kx, ky, kz)
def fft(x): N = len(x) if N <= 1: return x even = fft(x[0::2]) odd = fft(x[1::2]) return [even[k] + exp(-2j*pi*k/N)*odd[k] for k in range(int(N/2))] + \ [even[k] - exp(-2j*pi*k/N)*odd[k] for k in range(int(N/2))]
def _updateMatrix(self): """Updates the PMNS matrix and its complex conjugate. Must be called by the class each time one of the PMNS matrix parameters are changed. """ zero = complex( 0.0, 0.0 ) c12 = complex( math.cos( self.theta_12 ), 0.0 ) c13 = complex( math.cos( self.theta_13 ), 0.0 ) c23 = complex( math.cos( self.theta_23 ), 0.0 ) s12 = complex( math.sin( self.theta_12 ), 0.0 ) s13 = complex( math.sin( self.theta_13 ), 0.0 ) s23 = complex( math.sin( self.theta_23 ), 0.0 ) eid = cmath.exp( complex(0.0, self.delta_cp) ) # e^( i * delta_cp) emid = cmath.exp( complex(0.0, -self.delta_cp) ) # e^(-i * delta_cp) self.matrix = [[zero,zero,zero],[zero,zero,zero],[zero,zero,zero]] self.anti_matrix = [[zero,zero,zero],[zero,zero,zero],[zero,zero,zero]] self.matrix[0][0] = c12 * c13 self.matrix[0][1] = s12 * c13 self.matrix[0][2] = s13 * emid self.matrix[1][0] = (zero - s12*c23 ) - ( c12*s23*s13*eid ) self.matrix[1][1] = ( c12*c23 ) - ( s12*s23*s13*eid ) self.matrix[1][2] = s23*c13 self.matrix[2][0] = ( s12*s23 ) - ( c12*c23*s13*eid) self.matrix[2][1] = ( zero - c12*s23 ) - ( s12*c23*s13*eid ) self.matrix[2][2] = c23*c13 for i in range(3): for j in range(3): self.anti_matrix[i][j] = self.matrix[i][j].conjugate()
def initialize(self): """ Compute mdct of the residual and instantiate various windows and twiddle coefficients""" #Windowing L = self.scale self.w_long = np.array([np.sin(float(l + 0.5) * (np.pi / L)) for l in range(L)]) # twidlle coefficients self.pre_twid_vec = np.array([exp(n * (-1j) * np.pi / L) for n in range(L)]) self.post_twid_vec = np.array( [exp((float(n) + 0.5) * -1j * np.pi * (L / 2 + 1) / L) for n in range(L / 2)]) if self.windowType == 'half1': self.w_long[0:L / 2] = 0 # twidlle coefficients self.pre_twid_vec[0:L / 2] = 0 # self.fftMat = zeros((self.scale , self.frameNumber) , complex) # self.normaCoeffs = sqrt(1/float(L)) # score tree - first version simplified self.best_score_tree = np.zeros(self.frame_num) if self.HF: self.bestScoreHFTree = np.zeros(self.frame_num) # OPTIM -> do pre-twid directly in the windows self.locCoeff = self.w_long * self.pre_twid_vec
def test05 (self): # 8PSK Convergence test with static rotation natfreq = 0.25 order = 8 self.test = digital_swig.costas_loop_cc(natfreq, order) rot = cmath.exp(-cmath.pi/8.0j) # rotate to match Costas rotation #const = psk.psk_constellation(order) const_points = ((1+0j), (0.70710676908493042+0.70710676908493042j), (6.1232342629258393e-17+1j), (-0.70710676908493042+0.70710676908493042j), (-1+1.2246468525851679e-16j), (-0.70710676908493042-0.70710676908493042j), (-1.8369701465288538e-16-1j), (0.70710676908493042-0.70710676908493042j)) data = [random.randint(0,7) for i in xrange(100)] data = [2*rot*const_points[d] for d in data] N = 40 # settling time expected_result = data[N:] rot = cmath.exp(0.1j) # some small rotation data = [rot*d for d in data] self.src = gr.vector_source_c(data, False) self.snk = gr.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() dst_data = self.snk.data()[N:] # generously compare results; the loop will converge near to, but # not exactly on, the target data self.assertComplexTuplesAlmostEqual (expected_result, dst_data, 2)
def fieldValue(self, z): temp = (z-self.z1)*exp(-self.theta*1j) x = self.length/temp v1 = np.conjugate(-1.0j/2/pi*((1.0/x - 1)*log(1-x) + 1))*exp(self.theta*1j) v2 = np.conjugate(1.0j/2/pi*((1.0/x)*log(1-x) + 1))*exp(self.theta*1j) return (v1*self.strength1 + v2*self.strength2)
def cal_rrr(self, rf0, rrr1, kz1, d1): # reflectivity, [Reflect] v = 2.0*kz1*d1 u = -v.imag + v.real*1.0J z1 = rrr1*cmath.exp(u) + rf0 z2 = 1.0 + rf0*rrr1*cmath.exp(u) z=z1/z2 self.rrr=z
def int_temp(kA): qp = acos( 0.5*(-cos(kA) + sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) qm = acos( 0.5*(-cos(kA) - sqrt( (E**2/t**2) - (sin(kA))**2 ) ) ) if qp.imag < 0.0: qp = -qp if qm.imag < 0.0: qm = -qm sig = copysign(1,m-n) const = 1j/(4.0*pi*t**2) if s == 0: return const*E*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) ) / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) ) / ( sin(2*qm) + sin(qm)*cos(kA) ) ) elif s == 1: fp = t*( 1.0 + 2.0*cos(qp)*exp(1j*kA) ) fm = t*( 1.0 + 2.0*cos(qm)*exp(1j*kA) ) return const*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) )*fp / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) )*fm / ( sin(2*qm) + sin(qm)*cos(kA) ) ) elif s == -1: ftp = t*( 1.0 + 2.0*cos(qp)*exp(-1j*kA) ) ftm = t*( 1.0 + 2.0*cos(qm)*exp(-1j*kA) ) return const*( exp( 1j*( kA*(m+n) + sig*qp*(m-n) ) )*ftp / ( sin(2*qp) + sin(qp)*cos(kA) ) \ + exp( 1j*( kA*(m+n) + sig*qm*(m-n) ) )*ftm / ( sin(2*qm) + sin(qm)*cos(kA) ) ) else: print "Sublattice error in gBulk_kA"
def test05(self): # 8PSK Convergence test with static rotation natfreq = 0.25 order = 8 self.test = digital.costas_loop_cc(natfreq, order) rot = cmath.exp(-cmath.pi/8.0j) # rotate to match Costas rotation const = psk.psk_constellation(order) data = [random.randint(0,7) for i in xrange(100)] data = [2*rot*const.points()[d] for d in data] N = 40 # settling time expected_result = data[N:] rot = cmath.exp(0.1j) # some small rotation data = [rot*d for d in data] self.src = blocks.vector_source_c(data, False) self.snk = blocks.vector_sink_c() self.tb.connect(self.src, self.test, self.snk) self.tb.run() dst_data = self.snk.data()[N:] # generously compare results; the loop will converge near to, but # not exactly on, the target data self.assertComplexTuplesAlmostEqual(expected_result, dst_data, 2)
def Dlmk(l, m, k, phi1, phi2, theta1, theta2): """ returns value of D^l_mk as defined in allen, ottewill 97. """ return ( exp(complex(0.0, -m * phi1)) * dlmk(l, m, k, theta1) * exp(complex(0.0, -k * gamma(phi1, phi2, theta1, theta2))) )
def empirical_proof(g, ffp, fdp, alpha): # Mathematica: f = g (ffp + I fdp) Exp[I alpha] c = g * (ffp + 1j*fdp) * cmath.exp(1j*alpha) a = g * ffp * math.cos(alpha) - g * fdp * math.sin(alpha) b = g * ffp * math.sin(alpha) + g * fdp * math.cos(alpha) assert approx_equal(a, c.real) assert approx_equal(b, c.imag) # # Mathematica: D[f,alpha] d_c_d_alpha = g * (ffp + 1j*fdp) * 1j*cmath.exp(1j*alpha) d_a_d_alpha = g * ffp * -math.sin(alpha) - g * fdp * math.cos(alpha) d_b_d_alpha = g * ffp * math.cos(alpha) - g * fdp * math.sin(alpha) assert approx_equal(d_a_d_alpha, d_c_d_alpha.real) assert approx_equal(d_b_d_alpha, d_c_d_alpha.imag) # # Mathematica: D[f,g] d_c_d_g = (ffp + 1j*fdp) * cmath.exp(1j*alpha) d_a_d_g = ffp * math.cos(alpha) - fdp * math.sin(alpha) d_b_d_g = ffp * math.sin(alpha) + fdp * math.cos(alpha) assert approx_equal(d_a_d_g, d_c_d_g.real) assert approx_equal(d_b_d_g, d_c_d_g.imag) # # Mathematica: D[f,ffp] d_c_d_ffp = g * cmath.exp(1j*alpha) d_a_d_ffp = g * math.cos(alpha) d_b_d_ffp = g * math.sin(alpha) assert approx_equal(d_a_d_ffp, d_c_d_ffp.real) assert approx_equal(d_b_d_ffp, d_c_d_ffp.imag) # # Mathematica: D[f,fdp] d_c_d_fdp = g * 1j * cmath.exp(1j*alpha) d_a_d_fdp = -g * math.sin(alpha) d_b_d_fdp = g * math.cos(alpha) assert approx_equal(d_a_d_fdp, d_c_d_fdp.real) assert approx_equal(d_b_d_fdp, d_c_d_fdp.imag)
def ckm_tree(Vus, Vub, Vcb, gamma): r"""CKM matrix in the tree parametrization and standard phase convention. In this parametrization, the parameters are directly measured from tree-level $B$ decays. It is thus particularly suited for new physics analyses because the tree-level decays should be dominated by the Standard Model. This function involves no analytical approximations. Relation to the standard parametrization: - $V_{us} = \cos \theta_{13} \sin \theta_{12}$ - $|V_{ub}| = |\sin \theta_{13}|$ - $V_{cb} = \cos \theta_{13} \sin \theta_{23}$ - $\gamma=\delta$ Parameters ---------- - `Vus`: CKM matrix element $V_{us}$ - `Vub`: Absolute value of CKM matrix element $|V_{ub}|$ - `Vcb`: CKM matrix element $V_{cb}$ - `gamma`: CKM phase $\gamma=\delta$ in radians """ return np.array([[sqrt(1 - Vub**2)*sqrt(1 - Vus**2/(1 - Vub**2)), Vus, Vub/exp(1j*gamma)], [-((sqrt(1 - Vcb**2/(1 - Vub**2))*Vus)/sqrt(1 - Vub**2)) - (Vub*exp(1j*gamma)*Vcb*sqrt(1 - Vus**2/(1 - Vub**2)))/sqrt(1 - Vub**2), -((Vub*exp(1j*gamma)*Vcb*Vus)/(1 - Vub**2)) + sqrt(1 - Vcb**2/(1 - Vub**2))*sqrt(1 - Vus**2/(1 - Vub**2)), Vcb], [(Vcb*Vus)/(1 - Vub**2) - Vub*exp(1j*gamma)*sqrt(1 - Vcb**2/(1 - Vub**2))*sqrt(1 - Vus**2/(1 - Vub**2)), -((Vub*exp(1j*gamma)*sqrt(1 - Vcb**2/(1 - Vub**2))*Vus)/sqrt(1 - Vub**2)) - (Vcb*sqrt(1 - Vus**2/(1 - Vub**2)))/sqrt(1 - Vub**2), sqrt(1 - Vub**2)*sqrt(1 - Vcb**2/(1 - Vub**2))]])
def ckm_standard(t12, t13, t23, delta): r"""CKM matrix in the standard parametrization and standard phase convention. Parameters ---------- - `t12`: CKM angle $\theta_{12}$ in radians - `t13`: CKM angle $\theta_{13}$ in radians - `t23`: CKM angle $\theta_{23}$ in radians - `delta`: CKM phase $\delta=\gamma$ in radians """ c12 = cos(t12) c13 = cos(t13) c23 = cos(t23) s12 = sin(t12) s13 = sin(t13) s23 = sin(t23) return np.array([[c12*c13, c13*s12, s13/exp(1j*delta)], [-(c23*s12) - c12*exp(1j*delta)*s13*s23, c12*c23 - exp(1j*delta)*s12*s13*s23, c13*s23], [-(c12*c23*exp(1j*delta)*s13) + s12*s23, -(c23*exp(1j*delta)*s12*s13) - c12*s23, c13*c23]])
def Theta(z,tau): ''' The standard Jacoby Theta function. Tau should have an imaginary part greater than zero. ''' if tau.imag<=0: raise q=cmath.exp(pi*i*tau) zeta=cmath.exp(2*pi*i*z) cur=complex(1,0) cur1=complex(1,0) threshold=1e-7 maxrecursion=10000 n=1 curq=complex(1,0) curzeta1=complex(1,0) curzeta2=curzeta1 while True: cur1=cur curq=q**(n*n) curzeta1*=zeta curzeta2/=zeta n+=1 cur+=curq*(curzeta1+curzeta2) if abs(cur-cur1)<threshold*abs(cur): return cur if n>maxrecursion: return float('inf')
def twoRay(distance, frequency, transmitterHeight, receiverHeight, transmitterPower, transmitterGain =1, receiverGain=1): # print "" # print distance, frequency, transmitterPower, transmitterGain, receiverGain, transmitterHeight, receiverHeight # print "" #distance [m], frequency [MHz] c = 299792458.0 #speed of light m/s f = frequency*math.pow(10.0,6.0) #convert from MHz to Hz lamba = c/f #wavelength in m R = -0.8 #reflection loss #Radio propergation for modern wireless systems henry l. bertoni r1=((distance**2.)+((transmitterHeight-receiverHeight)**2.))**(.5) r2=((distance**2.)+((transmitterHeight+receiverHeight)**2.))**(.5) #print r1, r2 beta = (2*math.pi)/lamba #Pr =((lamba/(4*math.pi*d))**2)*abs(1+R*cmath.exp(1j*beta*((2*transmitterHeight*receiverHeight)/distance)))**2 #Pr = transmitterPower*transmitterGain*receiverGain*2*((lamba/(4*math.pi*distance))**2)*(1-math.cos((2*beta*transmitterHeight*receiverHeight)/distance)) #Pr = transmitterPower*transmitterGain*receiverGain*2*((lamba/(4*math.pi*distance))**2)*abs((math.sin((beta*transmitterHeight*receiverHeight)/distance)))**2 #Pr = transmitterPower*transmitterGain*receiverGain*((lamba/(4*cmath.pi*distance))**2)*abs(1+R*cmath.exp(1j*beta*((2*transmitterHeight*receiverHeight)/distance)))**2 Pr = transmitterPower*transmitterGain*receiverGain*((lamba/(4*cmath.pi))**2)*abs( ((cmath.exp(1j*beta*r1))/r1)+(R*(cmath.exp(1j*beta*r2))/r2))**2 #print Pr Pr = 10*np.log10(Pr) return Pr
def update_data(self): # THIS IS TOTALLY OLD WAY NEED TO UPDATE BUT NOT TRIVIAL eeff = empty(self.lambdas.shape, dtype="complex") for i in range(len(self.lambdas)): entry = self.lambdas[i] f1 = 1.0 / entry ** 2 f2 = 1.0 / (entry * self.gamp) f3 = complex(f1, f2) den = self.lamp ** 2 * f3 term1 = 1.53 - (1.0 / den) tempsum = 0.0 for j in range(2): if j == 0: Aj = 0.94 lamj = 468 # nm gamj = 2300 phij = -math.pi / 4.0 elif j == 1: Aj = 1.36 lamj = 331 gamj = 940 phij = -math.pi / 4.0 den1 = complex((1.0 / lamj - 1.0 / entry), (-1.0 / gamj)) den2 = complex((1.0 / lamj + 1.0 / entry), (1.0 / gamj)) expj1 = cmath.exp(complex(0, phij)) expj2 = cmath.exp(complex(0, -phij)) tempsum = tempsum + ((Aj / lamj) * (expj1 / den1 + expj2 / den2)) # SHORT LAMBDA CORRECTION!!! final = term1 + tempsum fr = final.real fi = final.imag omega = (2.0 * math.pi * self.c) / (self.nm_conv * entry) fi = fi + (self.wplasma ** 2 / omega ** 3) * (self.v_fermi / (self.r_core * self.nm_conv)) eeff[i] = complex(fr, fi) self.earray = eeff self.CoreMaterial = self
def test_PDE(self): omega=1. mu0=0.123 SIGMA=15. k=cmath.sqrt(1j*omega*mu0*SIGMA) # Ex=exp(k*z) NE=101 domain=ripRectangle(max(NE,30*mpisize-1),max(NE,30*mpisize-1), d1=mpisize) Z0=0.5 H=1./NE X1=(int(0.3/H)+0.5)*H X2=(int(0.6/H)+0.5)*H IMP=-(1j*omega*mu0)/k*cmath.exp(k*Z0)/cmath.exp(k*Z0) Z_XY=[ IMP, IMP ] x=[ [X1,Z0], [X2,Z0] ] eta=None z=domain.getX()[1] Ex0_ex=cos(k.imag*(z-1))*exp(k.real*(z-1)) Ex1_ex=sin(k.imag*(z-1))*exp(k.real*(z-1)) Ex0_ex_z=-sin(k.imag*(z-1))*k.imag*exp(k.real*(z-1))+cos(k.imag*(z-1))*exp(k.real*(z-1))*k.real Ex1_ex_z=cos(k.imag*(z-1))*k.imag*exp(k.real*(z-1))+sin(k.imag*(z-1))*exp(k.real*(z-1))*k.real model=MT2DModelTEMode(domain, omega, x, Z_XY, eta, mu=mu0, tol=1e-9, directSolver=True, sigma0=SIGMA) args=model.getArguments(SIGMA) Ex=args[0] Exz=args[1] self.assertLess(Lsup(Ex[0]-Ex0_ex), 1e-4 * Lsup(Ex0_ex)) self.assertLess(Lsup(Ex[1]-Ex1_ex), 1e-4 * Lsup(Ex1_ex)) self.assertLess(Lsup(Exz[0]-Ex0_ex_z), 1e-2 * Lsup(Ex0_ex_z)) self.assertLess(Lsup(Exz[1]-Ex1_ex_z), 1e-2 * Lsup(Ex1_ex_z)) argsr=model.getArguments(0.) ref=model.getDefect(0., *argsr) # this should be almost zero: args=model.getArguments(SIGMA) d=model.getDefect(SIGMA, *args) self.assertTrue( d > 0.) self.assertTrue( ref > 0.) self.assertLess( d, 3e-3 * ref ) # d should be zero (some sort of) z=ReducedFunction(domain).getX()[1] Ex0_ex=cos(k.imag*(z-1))*exp(k.real*(z-1)) Ex1_ex=sin(k.imag*(z-1))*exp(k.real*(z-1)) Ex0_ex_z=-sin(k.imag*(z-1))*k.imag*exp(k.real*(z-1))+cos(k.imag*(z-1))*exp(k.real*(z-1))*k.real Ex1_ex_z=cos(k.imag*(z-1))*k.imag*exp(k.real*(z-1))+sin(k.imag*(z-1))*exp(k.real*(z-1))*k.real # and this should be zero d0=model.getDefect(SIGMA, Ex0_ex*[1.,0]+ Ex1_ex*[0,1.], Ex0_ex_z*[1.,0]+ Ex1_ex_z*[0,1.]) self.assertTrue( d0 <= 1e-8 * ref ) # d should be zero (some sort of) # and this too dg=model.getGradient(SIGMA, Ex0_ex*[1.,0]+ Ex1_ex*[0,1.], Ex0_ex_z*[1.,0]+ Ex1_ex_z*[0,1.]) self.assertTrue(isinstance(dg, Data)) self.assertTrue(dg.getShape()==()) self.assertLess(Lsup(dg), 1e-10)
def getHam(Lambda,p): p0 = p # mu0 = Lambda[0][0] + 1j * Lambda[1][0] # mu1 = Lambda[0][1] + 1j * Lambda[1][1] # t0 = Lambda[0][2] + 1j * Lambda[1][2] # Delta0 = Lambda[0][3] + 1j * Lambda[1][3] # t1 = Lambda[0][4] + 1j * Lambda[1][4] # Delta1 = Lambda[0][5] + 1j * Lambda[1][5] # t2 = Lambda[0][6] + 1j * Lambda[1][6] # Delta2 = Lambda[0][7] + 1j * Lambda[1][7] # t3 = Lambda[0][8] + 1j * Lambda[1][8] # Delta3 = Lambda[0][9] + 1j * Lambda[1][9] # t4 = Lambda[0][10] + 1j * Lambda[1][10] # Delta4 = Lambda[0][11] + 1j * Lambda[1][11] mu0 = Lambda[0][0] mu1 = Lambda[0][1] t0 = 1j * Lambda[1][2] Delta0 = 1j * Lambda[1][3] t1 = Lambda[0][4] Delta1 = Lambda[0][5] t2 = 1j * Lambda[1][6] Delta2 = 1j * Lambda[1][7] t3 = 1j * Lambda[1][8] Delta3 = 1j * Lambda[1][9] t4 = Lambda[0][10] Delta4 = Lambda[0][11] I = 1j Ham = array([[mu0 + t1*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(t1)/2, t0/2 + t2*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(t3)/2, -Delta1*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(Delta1)/2, -Delta0/2 - Delta2*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(Delta3)/2], [t3*cm.exp(I*p0)/2 + conjugate(t0)/2 + cm.exp(-I*p0)*conjugate(t2)/2, mu1 + t4*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(t4)/2, -Delta3*cm.exp(I*p0)/2 + conjugate(Delta0)/2 + cm.exp(-I*p0)*conjugate(Delta2)/2, -Delta4*cm.exp(I*p0)/2 + cm.exp(-I*p0)*conjugate(Delta4)/2], [-Delta1*cm.exp(-I*p0)/2 + cm.exp(I*p0)*conjugate(Delta1)/2, -Delta3*cm.exp(-I*p0)/2 + cm.exp(I*p0)*conjugate(Delta2)/2 + conjugate(Delta0)/2, -mu0 - t1*cm.exp(I*p0)/2 - cm.exp(-I*p0)*conjugate(t1)/2, -t0/2 - t2*cm.exp(I*p0)/2 - cm.exp(-I*p0)*conjugate(t3)/2], [-Delta0/2 - Delta2*cm.exp(-I*p0)/2 + cm.exp(I*p0)*conjugate(Delta3)/2, -Delta4*cm.exp(-I*p0)/2 + cm.exp(I*p0)*conjugate(Delta4)/2, -t3*cm.exp(I*p0)/2 - conjugate(t0)/2 - cm.exp(-I*p0)*conjugate(t2)/2, -mu1 - t4*cm.exp(I*p0)/2 - cm.exp(-I*p0)*conjugate(t4)/2]]) #Ham = array([[mu0 + t1*cos(p0), t0/2.0 + t2*cm.exp(I*p0)/2.0 + t3*cm.exp(-I*p0)/2.0,-I*Delta1*sin(p0), -Delta0/2.0 - Delta2*cm.exp(I*p0)/2 + Delta3*cm.exp(-I*p0)/2.0],[t0/2.0 + t2*cm.exp(-I*p0)/2.0 + t3*cm.exp(I*p0)/2.0, mu1 + t4*cos(p0), Delta0/2.0 + Delta2*cm.exp(-I*p0)/2.0 - Delta3*cm.exp(I*p0)/2.0, -I*Delta4*sin(p0)], [I*Delta1*sin(p0),Delta0/2.0 + Delta2*cm.exp(I*p0)/2.0 - Delta3*cm.exp(-I*p0)/2.0, -mu0 - t1*cos(p0),-t0/2.0 - t2*cm.exp(I*p0)/2 - t3*cm.exp(-I*p0)/2.0], [-Delta0/2.0 - Delta2*cm.exp(-I*p0)/2.0 + Delta3*cm.exp(I*p0)/2.0, I*Delta4*sin(p0), -t0/2.0 - t2*cm.exp(-I*p0)/2.0 - t3*cm.exp(I*p0)/2.0,-mu1 - t4*cos(p0)]]) return Ham
def oh_r(eps_top, eps_low, f, theta, rms_g): """ Oh et.al. (1992) surface backscatter calculations This functions calculations surface backscatter using the Oh et al. (1992) surface model. References Oh et al., 1992, An empirical model and an inversion technique for rader scattering from bare soil surfaces. IEEE Trans. Geos. Rem., 30, pp. 370-380 Parameters ---------- eps_top : complex number complex permittivity of upper(incoming) medium eps_low : complex number complex permittivity of lower medium f : float frequency in hertz theta : float incidence angle in degrees rms_g : float surface rms height in m """ # speed of light in m/s c = 2.998e8 # calculate wavelength in upper medium by using real part of refarctive index n_upper = cmath.sqrt(eps_top) wavelength = (c / f) / n_upper.real k_rms = (2. * cmath.pi / wavelength) * rms_g eps_eff = eps_low / eps_top gam0 = gammah(eps_eff, 0) gamh = gammah(eps_eff, theta) gamv = gammav(eps_eff, theta) theta = theta / 180.0 * cmath.pi # precalulcate cosines of angles ct = cmath.cos(theta) # Oh model equations g = 0.7 * (1. - cmath.exp(-0.65 * k_rms ** 1.8)) root_p = 1. - ((2. * theta / cmath.pi) ** (1. / (3. * gam0))) * cmath.exp(-k_rms) p = (1 - (2 * theta / cmath.pi) ** (1 / (3 * gam0)) * cmath.exp(-1 * k_rms)) ** 2 q = 0.23 * cmath.sqrt(gam0) * (1. - cmath.exp(-k_rms)) sigma0 = {} sigma0['vv'] = g * (ct * (ct * ct)) * (gamv + gamh) / root_p # sig0vv = ((g*(cos(theta))^3)/sqrt(p))*(gamv+gamh); sigma0['vh'] = q * sigma0['vv'] sigma0['hh'] = root_p * root_p * sigma0['vv'] return sigma0
def f(x, upcoeffs, downcoeffs): up = 1 + 0j for upcoeff in upcoeffs: up += upcoeff[0]*cmath.exp(((x*upcoeff[1]))*1j) down = 1 + 0j for downcoeff in downcoeffs: down += downcoeff[0]*cmath.exp((x*downcoeff[1])*1j) return up/down
def test_Differential(self): INC=0.001 omega=5. mu0=0.123 SIGMA=15. k=cmath.sqrt(1j*omega*mu0*SIGMA) # Ex=exp(k*z) NE=101 domain=ripRectangle(max(NE,50*mpisize-1), max(NE,50*mpisize-1), d1=mpisize) Z0=0.5 IMP=-(1j*omega*mu0)/k*(cmath.exp(k*Z0)-cmath.exp(-k*Z0))/(cmath.exp(k*Z0)+cmath.exp(-k*Z0)) Z_XY=[ IMP, IMP ] H=1./NE X1=(int(0.3/H)+0.5)*H X2=(int(0.6/H)+0.5)*H x=[ [X1,Z0], [X2,Z0] ] eta=None z=domain.getX()[1] Ex0_ex=cos(k.imag*z)*(exp(k.real*z)-exp(-k.real*z)) Ex0_ex_z=-sin(k.imag*z)*k.imag*(exp(k.real*z)-exp(-k.real*z))+cos(k.imag*z)*(exp(k.real*z)+exp(-k.real*z))*k.real Ex1_ex=sin(k.imag*z)*(exp(k.real*z)+exp(-k.real*z)) Ex1_ex_z=cos(k.imag*z)*k.imag*(exp(k.real*z)+exp(-k.real*z))+sin(k.imag*z)*(exp(k.real*z)-exp(-k.real*z))*k.real model=MT2DModelTEMode(domain, omega, x, Z_XY, eta, mu=mu0, sigma0=SIGMA, tol=1e-9, directSolver=True, airLayerLevel=1.) # this is the base line: xx=domain.getX()[0] SIGMA0=3.*(xx+0.3) args0=model.getArguments(SIGMA0) d0=model.getDefect(SIGMA0, *args0) dg0=model.getGradient(SIGMA0, *args0) self.assertTrue(isinstance(dg0, Data)) self.assertTrue(dg0.getShape()==()) X=Function(domain).getX() # test 1 p=INC SIGMA1=SIGMA0+p args1=model.getArguments(SIGMA1) d1=model.getDefect(SIGMA1, *args1) self.assertLess( abs( d1-d0-integrate(dg0*p) ), 1e-2*abs(d1-d0) ) # test 2 p=exp(-length(X-(0.2,0.2))**2/10)*INC SIGMA1=SIGMA0+p args1=model.getArguments(SIGMA1) d1=model.getDefect(SIGMA1, *args1) self.assertLess( abs( d1-d0-integrate(dg0*p) ), 1e-2*abs(d1-d0) ) # test 3 p=sin(length(X)*3*3.14)*INC SIGMA1=SIGMA0+p args1=model.getArguments(SIGMA1) d1=model.getDefect(SIGMA1, *args1) self.assertLess( abs( d1-d0-integrate(dg0*p) ), 1e-2*abs(d1-d0) )
def _iFFT( ls ): N = len(ls) if N <= 1: return ls else: even = iFFT(ls[0::2]) odd = iFFT(ls[1::2]) return [(even[k] + cmath.exp(2j*pi*k/N)*odd[k]) for k in xrange(N/2)] + \ [(even[k] - cmath.exp(2j*pi*k/N)*odd[k]) for k in xrange(N/2)]
def SCF(y,a,fs=1): # a is cylic frequecy N=len(y) u=[y[x]*cx.exp(math.pi*(-1j)*a*float(x)/float(fs)) for x in range(N)] v=[(y[x]*cx.exp(math.pi*(1j)*a*float(x)/float(fs))).conjugate() for x in range(N)] lag,cc=correlation(u+[0]*5000,v+[0]*5000) pl.plot(lag,[abs(w) for w in cc]) freq,F = spectrum(cc,fs) return [freq,F]
def solve(coefs, n, m): for i in range(m): base = cmath.exp(2 * math.pi * i / m * 1j) val = 0.0 + 0.0 * 1j for (j, coef) in enumerate(coefs): val = val + coef * cmath.exp(-2 * math.pi * i * j / m * 1j) count = int(round(val.real)) // m for _ in xrange(count): print('%.9f %.9f' % (base.real, base.imag))
def transform(self, coord): if self.symmetry < 0: if random.randrange(2): coord = -coord.conjugate() return coord * cmath.exp(1j*random.randrange(-self.symmetry)*cmath.pi*2/-self.symmetry) elif self.symmetry == 0: return coord else: return coord * cmath.exp(1j*random.randrange(self.symmetry)*cmath.pi*2/self.symmetry)
def __complex__(self): return cmath.exp(self._logz)
# --- below are treated as global variables, the angle (corner_turn) could theoretically be a parameter as well --------- bottom = -0.75 left = -1. view_window = ((left, bottom), (left + 2, bottom + 2)) drawings_fill_color = "lightgreen" drawings_stroke_color = "orangered" """ drawings_fill_color = "gold" drawings_stroke_color = "goldenrod" """ centers_relative_distance_to_center = 1 - rescaling_factor turn_direction = cmath.exp(two_pi * corner_turn * 1.j) #rotation_direction = cmath.exp(two_pi * triangle_rotation * 1.j) up_vector = [0., 1.] right_vector = [turn_direction.real, turn_direction.imag] left_vector = [-right_vector[0], right_vector[1]] """ up_vector = rotate_vector(rotation_direction, up_vector) right_vector = rotate_vector(rotation_direction, right_vector) left_vector = rotate_vector(rotation_direction, left_vector) """ centers_relative_positions = [ [ up_vector[0] * centers_relative_distance_to_center,
def f(c1, c2, L): return (2 * J * (cmath.exp(j * (np.dot(k(c1, c2, L), n1))) + cmath.exp(j * np.dot(k(c1, c2, L), n2)) + 1))
def af_symmetrical_timescannig(bx, by, bz, f, f0, steering_angle, Nx, Ny, Nz, increase_rate, plane): ''' This section is all about defining the inter element spacing which depends on lambda and increase rate. ''' #To create an symmetrical array: if Nx > 1: distances_along_x = [] dx = bx #origin for n in range(int(Nx / 2)): distances_along_x.append(dx) dx = dx + increase_rate new_list_x = sorted(distances_along_x, reverse=True) new_list_x.remove(bx) new_list_x.extend(distances_along_x) new_list_x.insert( 0, 0) #new_list_x contains the position of each element along x axis if Ny > 1: distances_along_y = [] dy = by #origin for n in range(int(Ny / 2)): distances_along_y.append(dy) dy = dy + increase_rate new_list_y = sorted(distances_along_y, reverse=True) new_list_y.remove(by) new_list_y.extend(distances_along_y) new_list_y.insert( 0, 0) #new_list_y contains the position of each element along y axis if Nz > 1: distances_along_z = [] dz = bz #origin for n in range(int(Nz / 2)): distances_along_z.append(dz) dz = dz + increase_rate new_list_z = sorted(distances_along_z, reverse=True) new_list_z.remove(bz) new_list_z.extend(distances_along_z) new_list_z.insert( 0, 0) #new_list_z contains the position of each element along z axis c = 3e8 lamda = c / f lamda0 = c / f0 k = 2 * pi / lamda incoming_angle = np.arange(-180, 180, 0.2) #define the x-axis of the plot. array_factor_x = np.zeros( len(incoming_angle )) #to create empty array which will be filled by for loop below array_factor_y = np.zeros( len(incoming_angle )) #to create empty array which will be filled by for loop below array_factor_z = np.zeros( len(incoming_angle )) #to create empty array which will be filled by for loop below for i in range(len(incoming_angle)): #%%Array Factor along X axis if Nx > 1: # Based on the plane, either phi or theta must be kept constant. if plane == 'E': phi = np.zeros(len(incoming_angle)) phi0 = phi theta = incoming_angle theta0 = np.ones(len(incoming_angle)) * steering_angle if plane == 'H': theta = np.ones(len(incoming_angle)) * 90 # theta=np.transpose(theta) theta0 = theta phi = incoming_angle phi0 = np.ones(len(incoming_angle)) * steering_angle phase_function_x = ( sin(theta[i] * pi / 180) * cos(phi[i] * pi / 180)) - sin( theta0[i] * pi / 180) * cos(phi0[i] * pi / 180) all_received_signals_x = [] for n in range(0, Nx): dist = sum(new_list_x[:n + 1]) * lamda0 received_signal_x = cmath.exp(1j * k * dist * phase_function_x) all_received_signals_x.append(received_signal_x) array_factor_x[i] = (abs(sum(all_received_signals_x))) * (1 / Nx) else: array_factor_x = int(1) if Ny > 1: #%%Array Factor along Y axis # Based on the plane, either phi or theta must be kept constant. if plane == 'E': phi = np.ones(len(incoming_angle)) * 90 phi0 = phi theta = incoming_angle theta0 = np.ones(len(incoming_angle)) * steering_angle if plane == 'H': theta = np.ones(len(incoming_angle)) * 90 theta0 = theta phi = incoming_angle phi0 = np.ones(len(incoming_angle)) * steering_angle phase_function_y = (sin(theta[i] * pi / 180) * sin( phi[i] * pi / 180)) - (sin(theta0[i] * pi / 180) * sin(phi0[i] * pi / 180)) all_received_signals_y = [] for n in range(0, Ny): dist = sum(new_list_y[:n + 1]) * lamda0 received_signal_y = cmath.exp(1j * k * dist * phase_function_y) all_received_signals_y.append(received_signal_y) array_factor_y[i] = (abs(sum(all_received_signals_y))) * (1 / Ny) else: array_factor_y = int(1) #%%Array Factor along Z axis if Nz > 1: theta = incoming_angle theta0 = np.ones(len(incoming_angle)) * steering_angle phase_function_z = cos(theta[i] * pi / 180) - cos( theta0[i] * pi / 180) all_received_signals_z = [] for n in range(0, Nz): dist = sum(new_list_z[:n + 1]) * lamda0 received_signal_z = cmath.exp(1j * k * dist * phase_function_z) all_received_signals_z.append(received_signal_z) array_factor_z[i] = (abs(sum(all_received_signals_z))) * (1 / Nz) else: array_factor_z = int(1) array_factor = array_factor_x * array_factor_y * array_factor_z return incoming_angle, array_factor, array_factor_x, array_factor_y, array_factor_z
def psi0_m(x): return A * exp(1j * q(m) * x)
def tk_to_cirq(tkcirc: Circuit) -> cirq.circuits.Circuit: """Converts a tket :py:class:`Circuit` object to a Cirq :py:class:`Circuit`. :param tkcirc: The input tket :py:class:`Circuit` :return: The Cirq :py:class:`Circuit` corresponding to the input circuit """ qmap = {} line_name = None grid_name = None # Since Cirq can only support registers of up to 2 dimensions, we explicitly # check for 3-dimensional registers whose third dimension is trivial. # SquareGrid architectures are of this form. indices = [qb.index for qb in tkcirc.qubits] is_flat_3d = all(idx[2] == 0 for idx in indices if len(idx) == 3) for qb in tkcirc.qubits: if len(qb.index) == 0: qmap.update({qb: cirq.ops.NamedQubit(qb.reg_name)}) elif len(qb.index) == 1: if line_name != None and line_name != qb.reg_name: raise NotImplementedError( "Cirq can only support a single linear register") line_name = qb.reg_name qmap.update({qb: LineQubit(qb.index[0])}) elif len(qb.index) == 2 or (len(qb.index) == 3 and is_flat_3d): if grid_name != None and grid_name != qb.reg_name: raise NotImplementedError( "Cirq can only support a single grid register") grid_name = qb.reg_name qmap.update({qb: GridQubit(qb.index[0], qb.index[1])}) else: raise NotImplementedError( "Cirq can only support registers of dimension <=2") oplst = [] for command in tkcirc: op = command.op optype = op.type try: gatetype = _ops2cirq_mapping[optype] except KeyError as error: raise NotImplementedError("Cannot convert tket Op to Cirq gate: " + op.get_name()) from error if optype == OpType.Measure: qid = qmap[command.args[0]] bit = command.args[1] cirqop = cirq.ops.measure(qid, key=bit.__repr__()) else: qids = [qmap[qbit] for qbit in command.args] params = op.params if len(params) == 0: cirqop = gatetype(*qids) elif optype == OpType.PhasedX: cirqop = gatetype(phase_exponent=params[1], exponent=params[0])(*qids) elif optype == OpType.FSim: cirqop = gatetype(theta=float(params[0] * pi), phi=float(params[1] * pi))(*qids) elif optype == OpType.PhasedISWAP: cirqop = gatetype(phase_exponent=params[0], exponent=params[1])(*qids) else: cirqop = gatetype(exponent=params[0])(*qids) oplst.append(cirqop) try: coeff = cmath.exp(float(tkcirc.phase) * cmath.pi * 1j) if coeff != 1.0: oplst.append(cirq.ops.GlobalPhaseOperation(coeff)) except ValueError: warning( "Global phase is dependent on a symbolic parameter, so cannot adjust for " "phase") return cirq.circuits.Circuit(*oplst)
def test_PDE(self): omega=10. mu0=0.123 RHO=0.15 SIGMA=1/RHO k=cmath.sqrt(1j*omega*mu0/RHO) # Hx=exp(k*z) NE=151 L=1 domain=ripRectangle(NE,NE, d0=mpisize) Z0=0.5 H=1./NE X1=(int(0.3/H)+0.5)*H X2=(int(0.6/H)+0.5)*H IMP=RHO*k*cmath.exp(k*(Z0-L))/cmath.exp(k*(Z0-L)) Z_XY=[ IMP, IMP ] x=[ [X1,Z0], [X2,Z0] ] eta=None z=domain.getX()[1] Hx0_ex=cos(k.imag*(z-L))*exp(k.real*(z-L)) Hx1_ex=sin(k.imag*(z-L))*exp(k.real*(z-L)) Hx0_ex_z=-sin(k.imag*(z-L))*k.imag*exp(k.real*(z-L))+cos(k.imag*(z-L))*exp(k.real*(z-L))*k.real Hx1_ex_z=cos(k.imag*(z-L))*k.imag*exp(k.real*(z-L))+sin(k.imag*(z-L))*exp(k.real*(z-L))*k.real model=MT2DModelTMMode(domain, omega, x, Z_XY, eta, mu=mu0, sigma0=SIGMA, tol=1e-9, directSolver=True, airLayerLevel=1.) args=model.getArguments(RHO) Hx=args[0] g_Hx=args[1] Hxz=g_Hx[:,1] self.assertLess(Lsup(Hx[0]-Hx0_ex), 1e-4 * Lsup(Hx0_ex)) self.assertLess(Lsup(Hx[1]-Hx1_ex), 1e-4 * Lsup(Hx1_ex)) self.assertLess(Lsup(Hxz[0]-Hx0_ex_z), 1e-2 * Lsup(Hx0_ex_z)) self.assertLess(Lsup(Hxz[1]-Hx1_ex_z), 1e-2 * Lsup(Hx1_ex_z)) argsr=model.getArguments(1.) ref=model.getDefect(1., *argsr) # this should be almost zero: args=model.getArguments(RHO) d=model.getDefect(RHO, *args) self.assertTrue( d > 0.) self.assertTrue( ref > 0.) self.assertTrue( d <= 3e-3 * ref ) # d should be zero (some sort of) z=ReducedFunction(domain).getX()[1] Hx0_ex=cos(k.imag*(z-L))*exp(k.real*(z-L)) Hx1_ex=sin(k.imag*(z-L))*exp(k.real*(z-L)) Hx0_ex_z=-sin(k.imag*(z-L))*k.imag*exp(k.real*(z-L))+cos(k.imag*(z-L))*exp(k.real*(z-L))*k.real Hx1_ex_z=cos(k.imag*(z-L))*k.imag*exp(k.real*(z-L))+sin(k.imag*(z-L))*exp(k.real*(z-L))*k.real g_Hx = Data(0, (2,2), Hx0_ex_z.getFunctionSpace()) g_Hx[0,1] = Hx0_ex_z g_Hx[1,1] = Hx1_ex_z # and this should be zero d0=model.getDefect(RHO, Hx0_ex*[1.,0]+ Hx1_ex*[0,1.], g_Hx) self.assertLess( d0, 1e-8 * ref ) # d should be zero (some sort of) # and this too dg=model.getGradient(RHO, Hx0_ex*[1.,0]+Hx1_ex*[0,1.], g_Hx) self.assertTrue(isinstance(dg, Data)) self.assertTrue(dg.getShape()==()) self.assertLess(Lsup(dg), 1e-10)
lengths = compute_lengths(max_length, smallest_interval, density) #print(lengths) if (object_type == "disconnected-straight-brush"): view_window = ((-padding, -padding), (1 + padding, 1 + padding)) image = mathsvg.SvgImage(pixel_density=image_main_scale, view_window=view_window) for element in lengths: image.draw_line_segment([element[0], 0], [element[0], element[1]]) elif (object_type == "compact-cantor-bouquet"): view_window = ((-1 - padding, -1 - padding), (1 + padding, 1 + padding)) image = mathsvg.SvgImage(pixel_density=image_main_scale, view_window=view_window) for element in lengths: endpoint = element[1] * cmath.exp(2. * math.pi * element[0] * 1.j) image.draw_line_segment([0, 0], [endpoint.real, endpoint.imag]) elif (object_type == "one-sided-hairy-circle"): view_window = ((-1 - padding, -1 - padding), (1 + padding, 1 + padding)) image = mathsvg.SvgImage(pixel_density=image_main_scale, view_window=view_window) image.draw_circle((0, 0), 0.5) for element in lengths: direction = cmath.exp(2. * math.pi * element[0] * 1.j) start_point = 0.5 * direction endpoint = start_point + 0.5 * element[1] * direction image.draw_line_segment([start_point.real, start_point.imag], [endpoint.real, endpoint.imag]) image.save(image_name)
def _pw_amp(x): return cmath.exp(1j * k.dot(x + x0))
def _eigvals(cls, *params): theta = params[0] p = cmath.exp(-0.5j * theta) return np.array([p, p.conjugate()])
def get_bs_amp(n1, n2, m1, m2, tau_mag, tau_degs, rho_degs): """ Get beam splitter amplitude for arbitrary tau and rho, not self.tau, self.rho. Parameters ---------- n1 : int n2 : int m1 : int m2 : int tau_mag : float tau_degs : float rho_degs : float Returns ------- complex """ # from TWO_MODE_FUN::get_bs_amp() tau_rads = tau_degs * math.pi / 180 rho_rads = rho_degs * math.pi / 180 rho_mag = math.sqrt(1 - tau_mag**2) tau = tau_mag * cmath.exp(1j * tau_rads) rho = rho_mag * cmath.exp(1j * rho_rads) # no incoming photons if n1 + n2 + m1 + m2 == 0: return 1 + 0j # zero amp cases if n1 <= m1: up_lim = n1 else: up_lim = m1 if m1 <= n2: lo_lim = 0 else: lo_lim = m1 - n2 if (n1 + n2 != m1 + m2) or (lo_lim > up_lim): return 0 + 0j # tau_mag=1 case n_dif = n1 - n2 if abs(tau_mag - 1) < 1e-6: if n1 == m1 and n2 == m2: return cmath.exp(1j * tau_rads * n_dif) else: return 0 + 0j # tau_mag=0 case if tau_mag < 1e-6: if n1 == m2 and n2 == m1: return cmath.exp(1j * (rho_degs / 180 * n_dif + n2) * math.pi) else: return 0 + 0j tot_sum = 0 + 0j for j1 in range(lo_lim, up_lim + 1): term = np.power(tau, j1) / math.factorial(j1) j = n2 - m1 + j1 term = term * np.power(np.conj(tau), j) / math.factorial(j) j = n1 - j1 term = term * np.power(rho, j) / math.factorial(j) j = m1 - j1 term = term * np.power(np.conj(-rho), j) / math.factorial(j) tot_sum += term return math.sqrt( math.factorial(n1) * math.factorial(n2) * math.factorial(m1) * math.factorial(m2)) * tot_sum
def Round_Selection(pcb,distI,segments): global delete_before_connect tracks = [] #print ("TRACKS WHICH MATCH CRITERIA:") for item in pcb.GetTracks(): if type(item) is TRACK and item.IsSelected(): #item.GetNetname() == net_name: tracks.append(item) wxLogDebug(str(len(tracks)),debug) if len (tracks) == 2: #add all the possible intersections to a unique set, for iterating over later intersections = set(); for t1 in range(len(tracks)): for t2 in range(t1+1, len(tracks)): #check if these two tracks share an endpoint # reduce it to a 2-part tuple so there are not multiple objects of the same point in the set if(tracks[t1].IsPointOnEnds(tracks[t2].GetStart())): intersections.add((tracks[t2].GetStart().x, tracks[t2].GetStart().y)) if(tracks[t1].IsPointOnEnds(tracks[t2].GetEnd())): intersections.add((tracks[t2].GetEnd().x, tracks[t2].GetEnd().y)) if len(intersections)==1: for ip in intersections: (x,y) = ip wxLogDebug("intersections: "+str(ToUnits(x))+":"+str(ToUnits(y)),debug) #wx.LogMessage(str(tracks[0].GetStart())) intersection = wxPoint(x,y) if tracks[0].GetStart() == pcbnew.wxPoint(x,y): first_trk_extNode = tracks[0].GetEnd() #wx.LogMessage("tracks[0] external node="+str(ToUnits(tracks[0].GetEnd().x))+";"+str(ToUnits(tracks[0].GetEnd().y))) else: first_trk_extNode = tracks[0].GetStart() #wx.LogMessage("tracks[0] external node="+str(ToUnits(tracks[0].GetStart().x))+";"+str(ToUnits(tracks[0].GetStart().y))) if tracks[1].GetStart() == pcbnew.wxPoint(x,y): last_trk_extNode = tracks[1].GetEnd() #wx.LogMessage("tracks[1] external node="+str(ToUnits(tracks[1].GetEnd().x))+";"+str(ToUnits(tracks[1].GetEnd().y))) else: last_trk_extNode = tracks[1].GetStart() #wx.LogMessage("tracks[1] external node="+str(ToUnits(tracks[1].GetStart().x))+";"+str(ToUnits(tracks[1].GetStart().y))) angle1 = math.degrees((getTrackAngle(tracks[0],intersection))) angle2 = math.degrees((getTrackAngle(tracks[1],intersection))) end_coord1 = (distI) * cmath.exp(math.radians(angle1)*1j) #cmath.rect(r, phi) : Return the complex number x with polar coordinates r and phi. end_coord2 = (distI) * cmath.exp(math.radians(angle2)*1j) startP = wxPoint(end_coord1.real+x,end_coord1.imag+y) endP = wxPoint(end_coord2.real+x,end_coord2.imag+y) layer = tracks[0].GetLayer() width = ToMM(tracks[0].GetWidth()) Nname = tracks[0].GetNet() #.GetNetname() wxLogDebug("offset1 = "+str(ToUnits(startP)),debug) #+":"+str(ToUnits(endP)),debug) wxLogDebug("offset2 = "+str(ToUnits(endP)),debug) #end_coord2.real+x))+":"+str(ToUnits(end_coord2.imag+y))) center,radius = getCircleCenterRadius( startP,endP,intersection ) #rad = math.hypot(center.x-startP.x,center.y-startP.y) wxLogDebug('radius'+str(ToMM(radius)),debug) wxLogDebug('center'+str(ToMM(center)),debug) # import round_trk; import importlib; importlib.reload(round_trk) lenT1 = GetTrackLength(tracks[0]) dist1 = math.hypot(startP.y-intersection.y,startP.x-intersection.x) lenT2 = GetTrackLength(tracks[1]) dist2 = math.hypot(endP.y-intersection.y,endP.x-intersection.x) wxLogDebug('Len T1 {0:.3f} mm, dist1 {1:.3f} mm, LenT2 {2:.3f} mm, dist2 {3:.3f} mm'.format(ToMM(lenT1),ToMM(dist1),ToMM(lenT2),ToMM(dist2)),debug) if show_points: create_Draw(pcb,startP,startP,F_Mask,0.2) create_Draw(pcb,intersection,intersection,Eco1_User,1.5) create_Draw(pcb,endP,endP,B_Mask,0.2) create_Draw(pcb,center,center,F_SilkS,2.) create_round_points(pcb,startP,angle1,endP,angle2,center,radius,segments) pcbnew.Refresh() selectListTracks(pcb,tracks) if (lenT1 < dist1) or (lenT2 < dist2): wxLogDebug('Segments too short compared to selected distance {0:.3f} mm'.format(ToMM(distI)),True) else: #create_Track(pcb,first_trk_extNode,startP,layer,width,Nname) #B_Cu,0.2) #if delete_before_connect: deleteListTracks(pcb,tracks) create_Track(pcb,startP,first_trk_extNode,layer,width,Nname) #B_Cu,0.2) #create_Draw(pcb,startP,startP,F_Mask,1.5) newEP = create_round_segments(pcb,startP,angle1,endP,angle2,center,radius,layer,width,Nname,segments) #B_Cu,0.2) #wxLogDebug(str(newEP)+':'+str(endP),True) #create_Draw(pcb,endP,endP,B_Mask,1.9) create_Track(pcb,endP,last_trk_extNode,layer,width,Nname) # B_Cu,0.2) #create_Track(pcb,last_trk_extNode,endP,layer,width,Nname) # B_Cu,0.2) #deleteSelectedTracks(pcb) #selectListTracks(pcb,tracks) w3 = 3*float(width) rad = float(ToMM(radius)) wxLogDebug(str(w3),debug) msg = u'Corner Radius: {0:.3f} mm'.format(rad) msg+= u'\nAngle between tracks: {0:.1f} deg'.format(angle1-angle2) if rad < w3: msg += u'\n\u2718 ALERT: Radius < 3 *(track width) !!!\n[{0:.3f}mm < 3*{1:.3f}mm]'.format(rad,width) #else: # #msg = u'\n\u2714 Radius > 3 * (track width)' # msg = u'\u2714 Corner Radius: {0:.3f} mm'.format(rad) wxLogDebug(msg,True) pcbnew.Refresh() # import round_trk; reload(round_trk) # import round_trk; import importlib; importlib.reload(round_trk) else: wxLogDebug("you must select two tracks (only)",not debug)
def _eigvals(cls, *params): phi = params[0] return np.array([1, cmath.exp(1j * phi)])
def mix(lo, data, phase=0.0): cphase = cmath.exp(1j * phase) y = [lo_i * data_i * cphase for lo_i, data_i in zip(lo, data)] return y
def _eigvals(cls, *params): theta = params[0] return np.array([1, 1, cmath.exp(-0.5j * theta), cmath.exp(0.5j * theta),])
def TesterValeur(nomPara, valPu, valRef, res, epsi, crit, sSigne): """ Teste de la valeur calculee par rapport a la valeur de reference """ import aster import cmath import math isTestOk = 0 vtc = valRef[0] if is_sequence(vtc): assert((vtc[0] == 'RI') | (vtc[0] == 'MP')), vtc[0] if vtc[0] == 'RI': vtc = vtc[1] + 1j * vtc[2] else: vtc = vtc[1] * cmath.exp(1j * math.pi * vtc[2] / 180) if sSigne == 'OUI': res = abs(res) if is_complex(valRef[0]): vtc = abs(vtc) # Recherche de la valeur la plus proche de la valeur calculee # dans le tableau valRef minTmp = abs(res - vtc) curI = 0 for i in range(len(valRef)): vtc = valRef[i] if is_sequence(vtc): assert((vtc[0] == 'RI') | (vtc[0] == 'MP')), vtc[0] if vtc[0] == 'RI': vtc = vtc[1] + 1j * vtc[2] else: vtc = vtc[1] * cmath.exp(1j * math.pi * vtc[2] / 180) if sSigne == 'OUI' and is_complex(vtc): vtc = abs(vtc) valTmp = abs(res - vtc) if valTmp < minTmp: valTmp = minTmp curI = i vtc = valRef[curI] if is_sequence(vtc): assert((vtc[0] == 'RI') | (vtc[0] == 'MP')), vtc[0] if vtc[0] == 'RI': vtc = vtc[1] + 1j * vtc[2] else: vtc = vtc[1] * cmath.exp(1j * math.pi * vtc[2] / 180) if sSigne == 'OUI' and is_complex(vtc): vtc = abs(vtc) testOk = 'NOOK' curEps = 0 err = 0 pourcent = ' ' # Calcul de l'erreur commise if crit[0:4] == 'RELA': isTestOk = (abs(res - vtc) <= epsi * abs(vtc)) if vtc != 0: if is_complex(res) or is_complex(vtc): err = abs(res - vtc) / abs(vtc) * 100 else: err = (res - vtc) / vtc * 100 else: err = 999.999999 if isTestOk: testOk = ' OK ' curEps = epsi * 100 pourcent = '%' else: isTestOk = (abs(res - vtc) <= epsi) if is_complex(res) or is_complex(vtc): err = abs(res - vtc) else: err = res - vtc if isTestOk: testOk = ' OK ' curEps = epsi return {'testOk': testOk, 'erreur': err, 'epsilon': curEps, 'valeurRef': vtc}
def psi0_n(x): return A * exp(1j * q(n) * x)
def test_polar_1(self): num, unit = utils.parse_complex_str('+348863+13.716d VA') self.assertEqual(unit, 'VA') expected_num = 348863 * cmath.exp(1j * math.radians(13.716)) self.assertEqual(num, expected_num)
def redraw(x, y, tt=t): vector = (x - focus_x, y - focus_y) if abs(vector[0]) > 1e-8: theta = atan2(vector[1], vector[0]) phi = theta + pi / 2 r = plane_length plane.x, plane.y = x + r / 2 * cos(phi), y + r / 2 * sin(phi) plane.x2, plane.y2 = x - r / 2 * cos(phi), y - r / 2 * sin(phi) t = tan(theta) b = -(2 * a * vertex[0] + t) phase1 = 0 phase2 = 0 for i, (ray, ref, rtext) in enumerate(zip(rays, refs, rtexts)): denom = len(rays) - 1 ray.x, ray.y = plane.x - i / denom * r * cos( phi), plane.y - i / denom * r * sin(phi) c = a * vertex[0]**2 + vertex[1] - ray.y + t * ray.x try: x1 = (-b + sqrt(b**2 - 4 * a * c)) / (2 * a) x2 = (-b - sqrt(b**2 - 4 * a * c)) / (2 * a) if vertex[0] - parabola_width / 2 <= x1 <= vertex[ 0] + parabola_width / 2: ray.x2 = x1 else: ray.x2 = x2 ray.y2 = (ray.x2 - vertex[0])**2 * a + vertex[1] except: pass y_prime = 2 * a * (ray.x2 - vertex[0]) pt = atan(y_prime) ptm = (pt + pi) % (2 * pi) if abs(theta - pt) < abs(theta - ptm): if theta < pt: theta_out = ptm + abs(theta - pt) else: theta_out = ptm - abs(theta - pt) else: if theta < ptm: theta_out = pt + abs(theta - ptm) else: theta_out = pt - abs(theta - ptm) ref.x, ref.y, ref.x2, ref.y2 = ray.x2, ray.y2, ray.x2 + 500 * cos( theta_out), ray.y2 + 500 * sin(theta_out) bl = 0 ray_length = sqrt((ray.x2 - ray.x)**2 + (ray.y2 - ray.y)**2) ray_uv = (ray.x2 - ray.x) / ray_length, (ray.y2 - ray.y) / ray_length reflected = False tp = (tt[0] % period) / period bx, by = ray.x, ray.y bx, by = bx + ray_uv[0] * bdr * 2 * tp, by + ray_uv[ 1] * bdr * 2 * tp bl += bdr * 2 * tp for j, ball in enumerate(balls[i]): if not reflected: if bl + bdr < ray_length: bx, by = bx + ray_uv[0] * bdr, by + ray_uv[1] * bdr if ball.color[2] > 50: ball.color = (10, 10, 100) else: ball.color = (100, 10, 10) bl += bdr else: bx, by = ref.x, ref.y remaining_offset = (bl + bdr - ray_length) ref_length = sqrt((ref.x2 - ref.x)**2 + (ref.y2 - ref.y)**2) ref_uv = (ref.x2 - ref.x) / ref_length, ( ref.y2 - ref.y) / ref_length bx, by = bx + ref_uv[0] * remaining_offset, by + ref_uv[ 1] * remaining_offset reflected = True bl += bdr else: if ball.color[2] > 50: ball.color = (20, 20, 200) else: ball.color = (200, 20, 20) bx, by = bx + ref_uv[0] * bdr, by + ref_uv[1] * bdr bl += bdr ball.x = bx ball.y = by if False: path_length = sqrt((ray.x2 - ray.x)**2 + (ray.y2 - ray.y)**2) + sqrt( (ref.x2 - ref.x)**2 + (ref.y2 - ref.y)**2) f1 = 30e4 f2 = 20e4 w1 = 3e9 / f1 * 39.37 w2 = 3e9 / f2 * 39.37 in_pp = 29 / parabola_width path_length_in = in_pp * path_length p1 = (path_length_in % w1) / w1 * 2 * pi p2 = (path_length_in % w2) / w2 * 2 * pi rtext.text = '%0.3f, %0.3f' % (p1, p2) phase1 += exp(1j * p1) phase2 += exp(1j * p2)
def test_polar_2(self): num, unit = utils.parse_complex_str('-12.2+13d I') self.assertEqual(unit, 'I') expected_num = -12.2 * cmath.exp(1j * math.radians(13)) self.assertEqual(num, expected_num)
v[i] = 0.0 # initial values for psiR and psiI p0 = 4.0 p02 = p0*p0 dp = 0.5 dp2 = dp*dp for i in range(1,NX-1): # psiR at t = 0 t = -dt; x = (i-ic)*dx ta = complex(-dp2*x*x/2.0, -p02*t/2.0 + p0*x) tb = complex(1.0, dp2*t) ta = ta/tb ta = cmath.exp(ta) tc = complex(dp,0.0) tc = tc/tb tc = cmath.sqrt(tc) tc = tc*ta psim1[i]= tc # psi at time dt t = 0 x = (i-ic)*dx ta = complex(-dp2*x*x/2.0, -p02*t/2.0 + p0*x) tb = complex(1.0, dp2*t) ta = ta/tb ta = cmath.exp(ta) tc = complex(dp,0.0) tc = tc/tb tc = cmath.sqrt(tc)
def test_polar_3(self): num, unit = utils.parse_complex_str('+3.258-2.14890r kV') self.assertEqual(unit, 'kV') expected_num = 3.258 * cmath.exp(1j * -2.14890) self.assertEqual(num, expected_num)
def sigmoid(a, b, l, d, x): return 1 / (1 + cmath.exp((x - l) / d)) * a + b
def _matrix(cls, *params): theta = params[0] p = cmath.exp(-0.5j * theta) return np.array([[p, 0], [0, p.conjugate()]])
def __p(kappa, theta, sigma, rho, v0, r, T, s0, K, status): integrand = lambda phi: (cmath.exp(-1j * phi * math.log(K)) * __f( phi, kappa, theta, sigma, rho, v0, r, T, s0, status) / (1j * phi)).real return (0.5 + (1 / math.pi) * quad(integrand, 0, 100)[0])
def _eigvals(cls, *params): return np.array([1, cmath.exp(1j * np.pi / 4)])
def _matrix(cls, *params): return np.array([[1, 0], [0, cmath.exp(1j * np.pi / 4)]])
def _matrix(cls, *params): phi, lam = params return INV_SQRT2 * np.array( [[1, -cmath.exp(1j * lam)], [cmath.exp(1j * phi), cmath.exp(1j * (phi + lam))]] )
xoffset = 640 yoffset = 360 omega = 1 / 20 nt = 100 tracelist = [0] * (2 * nt) plist = [ 1, 1 + 0.25j, 1 + 0.5j, 1 + 0.75j, 1 + 1j, 0.75 + 1j, 0.5 + 1j, 0.25 + 1j, 0 + 1j, -0.25 + 1j, -0.5 + 1j, -0.75 + 1j, -1 + 1j, -1 + 0.75j, -1 + 0.5j, -1 + 0.25j, -1 + 0j, -1 - 0.25j, -1 - 0.5j, -1 - 0.75j, -1 - 1j, -0.75 - 1j, -0.5 - 1j, -0.25 - 1j, 0 - 1j, 0.25 - 1j, 0.5 - 1j, 0.75 - 1j, 1 - 1j, 1 - 0.75j, 1 - 0.5j, 1 - 0.25j ] # 32 element från en kvadrat plist = [ cmath.exp(twopii * k / 16) + (random.uniform(-1, 1) + 1j * random.uniform(-1, 1)) for k in range(16) ] #flist = numpy.fft.fft(plist,norm = "ortho") #plist = plist[::4] #plist = [0,0.5,1,0.5+0.5j,1j,0.5j] #plist = [0,0.5,1,1j,0.5j] flist = [c / len(plist) for c in numpy.fft.fft(plist)] n = len(flist) // 2 def poscoeff(n): return flist[n]
def _matrix(cls, *params): phi = params[0] return np.array([[1, 0], [0, cmath.exp(1j * phi)]])