def calcphibar(self,phi_set): ''' calculate centroid phases for given set input data structure [[phia_refl_1, phia_refl_2, phia_refl_3...], [phib_refl_1,phib_refl_2,phib_refl_3..], ...] average phia_refl_1, phib_refl_1,... ''' import cmath n_pop_size=len(phi_set) n_refl=len(phi_set[0]) flex_phi_bar=flex.double(n_refl) txt_phi_bar="" for i in range(n_refl): sum_phis=cmath.rect(0,0) for j in range(n_pop_size): sum_phis+=cmath.rect(1,phi_set[j][i]*math.pi/180) flex_phi_bar[i]=cmath.phase(sum_phis)*180/math.pi txt_phi_bar+=str(flex_phi_bar[i])+"," txt_phi_bar+="\n" return flex_phi_bar,txt_phi_bar
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 fix(self): """ Proceeds the fixing of the rule, if possible. """ from copy import deepcopy module = self.module a=0 if self.check(): for graph in self.bad_width: graph['width'] = 0.15 for inter in self.intersections: pad=inter['pad'] graph=inter['graph'] if 'angle' in graph: #TODO pass elif 'center' in graph: #TODO pass else: padComplex=complex(pad['pos']['x'],pad['pos']['y']) startComplex=complex(graph['start']['x'],graph['start']['y']) endComplex=complex(graph['end']['x'],graph['end']['y']) if endComplex.imag<startComplex.imag: tmp=endComplex endComplex=startComplex startComplex=tmp graph['start']['x']=startComplex.real graph['start']['y']=startComplex.imag graph['end']['x']=endComplex.real graph['end']['y']=endComplex.imag vector=endComplex-startComplex padComplex=padComplex-startComplex length=abs(vector) phase=cmath.phase(vector) vectorR=cmath.rect(1,-phase) padComplex=padComplex*vectorR distance=cmath.sqrt((pad['size']['x']/2+0.226)**2-(padComplex.imag)**2).real padMin=padComplex.real-distance padMax=padComplex.real+distance if padMin<length and padMin>0: if padMax>length: padComplex=(padMin+0j)*cmath.rect(1,phase)+startComplex graph['end']['x']=round(padComplex.real,3) graph['end']['y']=round(padComplex.imag,3) else: padComplex=(padMin+0j)*cmath.rect(1,phase)+startComplex graph2=deepcopy(graph) graph['end']['x']=round(padComplex.real,3) graph['end']['y']=round(padComplex.imag,3) padComplex=(padMax+0j)*cmath.rect(1,phase)+startComplex graph2['start'].update({'x':round(padComplex.real,3)}) graph2['start'].update({'y':round(padComplex.imag,3)}) module.lines.append(graph2) elif padMin<0 and padMax>0 and padMax<length: padComplex=(padMax+0j)*cmath.rect(1,phase)+startComplex graph['start']['x']=round(padComplex.real,3) graph['start']['y']=round(padComplex.imag,3) elif (padMax>length and padMin<0): module.lines.remove(graph)
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 fft(a,x): n = len(a) if(n <= 0): print "\nERROR going to use FFT on list of size <=0" quit() A = [complex] * n if (n==1): A[0] = a[0] return A if(x == 1): wn = complex(cmath.rect(1, 2*cmath.pi/n)) else: wn = complex(1,0)/complex(cmath.rect(1, 2*cmath.pi/n)) w = complex(1,0) n_2 = n/2 a_even = [complex] * n_2 a_odd = [complex] * n_2 for i in range(0,n_2): a_even[i] = a[i*2] a_odd[i] = a[i*2+1] A_even = fft(a_even,x) A_odd = fft(a_odd,x) for k in range(0,n_2): A[k] = A_even[k] + (A_odd[k] * w) A[k+n_2] = A_even[k] - (A_odd[k] * w) w = w * wn return A
def _mouse_release(self, widget, event): '''rotate if mouse pressed in compass N area, otherwise pan move''' cm = complex(self._mouseX, WIN_Y - self._mouseY) self._dragDeltaX = event.x - self._mouseX self._dragDeltaY = event.y - self._mouseY # position of compass pointer nloc = cmath.rect(CMPS_SIZE, self.rotate + pi / 2) cc = complex(WIN_X - 60, WIN_Y - 60) # center of big compass circle cn = nloc + complex(WIN_X - 60, WIN_Y - 60) # center of N # mouse start from little N if abs(cm - cn) <= (CMPS_N_SIZE + 3) and not self.dialog: cnew = complex(event.x, WIN_Y - event.y) k_old = cmath.rect(self.zoomlevel * SCALE, self.rotate) # center of screen cscr_c = complex(WIN_X / 2, WIN_Y / 2) rotate_new = cmath.phase(cnew - cc) - pi / 2 k_new = cmath.rect(self.zoomlevel * SCALE, rotate_new) c_new = cscr_c * (k_new - k_old) / (k_new * k_old) + self.ref self.ref = c_new self.rotate = rotate_new elif self.dialog and self._dragDeltaX == self._dragDeltaY == 0: if not self.flag_ruler_start: self.ruler_start = self.xy2wgs84(event.x, event.y) self.flag_ruler_start = True self.flag_ruler_end = False else: self.flag_ruler_end = True self.flag_ruler_start = False self.queue_draw() else: k = cmath.rect(self.zoomlevel * SCALE, self.rotate) self.ref -= complex(self._dragDeltaX, -1 * self._dragDeltaY) / k self.refresh_shoreline() self.queue_draw()
def draw_compass(self): '''draw a compass''' # out circle self.cr.set_source_rgba(1, 1, 1, 0.7) self.cr.set_line_width(3) self.cr.arc(self.size_x - 60, 60, CMPS_SIZE, 0, 2 * pi) self.cr.stroke() # position of compass pointer nloc = cmath.rect(CMPS_SIZE, self.rotate + pi / 2) x, y = nloc.real + self.size_x - 60, nloc.imag + self.size_y - 60 self.cr.arc(x, self.size_y - y, CMPS_N_SIZE + 3, 0, 2 * pi) self.cr.close_path() self.cr.fill() # draw N self.cr.set_source_rgb(0, 0, 0) shape_n = np.array([cmath.rect(CMPS_N_SIZE, self.rotate + pi * 5 / 4), cmath.rect(CMPS_N_SIZE, self.rotate + pi * 3 / 4), cmath.rect(CMPS_N_SIZE, self.rotate + pi * 7 / 4), cmath.rect(CMPS_N_SIZE, self.rotate + pi * 1 / 4)]) # move to the location of compass pointer shape_n += complex(x, y) self.cr.move_to(shape_n[0].real, self.size_y - shape_n[0].imag) for point in shape_n[1:]: self.cr.line_to(point.real, self.size_y - point.imag) self.cr.stroke()
def __init__(self,parent): lineparams_gui.__init__(self,parent) self.phase_voltage = float(self.entries[30].get())/np.sqrt(3) self.v_mat = np.array([[cmath.rect(self.phase_voltage,np.pi*0/180)],\ [cmath.rect(self.phase_voltage,np.pi*-120/180)],\ [cmath.rect(self.phase_voltage,np.pi*120/180)]]) self.voltagegradient_button = Button(self.output_frame,text="Compute Surface Voltage"\ "Gradient",font=("Fixedsys",9,"bold"),command=self.display_vg) self.voltagegradient_button.pack(side=LEFT,padx=5) self.corona_button=Button(self.output_frame,text="Corona performance",\ font=("Fixedsys",9,"bold"),command=self.display_corona) self.corona_button.pack(side=LEFT,padx=5) self.Electricfield_button = Button(self.output_frame,text="Electric field",\ font=("Fixedsys",9,"bold"),command=self.compute_display_ef) self.Electricfield_button.pack(side=LEFT,padx=5) self.Magneticfield_button = Button(self.output_frame,text="Magnetic field",\ font=("Fixedsys",9,"bold"),command=self.compute_display_mf) self.Magneticfield_button.pack(side=LEFT,padx=5) self.VolProfile_button = Button(self.output_frame,text="Voltage Profile",\ font=("Fixedsys",9,"bold"),command=self.compute_display_volprof) self.VolProfile_button.pack(side=LEFT,padx=5) self.VolProfile_button = Button(self.output_frame,text="Compensation",\ font=("Fixedsys",9,"bold"),command=self.compute_display_compensation) self.VolProfile_button.pack(side=LEFT,padx=5)
def neg_seq(mag1, ang1, mag2, ang2, mag3, ang3): e1 = cmath.rect(mag1, np.deg2rad(ang1)) e2 = cmath.rect(mag2, np.deg2rad(ang2)) e3 = cmath.rect(mag3, np.deg2rad(ang3)) a = cmath.rect(1.0, np.deg2rad(120)) V2 = (e1 + a**2*e2 + a*e3) return round(abs(V2)/3,2), round(np.rad2deg(np.angle(V2)))
def console (): expr = raw_input("Ingrese la ecuacion: ") inicial = -cm.sqrt(-1) err = 0.001 nr = NewtonRapson(0, expr, err) raiz = cm.polar(compleja(nr, inicial, err)) print cm.rect(raiz[0], raiz[1])
def zero_seq(mag1, ang1, mag2, ang2, mag3, ang3): e1 = cmath.rect(mag1, np.deg2rad(ang1)) e2 = cmath.rect(mag2, np.deg2rad(ang2)) e3 = cmath.rect(mag3, np.deg2rad(ang3)) a = cmath.rect(1.0, np.deg2rad(120)) V0 = (e1 + e2 + e3) return round(abs(V0)/3,2), round(np.rad2deg(np.angle(V0)))
def fft(poly1, poly2): #Find dimension that is greater than deg1 + deg2 and is a power of 2 dim = len(poly1) + len(poly2) - 1 dim = int(pow(2, math.ceil(math.log(dim,2)))) #determine omega in radians w = 360.0/dim w = w/180 * cmath.pi #Create matrix M M = [] for i in range(dim): row = [] for j in range(dim): row.append(cmath.rect(1,i*j*w)) M.append(row) #determine M inverse M = np.matrix(M) invM = linalg.inv(M) #Create vector V poly1_arr = [] for i in range(1,dim+1): omega = i*w sum = 0 for j in range(0, len(poly1)): sum = sum + poly1[j]*cmath.rect(1,j*omega) poly1_arr.append(sum) poly2_arr = [] for i in range(1,dim+1): omega = i*w sum = 0 for j in range(0, len(poly2)): sum = sum + poly2[j]*cmath.rect(1,j*omega) poly2_arr.append(sum) #Determine V V = [] for i in range(dim-1, -1, -1): V.append([poly1_arr[i]*poly2_arr[i]]) V = np.matrix(V) #Find the Coefficients of polynomial C = invM * V C = np.squeeze(np.asarray(C)) #Get relevant terms and store in C temp = [] temp.append(C[0].real) for i in range(dim-1, 0, -1): temp.append(C[i].real) C = temp[:(len(poly1)+len(poly2)-1)] return C
def reorient_data2D(x_values, y_values, x_sensor_angle = 0 , y_sensor_angle = 90): """ Re-orient time series data of a sensor pair, which has not been in default (x=0, y=90) orientation. Input: - x-values - Numpy array - y-values - Numpy array Note: same length for both! - If not, the shorter length is taken Optional: - Angle of the x-sensor - measured in degrees, clockwise from North (0) - Angle of the y-sensor - measured in degrees, clockwise from North (0) Output: - corrected x-values (North) - corrected y-values (East) """ x_values = np.array(x_values) y_values = np.array(y_values) try: if x_values.dtype not in ['complex', 'float', 'int']: raise if len(x_values) != len(y_values): raise except: raise MTex.MTpyError_inputarguments('ERROR - both input arrays must be of same length') if len(x_values) != len(y_values): l = min(len(x_values) , len(y_values)) x_values = x_values[:l] y_values = y_values[:l] in_array = np.zeros((len(x_values), 2), x_values.dtype) in_array[:,0] = x_values in_array[:,1] = y_values try: x_angle = math.radians(x_sensor_angle) y_angle = math.radians(y_sensor_angle) except: raise MTex.MTpyError_inputarguments('ERROR - both angles must be of type int or float') T = np.matrix( [[ np.real(cmath.rect(1,x_angle)), np.imag(cmath.rect(1,x_angle))],[np.real(cmath.rect(1,y_angle)), np.imag(cmath.rect(1,y_angle))]]) try: new_array = np.dot(in_array, T.I) except: raise MTex.MTpyError_inputarguments('ERROR - angles must define independent axes to span 2D') #print new_array.shape return new_array[:,0], new_array[:,1]
def compute_display_mf(self): #ground conductors excluded..as charge on them is usually very small self.compute_lineobj(False) phase_current = float(float(self.entries[20].get()) / \ (np.sqrt(3) * float(self.entries[30].get()))) self.phase_current = float(phase_current)*(1e+3) self.c_mat = np.array([[cmath.rect(self.phase_current,np.pi*0/180)],\ [cmath.rect(self.phase_current,np.pi*-120/180)],\ [cmath.rect(self.phase_current,np.pi*120/180)]]) if self.line_type.get()=="Single line configuration": self.a = (self.lineobj.a1,self.lineobj.a2,self.lineobj.a3) self.p = (float(self.entries[104].get()),float(self.entries[105].get())) self.smf = magnetic_field_single(self.c_mat,self.a,self.p) self.text.config(state=NORMAL) self.text.delete(1.0, END) self.text.insert(END, "\nMagnetic field at given coordinates is:\n"+str(self.smf)+" mG\n") self.text.config(state=DISABLED) h = float(self.entries[106].get()) x = list(range(-30,30,1)) f = [] for i in x: f.append(magnetic_field_single(self.c_mat,self.a,(i,h))[0][0]) ax = plt.gca() ax.spines['left'].set_position(('data',0)) plt.figure(1) plt.plot(np.array(x),np.array(f),label="Magnetic field-I in mG") plt.title('Magnetic Field'); plt.xlabel('Distance from the tower (m)'); plt.legend(loc='best') plt.show() else: self.a = (self.lineobj.a1,self.lineobj.a2,self.lineobj.a3,\ self.lineobj.a4,self.lineobj.a5,self.lineobj.a6) self.p = (float(self.entries[104].get()),float(self.entries[105].get())) self.smf = magnetic_field_double(self.c_mat,self.a,self.p) self.text.config(state=NORMAL) self.text.delete(1.0, END) self.text.insert(END, "\nMagnetic field at given coordinates is:\n"+str(self.smf)+" mG\n") self.text.config(state=DISABLED) h = float(self.entries[106].get()) x = list(range(-30,30,1)) f = [] for i in x: f.append(magnetic_field_double(self.c_mat,self.a,(i,h))[0][0]) ax = plt.gca() ax.spines['left'].set_position(('data',0)) plt.figure(1) plt.plot(np.array(x),np.array(f),label="Magnetic field-II in mG") plt.title('Magnetic Field'); plt.xlabel('Distance from the tower (m)'); plt.legend(loc='best') plt.show()
def generatepixelhillasparameters(self, showerazimuth, showeraltitude, findBDT, DCtel=None): """Uses the general shower azimuth and altitude to form the various Hillas parameters. Firstly the nearest neighbour entries are found. Then the image-specific shower direction is found. This is recorded as self.hillas.showerx/y. In addition the aspect ration is found. The cog/shower positions are passed as an argument to each pixel, to find the hillas parameters for every pixel. """ self.fillnearestneighbours() cogx = self.hillas.image_cog_x_ cogy = self.hillas.image_cog_y_ angle = math.radians(float(self.hillas.orientation_)) deltaaz = float(showerazimuth) - float(self.azimuth) deltaalt= float(showeraltitude) - float(self.altitude) showery=cmath.rect(deltaalt, math.radians(180 - float(showerazimuth))).imag showerx=cmath.rect(deltaalt, math.radians(180 - float(showerazimuth))).real self.hillas.showery = showery self.hillas.showerx = showerx width=self.hillas.width_ length=self.hillas.length_ distance = self.hillas.distance_ aspectratio = width/length self.hillas.aspect_ratio_ = aspectratio sm = (cogy-showery)/(cogx - showerx) sc = showery - (sm * showerx) itot = self.hillas.image_size_amplitude_ for pixelentry in self.pixels: pixelentry.hillas(cogx, cogy, showerx, showery, sm, sc) pixelentry.hillasparams = container() for variable in vars(self.hillas): value = getattr(self.hillas, variable) setattr(pixelentry.hillasparams, variable, value) pixelentry.dchillasparams = container() if DCtel != None: for variable in vars(DCtel.hillas): value = getattr(DCtel.hillas, variable) setattr(pixelentry.dchillasparams, variable, value) else: for variable in vars(self.hillas): setattr(pixelentry.dchillasparams, variable, None) arg = itot / (math.sin(math.radians(float(self.altitude)))*161) self.qdccut = 0.14 * math.log(arg) self.findQDCpixel() self.findrawQDCpixel() print "FindBDT is", findBDT, if findBDT == "True": print True self.findBDTpixel() else: print False
def collide(obj, obk): dist, phi = cmath.polar(obj.pos - obk.pos) rsum = obj.radius + obk.radius if dist > rsum: return obj.velocity += cmath.rect((rsum - dist) / rsum, phi) obk.velocity += cmath.rect((dist - rsum) / rsum, phi) if obj.team != obk.team: obj.hit_by(obk) obk.hit_by(obj)
def rotate(self, widget, angle): rotate_new = self.widget.rotate + angle * pi / 180 k_old = cmath.rect(self.widget.zoomlevel * SCALE, self.widget.rotate) # center of screen cm = complex(WIN_X / 2, WIN_Y / 2) k_new = cmath.rect(self.widget.zoomlevel * SCALE, rotate_new) c_new = cm * (k_new - k_old) / (k_new * k_old) + self.widget.ref self.widget.ref = c_new self.widget.rotate = rotate_new self.widget.queue_draw()
def compute_display_ef(self): #ground conductors excluded..as charge on them is usually very small self.compute_lineobj(False) self.phase_voltage = float(self.entries[30].get())/np.sqrt(3) self.v_mat = np.array([[cmath.rect(self.phase_voltage,np.pi*0/180)],\ [cmath.rect(self.phase_voltage,np.pi*-120/180)],\ [cmath.rect(self.phase_voltage,np.pi*120/180)]]) if self.line_type.get()=="Single line configuration": self.a = (self.lineobj.a1,self.lineobj.a2,self.lineobj.a3) self.p = (float(self.entries[101].get()),float(self.entries[102].get())) self.sef = electric_field_single(self.lineobj.pcc_mat(self.v_mat).transpose(),self.a,self.p) self.text.config(state=NORMAL) self.text.delete(1.0, END) self.text.insert(END, "\nElectric field at given coordinates is:\n"+str(self.sef)+" Kv/m\n") self.text.config(state=DISABLED) h = float(self.entries[103].get()) x = list(range(-30,30,1)) f = [] for i in x: f.append(electric_field_single(self.lineobj.pcc_mat(self.v_mat).transpose(),self.a,(i,h))[0][0]) ax = plt.gca() ax.spines['left'].set_position(('data',0)) plt.figure(1) plt.plot(np.array(x),np.array(f),label="Electric field-I(kv/m)") plt.title('Electric Field'); plt.xlabel('Distance from the tower (m)'); plt.legend(loc='best') plt.show() else: self.a = (self.lineobj.a1,self.lineobj.a2,self.lineobj.a3,\ self.lineobj.a4,self.lineobj.a5,self.lineobj.a6) self.p = (float(self.entries[101].get()),float(self.entries[102].get())) self.sef = electric_field_double(self.lineobj.pcc_mat(self.v_mat).transpose(),self.a,self.p) self.text.config(state=NORMAL) self.text.delete(1.0, END) self.text.insert(END, "\nElectric field at given coordinates is:\n"+str(self.sef)+" Kv/m\n") self.text.config(state=DISABLED) h = float(self.entries[103].get()) x = list(range(-30,30,1)) f = [] for i in x: f.append(electric_field_double(self.lineobj.pcc_mat(self.v_mat).transpose(),self.a,(i,h))[0][0]) ax = plt.gca() ax.spines['left'].set_position(('data',0)) plt.figure(1) plt.plot(np.array(x),np.array(f),label="Electric field-II(kv/m)") plt.title('Electric Field'); plt.xlabel('Distance from the tower (m)'); plt.legend(loc='best') plt.show()
def __init__(self, fs, tau=75e-6, fh=-1.0): """ Args: fs: sampling frequency in Hz (float) tau: Time constant in seconds (75us in US, 50us in EUR) (float) fh: High frequency at which to flatten out (< 0 means default of 0.925*fs/2.0) (float) """ gr.hier_block2.__init__(self, "fm_preemph", gr.io_signature(1, 1, gr.sizeof_float), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature # Set fh to something sensible, if needed. # N.B. fh == fs/2.0 or fh == 0.0 results in a pole on the unit circle # at z = -1.0 or z = 1.0 respectively. That makes the filter unstable # and useless. if fh <= 0.0 or fh >= fs/2.0: fh = 0.925 * fs/2.0 # Digital corner frequencies w_cl = 1.0 / tau w_ch = 2.0 * math.pi * fh # Prewarped analog corner frequencies w_cla = 2.0 * fs * math.tan(w_cl / (2.0 * fs)) w_cha = 2.0 * fs * math.tan(w_ch / (2.0 * fs)) # Resulting digital pole, zero, and gain term from the bilinear # transformation of H(s) = (s + w_cla) / (s + w_cha) to # H(z) = b0 (1 - z1 z^-1)/(1 - p1 z^-1) kl = -w_cla / (2.0 * fs) kh = -w_cha / (2.0 * fs) z1 = (1.0 + kl) / (1.0 - kl) p1 = (1.0 + kh) / (1.0 - kh) b0 = (1.0 - kl) / (1.0 - kh) # Since H(s = infinity) = 1.0, then H(z = -1) = 1.0 and # this filter has 0 dB gain at fs/2.0. # That isn't what users are going to expect, so adjust with a # gain, g, so that H(z = 1) = 1.0 for 0 dB gain at DC. w_0dB = 2.0 * math.pi * 0.0 g = abs(1.0 - p1 * cmath.rect(1.0, -w_0dB)) \ / (b0 * abs(1.0 - z1 * cmath.rect(1.0, -w_0dB))) btaps = [ g * b0 * 1.0, g * b0 * -z1 ] ataps = [ 1.0, -p1 ] if 0: print "btaps =", btaps print "ataps =", ataps global plot2 plot2 = gru.gnuplot_freqz(gru.freqz(btaps, ataps), fs, True) preemph = filter.iir_filter_ffd(btaps, ataps, False) self.connect(self, preemph, self)
def random_arma(p, q, k = 1, z_radius = 1, p_radius = 0.75): ''' Returns a random ARMA(p, q) filter. The parameters p and q define the order of the filter where p is the number of AR coefficients (poles) and q is the number of MA coefficients (zeros). k is the gain of the filter. The z_radius and p_radius paramters specify the maximum magnitude of the zeros and poles resp. In order for the filter to be stable, we should have p_radius < 1. The poles and zeros will be placed uniformly at random inside a disc of the specified radius. We also force the coefficients to be real. This is done by ensuring that for every complex pole or zero, it's recipricol conjugate is also present. If p and q are even, then all the poles/zeros could be complex. But if p or q is odd, then one of the poles and or zeros will be purely real. The filter must be causal. That is, we assert p >= q. Finally, note that in order to generate complex numbers uniformly over the disc we can't generate R and theta uniformly then transform them. This will give a distribution concentrated near (0, 0). We need to generate u uniformly [0, 1] then take R = sqrt(u). This can be seen by starting with a uniform joint distribution f(x, y) = 1/pi, then applying a transform to (r, theta) with x = rcos(theta), y = rsin(theta), calculating the distributions of r and theta, then applying inverse transform sampling. ''' assert(p >= q), 'System is not causal' P = [] Z = [] for i in range(p % 2): pi_r = stats.uniform.rvs(loc = -p_radius, scale = 2*p_radius) P.append(pi_r) for i in range((p - (p % 2)) / 2): pi_r = sqrt(stats.uniform.rvs(loc = 0, scale = p_radius)) pi_ang = stats.uniform.rvs(loc = -np.pi, scale = 2*np.pi) P.append(cmath.rect(pi_r, pi_ang)) P.append(cmath.rect(pi_r, -pi_ang)) for i in range(q % 2): zi_r = stats.uniform.rvs(loc = -z_radius, scale = 2*z_radius) Z.append(zi_r) for i in range((q - (q % 2)) / 2): zi_r = stats.uniform.rvs(loc = 0, scale = z_radius) zi_ang = stats.uniform.rvs(loc = -np.pi, scale = 2*np.pi) Z.append(cmath.rect(zi_r, zi_ang)) Z.append(cmath.rect(zi_r, -zi_ang)) b, a = signal.zpk2tf(Z, P, k) return b, a
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 c_seq(mag1, ang1, mag2, ang2, mag3, ang3): v0, a0 = zero_seq(mag1, ang1, mag2, ang2, mag3, ang3) v1, a1 = pos_seq(mag1, ang1, mag2, ang2, mag3, ang3) v2, a2 = neg_seq(mag1, ang1, mag2, ang2, mag3, ang3) e0 = cmath.rect(v0, np.deg2rad(a0)) e1 = cmath.rect(v1, np.deg2rad(a1)) e2 = cmath.rect(v2, np.deg2rad(a2)) a = cmath.rect(1.0, np.deg2rad(120)) V2 = (e0 + a*e1 + a**2*e2) return round(abs(V2),2), round(np.rad2deg(np.angle(V2)))
def generate(self): number = int(self.sampling_frequency * self.impulse_length) self.time_segment = [float(n) / self.sampling_frequency for n in range(number)] #Generating 4 sinusoids with different frequencies self.freq1 = [cmath.rect(1.0, 2 * cmath.pi * t * self.frequency) for t in self.time_segment] self.freq1 = numpy.array(self.freq1) self.freq2 = [cmath.rect(1.0, 2 * cmath.pi * t * self.frequency2) for t in self.time_segment] self.freq2 = numpy.array(self.freq2) self.freq3 = [cmath.rect(1.0, 2 * cmath.pi * t * self.frequency3) for t in self.time_segment] self.freq3 = numpy.array(self.freq3) self.freq4 = [cmath.rect(1.0, 2 * cmath.pi * t * self.frequency4) for t in self.time_segment] self.freq4 = numpy.array(self.freq4)
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 _tcf(s, x): # 1 - |a|² = |b|² = |xa|² => |a|² = 1/(|x|² + 1) a = math.sqrt(1 / (abs(x)**2 + 1)) b = a * x b_ = b.conjugate() u_A = np.array([ [ a, b], [-b_, a], ]) #t0, t1 = np.tensordot(u_A, [t0, t1], 1) u_A = kron(u_A, np.eye(4)) s1 = u_A @ s t = s1.reshape((2, 2, 2)) # Now diagonalize T₀ = U^† S V^† <=> D = U T₀ V # <=> |ψ'> = (1 ⊗ U ⊗ V^T) |ψ> U_, S, V_ = np.linalg.svd(t[0]) u_BC = kron(np.eye(2), dagger(U_), dagger(V_).T) s2 = u_BC @ s1 # Next, absorb phases into |0>_A, |1>_A, |1>_B, |1>_C: phi = {i: cmath.phase(s2[i]) for i in (0, 5, 6, 7)} A0 = cmath.rect(1, -phi[0]) A1 = cmath.rect(1, phi[7] - phi[5] - phi[6]) B = cmath.rect(1, phi[5] - phi[7]) C = cmath.rect(1, phi[6] - phi[7]) U_phase = np.array([ [[A0, 0], [0, A1]], [[1, 0], [0, B]], [[1, 0], [0, C]], ]) s3 = kron(*U_phase) @ s2 assert np.allclose(0, s3[1:4]) assert np.allclose(0, [ cmath.phase(x) for x in s3[[0, 5, 6, 7]] ]) return s3
def generate_map(sectors, radius, width, scale): """ :param sectors: number of sectors in the map :param radius: average distance between 0 and inner point of map :param width: distance between inner and outer points of map :param scale: scale of radius variation, as in np.random.normal(loc=radius, scale=scale, size=sectors) :return: list of tuples (`inner_point`, `outer_point`) of length :param sectors: """ sector_angles = get_partition(sectors, -pi, pi) sector_radii = np.random.normal(loc=radius, scale=scale, size=sectors) sector_radii[sector_radii <= 0] = 1e-6 inner_points = [rect(r, phi) for phi, r in zip(sector_angles, sector_radii)] outer_points = [rect(r, phi) for phi, r in zip(sector_angles, sector_radii + width)] return list(zip(inner_points, outer_points))
def triangle(pos, side, ang=0): r = side/(2*cos(pi/6)) p1 = pos + rect(r, 7*pi/6 + ang) p2 = pos + rect(r, pi/2 + ang) p3 = pos + rect(r, -pi/6 + ang) glBegin(GL_TRIANGLES) glColor3f(0,1,0,1) glVertex2f(p1.real, p1.imag) glColor3f(1,0,0,1) glVertex2f(p2.real, p2.imag) glColor3f(0,0,1,1) glVertex2f(p3.real, p3.imag) glEnd()
def generate_obstacles(num, radii, angles, step): obstacles = [] for i in range(num): angle = angles[i] - step/100 radius = radii[i] #radius = np.random.normal(loc=radius, scale=0.1, size=1) #obstacle_angles = get_partition(6, -pi, pi) obstacle_angles = [-pi+pi/4*i for i in range(8)] #obstacle_radii = np.random.normal(loc=radius/15, scale=0.01, size=8) obstacle_radii = [radius/15] * 8 #radius = np.random.normal(loc=radius, scale=0.01, size=1) obstacle_center = rect(radius, angle) obstacle_points = [obstacle_center + rect(r, phi) for phi, r in zip(obstacle_angles, obstacle_radii)] obstacles.append(obstacle_points) return obstacles
def lotus(root, canvas): ''' Docstring goes here ''' origin = 250+250j palette = ((origin+rect(θ*0.3, θ*π/180.0), hexString((θ % 255, int(θ*1.5) % 255, int(θ*2.5) % 255))) for θ in range(0, 360, 10)) def animate(): for pos, colour in palette: id = canvas.create_oval((pos.real-2, pos.imag-2, pos.real+2, pos.imag+2), fill=colour) for r in range(2, 9): canvas.coords(id, (pos.real-r, pos.imag-r, pos.real+r, pos.imag+r)) root.after(1000//24, lambda: next(frames)) yield # time.sleep(1.0/24) frames = animate() try: next(frames) except StopIteration: pass
def gain2matlab(msname='test1.MS', gainfilename='bbsgain.mat', timeslot=0, instrumentname='instrument'): parmdb=msname+'/'+instrumentname antenna=msname+'/ANTENNA' valstable=table(parmdb,ack=False) namestable=table(parmdb+"::NAMES",ack=False) antennatable=table(antenna,ack=False) vals=valstable.col('VALUES') names=namestable.col('NAME') antennas=antennatable.col('NAME') antennamap={}; for i in range(antennas.nrows()): antennamap[antennas[i]]=i g = np.zeros((len(antennamap)*2,2),dtype=np.complex) for i in range(vals.nrows()): (bla, xcor, ycor, reim, ant) = names[i].split(':') antnr=antennamap[ant] (xcor,ycor)=(int(xcor),int(ycor)) if reim=="Real": val=vals[i][timeslot][0] elif reim=="Imag": val=vals[i][timeslot][0]*(1.j) elif reim=="Phase": val=cmath.rect(1,vals[i][timeslot][0]) #print antnr, xcor, ycor, antnr*2+xcor, ycor, val g[antnr*2+ycor][xcor]+=val.conjugate() scipy.io.savemat(gainfilename, dict(g=g), oned_as='row') print "Stored timeslot",timeslot,"gains from", msname, "/",instrumentname,"as",gainfilename
for l in inductances: V_first_node = nodes_Voltages_sym[l.first_node] # V1 V_sec_node = nodes_Voltages_sym[l.second_node] # V2 if l.first_node != 0: equations[l.first_node] += (V_first_node - V_sec_node) * l.admittance if l.second_node != 0: equations[l.second_node] += (V_sec_node - V_first_node) * l.admittance # filling the data of the I_src for cs in Isrcs: V_p_node = nodes_Voltages_sym[cs.pos_terminal] V_n_node = nodes_Voltages_sym[cs.neg_terminal] if cs.pos_terminal != 0: equations[cs.pos_terminal] -= cmath.rect(cs.magnitude, cs.phase) if cs.neg_terminal != 0: equations[cs.neg_terminal] += cmath.rect(cs.magnitude, cs.phase) for vs in Vsrcs: V_p_node = nodes_Voltages_sym[vs.pos_terminal] V_n_node = nodes_Voltages_sym[vs.neg_terminal] equations.append(V_p_node - V_n_node - cmath.rect(vs.magnitude, vs.phase)) if vs.pos_terminal != 0: equations[vs.pos_terminal] += current_in_vs_sym[vs.id] if vs.neg_terminal != 0: equations[vs.neg_terminal] -= current_in_vs_sym[vs.id] for vccs in Vccss:
vertsface[(A,C)][B] = (faceindex,color) if not (B,C) in vertsface: vertsface[(B,C)] = {A:(faceindex,color)} else: if not A in vertsface[(B,C)]: vertsface[(B,C)][A] = (faceindex,color) if MGOLDENRATIO: goldenRatio = measurePhi() # Create wheel of red triangles around the origin triangles = [] for i in range(POLY): ## if i % 2 == 0: B = cmath.rect(1, (2*i - 1) * math.pi / POLY) C = cmath.rect(1, (2*i + 1) * math.pi / POLY) ## else: ## B = cmath.rect(0.6180339887498948, (2*i - 1) * math.pi / 10) ## C = cmath.rect(1, (2*i + 1) * math.pi / 10) if i % 2 == 0: B, C = C, B # Make sure to mirror every second triangle triangles.append((0, 0j, B, C)) # Perform subdivisions for i in range(NUM_SUBDIVISIONS): triangles = subdivide(triangles) # Prepare cairo surface ##surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, IMAGE_SIZE[0], IMAGE_SIZE[1]) ##cr = cairo.Context(surface)
def get_B(): # ============================================================================= # # Create the matrix Un: Trial mass Magnitudes Ui, U2, . . . ., UN of trial masses in the N balance planes. # ============================================================================= print() print('======Trail Masses Data======') print('******************************') U = [] for i in range(N): print("Insert Trial mass Magnitudes at Balancing Plane", i + 1) while True: try: uM, uP = [ float(x) for x in input( "Enter Magnitude in (grams)and phase (with space between): " ).split() ] u = cm.rect(uM, uP * cm.pi / 180) U.append([u]) except: print("Please Enter Valid Data!") else: break U = np.array(U) # ============================================================================= # # Trial-mass data: Bmn m = 1, . . . ., M & n = 1, , N # ============================================================================= B = [] for row in range(N): b = [] bM = 0 bP = 0 print() print("Run #", row + 1, " with trail mass @ Plane", row + 1) print("********************************************") for i in range(K): print() print("Enter Data for speed and load condition #", i + 1) print("******************************************") for col in range(L): print("Insert The vibration value at measuring plane number", col + 1, "with the trial mass @ plane", row + 1) while True: try: bM, bP = [ float(x) for x in input( "Enter Magnitude and phase (with space between): " ).split() ] bmn = cm.rect( bM, bP * cm.pi / 180) # getting the row of the the matrix B b.append(bmn) except: print("Please Enter Valid Data!") else: break B.append(b) # filling the rows of the matrix B B = np.array(B) B = np.transpose( B) # getting each column to be for each trail mass measurements B = np.subtract(B, Ae) # ============================================================================= # # Create the matrices response coefficients Alpha(MN)=(Bmn-Amn)/Un # ============================================================================= ALPHA = np.zeros((M, N), dtype=complex) if ck.confirm("The trail mass was removed each time"): for i in range(M): for j in range(N): element = (B[i, j] - A[i]) / U[j] ALPHA[i, j] = element.item(0) element = [] else: for i in range(M): element = (B[i, 0] - A[i]) / U[0] ALPHA[i, 0] = element.item(0) element = [] for i in range(M): for j in range(1, N): element = (B[i, j] - B[i, j - 1]) / U[j] ALPHA[i, j] = element.item(0) element = [] return ALPHA
def rotate(self, angle): return self.__class__(self._data * cm.rect(1.0, angle))
if color == 0: # Subdivide red triangle P = A + (B - A) / goldenRatio result += [(0, C, P, B), (1, P, C, A)] else: # Subdivide blue triangle Q = B + (A - B) / goldenRatio R = B + (C - B) / goldenRatio result += [(1, R, C, A), (1, Q, R, B), (0, R, Q, A)] return result # Create wheel of red triangles around the origin triangles = [] for i in xrange(10): B = cmath.rect(1, (2 * i - 1) * math.pi / 10) C = cmath.rect(1, (2 * i + 1) * math.pi / 10) if i % 2 == 0: B, C = C, B # Make sure to mirror every second triangle triangles.append((0, 0j, B, C)) # Perform subdivisions for i in xrange(NUM_SUBDIVISIONS): triangles = subdivide(triangles) # Prepare cairo surface surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, IMAGE_SIZE[0], IMAGE_SIZE[1]) cr = cairo.Context(surface) cr.translate(IMAGE_SIZE[0] / 2.0, IMAGE_SIZE[1] / 2.0) wheelRadius = 1.2 * math.sqrt((IMAGE_SIZE[0] / 2.0)**2 + (IMAGE_SIZE[1] / 2.0)**2)
def getExitState(target, TIME, state0): #os.chdir("./SPICE/") #constant storing the planet's basic info: [radius(km), gm, SOI radius(km)] plntConst = getConst(target, TIME) #unpack & init pos = complex(state0[0], state0[1]) #posLog = [] vel = complex(state0[2], state0[3]) gm, soi = plntConst #print("r0:",pos) #print("v:",vel) #print("gm:",gm) #print("SoI:",soi) dist = abs(pos) #print("r:",dist) #see Basyal semiMajor = 1 / (2 / dist - abs(vel)**2 / gm) specificAngMomentum = dist * abs(vel) specificOrbitalEnergy = abs(vel)**2 / 2 - gm / dist trm = dist**2 trm1 = abs(vel)**2 #print("trm:", trm) #print("trm1:",trm1) eccen = np.sqrt(1 + specificOrbitalEnergy * trm * trm1 / gm**2) #eccentricity determines shape, hyperbola eccen>1 if eccen <= 1: return False #print("a:",semiMajor) #print("e:",eccen) trueAnom = np.arccos((semiMajor * (1 - eccen**2) - dist) / (eccen * dist)) #correct quadrant of arccos for trueAnom, using the sign of flightPathAngle flightPathAngle = np.arctan(eccen * np.sin(trueAnom) / (1 + eccen * np.cos(trueAnom))) if (flightPathAngle > 0 and trueAnom < 0) or (flightPathAngle < 0 and trueAnom > 0): trueAnom *= -1 trueAnom -= np.pi #print("initAnom:",trueAnom) #actual angle = angle of position vector to the hofizontal axis, not the axis #of the hyperbola actualAngle = findAngle(pos.real, pos.imag) #print("entranceAngle:",actualAngle) exitAngle = actualAngle + 2 * trueAnom #print("exitAngle:",exitAngle) c = semiMajor * eccen centerAxisAngle = actualAngle + trueAnom center = cmath.rect(c, centerAxisAngle) #print("center position:",center) #magnitude of exiting velocity, calculated from the conservation of angular momentum exitDisplacement = specificAngMomentum / soi #find anomaly at the end by plugging in r = soi and then flipping the result exitAnom = np.arccos((semiMajor * (1 - eccen**2) - soi) / (eccen * soi)) #correct quadrant of arccos for exitAnom, using the sign of exitFlightPathAngle exitFlightPathAngle = np.arctan(eccen * np.sin(exitAnom) / (1 + eccen * np.cos(exitAnom))) if (exitFlightPathAngle > 0 and exitAnom < 0) or (exitFlightPathAngle < 0 and exitAnom > 0): exitAnom *= -1 exitAnom -= np.pi exitAnom *= -1 #print("exitAnom:",exitAnom) #calculate exit position by traversing (angularly) from r0 to rf #and plug in r = roi exitPos = cmath.rect(soi, actualAngle + trueAnom + exitAnom) #print("exitPos",exitPos) #direction of exitVel goes from center of hyperbola to exit position cToExitPos = exitPos - center #get exitVel exitVel = cmath.rect(exitDisplacement, cmath.polar(cToExitPos)[1]) #print("exitVel",exitVel) return [exitPos.real, exitPos.imag, exitVel.real, exitVel.imag]
def rect_complex(z): """Wrapped version of rect that accepts a complex number instead of two float arguments.""" return cmath.rect(z.real, z.imag)
def fourier_series(t): return_val=0 for freq in coefficients: return_val+=coefficients[freq]*cmath.rect(1,2*cmath.pi*freq*t) return(return_val)
def restore_ast(diff, zero): ast = cmath.rect(diff[1], diff[0]) ast += zero ast = complex(round(ast.real), round(ast.imag)) return ast
import cmath import time import turtle import numpy as np import math import tkinter as tk import msvcrt c1=cmath.rect(1,2*cmath.pi*3.3) print(c1) print(3*c1) #Making a complex function to find its fourier series def f(t): # #f(t) is a spiral input is time, output is a complex number # return(10*t*cmath.rect(1,7*cmath.pi*t)) # #f(t) is an oval # return(complex(4*cmath.cos(2*cmath.pi*t),3*cmath.sin(2*cmath.pi*t))) # #f(t) is a flower-shape # return(cmath.rect(4*cmath.sin(4*cmath.pi*t).real,2*cmath.pi*t)) # #f(t) is a Lissajous pattern # return(complex(4*math.sin(2*2*math.pi*t),3*math.cos(6*2*math.pi*t))) #f(t) is a step-spiral input is time, output is a complex number return(math.floor(10*t)*cmath.rect(1,7*cmath.pi*t))
def _SWSH(Ra, Rb, s, indices, values): """Compute spin-weighted spherical harmonics from rotor components This is the core function that does all the work in the computation, but it is strict about its inputs, and does not check them for validity -- though numba provides some degree of safety. _SWSH(Ra, Rb, s, indices, values) Parameters ---------- Ra : complex Component `a` of the rotor Rb : complex Component `b` of the rotor s : int Spin weight of the field to evaluate indices : 2-d array of int Array of (ell,m) values to evaluate values : 1-d array of complex Output array to contain values. Length must equal first dimension of `indices`. Needed because numba cannot create arrays at the moment. Returns ------- void The input/output array `values` is modified in place. """ N = indices.shape[0] # These constants are the recurring quantities in the computation # of the matrix values, so we calculate them here just once ra, phia = cmath.polar(Ra) rb, phib = cmath.polar(Rb) if ra <= epsilon: for i in xrange(N): ell, m = indices[i, 0:2] if (m != s or abs(m) > ell or abs(s) > ell): values[i] = 0.0j else: if (ell) % 2 == 0: values[i] = math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Rb**(-2 * s) else: values[i] = -math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Rb**(-2 * s) elif rb <= epsilon: for i in xrange(N): ell, m = indices[i, 0:2] if (m != -s or abs(m) > ell or abs(s) > ell): values[i] = 0.0j else: if (s) % 2 == 0: values[i] = math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Ra**(-2 * s) else: values[i] = -math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Ra**(-2 * s) elif ra < rb: # We have to have these two versions (both this ra<rb branch, # and ra>=rb below) to avoid overflows and underflows absRRatioSquared = -ra * ra / (rb * rb) for i in xrange(N): ell, m = indices[i, 0:2] if (abs(m) > ell or abs(s) > ell): values[i] = 0.0j else: rhoMin = max(0, -m + s) # Protect against overflow by decomposing Ra,Rb as # abs,angle components and pulling out the factor of # absRRatioSquared**rhoMin. Here, ra might be quite # small, in which case ra**(-s+m) could be enormous # when the exponent (-s+m) is very negative; adding # 2*rhoMin to the exponent ensures that it is always # positive, which protects from overflow. Meanwhile, # underflow just goes to zero, which is fine since # nothing else should be very large. Prefactor = cmath.rect( coeff(ell, -m, -s) * rb**(2 * ell + s - m - 2 * rhoMin) * ra**(-s + m + 2 * rhoMin), phib * (-s - m) + phia * (-s + m)) if (Prefactor == 0.0j): values[i] = 0.0j else: if ((ell + rhoMin) % 2 != 0): Prefactor *= -1 rhoMax = min(ell - m, ell + s) N1 = ell - m + 1 N2 = ell + s + 1 M = -s + m Sum = 1.0 for rho in xrange(rhoMax, rhoMin, -1): Sum *= absRRatioSquared * ((N1 - rho) * (N2 - rho)) / (rho * (M + rho)) Sum += 1 # Sum = 0.0 # for rho in xrange(rhoMax, rhoMin-1, -1): # Sum = ( binomial_coefficient(ell-m,rho) * binomial_coefficient(ell+m, ell-rho+s) # + Sum * absRRatioSquared ) values[i] = math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Prefactor * Sum else: # ra >= rb # We have to have these two versions (both this ra>=rb branch, # and ra<rb above) to avoid overflows and underflows absRRatioSquared = -rb * rb / (ra * ra) for i in xrange(N): ell, m = indices[i, 0:2] if (abs(m) > ell or abs(s) > ell): values[i] = 0.0j else: rhoMin = max(0, m + s) # Protect against overflow by decomposing Ra,Rb as # abs,angle components and pulling out the factor of # absRRatioSquared**rhoMin. Here, rb might be quite # small, in which case rb**(-s-m) could be enormous # when the exponent (-s-m) is very negative; adding # 2*rhoMin to the exponent ensures that it is always # positive, which protects from overflow. Meanwhile, # underflow just goes to zero, which is fine since # nothing else should be very large. Prefactor = cmath.rect( coeff(ell, m, -s) * ra**(2 * ell + s + m - 2 * rhoMin) * rb**(-s - m + 2 * rhoMin), phia * (-s + m) + phib * (-s - m)) if (Prefactor == 0.0j): values[i] = 0.0j else: if ((rhoMin + s) % 2 != 0): Prefactor *= -1 rhoMax = min(ell + m, ell + s) N1 = ell + m + 1 N2 = ell + s + 1 M = -s - m Sum = 1.0 for rho in xrange(rhoMax, rhoMin, -1): Sum *= absRRatioSquared * ((N1 - rho) * (N2 - rho)) / (rho * (M + rho)) Sum += 1 # Sum = 0.0 # for rho in xrange(rhoMax, rhoMin-1, -1): # Sum = ( binomial_coefficient(ell+m,rho) * binomial_coefficient(ell-m, ell-rho+s) # + Sum * absRRatioSquared ) values[i] = math.sqrt( (2 * ell + 1) / (4 * np.pi)) * Prefactor * Sum
def _SWSHs(Rs, s, ell, m, values): """Compute spin-weighted spherical harmonics from rotor components This is the core function that does all the work in the computation, but it is strict about its inputs, and does not check them for validity -- though numba provides some degree of safety. _SWSHs(Rs, s, ell, m, values) Parameters ---------- Rs : 2-d array of float Components of the rotors, with the 0 index iterating over rotor, and the 1 index iterating over component. s : int Spin weight of the field to evaluate ell : int m : int Values of (ell,m) to output values : 1-d array of complex Output array to contain values. Length must equal 0 dimension of `Rs`. Needed because numba cannot create arrays at the moment. Returns ------- void The input/output array `values` is modified in place. """ N = Rs.shape[0] if (abs(m) > ell or abs(s) > ell): for i in xrange(N): values[i] = 0.0j else: constant = math.sqrt((2 * ell + 1) / (4 * np.pi)) ell_even = (ell % 2 == 0) s_even = (s % 2 == 0) rhoMin_a = max(0, m + s) rhoMax_a = min(ell + m, ell + s) coefficient_a = coeff(ell, m, -s) if ((rhoMin_a + s) % 2 != 0): coefficient_a *= -1 N1_a = ell + m + 1 N2_a = ell + s + 1 M_a = -s - m rhoMin_b = max(0, -m + s) rhoMax_b = min(ell - m, ell + s) coefficient_b = coeff(ell, -m, -s) if ((ell + rhoMin_b) % 2 != 0): coefficient_b *= -1 N1_b = ell - m + 1 N2_b = ell + s + 1 M_b = -s + m for i in xrange(N): Ra = complex(Rs[i, 0], Rs[i, 3]) ra, phia = cmath.polar(Ra) Rb = complex(Rs[i, 2], Rs[i, 1]) rb, phib = cmath.polar(Rb) if ra <= epsilon: if m != s: values[i] = 0.0j elif ell_even: values[i] = constant * Rb**(-2 * s) else: values[i] = -constant * Rb**(-2 * s) elif rb <= epsilon: if m != -s: values[i] = 0.0j elif s_even: values[i] = constant * Ra**(-2 * s) else: values[i] = -constant * Ra**(-2 * s) elif ra < rb: if (coefficient_b == 0.0j): values[i] = 0.0j else: absRRatioSquared = -ra * ra / (rb * rb) Prefactor = cmath.rect( coefficient_b * rb**(2 * ell + s - m - 2 * rhoMin_b) * ra**(-s + m + 2 * rhoMin_b), phib * (-s - m) + phia * (-s + m)) Sum = 1.0 for rho in xrange(rhoMax_b, rhoMin_b, -1): Sum *= absRRatioSquared * ( (N1_b - rho) * (N2_b - rho)) / (rho * (M_b + rho)) Sum += 1 values[i] = constant * Prefactor * Sum else: # ra >= rb if (coefficient_a == 0.0j): values[i] = 0.0j else: absRRatioSquared = -rb * rb / (ra * ra) Prefactor = cmath.rect( coefficient_a * ra**(2 * ell + s + m - 2 * rhoMin_a) * rb**(-s - m + 2 * rhoMin_a), phia * (-s + m) + phib * (-s - m)) Sum = 1.0 for rho in xrange(rhoMax_a, rhoMin_a, -1): Sum *= absRRatioSquared * ( (N1_a - rho) * (N2_a - rho)) / (rho * (M_a + rho)) Sum += 1 values[i] = constant * Prefactor * Sum
def fix(self): """ Proceeds the fixing of the rule, if possible. """ from copy import deepcopy module = self.module if self.check(): for graph in self.bad_width: graph['width'] = 0.15 for inter in self.intersections: pad = inter['pad'] graph = inter['graph'] if 'angle' in graph: #TODO pass elif 'center' in graph: #TODO pass else: padComplex = complex(pad['pos']['x'], pad['pos']['y']) startComplex = complex(graph['start']['x'], graph['start']['y']) endComplex = complex(graph['end']['x'], graph['end']['y']) if endComplex.imag < startComplex.imag: tmp = endComplex endComplex = startComplex startComplex = tmp graph['start']['x'] = startComplex.real graph['start']['y'] = startComplex.imag graph['end']['x'] = endComplex.real graph['end']['y'] = endComplex.imag vector = endComplex - startComplex padComplex = padComplex - startComplex length = abs(vector) phase = cmath.phase(vector) vectorR = cmath.rect(1, -phase) padComplex = padComplex * vectorR distance = cmath.sqrt((pad['size']['x'] / 2 + 0.226)**2 - (padComplex.imag)**2).real padMin = padComplex.real - distance padMax = padComplex.real + distance if padMin < length and padMin > 0: if padMax > length: padComplex = (padMin + 0j) * cmath.rect( 1, phase) + startComplex graph['end']['x'] = round(padComplex.real, 3) graph['end']['y'] = round(padComplex.imag, 3) else: padComplex = (padMin + 0j) * cmath.rect( 1, phase) + startComplex graph2 = deepcopy(graph) graph['end']['x'] = round(padComplex.real, 3) graph['end']['y'] = round(padComplex.imag, 3) padComplex = (padMax + 0j) * cmath.rect( 1, phase) + startComplex graph2['start'].update( {'x': round(padComplex.real, 3)}) graph2['start'].update( {'y': round(padComplex.imag, 3)}) module.lines.append(graph2) elif padMin < 0 and padMax > 0 and padMax < length: padComplex = (padMax + 0j) * cmath.rect( 1, phase) + startComplex graph['start']['x'] = round(padComplex.real, 3) graph['start']['y'] = round(padComplex.imag, 3) elif (padMax > length and padMin < 0): module.lines.remove(graph)
def check(self): """ Proceeds the checking of the rule. The following variables will be accessible after checking: * f_silk * b_silk * bad_width """ module = self.module self.f_silk = module.filterGraphs('F.SilkS') self.b_silk = module.filterGraphs('B.SilkS') # check the width self.bad_width = [] for graph in (self.f_silk + self.b_silk): if graph['width'] != 0.15: self.bad_width.append(graph) # check intersections between line and pad, translate the line and pad # to coordinate (0, 0), rotate the line and pad self.intersections = [] for graph in (self.f_silk + self.b_silk): if 'angle' in graph: #TODO pass elif 'center' in graph: for pad in module.pads: padComplex = complex(pad['pos']['x'], pad['pos']['y']) padOffset = 0 + 0j if 'offset' in pad['drill']: if 'x' in pad['drill']['offset']: padOffset = complex(pad['drill']['offset']['x'], pad['drill']['offset']['y']) edgesPad = {} edgesPad[0] = complex( pad['size']['x'] / 2, pad['size']['y'] / 2) + padComplex + padOffset edgesPad[1] = complex( -pad['size']['x'] / 2, -pad['size']['y'] / 2) + padComplex + padOffset edgesPad[2] = complex( pad['size']['x'] / 2, -pad['size']['y'] / 2) + padComplex + padOffset edgesPad[3] = complex( -pad['size']['x'] / 2, pad['size']['y'] / 2) + padComplex + padOffset vectorR = cmath.rect( 1, cmath.pi / 180 * pad['pos']['orientation']) for i in range(4): edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex centerComplex = complex(graph['center']['x'], graph['center']['y']) endComplex = complex(graph['end']['x'], graph['end']['y']) radius = abs(endComplex - centerComplex) if 'circle' in pad['shape']: distance = radius + pad['size']['x'] / 2 + 0.075 if (abs(centerComplex - padComplex) < distance and abs(centerComplex - padComplex) > abs(-radius + pad['size']['x'] / 2 + 0.075)): self.intersections.append({ 'pad': pad, 'graph': graph }) else: # if there are edges inside and outside the circle, we have an intersection edgesInside = [] edgesOutside = [] for i in range(4): if abs(centerComplex - edgesPad[i]) < radius: edgesInside.append(edgesPad[i]) else: edgesOutside.append(edgesPad[i]) if edgesInside and edgesOutside: self.intersections.append({ 'pad': pad, 'graph': graph }) else: for pad in module.pads: padComplex = complex(pad['pos']['x'], pad['pos']['y']) padOffset = 0 + 0j if 'offset' in pad['drill']: if 'x' in pad['drill']['offset']: padOffset = complex(pad['drill']['offset']['x'], pad['drill']['offset']['y']) edgesPad = {} edgesPad[0] = complex( pad['size']['x'] / 2, pad['size']['y'] / 2) + padComplex + padOffset edgesPad[1] = complex( -pad['size']['x'] / 2, -pad['size']['y'] / 2) + padComplex + padOffset edgesPad[2] = complex( pad['size']['x'] / 2, -pad['size']['y'] / 2) + padComplex + padOffset edgesPad[3] = complex( -pad['size']['x'] / 2, pad['size']['y'] / 2) + padComplex + padOffset vectorR = cmath.rect( 1, cmath.pi / 180 * pad['pos']['orientation']) for i in range(4): edgesPad[i] = (edgesPad[i] - padComplex) * vectorR + padComplex startComplex = complex(graph['start']['x'], graph['start']['y']) endComplex = complex(graph['end']['x'], graph['end']['y']) if endComplex.imag > startComplex.imag: vector = endComplex - startComplex padComplex = padComplex - startComplex for i in range(4): edgesPad[i] = edgesPad[i] - startComplex else: vector = startComplex - endComplex padComplex = padComplex - endComplex for i in range(4): edgesPad[i] = edgesPad[i] - endComplex length = abs(vector) vectorR = cmath.rect(1, -cmath.phase(vector)) padComplex = padComplex * vectorR for i in range(4): edgesPad[i] = edgesPad[i] * vectorR if 'circle' in pad['shape']: distance = cmath.sqrt((pad['size']['x'] / 2)**2 - (padComplex.imag)**2).real padMinX = padComplex.real - distance padMaxX = padComplex.real + distance else: edges = [[0, 3], [0, 2], [2, 1], [1, 3]] #lines of the rectangle pads x0 = [] #vector of value the x to y=0 for edge in edges: x1 = edgesPad[edge[0]].real x2 = edgesPad[edge[1]].real y1 = edgesPad[edge[0]].imag y2 = edgesPad[edge[1]].imag if y1 != y2: x = -y1 / (y2 - y1) * (x2 - x1) + x1 if x < max(x1, x2) and x > min(x1, x2): x0.append(x) if x0: padMinX = min(x0) padMaxX = max(x0) else: continue if ((padMinX < length and padMinX > 0) or (padMaxX < length and padMaxX > 0) or (padMaxX > length and padMinX < 0)): if 'circle' in pad['shape']: distance = pad['size']['x'] / 2 padMin = padComplex.imag - distance padMax = padComplex.imag + distance else: padMin = min(edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag) padMax = max(edgesPad[0].imag, edgesPad[1].imag, edgesPad[2].imag, edgesPad[3].imag) try: differentSign = padMax / padMin except: differentSign = padMin / padMax if (differentSign < 0) or (abs(padMax) < 0.075) or ( abs(padMin) < 0.075): self.intersections.append({ 'pad': pad, 'graph': graph }) return True if (len(self.bad_width) or len(self.intersections)) else False
# -*- coding: utf-8 -*- """ Created on Wed Aug 28 14:41:27 2013 @author: jcheers """ import scipy as sp from cmath import rect from cmath import polar from math import pi from math import sqrt import numpy as np a = rect(1, (2 * pi) / 3) Amat = sp.mat([[1, 1, 1], [1, a**2, a], [1, a, a**2]]) Ainv = (1.0 / 3.0) * sp.mat([[1, 1, 1], [1, a, a**2], [1, a**2, a]]) compd = (1 / sqrt(3)) * sp.array([[0], [(1 - a)], [(1 - a**2)]]) compy = (1 / sqrt(3)) * sp.array([[0], [(1 - a**2)], [(1 - a)]]) #xr ratio curve from GE manual MW,XR) xrcurve = sp.array([[0.05, 1], [0.06, 1.3], [0.07, 1.5], [0.08, 1.7], [0.09, 1.85], [0.1, 2], [0.15, 2.4], [0.2, 2.7], [0.25, 2.9], [0.3, 3], [0.35, 3.1], [0.4, 3.2], [0.45, 3.5], [0.4999, 3.8], [0.5, 4], [0.6, 4.5], [0.7, 5], [0.8, 5.3], [0.9, 5.7], [1, 6], [1.5, 6.8], [2, 7.4], [2.5, 8], [2.9999, 8.4], [3, 10.5], [3.5, 10.8], [4, 11.3], [4.5, 11.5], [5, 12], [6, 12.7], [7, 13.5], [8, 14.1], [9, 15], [10, 15.8], [15, 19], [20, 21.8], [25, 24],
def mean_angle(deg): angle = degrees(phase(sum(rect(1, radians(d)) for d in deg) / len(deg))) if angle < 0: return 360 + angle else: return angle
def test_rect(self): self.assertCEqual(rect(0, 0), (0, 0)) self.assertCEqual(rect(1, 0), (1., 0)) self.assertCEqual(rect(1, -pi), (-1., 0)) self.assertCEqual(rect(1, pi / 2), (0, 1.)) self.assertCEqual(rect(1, -pi / 2), (0, -1.))
def main(): global alpr; global alph; global beta; global ep; global gamma; global delt; global k; global f global p; global ppr #alpr=float(raw_input("Enter Alpha Prime Value: \t")) alpr= 0.0025 #beta=float(raw_input("Enter Beta Value: \t")) beta=1.0/5.0 lambd=0.0621 gamma=0.2*f delt=1.0/120.0 ep=(lambd/(gamma*(gamma+ lambd)))*((gamma)**2 + (ppr*delt)*(gamma+lambd)) #delta= float(raw_input("Enter Undocking Rate Value: \t")) k= float(raw_input("Enter K Value: \t")) m= 1 + gamma/k theta= delt*(1+ppr*lambd/gamma) b_pr= gamma + theta -ep*(1 + gamma/k) omeg= 1 + lambd/gamma -ep- p*(lambd/gamma + delt/b_pr) n= alpr*(gamma+theta+m*(1-alpr))+ delt*p+ b_pr*lambd*ppr/gamma -(gamma+theta) print "omega:\t%5.3f\tn:\t%5.3f\tb_pr:\t%5.3f\tm:\t%5.3f\t" %(omeg,n,b_pr,m) #Coefficients of the cubic polynomial a=1 b= (2+m)*alpr -(m+gamma+theta+ep) c= (gamma+theta+m - (1+m)*alpr)*(ep-alpr) - n d= n*(ep-alpr)- lambd*ppr*delt*b_pr*omeg/gamma print "b:\t%5.3f\tc:\t%5.3f\td:\t%5.3f\t" %(b,c,d) '''Applying Tschinachius' Transformation here''' p= (3*a*c-b**2)/(3*a*a) q= (2*b**3-9*a*b*c + 27*(a*a)*d)/(27*a**3) chec1= 4*p**3 +27*q**2 chec2= 18*a*b*c*d - 4*(b**3)*d+ (b**2)*(c**2)- 4*a*(c**3) -27*(a*d)**2 print("p q check:\t%4f" %(chec1)) print("Discriminant check:\t%f" %(chec2)) i= math.pow((-((q/2)**2 +(p/3)**3)), 0.5) #Cube root is imaginary z= complex(-q/2,i) z_con= z.conjugate() za=pow(z, 1/3) print 'Predicted Cube Root Of Z:\t'+str(za) print "Z:\t"+str(z)+"\tZ Conj:\t"+str(z_con) r,phi = cmath.polar(z) r_con, phi_con = cmath.polar(z_con) #Converting To Polar Co-ordinates r= math.pow(r, 1/3) r_con=math.pow(r_con, 1/3) phi1=[]; phi_con1=[] for x in range(-2,3,2): print"x:\t%d" %(x) phi1.append((phi/3+x*cmath.pi/3)) phi_con1.append((phi_con/3+x*cmath.pi/3)) #Generating the phase values of all the different cube roots. flag=0; flag_con=0 #Stores maximum real value print "Possible Cubic Roots Of Z" for t in range(0,len(phi1)): z1=cmath.rect(r, phi1[t]) print z1 z1_con=cmath.rect(r_con, phi_con1[t]) if z1.real>= flag: flag=z1.real z=z1 if z1_con.real>= flag_con: flag_con=z1_con.real z_con=z1_con print "Maximal Principal Cube Root Of" print "Z:\t"+str(z) print "Z Conjugate:\t"+str(z_con) print "Possible Roots of Depressed Cubic" omg1=1 omg2=complex(-1/2, (math.pow(3,1/2)/2)) omg3=complex(-1/2, -(math.pow(3,1/2)/2)) #Cube Roots of Unity t=[] #Stores the roots of depressed cubic r=z_con+z t.append(r.real-b/(3*a)) print r.real r=omg2*z +omg3*z_con t.append(r.real-b/(3*a)) print r.real r=omg3*z +omg2*z_con t.append(r.real-b/(3*a)) print r.real print "Possible Roots of Actual Cubic" print t print "Checking by Other Method" roots= np.roots([a,b,c,d]) print roots
def demod(self, signal, direction=None, return_final_offset=False, start_sample=None, timestamp=None): self._errors = '' self._nsymbols = 0 level = abs(numpy.mean(signal[:16 * self._samples_per_symbol])) lmax = abs(numpy.max(signal[:16 * self._samples_per_symbol])) if self._verbose: print "level:", level print 'lmax:', lmax i = start_sample # Make sure we do not get a slightly negative index # from the correlations i = max(i, 0) symbols = [] if self._debug: self.samples = [] #Graphical debugging stuff (the *.peaks file) if self._debug: self.peaks = [complex(-lmax, 0)] * len(signal) self.turned_signal = [0 + 0j] * len(signal) mapping = [2, 1, -2, -1] # mapping: symbols->*.peaks output if self._verbose: print "len:", len(signal) phase = 0 # Current phase offset alpha = 2 # How many degrees is still fine. delay = 0 sdiff = 2 # Timing check difference low = 0 # Number of signals below threshold if (self._samples_per_symbol < 20): sdiff = 1 while True: if self._debug: self.peaks[i] = complex(-lmax, lmax / 10.) """ # Adjust our sample rate to reality try: cur=signal[i].real pre=signal[i-self._samples_per_symbol].real post=signal[i+self._samples_per_symbol].real curpre=signal[i-sdiff].real curpost=signal[i+sdiff].real if pre<0 and post<0 and cur>0: if curpre>cur and cur>curpost: if self._verbose: print "Sampled late" i-=sdiff delay-=sdiff if curpre<cur and cur<curpost: if self._verbose: print "Sampled early" i+=sdiff delay-=sdiff elif pre>0 and post>0 and cur<0: if curpre>cur and cur>curpost: if self._verbose: print "Sampled early" i+=sdiff delay+=sdiff if curpre<cur and cur<curpost: if self._verbose: print "Sampled late" i-=sdiff delay-=sdiff else: cur=signal[i].imag pre=signal[i-self._samples_per_symbol].imag post=signal[i+self._samples_per_symbol].imag curpre=signal[i-sdiff].imag curpost=signal[i+sdiff].imag if pre<0 and post<0 and cur>0: if curpre>cur and cur>curpost: if self._verbose: print "Sampled late" i-=sdiff delay-=sdiff if curpre<cur and cur<curpost: if self._verbose: print "Sampled early" i+=sdiff delay+=sdiff elif pre>0 and post>0 and cur<0: if curpre>cur and cur>curpost: if self._verbose: print "Sampled early" i+=sdiff delay+=sdiff if curpre<cur and cur<curpost: if self._verbose: print "Sampled late" i-=sdiff delay-=sdiff except IndexError: if self._verbose: print "Last sample" """ lvl = abs(signal[i]) / level ang = cmath.phase(signal[i]) / math.pi * 180 symbol, offset = self.qpsk(ang + phase) phase += offset / 5. """ if(offset>alpha): if self._debug: try: self.peaks[i+self._samples_per_symbol/10]=complex(-lmax*0.8,0); except IndexError: if self._verbose: print "Last sample" if self._verbose: print "offset forward" phase+=sdiff if(offset<-alpha): if self._debug: self.peaks[i-self._samples_per_symbol/10]=complex(-lmax*0.8,0); if self._verbose: print "offset backward" phase-=sdiff """ symbols = symbols + [symbol] if self._debug: self.samples = self.samples + [signal[i]] if self._verbose: print "Symbol @%06d (%3d°,%3.0f%%)=%d delay=%d phase=%d" % ( i, ang % 360, lvl * 100, symbol, delay, phase) if self._debug: self.peaks[i] = complex(+lmax, mapping[symbol] * lmax / 5.) self.turned_signal[i:i + self._samples_per_symbol] = signal[ i:i + self._samples_per_symbol] * cmath.rect( 1, numpy.radians(phase)) i += self._samples_per_symbol if i >= len(signal): break if abs(signal[i]) < lmax / 8.: low += 1 if low > 2: break if self._verbose: print "Done." access = "" for s in symbols[:iridium.UW_LENGTH]: access += str(s) # Do gray code on symbols data = "" oldsym = 0 dataarray = [] for s in symbols: bits = (s - oldsym) % 4 if bits == 0: bits = 0 elif bits == 1: bits = 2 elif bits == 2: bits = 3 else: bits = 1 oldsym = s data += str((bits & 2) / 2) + str(bits & 1) dataarray += [(bits & 2) / 2, bits & 1] if access == UW_DOWNLINK or access == UW_UPLINK: access_ok = True else: access_ok = False lead_out = "100101111010110110110011001111" lead_out_ok = lead_out in data if lead_out_ok: # TODO: Check if we are above 1626 MHz data = data[:data.find(lead_out)] self._nsymbols = (len(data) + len(lead_out)) / 2 self._errors = self._errors[:self._nsymbols] error_count = self._errors.count('1') confidence = (1 - float(error_count) / self._nsymbols) * 100 self._real_freq_offset = phase / 360. * iridium.SYMBOLS_PER_SECOND / self._nsymbols if self._verbose: print "access:", access_ok, "(%s)" % access print "leadout:", lead_out_ok print "len:", self._nsymbols print "confidence:", confidence print "data:", data print "final delay", delay print "final phase", phase print "frequency offset:", self._real_freq_offset if access_ok: data = "<" + data[:iridium.UW_LENGTH * 2] + "> " + data[iridium.UW_LENGTH * 2:] data = re.sub(r'([01]{32})', r'\1 ', data) if return_final_offset: return (dataarray, data, access_ok, lead_out_ok, confidence, level, self._nsymbols, self._real_freq_offset) else: return (dataarray, data, access_ok, lead_out_ok, confidence, level, self._nsymbols)
beta_l = (2 * math.pi) * length input_impedance = (z_zero * complex(z_load, z_zero * math.tan(beta_l))) / complex(z_zero, z_load*math.tan(beta_l)) i_in = v_generator / (z_generator + input_impedance) i_in_star = complex(i_in.real, -i_in.imag) v_in = i_in * input_impedance p_in = 0.5 * (v_in * i_in_star).real refl_coefficient = (z_load - z_zero) / (z_load + z_zero) v_zero_plus = v_in * (1 / (cmath.rect(1, beta_l) + complex(abs(refl_coefficient), cmath.phase(refl_coefficient) - beta_l))) v_load = v_zero_plus * (1 + refl_coefficient) i_load = (v_zero_plus / z_zero) * (1 - refl_coefficient) i_load_star = complex(i_load.real, -i_load.imag) p_load = 0.5 * (v_load * i_load_star).real p_generator = 0.5 * (v_generator * i_in).real p_z_generator = 0.5 * (abs(i_in) ** 2) * z_generator print('IN RECTANGULAR:') print(f'Zin: {input_impedance:.3f} Ohms')
def act_scout(self, view, msg): me = view.get_me() if self.x is None: self.choose_new_direction(view, msg) currentEnergy = view.get_energy().get(me.x, me.y) # Grabbing a plant is the most important thing, we get this we win plants = view.get_plants() if plants: plant = (plants[0]).get_pos() if plant != self.plant: if self.plants.count(plant) == 0: #print "Found a new plant, resetting time: " + str(len(self.plants)) msg.send_message( (MessageType.FOUNDPLANT, 0, self.id, me.x, me.y)) self.plants.append(plant) self.time = 0 self.plant = plant self.type = Type.PARENT self.search = None #print str(len(self.plants)) + " " + str(me.get_team()) return self.act_parent(view, msg) else: # Don't let this go to waste if currentEnergy >= 3: return cells.Action(cells.ACT_EAT) if self.search: if me.energy > 100: spawn_x, spawn_y = self.smart_spawn(me, view) return cells.Action(cells.ACT_SPAWN, (me.x + spawn_x, me.y + spawn_y, self)) if (currentEnergy > 3): return cells.Action(cells.ACT_EAT) # Make sure we wont die if (me.energy < 25 and currentEnergy > 1): return cells.Action(cells.ACT_EAT) # hit world wall, bounce back map_size = view.energy_map.width if me.x <= 0 or me.x >= map_size - 1 or me.y <= 0 or me.y >= map_size - 1: self.choose_new_direction(view, msg) # If I get the message of help go and rescue! if self.step == 0 and (not self.search) and (random.random() > 0.2): ax = 0 ay = 0 best = 300 + self.time / 2 message_count = len(msg.get_messages()) for m in msg.get_messages(): (type, count, id, ox, oy) = m if (id == self.id and type == MessageType.ATTACK): dist = abs(me.x - ax) + abs(me.y - ay) if count >= 2: dist /= count if dist < best and dist > 1: ax = ox ay = oy best = dist if (ax != 0 and ay != 0): dir = ax - me.x + (ay - me.y) * 1j r, theta = cmath.polar(dir) theta += 0.1 * random.random() - 0.5 dir = cmath.rect(r, theta) self.x = dir.real self.y = dir.imag # if (message_count > 1) : # # Attack the base, not the front # agent_scale = 1 + random.random() # self.x *= agent_scale # self.y *= agent_scale # don't stand still once we get there if (self.x == 0 and self.y == 0): self.x = random.randrange(-2, 2) self.y = random.randrange(-2, 2) self.step = random.randrange( 1, min(30, max(2, int((best + 2) / 2)))) self.rescue = True if not self.rescue and me.energy > cells.SPAWN_MIN_ENERGY and me.energy < 100: spawn_x, spawn_y = self.smart_spawn(me, view) return cells.Action(cells.ACT_SPAWN, (me.x + spawn_x, me.y + spawn_y, self)) # Back to step 0 we can change direction at the next attack. if self.step: self.step -= 1 return self.smart_move(view, msg)
def stringArt(img, nails_count=200, bgcolor=(255, 255, 255), color=(0, 0, 0), shape=Shape.CIRCLE): random.seed(16) # Initialize images img_basis = crop(img, shape) img_basis = cv2.resize(img_basis, (900, 900)) img_basis = Image.fromarray(img_basis) img_basis_enhancer = ImageEnhance.Brightness(img_basis) img_basis = img_basis_enhancer.enhance(1) img_basis_enhancer = ImageEnhance.Contrast(img_basis) img_basis = img_basis_enhancer.enhance(1) img_basis = np.asarray(img_basis) img_art = np.full(img_basis.shape, bgcolor, dtype=np.uint8) img_art = crop(img_art, shape) # Initialize nail locations nails = set() angle_step = 2 * cmath.pi / nails_count radius = img_art.shape[0] / 2 - 3 for i in range(nails_count): complex_rect = cmath.rect( radius, angle_step * i) + complex(*getCenter(img_art)) nails.add((round(complex_rect.real + random.random() * 3), round(complex_rect.imag + random.random() * 3))) # debug draw nails for nail in nails: cv2.circle(img_art, nail, 3, (0, 255, 0), -1) # debug show img_basis cv2.imshow("img_basis", img_basis) # Produce lines lines = set() current_nail = nails.pop() nails.add(current_nail) while True: candidate_metric = -math.inf candidate = None c_rr, c_cc = None, None for nail in nails: if nail == current_nail or (current_nail, nail) in lines: continue rr, cc = skimage.draw.line(*nail, *current_nail) line_metric = getLineMetric(img_basis, rr, cc, color) if line_metric > candidate_metric: candidate_metric = line_metric candidate = nail c_rr, c_cc = rr, cc if candidate is None: break # Add line to lines made lines.add((current_nail, candidate)) lines.add((candidate, current_nail)) # Shade img_art img_art[c_rr, c_cc] = cv2.subtract(img_art[c_rr, c_cc], 40) # Debug cv2.imshow("img_art", img_art) cv2.waitKey(1) # Move to new nail current_nail = candidate # debug cv2.imshow("img_art", img_art) return img_art
def Split(W): print() print() print("***********************") print("SPLITTING CONSTRAINTS") print("***********************") print() # ============================================================================= # ## Nh ...........get Available holes for spiltting # ============================================================================= def get_H_angles(): Nh = ck.prompt("How many Candidate holes available for splitting?", type=int) while Nh < 1: print('At least on hole should be available') Nh = ck.prompt("How many Candidate holes available for splitting?", type=int) continue H_angles = [] for i in range(Nh): h_angle = ck.prompt( "Enter the angle of hole available for for splittling", type=float) while h_angle < 0 or h_angle > 360: print('Enter angle between 0-360') Nh = ck.prompt( "Enter the angle of hole available for for splittling", type=float) continue H_angles.append(h_angle) H_angles = np.array(H_angles) return H_angles, Nh # ============================================================================= # ## Nw ...........get Available weight for balancing # ============================================================================= def get_W_tpes(): Nw = ck.prompt("How many weights types available for splitting?", type=int) while Nw < 1: print('At least on weight type should be available') Nw = ck.prompt("How many weights types available for splitting?", type=int) continue W_types = [] # List of the available holes angles for i in range(Nw): w_type = ck.prompt('Enter weight type available for splitting', type=float) while w_type < 0: print('Enter valid weight type in grams') w_type = ck.prompt('Enter weight type available for splitting', type=float) continue W_types.append(w_type) W_types = np.array(W_types) return W_types, Nw # ============================================================================= # # MATRIX OF WEIGHTS AT EVERY LOCATION # ============================================================================= H_angles, Nh = get_H_angles() W_types, Nw = get_W_tpes() W_MAT = [] for i in range(Nw): Vc_row = [] for j in range(Nh): Vc_element = cm.rect(W_types[i], H_angles[j] * cm.pi / 180) Vc_row.append(Vc_element) W_MAT.append(Vc_row) Vc_row = [] W_MAT = np.array(W_MAT) # ============================================================================= # # Define the objecive function # ============================================================================= S = cp.Variable((Nw, Nh), boolean=True) Real = cp.norm((cp.sum(cp.multiply(np.real(W_MAT), S)) - np.real(W))) Imag = cp.norm((cp.sum(cp.multiply(np.imag(W_MAT), S)) - np.imag(W))) Residules = cp.norm(cp.hstack([Real, Imag]), 2) obj_split = cp.Minimize(Residules) # ============================================================================= # # Set thelver CONSTRAINTS # ============================================================================= Nh_max = ck.prompt('Enter maximum number of weights per hole', type=int) Const1 = [cp.sum(S, axis=0) <= Nh_max] # ============================================================================= # # Solve the poblem # ============================================================================= Prob_S = cp.Problem(obj_split, Const1) Prob_S.solve(solver=cp.ECOS_BB) S = np.array(np.round(S.value)) # ============================================================================= # # PRINTING RESULTS # ============================================================================= print('PLANE #', N) print('----------------') for i in range(Nw): for j in range(Nh): if S[i, j] > 0: print(W_types[i], 'grams @', H_angles[j], 'degrees') else: print('') print('Error in Splitting the weight vector', round(Prob_S.value, 2)) return S
def pow(z, n): (module, phase) = cmath.polar(z) res = cmath.rect(math.pow(module, n), phase * n) return res
def cepTransformador(Voc, Ioc, Poc, Vsc, Isc, Psc): """ Función \"cepTransformador\" para calcular el circuito equivalente de un transformador en el lado primário, en función de sus parametros de las pruebas de circuito abierto y corto circuito. Ejemplo: cepTransformador(Voc, Ioc, Poc, Vsc, Isc, Psc) Donde: Voc = Voltaje en prueba de circuito abierto en el lado primario. Ioc = Corriente en prueba de circuito abierto en el lado primario. Poc = Potencia en prueba de circuito abierto en el lado primario. Vsc = Voltaje en prueba de corto circuito en el lado primario. Isc = Corriente en prueba de corto circuito en el lado primario. Psc = Potencia en prueba de corto circuito en el lado primario. """ # Se importan los módulos necesarios. from cmath import rect from numpy import arccos, sqrt import SchemDraw as schem import SchemDraw.elements as e from numpy.ma import round as roundC # Análisis de circuito abierto. FP_oc = Poc / (Voc * Ioc) # FP de circuito abierto Ye = rect(Ioc / Voc, -arccos(FP_oc)) Rc = roundC(sqrt((1 / Ye.real * (1 / 1000))**2), 2) Xm = roundC(sqrt((1 / Ye.imag * (1 / 1000))**2), 2) # Análisis de cortocircuito. FP_sc = Psc / (Vsc * Isc) # FP de cortocircuito Zse = rect(Vsc / Isc, -arccos(FP_sc)) Req = roundC(sqrt(Zse.real**2), 2) Xeq = roundC(sqrt(Zse.imag**2), 2) # Se imprimen los valores en pantalla. print('Rc', '\t', '=', '\t', Rc, 'kOhms') print('Xm', '\t', '=', '\t', Xm, 'kOhms') print('Req', '\t', '=', '\t', Req, 'Ohms') print('Xeq', '\t', '=', '\t', Xeq, 'Ohms') # Se genera el diagrama del circuito equivalente. d = schem.Drawing() # Terminal voltaje primario positivo. Vp_mas = d.add(e.DOT_OPEN, label='+') d.add(e.LINE, d='right', l=6) # Nodo 1 D1 = d.add(e.DOT) # Resistencia y Reactancia equivalente en serie. d.add(e.LINE, d='right', l=2, xy=D1.start) eReq = d.add(e.RES, botlabel='{} $\Omega$'.format(Req)) eReq.add_label('$R_{eq}$', loc='top') d.add(e.LINE, d='right', l=1, xy=eReq.end) eXeq = d.add(e.INDUCTOR, botlabel='j{} $\Omega$'.format(Xeq)) eXeq.add_label('$jX_{eq}$', loc='top') d.add(e.LINE, d='right', l=2, xy=eXeq.end) # Terminal voltaje secundario positivo. Vs_mas = d.add(e.DOT_OPEN, label='+') # Nodo 2 d.add(e.LINE, d='down', l=3, xy=D1.start) D2 = d.add(e.DOT) d.add(e.LINE, d='right', l=3, xy=D2.start) d.add(e.LINE, d='down', l=1) # Reactancia Xm en paralelo. eXm = d.add(e.INDUCTOR, botlabel='$j{} \ k\Omega$'.format(Xm)) eXm.add_label('$jX_m$', loc='top') d.add(e.LINE, d='down', l=1) d.add(e.LINE, d='left', l=3) # Nodo 3 D3 = d.add(e.DOT) d.add(e.LINE, d='left', l=3) d.add(e.LINE, d='up', l=1) # Resistencia Rc en paralelo eRc = d.add(e.RES, botlabel='{} k$\Omega$'.format(Rc)) eRc.add_label('$R_c$', loc='top') d.add(e.LINE, d='up', l=1) d.add(e.LINE, d='right', l=3) # Nodo 4 d.add(e.LINE, d='down', l=3, xy=D3.start) D4 = d.add(e.DOT) # Terminal Voltaje secundario negativo. d.add(e.LINE, d='right', l=11, xy=D4.start) Vs_menos = d.add(e.DOT_OPEN, label='-') # Terminal Voltaje primario negativo. d.add(e.LINE, d='left', l=6, xy=D4.start) Vp_menos = d.add(e.DOT_OPEN, label='-') # Etiqueta invisible de terminal de voltaje primario. d.add(e.GAP_LABEL, label='$V_p$', endpts=[Vp_mas.start, Vp_menos.start]) # Etiqueta invisible de terminal de voltaje secundario. d.add(e.GAP_LABEL, label='$V_s$', endpts=[Vs_mas.start, Vs_menos.start]) # Se dibuja el diagrama. d.draw()
def mean_angle(deg): return degrees(phase(sum(rect(1, radians(d)) for d in deg) / len(deg)))
def Wigner_D(Ra, Rb, twol, twomp, twom): ra, phia = cmath.polar(Ra) rb, phib = cmath.polar(Rb) epsilon = 10**(-15) if ra <= epsilon: if twomp != -twom or abs(twomp) > twol or abs(twom) > twol: return 0.0j else: if (twol - twom) % 4 == 0: return Rb**twom else: return -Rb**twom elif rb <= epsilon: if twomp != twom or abs(twomp) > twol or abs(twom) > twol: return 0.0j else: return Ra**twom elif (ra < rb): x = -ra * ra / rb / rb if (abs(twomp) > twol or abs(twom) > twol): return 0.0j else: Prefactor = cmath.rect( _coeff(twol, -twomp, twom) * rb**(twol - (twom + twomp) / 2) * ra**((twom + twomp) / 2), phib * (twom - twomp) / 2 + phia * (twom + twomp) / 2) if Prefactor == 0.0j: return 0.0j else: l = twol / 2 mp = twomp / 2 m = twom / 2 kmax = round(min(l - mp, l - m)) kmin = round(max(0, -mp - m)) if ((twol - twom) % 4 != 0): Prefactor *= -1 Sum = 1 / factorial(kmax) / factorial( l - m - kmax) / factorial(mp + m + kmax) / factorial(l - mp - kmax) for k in range(kmax - 1, kmin - 1, -1): Sum *= x Sum += 1 / factorial(k) / factorial(l - m - k) / factorial( mp + m + k) / factorial(l - mp - k) Sum *= x**(kmin) return Prefactor * Sum else: x = -rb * rb / (ra * ra) if (abs(twomp) > twol or abs(twom) > twol): return 0.0j else: Prefactor = cmath.rect( _coeff(twol, twomp, twom) * ra**(twol - twom / 2 + twomp / 2) * rb**(twom / 2 - twomp / 2), phia * (twom + twomp) / 2 + phib * (twom - twomp) / 2) if Prefactor == 0.0j: return 0.0j else: l = twol / 2 mp = twomp / 2 m = twom / 2 kmax = round(min(l + mp, l - m)) kmin = round(max(0, mp - m)) Sum = 1 / factorial(kmax) / factorial( l + mp - kmax) / factorial(l - m - kmax) / factorial(-mp + m + kmax) for k in range(kmax - 1, kmin - 1, -1): Sum *= x Sum += 1 / factorial(k) / factorial( l + mp - k) / factorial(l - m - k) / factorial(-mp + m + k) Sum *= x**(kmin) return Prefactor * Sum
def xy2wgs84(self, x, y): '''convert a point(x, y) of gtk screen to WGS84 coordinate Return: a coordinate in complex number''' k = cmath.rect(self.zoomlevel * SCALE, self.rotate) return complex(x, WIN_Y - y) / k + self.ref
def band_eigenvalues_and_eigenvectors(params,kx,ky,kz,dft_vbm,proj_vec,type_): es = params[0] ep = params[1] ed = params[2] ed_ = params[3] vss = params[4] vxx = params[5] vxy = params[6] vsp = params[7] vsdS = params[8] vpdS = params[9] vpdP = params[10] vddS = params[11] vddP = params[12] vddD = params[13] v15 = vsdS/(3.0**0.5) v18 = 0 v19 = 0 v25 = ((3**0.5)*vpdS + vpdP)/(3.0*(3.0**0.5)) v26 = ((3**0.5)*vpdS - (2.0*vpdP))/(3.0*(3.0**0.5)) v27 = v25 v28 = vpdP/(3.0**0.5) v29 = -1.0*vpdP/3.0 v38 = -1.0*v28 v39 = v29 v48 = 0.0 v49 = -2.0*v29 v55 = ((3.0*vddS)+(2.0*vddP)+(4.0*vddD))/9.0 v56 = ((3.0*vddS)-vddP-(2.0*vddD))/9.0 v57 = v56 v58 = 0.0 v78 = (vddP-vddD)/3.0 v59 = -2.0*v78/(3.0**0.5) v68 = -1.0*v78 v79 = (vddP-vddD)/(3.0*(3.0**0.5)) v69 = v79 v88 = 2.0*(vddP/3.0)+(vddD/3.0) v89 = 0.0 v99 = v88 g = 0.25*np.array([cmath.rect(1,(np.pi/2)*(kx+ky+kz)) +cmath.rect(1,(np.pi/2)*(kx-ky-kz)) +cmath.rect(1,(np.pi/2)*(-kx+ky-kz)) +cmath.rect(1,(np.pi/2)*(-kx-ky+kz)), cmath.rect(1,(np.pi/2)*(kx+ky+kz)) +cmath.rect(1,(np.pi/2)*(kx-ky-kz)) -cmath.rect(1,(np.pi/2)*(-kx+ky-kz)) -cmath.rect(1,(np.pi/2)*(-kx-ky+kz)), cmath.rect(1,(np.pi/2)*(kx+ky+kz)) -cmath.rect(1,(np.pi/2)*(kx-ky-kz)) +cmath.rect(1,(np.pi/2)*(-kx+ky-kz)) -cmath.rect(1,(np.pi/2)*(-kx-ky+kz)), cmath.rect(1,(np.pi/2)*(kx+ky+kz)) -cmath.rect(1,(np.pi/2)*(kx-ky-kz)) -cmath.rect(1,(np.pi/2)*(-kx+ky-kz)) +cmath.rect(1,(np.pi/2)*(-kx-ky+kz))],dtype=complex) gc = np.conj(g) hamiltonian = np.array([ [es, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, vss*g[0], vsp*g[1], vsp*g[2], vsp*g[3], v15*g[3], v15*g[1], v15*g[2], v18*g[0], v19*g[0]], [0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -vsp*g[1], vxx*g[0], vxy*g[3], vxy*g[2], v25*g[2], v26*g[0], v27*g[3], v28*g[1], v29*g[1]], [0.0, 0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -vsp*g[2], vxy*g[3], vxx*g[0], vxy*g[1], v27*g[1], v25*g[3], v26*g[0],-v28*g[2], v29*g[2]], [0.0, 0.0, 0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0, -vsp*g[3], vxy*g[2], vxy*g[1], vxx*g[0], v26*g[0], v27*g[2], v25*g[1], v48*g[3], v49*g[3]], [0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0, 0.0, 0.0, v15*g[3],-v25*g[2],-v27*g[1],-v26*g[0], v55*g[0], v56*g[2], v56*g[1], v58*g[3], v59*g[3]], [0.0, 0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0, 0.0, v15*g[1],-v26*g[0],-v25*g[3],-v27*g[2], v56*g[2], v55*g[0], v56*g[3], v68*g[1], v69*g[1]], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0, v15*g[2],-v27*g[3],-v26*g[0],-v25*g[1], v56*g[1], v56*g[3], v55*g[0], v78*g[2], v79*g[2]], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed_, 0.0, v18*g[0],-v28*g[1], v28*g[2],-v48*g[3], v58*g[3], v68*g[1], v78*g[2], v88*g[0], v89*g[0]], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed_, v19*g[0],-v29*g[1],-v29*g[2],-v49*g[3], v59*g[3], v69*g[1], v79*g[2], v89*g[0], v99*g[0]], [vss*gc[0],-vsp*gc[1],-vsp*gc[2],-vsp*gc[3], v15*gc[3], v15*gc[1], v15*gc[2], v18*gc[0], v19*gc[0], es, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [gc[1]*vsp, vxx*gc[0], vxy*gc[3], vxy*gc[2],-v25*gc[2],-v26*gc[0],-v27*gc[3],-v28*gc[1],-v29*gc[1], 0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [gc[2]*vsp, vxy*gc[3], vxx*gc[0], vxy*gc[1],-v27*gc[1],-v25*gc[3],-v26*gc[0], v28*gc[2],-v29*gc[2], 0.0, 0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [gc[3]*vsp, vxy*gc[2], vxy*gc[1], vxx*gc[0],-v26*gc[0],-v27*gc[2],-v25*gc[1],-v48*gc[3],-v49*gc[3], 0.0, 0.0, 0.0, ep, 0.0, 0.0, 0.0, 0.0, 0.0], [v15*gc[3], v25*gc[2], v27*gc[1], v26*gc[0], v55*gc[0], v56*gc[2], v56*gc[1], v58*gc[3], v59*gc[3], 0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0, 0.0, 0.0], [v15*gc[1], v26*gc[0], v25*gc[3], v27*gc[2], v56*gc[2], v55*gc[0], v56*gc[3], v68*gc[1], v69*gc[1], 0.0, 0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0, 0.0], [v15*gc[2], v27*gc[3], v26*gc[0], v25*gc[1], v56*gc[1], v56*gc[3], v55*gc[0], v78*gc[2], v79*gc[2], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed, 0.0, 0.0], [v18*gc[0], v28*gc[1],-v28*gc[2], v48*gc[3], v58*gc[3], v68*gc[1], v78*gc[2], v88*gc[0], v89*gc[0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed_, 0.0], [v19*gc[0], v29*gc[1], v29*gc[2], v49*gc[3], v59*gc[3], v69*gc[1], v79*gc[2], v89*gc[0], v99*gc[0], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ed_]],dtype=complex) if type_ == 0: vss = proj_vec es = LA.eigvalsh(hamiltonian) else: es, vss = LA.eigh(hamiltonian) VBM = len(es)*[dft_vbm] return es+VBM, vss
import cmath a = 2 + 4j print(a**2) print(type(a)) # type casting error<TypeError: can't convert complex to float,int> print(float(a)) # phase(x) is equivalent to math.atan2(x.imag, x.real),The result lies in the range [-π, π] print(cmath.phase(a)) # representation of a in polar coordinates print(cmath.polar(a)) # Return the complex number a,=r * (math.cos(phi) + math.sin(phi)*1j print(cmath.rect(-1.0, 1.0)) # Returns the logarithm of a to the given base print(cmath.log10(12)) # Trigonometric value print(cmath.cos(45) + cmath.sin(45) + cmath.tan(60))