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 symcomp(v1, v2, v3): """ Returns the symmetrical components of the three phasors v1, v2, v3 which are in tuple (r, theta) form. """ #Convert first to complex rectangular form. v1z = cm.rect(v1[0], v1[1]) v2z = cm.rect(v2[0], v2[1]) v3z = cm.rect(v3[0], v3[1]) av2 = _a_ * v2z a2v2 = _a2_ * v2z av3 = _a_* v3z a2v3 = _a2_* v3z #Null sequence component. E0 = cm.polar((v1z.real+ v2z.real+ v3z.real)/3.0 + (v1z.imag+ v2z.imag+ v3z.imag)/3.0*1j) #Positive sequence component. E1 = cm.polar((v1z.real + av2.real + a2v3.real)/3.0+ (v1z.imag+ av2.imag+ a2v3.imag)/3.0*1j) #Negative sequence component. E2 = cm.polar((v1z.real + a2v2.real + av3.real)/3.0+ (v1z.imag+ a2v2.imag+ av3.imag)/3.0*1j) return (E0, E1, E2)
def GetAngle(self, origin_body, body1, body2): my_difference = origin_body.position - body1.position his_difference = origin_body.position - body2.position distance, angle1 = cmath.polar(complex(my_difference.x, my_difference.y)) distance, angle2 = cmath.polar(complex(his_difference.x, his_difference.y)) return angle1 - angle2
def b1_to_optimize(f1): # calculate diffraction efficiencies e0_g1 = cmath.polar(calc_diffraction_eff_vdw(0, f1, d, l, v, C3)[0])[0] e1_g1 = cmath.polar(calc_diffraction_eff_vdw(1, f1, d, l, v, C3)[0])[0] # return the negative so that minimize works return -(e0_g1 * e1_g1) ** 2 / (e0_g1 ** 2 + e1_g1 ** 2)
def symcomp2phasors(E0, E1, E2): """ Recreates the phasors form the symmetrical components. """ V1 = cm.polar(cm.rect(E0[0], E0[1]) + cm.rect(E1[0], E1[1]) + cm.rect(E2[0], E2[1])) V2 = cm.polar(cm.rect(E0[0], E0[1]) + _a2_* cm.rect(E1[0], E1[1]) + _a_ *cm.rect(E2[0], E2[1])) V3 = cm.polar(cm.rect(E0[0], E0[1]) + _a_* cm.rect(E1[0], E1[1]) + _a2_ * cm.rect(E2[0], E2[1])) return V1, V2, V3
def get_KOP(x1s,y1s,nbn): sum=0 for n in range(nbn): x=x1s[n]; y=y1s[n]; #get polar coordinate from (x,y) euclidean coordinates r,theta=cmath.polar(complex(x,y)) sum+=pb.exp(complex(0,theta)) return cmath.polar(sum/nbn)
def showResult(self,node_set): print "Results:" for n in node_set: s='Label: '+str(n.label)+'\n'+\ 'Sequence number: '+str(n.seq_num)+'\n'+\ 'Node voltage: a: '+str(cmath.polar(n.node_vol[0,0]))+'b: '+str(cmath.polar(n.node_vol[1,0]))+'c: '+str(cmath.polar(n.node_vol[2,0]))+'\n'+\ 'Branch current: '+str(n.branch_cur)+'\n'\ 'Load: '+str(n.fixed_load)+'\n\n' print s
def converge(Cx): temp=Cx lastlenth=cmath.polar(Cx)[0] nowlenth=0 for i in range(0,20): Cx=Cx*Cx+temp nowlenth=cmath.polar(Cx)[0] if nowlenth>100: return False lastlenth=nowlenth return True
def sensitivity_to_optimize(x): # calculate diffraction efficiencies e0_g1 = cmath.polar(calc_diffraction_eff_vdw(0, fixed_f, x[0], l, v, C3)[0])[0] e1_g1 = cmath.polar(calc_diffraction_eff_vdw(1, fixed_f, x[0], l, v, C3)[0])[0] e1_g2 = e1_g1 # calculate signal signal = 4.0 * I_inc * 0.23 * (e0_g1 * e1_g1 * e1_g2) ** 2 / (e0_g1 ** 2 + e1_g1 ** 2) return v * x[0] / (4.0 * np.pi * L ** 2 * np.sqrt(signal))
def intrinsicImped(omega,mu,sigma,epsilon): n = complex(0,omega*mu) d = complex(sigma,omega*epsilon) Eta = cmath.sqrt(n/d) real_eta = cmath.polar(Eta)[0] phase = cmath.polar(Eta)[1] phase = degrees(phase) print("Intrinsic impedance(complex) is: {}+{}j ohm".format(round(Eta.real,3),round(Eta.imag,3))) print("|Eta|= {} ohm".format(round(real_eta,3))) print("phase angle is: {}".format(phase)) return Eta
def get_KOP_noRest(x1s,y1s,nbn,baseVal): sum=0 for n in range(nbn): #x=x1s[n]; y=y1s[n]; #get polar coordinate from (x,y) euclidean coordinates r,theta=cmath.polar(complex(x1s[n],y1s[n])) #returns -pi < theta < pi if theta > -pb.pi/2 : sum += pb.exp(complex(0,theta)) else: sum += baseVal return cmath.polar(sum/nbn)
def makeComplexInvariant(G): #Scale invariance: normalizar por |G[0]| Gout = G[1:]/np.sum(G[1:]) #Rotation invariance: subtrair a fase do primeiro coeficiente r, phi = cmath.polar(Gout[0]) for u in range(1, len(Gout)): r_u, phi_u = cmath.polar(Gout[u]) phi_u -= u*phi Gout[u] = cmath.rect(r_u, phi_u) return Gout
def vocode(tWav, vWav): N = 1024 M = 3 H = N/M H_ = H/4 i = 0 window = numpy.blackman(N) tBytes = tWav.readframes(tWav.getnframes()) vBytes = vWav.readframes(vWav.getnframes()) tFloats = numpy.array(wave.struct.unpack("%dh"%(len(tBytes)/tWav.getsampwidth()), tBytes)) vFloats = numpy.array(wave.struct.unpack("%dh"%(len(vBytes)/vWav.getsampwidth()), vBytes)) oFloats = [0] * max(len(tFloats), len(vFloats)) ## with overlapping windows while (i+N < len(tFloats)) and (i+N < len(vFloats)): tFloatWin = tFloats[i:i+N]*window vFloatWin = vFloats[i:i+N]*window iAmp = max(max(tFloatWin), max(vFloatWin)) vFloatSum = sum(map(abs, vFloatWin)) # Take the full (complex) fft tFftData=numpy.fft.fft(tFloatWin) vFftData=numpy.fft.fft(vFloatWin) ## cartesian to polar tFftPolar = [cmath.polar(z) for z in tFftData] vFftPolar = [cmath.polar(z) for z in vFftData] ## multiply magnitudes oFftPolar = [(r0*r1, p0) for ((r0,p0), (r1,p1)) in zip(tFftPolar, vFftPolar)] ## polar to cartesian oFftData = [cmath.rect(r,p) for (r,p) in oFftPolar] ## ifft(mult-mags, tPhase) oFloatsZ = numpy.fft.ifft(oFftData) ## convert back to real oFloatsR = numpy.round([z.real for z in oFloatsZ]) ## scale and ignore parts of song without words oAmp = max(oFloatsR) oFloatsO = [(v/oAmp*iAmp).astype('int16') for v in oFloatsR] if vFloatSum>H_ else numpy.zeros(N) ## sum into output array oFloats[i:i+N] = [(x+y/M) for (x,y) in zip(oFloats[i:i+N], oFloatsO)] i += H return oFloats
def compleja(nr, inicial, err): fxi = nr.f(inicial) fdxi = nr.fdx(inicial) com = inicial - ((fxi*(cm.sqrt(-1))) / (fdxi*(cm.sqrt(-1)))) tempInicial = cm.polar(sp.sympify(inicial)) tempInicial = cm.rect(sp.sympify(tempInicial[0]), sp.sympify(tempInicial[1])) tempCom = cm.polar(sp.sympify(com)) tempCom = cm.rect(sp.sympify(tempCom[0]), sp.sympify(tempCom[1])) e = abs(tempInicial - tempCom) if e > err : return compleja(nr, com, err) else : return com
def half_components(self): """Yields decay coefficients and frequencies for components.""" roots = self.half_component_roots() filterf = self.filterf if filterf == None: # by default, filter to outside unit circle filterf = lambda c: abs(c) >= 1.0 froots = filter(filterf, roots) froots = filter(lambda c: c.imag >= 0, froots) decays = [np.log(polar(c)[0]) for c in froots] freqs = [polar(c)[1] / (2*pi) for c in froots] return zip(decays, freqs)
def printRawSpectrum(X,type): if(type == 'DFT'): print 'DFT' output = DFT(X) elif(type == 'HANN'): print 'Hann Solo shot first' output = DFThann(X) else: print 'FFT' output = FFT(X) count = 0 for i in output: # print(str(count) + ": ( " + str(round(cmath.polar(i)[0],2)) + ", " + str(round(cmath.polar(i)[1],2)) + " )") f.write((str(count) + ", " + str(round(cmath.polar(i)[0],2)) + ", " + str(round(cmath.polar(i)[1],2)) + " ") + '\n') count += 1
def rosenberg_pulse(N1, N2, pulselength, fftlen=1024, randomize=False, differentiate=True, normalize=False): N2 = int(math.floor(pulselength*N2)) N1 = int(math.floor(N1*N2)) if differentiate: gn = np.zeros(fftlen + 1) else: gn = np.zeros(fftlen) offset = fftlen/2 - N1 # Opening phase for n in range(0, N1): gn[n + offset] = 0.5 * (1-math.cos(np.pi*n / N1)) # Closing phase for n in range(N1, N2): gn[n + offset] = math.cos(np.pi*(n-N1)/(N2-N1)/2) if randomize: rnd_val += (random.random() - 0.5) * np.pi * 0.01 else: rnd_val = 0 if differentiate: gn = np.diff(gn) # Normalise in the FFT domain if normalize: gn = np.fft.fftshift(gn) pulse_fft = np.fft.rfft(gn) for i, c in enumerate(pulse_fft): if i != 0 and i != len(pulse_fft) -1: pulse_fft[i] = cmath.rect(1.0, cmath.polar(c)[1] + rnd_val) gn = np.fft.irfft(pulse_fft) gn = np.fft.ifftshift(gn) return gn
def __init__(self,player,duration,diff): self.duration = duration self.player_bones = player.bones self.start = globals.time self.damping = self.duration + self.damping_duration #The final frame will be the right arm pointing directly at it distance,angle = cmath.polar(complex(diff.x,diff.y)) r = cmath.rect(random.random()*5 + 8, angle) self.extra_speed = Point(r.real, r.imag) self.extra_rotation = (random.random()-0.5) * 0.1 final = {bone : angle for bone in bones.Bones.right_arm} start = {bone : self.player_bones[bone].angle for bone in bones.Bones.both_arms} torso_start_pos = self.player_bones[bones.Bones.TORSO].pos/player.size torso_start_angle = self.player_bones[bones.Bones.TORSO].angle start[bones.Bones.TORSO] = (torso_start_pos,torso_start_angle) adjust = math.pi*0.9 if abs(angle) > math.pi*0.5: adjust *= -1 middle = {bones.Bones.RIGHT_BICEP : (angle + adjust)%(math.pi*2), bones.Bones.RIGHT_FOREARM : angle, bones.Bones.TORSO : (torso_start_pos,torso_start_angle + adjust*0.1)} final[bones.Bones.TORSO] = (torso_start_pos, torso_start_angle - adjust*0.1) frames = [start,middle,final,final] for frame in frames[1:]: if abs(angle)*2 > math.pi: frame[bones.Bones.LEFT_BICEP] = -math.pi*0.55 frame[bones.Bones.LEFT_FOREARM] = math.pi*0.55 else: frame[bones.Bones.LEFT_BICEP] = -math.pi*0.45 frame[bones.Bones.LEFT_FOREARM] = math.pi*0.45 durations = (self.duration*0.4,self.duration*0.1,self.duration*0.5,1) super(Punch,self).__init__(frames,durations)
def act(self,view,msg): x_sum = 0 y_sum = 0 dir = 1 n = len(view.get_plants()) me = view.get_me() mp = (mx,my)= me.get_pos() for a in view.get_agents(): if (a.get_team()!=me.get_team()): msg.send_message(mp) return cells.Action(cells.ACT_ATTACK,a.get_pos()) for m in msg.get_messages(): r = random.random() if ((self.my_plant and random.random()>0.6) or (not self.my_plant and random.random() > 0.5)): self.mode = 5 (tx,ty) = m self.target = (tx+random.randrange(-3,4),ty+random.randrange(-3,4)) if n: best_plant = max(view.get_plants(), key=lambda x: x.eff) if not self.my_plant or self.my_plant.eff < best_plant.eff: self.my_plant = view.get_plants()[0] self.mode = 0 if self.mode == 5: dist = max(abs(mx-self.target[0]),abs(my-self.target[1])) self.target_range = max(dist,self.target_range) if me.energy > dist*1.5: self.mode = 6 if self.mode == 6: dist = max(abs(mx-self.target[0]),abs(my-self.target[1])) if dist > 4: return cells.Action(cells.ACT_MOVE,self.target) else: self.my_plant = None self.mode = 0 if (me.energy < self.target_range) and (view.get_energy().get(mx, my) > 0): return cells.Action(cells.ACT_EAT) if self.my_plant: dist = max(abs(mx-self.my_plant.get_pos()[0]),abs(my-self.my_plant.get_pos()[1])) if me.energy < dist*1.5: (mx,my) = self.my_plant.get_pos() return cells.Action(cells.ACT_MOVE,(mx+random.randrange(-1,2),my+random.randrange(-1,2))) if (random.random()>0.9999): (mx,my) = self.my_plant.get_pos() dtheta = random.random() * 2 * math.pi dr = random.randrange(100) curr_r, curr_theta = cmath.polar(mx + my*1j) m = cmath.rect(curr_r + dr, curr_theta + dtheta) msg.send_message((m.real, m.imag)) if (random.random()>0.9 and me.energy >= 50): return cells.Action(cells.ACT_SPAWN,(mx+random.randrange(-1,2),my+random.randrange(-1,2))) else: return cells.Action(cells.ACT_MOVE,(mx+random.randrange(-1,2),my+random.randrange(-1,2)))
def scan(self,command): #The scan will find three things: # - The other robot # - The axe # - The candy cane messages = ['SR'] self.move_end = globals.time-1 globals.sounds.move.fadeout(100) other_robot = self.map.robots[0] items = [('AX',self.map.axe_position+Point(0.5,0.5)), ('CC',self.map.candy.mid_point), ('RB',other_robot.mid_point())] if other_robot.axe: items = items[1:] globals.sounds.scanning.play() for name,item in items: vector = (self.mid_point() - item).Rotate((math.pi*0.5)-self.angle) distance = vector.length() r,a = cmath.polar(vector.x + vector.y*1j) a = (a + math.pi*2)%(math.pi*2) bearing = a*180.0/math.pi #we want it to be clockwise bearing = 360 - bearing distance = r/1.95 message = '%s DS %d BR %d' % (name,int(distance),int(bearing)) messages.append(message) globals.game_view.recv_morse.play('\n'.join(messages), self.morse_light) self.torch.colour = (0,0,1) self.begin_turn(math.pi*2,1) self.scanning = True
def __separate_signal_2_power_phase(signal): """ deprecated :param signal: :return: """ return zip(*map(lambda x: cmath.polar(x), signal))
def testPolar(self): """ cmath.polar return (magnitude, phasor) of a complex number """ magnitude,angle = cmath.polar(self._cplx) self.assertAlmostEqual(magnitude,abs(self._cplx)) self.assertAlmostEqual(angle,cmath.phase(self._cplx))
def draw(self, screen, size): texts = [ text.menu_multiplayer, '', text.menu_credits, text.menu_quit, text.menu_settings, '', text.menu_singleplayer] self.screen = screen self.size = w, h = size self.origin = ox, oy = w // 2, h // 2 r, _angle = cmath.polar(ox + oy * 1j) angle = -math.pi / 2 d = 2 * math.pi / 7 self.screen.fill((0, 0, 0)) font = pygame.font.SysFont('monospace', 16) for index in xrange(7): if index == self.highlight: left = cmath.rect(int(r * 1.25), angle) left = (ox + int(left.real), oy + int(left.imag)) right = cmath.rect(int(r * 1.25), angle + d) right = (ox + int(right.real), oy + int(right.imag)) self.draw_highlight( screen, (self.origin, left, right), colors.VYOLET) label = font.render(texts[index], True, colors.WHITE) pos = cmath.rect(int(r / 2.5), angle + d / 2) pos = (ox + int(pos.real), oy + int(pos.imag)) drawing.blit_center(screen, label, pos) angle += d pygame.display.flip()
def b2_to_optimize(f2): # calculate diffraction efficiency e1_g2 = cmath.polar(calc_diffraction_eff_vdw(1, f2, d, l, v, C3)[0])[0] # return the negative so that minimize works return -e1_g2 ** 2
def point_at(self, target): diff = target - self.torso.end_pos_abs distance,angle = cmath.polar(complex(diff.x,diff.y)) if self.punching: return if abs(angle)*2 > math.pi: self.dir = Directions.LEFT else: self.dir = Directions.RIGHT if abs(abs(angle)-0.5*math.pi) < 0.4: return frame = self.standing[self.dir][self.stance].frame aad = self.arm_angle_distance[self.dir][self.stance] frame[bones.Bones.RIGHT_BICEP] = angle - aad/2 frame[bones.Bones.LEFT_BICEP] = angle + aad/2 #Do the other side too otherwise it looks funny when we cross over... other_dir = Directions.LEFT if self.dir == Directions.RIGHT else Directions.RIGHT aad = self.arm_angle_distance[other_dir][self.stance] angle = math.pi - angle frame = self.standing[other_dir][self.stance].frame frame[bones.Bones.RIGHT_BICEP] = angle - aad/2 frame[bones.Bones.LEFT_BICEP] = angle + aad/2
def polar_decomposition(signal): """Returns the polar decomposition of a real-valued sinusoidal signal.""" padded_signal = pad(signal) rdft = rfft(padded_signal) ps = [polar(z) for z in ifft(rdft + [0.0] * (len(rdft) - 2))[:len(signal)]] rs, phis = zip(*ps) return zip(rs, unwrap_phase(phis))
def value(x, y, zoom): z, c = 0, lmap(x, y, zoom) iters = 0 while cmath.polar(z)[0] < 4 and iters < 1000: z = z*z + c iters += 1 return int(math.log(iters)/math.log(1000) * 10.0)
def Fire(self,pos): diff = pos - self.GetPos() distance,angle = cmath.polar(complex(diff.x,diff.y)) angle = (angle - (math.pi/2) - self.GetAngle())%(math.pi*2) #0 = pi*2 is straight ahead, pi is behind. #so 0.75 pi to 1.25 pi is disallowed if angle <= self.min_shoot and angle >= self.max_shoot: return if distance < self.min_shoot_distance: #If you aim too close then the shots go wild return if distance > self.max_shoot_distance: return if self.cooldown > self.t: return self.sound.play() self.fired = True self.cooldown = self.t + self.cooldown_time #if distance >= self.max_distance: # return for offset in self.cannon_positions: if self.wait_for_bullets and len(self.bullets) >= self.max_bullets: continue bpos = Point(*self.body.GetWorldPoint(tuple(offset*self.physics.scale_factor)))/self.physics.scale_factor bullet = self.bullet_type(self,self.physics,bpos,bpos+self.bullet_type.bullet_shape,tc = self.parent.atlas.TextureCoords(os.path.join(globals.dirs.sprites,'blast.png')),filter_group = self.filter_group,mass = self.bullet_mass) #print dir(bullet.body) if self.straight_up: pass else: bullet.body.linearVelocity = tuple(Point(*self.body.linearVelocity) + (pos - bpos).unit_vector()*self.bullet_velocity) self.bullets.append(bullet) if len(self.bullets) > self.max_bullets: bullet = self.bullets.pop(0) bullet.Destroy()
def dftplot(x,X): N=len(X) Xreal=[0.0]*N Ximag=[0.0]*N Xamp=[0.0]*N Xphase=[0.0]*N Xdb=[0,0]*N for i in range(len(X)): Xreal[i]=X[i].real Ximag[i]=X[i].imag Xamp[i],Xphase[i]=cmath.polar(X[i]) if Xamp[i]<1e-10: Xphase[i]=0 if Xamp[i] !=0.0: Xdb[i]=20*cmath.log10(Xamp[i]) f,axarr=plt.subplots(3,2) f.suptitle('figtitle') axarr[0,0].plot(x,'o-') axarr[0,1].plot(Xdb,'o-') axarr[1,0].plot(Xreal,'o-') axarr[2,0].plot(Ximag,'o-') axarr[1,1].plot(Xamp,'o-') axarr[2,1].plot(Xphase,'o-') plt.show
def UpdateMouse(self,pos,rel): diff = pos - ((self.pos*globals.tile_dimensions) + self.shoulder_pos) distance,angle = cmath.polar(complex(diff.x,diff.y)) #print distance,angle if not self.still: return if abs(angle)*2 > math.pi: self.dir = Directions.LEFT else: self.dir = Directions.RIGHT sector = math.pi/16 if abs(angle) < sector or abs(angle) > sector*15: GunAnimation.current_still = 0 self.gun_pos = {Directions.LEFT : Point(2,22),Directions.RIGHT : Point(23,22)} elif (sector*3 < angle < sector*5) or (sector*13 < angle < sector*15): GunAnimation.current_still = 1 self.gun_pos = {Directions.LEFT : Point(-4,28),Directions.RIGHT : Point(24,28)} elif (sector*5 < angle < sector*7) or (sector*11 < angle < sector*13): GunAnimation.current_still = 2 self.gun_pos = {Directions.LEFT : Point(4,30),Directions.RIGHT : Point(18,32)} elif (sector < -angle < sector*3) or (sector*13 < -angle < sector*15): GunAnimation.current_still = 3 self.gun_pos = {Directions.LEFT : Point(-4,15),Directions.RIGHT : Point(23,16)} elif (sector*3 < -angle < sector*5) or (sector*11 < -angle < sector*13): GunAnimation.current_still = 4 self.gun_pos = {Directions.LEFT : Point(1,13),Directions.RIGHT : Point(20,13)} self.angle = angle
def Run(): # Read Program File file = open('Program.txt', 'r') # Make it an Array program = file.readlines() # Initalize QBit array and data storage array QBits = [complex(0.0, 0.0)] * (2**int(program[0])) Data = [0] * (2**int(program[0])) # Set first item to 1 QBits[0] = complex(1.0, 0.0) # Set the deafault output as an array of probabilities outputData = False # Set the deafault number of times to loop when outputting actual data times = 0 checkFirst = True for i in xrange(1, len(program)): # loop all rows in 'Program.txt' command = program[i].strip().split() # split row into array at spaces if i == 1: try: # try int( command[0] ) # check if turning command[0] into an int returns an error outputData = True # change ouptutData to True (output result of running simulation) times = int(command[0]) # set times to the value of command[0] except ValueError: # except outputData = False # keep output data as false if command[0] == '#': # check if row is comment print str(program[i]) #[:-2] # if so print the comment elif command[0] == 'NOT': # check if row is a NOT gate QBits = QuantumGates.NOT(QBits, int( command[1])) # if so apply the NOT gate elif command[0] == 'CNOT': # check if row is a CNOT gate QBits = QuantumGates.CNOT(QBits, int(command[1]), int( command[2])) # if so apply the CNOT gate elif command[0] == 'CCNOT': # check if row is a CCNOT gate QBits = QuantumGates.CCNOT(QBits, int(command[1]), int( command[2]), int(command[3])) # if so apply the CCNOT gate elif command[0] == 'H' or command[ 0] == 'Hadamard': # check if row is a Hadamard gate QBits = QuantumGates.Hadamard(QBits, int( command[1])) # if so apply the Hadamard gate elif command[0] == 'ZNOT': # check if row is a ZNOT gate QBits = QuantumGates.ZNOT(QBits) # if so apply the ZNOT gate elif command[ 0] == 'OracleGA': # check if row is a Oracle gate (oracle from Grovers Algorithm) QBits = QuantumGates.OracleGA( QBits ) # if so apply the Oracle gate (oracle from Grovers Algorithm) elif command[0] == 'GroverDiffusion' or command[ 0] == 'GD': # check if row is Grover Diffusion QBits = QuantumGates.GroverDiffusion( QBits) # if so apply the Grover Diffusion checkFirst = False elif command[0] == 'HadamardOverZn' or command[ 0] == 'HZn': # check if row is Hadamard over Z to the n QBits = QuantumGates.HZn(QBits, int( command[1])) # if so apply Hadamard over Z to the n elif command[0] == 'ADD': # check if row is add QBits = QBits + ([complex(0, 0)] * ( (2**(int(command[1]) + int(program[0]))) - len(QBits)) ) # if so add n QBits to QBits Data = Data + ([0] * ( (2**(int(command[1]) + int(program[0]))) - len(Data)) ) # and Data elif command[ 0] == 'OracleSA': # check if row is a Oracle gate (oracle from Shor's Algorithm) QBits = QuantumGates.OracleSA( QBits, int(program[0]) ) # if so apply the Oracle gate (oracle from Shor's Algorithm) elif command[0] == 'Measure' or command[ 0] == 'M': # check if row is Measure QBits = QuantumGates.Measure(QBits, int(command[1]), times) # if so measure elif command[0] == 'R': # check if row is Rotate array = program[i][2:] array = array.split(',') array = [float(i) for i in array] QBits = QuantumGates.Rotate(QBits, array) # if so rotate if outputData == False: squared = [] for i in range(0, len(QBits)): squared.append((cmath.polar(QBits[i])[0])**2) return squared else: for i in range(0, times): test = random.uniform(0.0, 1.0) if checkFirst == True: prob = (cmath.polar(QBits[0])[0])**2 for i in range(0, len(QBits)): if test < prob and test > (prob - (cmath.polar(QBits[i])[0])**2): Data[i] = Data[i] + 1 if i != len(QBits) - 1: prob = prob + (cmath.polar(QBits[i])[0])**2 if QBits[i] == 0: Data[i] = 0 else: prob = (cmath.polar(QBits[1]).r)**2 for i in range(1, len(QBits)): if test < prob and test > (prob - (cmath.polar(QBits[i])[0])**2): Data[i] = Data[i] + 1 if i < len(QBits) - 1: prob = prob + (cmath.polar(QBits[i])[0])**2 if QBits[i] == 0: Data[i] = 0 return Data
import cmath [print(round(i,3)) for i in cmath.polar(complex(input()))]
def next_shift(obj, previous_shifts=[], previous_radius=[]): r""" :param obj: object of the class ``BrakeClass`` :param previous_shifts: python list for the previous shift points already calculated :param previous_radius: corresponding radius of the previous shift points :return: ``next_shift`` - next shift point in the target region :raises: ``Cover_BadInputError``, When the provided input is not as expected """ target = obj.target # Exceptions #------------------------------------------------------------ if len(target) == 0: raise Cover_BadInputError('The target is not specified') elif len(target) < 4: raise Cover_BadInputError('target region does not define a reactangle') elif target[1] <= target[0] or target[3] <= target[2]: raise Cover_BadInputError('the target reactangle is not defined') if (len(previous_shifts) == 0) and (len(previous_radius) == 0): first_shift = complex((target[0] + target[1]) / 2, (target[2] + target[3]) / 2) next_shift = first_shift else: x1 = target[0] x2 = target[1] y1 = target[2] y2 = target[3] if len(previous_shifts) != len(previous_radius): raise Cover_BadInputError( 'The shift and radius vector are not of the same length') #check if previous shifts lie in the target region for i in range(0, len(previous_shifts)): if previous_shifts[i].real < x1 \ or previous_shifts[i].real > x2 \ or previous_shifts[i].imag < y1 \ or previous_shifts[i].imag > y2: raise Cover_BadInputError('shift point not in target region') if np.amin(previous_radius) <= 0: raise Cover_BadInputError('The radius is nonpositive') #generate 1000 random sampling points and radius in the target region sampling_points = [] sampling_radius = [] for i in range(1000): x = random.randint(x1, x2) y = random.randint(y1, y2) sampling_points.append(complex(x, y)) sampling_radius.append(random.uniform(0, 1)) mean_radius = np.mean(sampling_radius) mean_previous_radius = np.mean(previous_radius) sampling_radius[:] = [ x * mean_previous_radius / mean_radius for x in sampling_radius ] #scanning for the best shift area_increment = 0 for i in range(0, len(sampling_points)): increment = 10000000 for j in range(0, len(previous_shifts)): delta = cmath.polar(sampling_points[i] - previous_shifts[j])[0] - previous_radius[j] if delta < 0: # Point i is inside Circle j increment = 0 break else: if delta < increment: increment = delta max_increment = [increment] max_increment.append(np.fabs(sampling_points[i].real - x1)) max_increment.append(np.fabs(sampling_points[i].real - x2)) max_increment.append(np.fabs(sampling_points[i].imag - y1)) max_increment.append(np.fabs(sampling_points[i].imag - y2)) increment = min(max_increment) if (increment > area_increment): area_increment = increment next_shift = sampling_points[i] return next_shift
def z_error2r_phi_error(x, x_error, y, y_error): """ Error estimation from rect to polar, but with small variation needed for MT: the so called 'relative phase error' is NOT the relative phase error, but the ABSOLUTE uncertainty in the angle that corresponds to the relative error in the amplitude. So, here we calculate the transformation from rect to polar coordinates, esp. the absolute/length of the value. Then we find the uncertainty in this length and calculate the relative error of this. The relative error of the resistivity will be double this value, because it's calculated by taking the square of this length. The relative uncertainty in length defines a circle around (x,y) (APPROXIMATION!). The uncertainty in phi is now the absolute of the angle beween the vector to (x,y) and the origin-vector tangential to the circle. BUT....since the phase angle uncertainty is interpreted with regard to the resistivity and not the Z-amplitude, we have to look at the square of the length, i.e. the relative error in question has to be halfed to get the correct relationship between resistivity and phase errors!!. """ # x_error, y_error define a rectangular uncertainty box # rho error is the difference between the closest and furthest point of the box (w.r.t. the origin) # approximation: just take corners and midpoint of edges lo_points = [(x + x_error, y), (x - x_error, y), (x, y - y_error), (x, y + y_error), (x - x_error, y - y_error), (x + x_error, y - y_error), (x + x_error, y + y_error), (x - x_error, y + y_error)] #check, if origin is within the box: origin_in_box = False if x_error >= np.abs(x) and y_error >= np.abs(y): origin_in_box = True lo_polar_points = [cmath.polar(np.complex(*i)) for i in lo_points] lo_rho = [i[0] for i in lo_polar_points] lo_phi = [math.degrees(i[1]) % 360 for i in lo_polar_points] #uncertainty in amplitude is defined by half the diameter of the box around x,y rho_err = 0.5 * (max(lo_rho) - min(lo_rho)) rho = cmath.polar(np.complex(x, y))[0] try: rel_error_rho = rho_err / rho except: rel_error_rho = 0. #if the relative error of the amplitude is >=100% that means that the relative #error of the resistivity is 200% - that is then equivalent to an uncertainty #in the phase angle of 90 degrees: if rel_error_rho > 1.: phi_err = 90 else: phi_err = np.degrees(np.arcsin(rel_error_rho)) return rho_err, phi_err
plt.pause(1) PLOT = 1 print("# of points:", n) MaxNpoints = 1000 if n > MaxNpoints: indices = np.linspace(0, n - 1, MaxNpoints, dtype=np.int32) pts = [pts[idx] for idx in indices] for i, p in enumerate(pts): #if i == 0 or i == n-1: # continue pos_x = [0] pos_y = [0] for (f, c) in zip(freq, coef): r, phase = cmath.polar(c) r /= n phase += 2.0 * math.pi * f * i / n c = cmath.rect(r, phase) x_s = c.real + pos_x[-1] x_e = c.imag + pos_y[-1] pos_x.append(x_s) pos_y.append(x_e) if PLOT: ax.add_patch(plt.Circle((x_s, x_e), r, alpha=0.3, fill=False)) end_pts_x.append(pos_x[-1]) end_pts_y.append(pos_y[-1]) if PLOT: ax.plot([x.real for x in pts], [x.imag for x in pts], "r-") ax.plot([p.real], [p.imag], 'r*') ax.plot(pos_x, pos_y, '-')
# Write a Python program to convert to/from rectangular coordinates # to Polar coordinates. Go to the editor # Expected Output : # Polar Coordinates: (5.0, 0.9272952180016122) # Polar to rectangular: (-2+2.4492935982947064e-16j) import cmath cn = complex(3, 4) # get polar coordinates print('Polar coordinates: ', cmath.polar(cn)) # polar to rectangular. Format for input is (length, <angle in radians>). cn1 = cmath.rect(2, cmath.pi) print('Polar to rectangular: ', cn1)
import cmath c_num = complex(input()) print(*cmath.polar(c_num), sep='\n')
def polar(self): return polar(self)
# Enter your code here. Read input from STDIN. Print output to STDOUT import cmath z = complex(input()) print(*cmath.polar(z), sep="\n")
def C_k(var, k): sumN = sum(np.exp(1j * k * var)) R, Theta = cmath.polar(sumN / (N)) return R, Theta
""" pvd = col.decoder.vecsum(colmod.x, colmod.centery, colmod.unitTracker) plt.figure(2) plt.plot(pvd.centSurDif, pvd.angShift, ".", markersize=1) #decoding bias +-3 plt.title("Decoding error in the non uniform model", fontsize=20) vecdict = param_dict(np.linspace(1, 360, 360), ["real", "imag", "theta", "r"]) for i in range(0, len(pvd.popSurVec)): #range between 1-360 real = [] imag = [] theta = [] r = [] for j in range(0, len(pvd.popSurVec[i])): real.append(pvd.popSurVec[i][j].real) imag.append(pvd.popSurVec[i][j].imag) r.append(c.polar(pvd.popSurVec[i][j])[0]) theta.append(c.polar(pvd.popSurVec[i][j])[1]) vecdict[i + 1]["real"] = real vecdict[i + 1]["imag"] = imag vecdict[i + 1]["theta"] = theta vecdict[i + 1]["r"] = r plt.figure(3) plt.polar(vecdict[1]["theta"], vecdict[1]["r"], ".", markersize=1, color="blue", label="1°") plt.polar(vecdict[23]["theta"],
def C_k(N, var): sumN = np.sum(np.exp(1j * var)) R, Theta = cmath.polar(sumN) return R/N, Theta
def comp_polar(n): return cmath.polar(n)
import functools, cmath, math n = int(input()) while True: points = [] for i in range(n - 1): x, y = map(int, input().split()) points.append(x + y * 1j) heights = sorted([int(input()) for _ in range(n)], reverse=True) points = sorted(points, key=lambda x: cmath.polar(x)[1]) triangles = [] for q, w in zip(points, points[1:] + [points[0]]): a, b, c = abs(q), abs(w), abs(q - w) s = (a + b + c) / 2 area = math.sqrt(s * (s - a) * (s - b) * (s - c)) triangles.append(area) poles = [0 for i in range(n - 1)] center = heights[0] heights = heights[1:] doubleTriangles = [] for a, b, i in zip(triangles, triangles[1:] + [triangles[0]], range(1, n)): doubleTriangles.append((a + b, i)) doubleTriangles = sorted(doubleTriangles, reverse=True) for (a, i), h in zip(doubleTriangles, heights): poles[i % (n - 1)] = h
def test_polar(self): self.assertCISEqual(polar(0), (0., 0.)) self.assertCISEqual(polar(1.), (1., 0.)) self.assertCISEqual(polar(-1.), (1., pi)) self.assertCISEqual(polar(1j), (1., pi / 2)) self.assertCISEqual(polar(-1j), (1., -pi / 2))
def QSpolar(x): if QSMODE == MODE_NORM: return cmath.polar(x) else: return mpmath.polar(x)
complex_array = np.vectorize(complex)(real_array, imag_array) return complex_array #read wav file samplingFrequency, signalData = np.array(wavfile.read('press_9.wav')) #find length of wav data len1 = np.shape(signalData)[0] fft_1 = np.fft.fft(signalData) #fft_1= my_dft(sin_array) #half length len1 = int(len1 / 2) #initialise FFT output array mag_only = np.zeros(len1) phase_only = np.zeros(len1) #calculate FFT and convert to POLAR form for i in range(len1): mag_only[i] = cmath.polar(fft_1[i])[0] phase_only[i] = cmath.polar(fft_1[i])[1] x_list = np.linspace(0, int(samplingFrequency / 2), len1) #Plot magnitude only plot.plot(x_list, mag_only / 1000)
import cmath a = complex(input()) z = cmath.polar(a) for i in z: print(i)
def polar(dev, origin, line, color): xs, ys = origin.real, origin.imag theta = cmath.polar(line)[1] dev.line(round(xs), round(ys), round(xs + line.real), round(ys - line.imag), color)
import cmath import regex as re r = complex('1+2j') print(*cmath.polar(complex('1+2j')),sep='\n') # N = 7 # M = N*3 # dots = ".|." # # print top layer # for i in range(0,N//2): # # print(((dots*i)+ dots + (dots*i)).center(M,'-')) # #print('Welcome'.center(M,'-')) # # print bottom layer # for i in range(0,N//2): # # print(((dots* (N//2-1-i))+dots+(dots* (N//2-1-i))).center(M,'-')) # l = ['1.414','+.5486468','0.5.0' ,'1+1.0' ,'0'] for i in l: try: print(isinstance(i, float)) except: print(False)
def plot(df, pred_df, mode="humain", path_name=None): # Réels et Imaginaires selon la pulsation plt.figure(figsize=(2 * 4, 4)) plt.subplot(1, 2, 1) plt.xlabel("$\omega$") plt.xscale('log') plt.ylabel("Re") plt.grid(True, linestyle='--') plt.scatter(df["w"], df["alpha_r"], s=50, label="JCAPL") plt.scatter(pred_df["w"], pred_df["alpha_r"], s=25, label="pred") plt.title("$R^2$=%.2f, MSE=%.2f" % (r2_score(df["alpha_r"], pred_df["alpha_r"]), mean_squared_error(df["alpha_r"], pred_df["alpha_r"]))) plt.legend() plt.subplot(1, 2, 2) plt.xlabel("$\omega$") plt.xscale('log') plt.ylabel("Im") plt.grid(True, linestyle='--') plt.scatter(df["w"], df["alpha_i"], s=50, label="JCAPL") plt.scatter(pred_df["w"], pred_df["alpha_i"], s=25, label="pred") plt.title("$R^2$=%.2f, MSE=%.2f" % (r2_score(df["alpha_i"], pred_df["alpha_i"]), mean_squared_error(df["alpha_i"], pred_df["alpha_i"]))) plt.legend() plt.tight_layout() if path_name is not None: plt.savefig('results/{0}/fig/reel_w_imag_w.png'.format(path_name)) if mode == "humain": plt.show() else: plt.close() # Réel suivis d'Imaginaire selon pulsation plt.figure(figsize=(8, 8)) plt.xlabel("$\omega$") plt.xscale('log') plt.ylabel("Im") plt.grid(True, linestyle='--') plt.scatter(df["w"].values + df["w"].values[-1] * pred_df["w"].values, df["alpha_r"].values + df["alpha_i"].values, s=50, label="JCAPL") plt.scatter(df["w"].values + df["w"].values[-1] * pred_df["w"].values, pred_df["alpha_r"].values + pred_df["alpha_i"].values, s=25, label="pred") plt.title("$R^2$=%.2f, MSE=%.2f" % (r2_score(df["alpha_r"].values + df["alpha_i"].values, pred_df["alpha_r"].values + pred_df["alpha_i"].values), mean_squared_error( df["alpha_r"].values + df["alpha_i"].values, pred_df["alpha_r"].values + pred_df["alpha_i"].values))) plt.legend() plt.tight_layout() if mode == "humain": plt.show() else: plt.close() # Imaginaire selon Réel plt.figure(figsize=(8, 8)) plt.xlabel("Re") plt.ylabel("Im") plt.grid(True, linestyle='--') plt.scatter(df["alpha_r"], df["alpha_i"], s=50, label="JCAPL") plt.scatter(pred_df["alpha_r"], pred_df["alpha_i"], s=25, label="pred") plt.title("$R^2$=%.2f, MSE=%.2f" % (r2_score(df["alpha_r"].values + df["alpha_i"].values, pred_df["alpha_r"].values + pred_df["alpha_i"].values), mean_squared_error( df["alpha_r"].values + df["alpha_i"].values, pred_df["alpha_r"].values + pred_df["alpha_i"].values))) plt.legend() plt.tight_layout() if path_name is not None: plt.savefig('results/{0}/fig/reel_imag.png'.format(path_name)) if mode == "humain": plt.show() else: plt.close() # Gain selon pulsation et Phase selon pulsation y_true = list(cmath.polar(complex(z)) for z in df["alpha"].values) y_pred = list(cmath.polar(complex(z)) for z in pred_df["alpha"].values) plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.semilogx(df["w"], [r for (r, phi) in y_true], linewidth=4, label="JCAPL") plt.semilogx(pred_df["w"], [r for (r, phi) in y_pred], linewidth=2, label="pred") plt.legend() plt.grid(True, linestyle='--') plt.xlabel("$\omega$") plt.xscale('log') plt.title("Magnetude") plt.subplot(2, 1, 2) plt.semilogx(df["w"], [phi * 180 / np.pi for (r, phi) in y_true], linewidth=4, label="JCAPL") plt.semilogx(pred_df["w"], [phi * 180 / np.pi for (r, phi) in y_pred], linewidth=2, label="pred") plt.legend() plt.grid(True, linestyle='--') plt.xlabel("$\omega$") plt.xscale('log') plt.title("Phase") plt.tight_layout() if path_name is not None: plt.savefig('results/{0}/fig/gain_phase.png'.format(path_name)) if mode == "humain": plt.show() else: plt.close()
def polar(x): if mode == mode_python: return cmath.polar(x) else: return mpmath.polar(x)
def average_wind(wdir, wspd): ''' source: http://www.intellovations.com/2011/01/16/ wind-observation-calculations-in-fortran-and-python/ wdir -- Pandas DataFrame group (or numpy array) of wind directions wspd -- Pandas DataFrame group (or numpy array) of wind speeds If array is 1D each value is function of time If array is 2D axis=0 is height and axis=1 is time ''' import cmath import math if len(wdir) == 2 and isinstance(wdir, tuple): ' pandas instance ' wdir = wdir[1].values.copy() wspd = wspd[1].values.copy() else: ' numpy instance ' wdir = wdir.copy() wspd = wspd.copy() array_dim = len(wdir.shape) wdir += 180 wdir = np.radians(wdir) if array_dim == 1: ''' if 1D array ''' n_wind = len(wspd) if n_wind >= 2: wind_vector_sum = None for i in range(n_wind): wind_polar = cmath.rect(wspd[i], wdir[i] - math.pi) if wind_vector_sum is None: wind_vector_sum = wind_polar else: wind_vector_sum += wind_polar r, phi = cmath.polar(wind_vector_sum / n_wind) if np.isnan(r) and np.isnan(phi): return np.nan, np.nan else: av_wdir = np.round(math.degrees(phi), 1) if av_wdir < 0: av_wdir += 360 av_wspd = int(round(r * 10)) / 10.0 return av_wdir, av_wspd else: return None, None elif array_dim == 2: ''' if 2D array ''' hn, tn = wdir.shape av_wdir_array = np.zeros((hn, 1)) av_wspd_array = np.zeros((hn, 1)) av_wsstd_array = np.zeros((hn, 1)) av_wdstd_array = np.zeros((hn, 1)) wsnans = np.zeros((hn, 1)) wdnans = np.zeros((hn, 1)) for n in range(hn): if tn >= 2: spd = wspd[n, :] dirr = wdir[n, :] wind_vector_sum = None wind_vectors = np.array([]) wsnan = 0 wdnan = 0 for i in range(tn): if ~np.isnan(spd[i]) and ~np.isnan(dirr[i]): wind_polar = cmath.rect(spd[i], dirr[i] - math.pi) wind_vectors = np.append(wind_vectors, wind_polar) else: wsnan += 1 wdnan += 1 ''' mean ''' r, phi = cmath.polar(wind_vectors.mean()) av_wdir = np.round(math.degrees(phi), 1) if av_wdir < 0: av_wdir += 360 av_wspd = int(round(r * 10)) / 10.0 av_wdir_array[n] = av_wdir av_wspd_array[n] = av_wspd ''' std dev ''' re = wind_vectors.real.std() im = wind_vectors.imag.std() r_std, phi_std = cmath.polar(complex(re, im)) wdir_std = np.round(math.degrees(phi_std), 1) wspd_std = np.round(math.degrees(r_std), 1) av_wdstd_array[n] = wdir_std av_wsstd_array[n] = wspd_std ''' nans ''' wsnans[n] = wsnan wdnans[n] = wdnan else: av_wdir_array[n] = None av_wspd_array[n] = None av_wdstd_array[n] = None av_wsstd_array[n] = None return av_wdir_array, av_wspd_array, av_wdstd_array, av_wsstd_array, wdnans, wsnans else: print('Arrays need to be 1D or 2D')
# Enter your code here. Read input from STDIN. Print output to STDOUT # solution a import cmath print(*cmath.polar(complex(input())), sep='\n') from math import * # solution b # only work if the input are all positive a, b = input().split("+") b = b[:-1] a, b = int(a), int(b) print(sqrt(a**2 + b**2)) print(atan(b/a))
from cmath import polar polar = polar(complex(input())) print(polar[0]) print(polar[1])
def signal_to_noise(K, noise_level): image_file = Image.open( "/Users/victorstorchan/Desktop/RA/ra/apple_original signal.png" ) # open colour image image_signal = image_file.convert('L') # convert image to black and white signal = np.asarray(image_signal) (a, b) = signal.shape randommat = np.zeros((400, 400), dtype=complex) for i in range(400): for j in range(400): randommat[i][j] += complex(np.random.normal(0, noise_level, 1)) signal_noisy = np.zeros((400, 400), dtype=complex) for i in range(a): for j in range(b): signal_noisy[10 + i][10 + j] = signal[i][j] for i in range(400): for j in range(400): signal_noisy[i][j] += randommat[i][j] m = signal_noisy.shape[0] n = signal_noisy.shape[1] vect_of_shift = create_shift(K) len_shift = len(vect_of_shift) #signal with shift: shifted_signals = [] shifted_signals_1 = [] shifted_signals_2 = [] for s in range(len_shift): y = np.zeros((n, m), dtype=complex) y1 = np.zeros((n, m), dtype=complex) y2 = np.zeros((n, m), dtype=complex) for k in range(m): for l in range(n): if (l < 10 + vect_of_shift[s][0] or l > 315 + vect_of_shift[s][0]) and ( k < 10 + vect_of_shift[s][1] or k > 324 + vect_of_shift[s][1]): y[k][l] = randommat[k][l] y1[k][l] = randommat[k][l] * np.exp(2J * np.pi * k / m) y2[k][l] = randommat[k][l] * np.exp(2J * np.pi * l / n) else: y[k][l] = signal_noisy[k - vect_of_shift[s][0]][ l - vect_of_shift[s][1]] y1[k][l] = signal_noisy[k - vect_of_shift[s][0]][ l - vect_of_shift[s][1]] * np.exp(2J * np.pi * k / m) y2[k][l] = signal_noisy[k - vect_of_shift[s][0]][ l - vect_of_shift[s][1]] * np.exp(2J * np.pi * l / n) shifted_signals.append(y) shifted_signals_1.append(y1) shifted_signals_2.append(y2) A = [] A_1 = [] A_2 = [] for i in range(len(shifted_signals)): A.append(np.matrix(np.fft.fft2(shifted_signals[i]))) A_1.append(np.matrix(np.fft.fft2(shifted_signals_1[i])).conjugate()) A_2.append(np.matrix(np.fft.fft2(shifted_signals_2[i])).conjugate()) G1 = [] G2 = [] for s in range(len_shift): G1.append(np.multiply(A[s], A_1[s])) G2.append(np.multiply(A[s], A_2[s])) A_mat1 = np.zeros((len_shift, n**2), dtype=complex) A_mat2 = np.zeros((len_shift, n**2), dtype=complex) for s in range(len_shift): for i in range(n): for k in range(n): A_mat1[s][400 * i + k] = G1[s][i, k] A_mat2[s][400 * i + k] = G2[s][i, k] A_mat1_mat = np.matrix(A_mat1) A_mat2_mat = np.matrix(A_mat2) A_mat1_transpose = A_mat1_mat.getH() A_mat2_transpose = A_mat2_mat.getH() A_prod1 = A_mat1_mat * A_mat1_transpose A_prod2 = A_mat2_mat * A_mat2_transpose A_final1 = A_prod1 / A_prod1[0, 0] A_final2 = A_prod2 / A_prod2[0, 0] (V1, sigma1, V_star1) = np.linalg.svd(A_final1) (V2, sigma2, V_star2) = np.linalg.svd(A_final2) v1 = V_star1[0].getH() v2 = V_star2[0].getH() #the shifts are recovered: output1 = np.zeros(len_shift) output2 = np.zeros(len_shift) for i in range(len_shift): output1[i] = -n * polar(-v1[i, 0])[1] / (2 * np.pi).real output2[i] = -n * polar(-v2[i, 0])[1] / (2 * np.pi).real recover_A = [] for i in range(len_shift): M = np.matrix(np.zeros((m, n), dtype=complex)) for l in range(m): for k in range(n): M[l, k] = A[i][l, k] / np.exp( -2J * np.pi * (l * output1[i] + k * output2[i]) / n) recover_A.append(M) A_final = [] for i in range(len_shift): A_final.append(np.fft.ifft2(recover_A[i])) recov_signal = np.zeros((m, n)) for i in range(m): for j in range(n): k = 0 for s in range(len_shift): k += A_final[s][i][j].real recov_signal[i][j] = k / len_shift recov_signal1 = recov_signal.astype(np.uint8) return np.linalg.norm(recov_signal1 - im3)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 02:32:10 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT import cmath number = complex(input().strip()) print("%.3f" % cmath.polar(number)[0]) print("%.3f" % cmath.polar(number)[1])
def polar_complex(z): """Wrapped version of polar that returns a complex number instead of two floats.""" return complex(*polar(z))
def C_k_local(N, var, klist): sumN = np.dot(klist, np.exp(1j * var)) R, Theta = cmath.polar(sumN) return R/np.sum(klist), Theta
inRingBuffer.writeAtIdx(inHop, frame, numFramesRead) # Read buffer size from input ring buffer sig = inRingBuffer.readAtIdx(frame + blockSize, blockSize) # Apply analysis window sig1 = np.multiply(sig[:, 0], window) sig2 = np.multiply(sig[:, 1], window) # Direct FFT dft1 = fft(sig1) dft2 = fft(sig2) # Convert cartesian (real + imag) to polar (magnitude, phase) for f in range(0, blockSize): pol1[f] = cmath.polar(dft1[f]) pol2[f] = cmath.polar(dft2[f]) # Get magnitude spectra # - Fourier transform in polar form consists of the magnitude and phase spectra # - Operations / processing (boosting, attenuating) are performed on the magnitude spectrum # - Phase information needs to be preserved to perform Inverse FFT outMag1 = pol1[:, 0] outMag2 = pol2[:, 0] # Analysis window amplitude correction outMag1 = outMag1 * windowAmpCorrection outMag2 = outMag2 * windowAmpCorrection # Scale magnitude spectrum to [0.0 : 1.0] outMag1 = outMag1 / ((blockSize / 2.0) + 1.0)