def main(): print("Main Start") g = gr.Graph() g.readVertexFile('vertices.txt') g.readEdgeFile('only_with_pairs.txt') print(len(g.V)) drawing.setID(g) # вставь граф physics.setConstans(g) while True: physics.physStep(g) drawing.drawing(g) #вставь граф drawing.canvas.update() rotate.rotate(g, [1, 2, 3], 0.01)
def toGeom(self, room): self.cx = self.x + (self.width / 2.0) self.cy = self.y + (self.height / 2.0) if self.transform: a, b, c, d, e, f = self.transform # rotate the "original" center back to new position # (see rotate.py for why we need this): self.cx, self.cy = rotate((self.cx,self.cy),(a,b,c,d,e,f)) # some blocks still wind up in the wrong quadrant. :/ # i thought this might fix it but it didn't... #if cx < 0: cx = -cx #if cy < 0: cy = -cy self.ode_matrix = (a,b,0,c,d,0,e,f,1) #print r #"cx, cy = (%s,%s)" % (cx, cy) else: self.ode_matrix = None room.addGeom(pixel2world(self.cx, self.cy), px2w(self.width), px2w(self.height), transform=self.ode_matrix, id=self.id)
def do_rotate(mytext, iterations, clockwise=False): if clockwise: # Subtract from 360 degree rotation in other direction iterations = 4 - iterations for _ in range(iterations): mytext = rotate(mytext) return mytext
def turn_towards_vector(self, timestep_inc): max_degrees = self.max_turning_rate * timestep_inc dev_angle = 360.0 * np.random.normal(0, self.angular_error_sd) vector = rotate(self.desired_direction, dev_angle) check_angle = smallest_angle_to(self.direction, self.desired_direction) if check_angle <= max_degrees: self.direction = self.desired_direction elif check_angle > max_degrees: # should be able to go from the cross product to the dot product cross_product = np.cross(self.direction, self.desired_direction) if cross_product > 0: self.direction = rotate(self.direction, max_degrees) else: self.direction = rotate(self.direction, -max_degrees)
def test_rotate_works_properly(): x = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] actual = rotate(x) expected = [[1, 1, 1], [2, 2, 2], [ 3, 3, 3, ]] assert actual == expected
def binstatus1(items): object = itemsensor() open = door.door() while object == False and open == True: object = itemsensor() open = door.door() if object == True: time.sleep(2) rotate.rotate( ) #rotate objects in the top compartment 90 degrees and update items photo.photo() #capture image of the object and assign it to variable a = identify.identify() #identify object in the image captured time.sleep(7) #wait 7 seconds for object identification items[1] = a #assign object type to compartments array print(items) return (items) if object == False and open == False: return (items)
def rotate_image(im, angle): h = im.shape[0] w = im.shape[1] midx = (w - 1) / 2 midy = (h - 1) / 2 max_h = -np.Infinity max_w = -np.Infinity total_point = h * w t_xy = np.zeros((2, total_point)) if len(im.shape) == 3: values = np.zeros((w * h, 3)) else: values = np.zeros((w * h)) #获取t_yx和values for i in range(im.shape[0]): for j in range(im.shape[1]): t_xy[0][i * w + j] = j - midx #i,j与x,y坐标的换算 t_xy[1][i * w + j] = midy - i values[i * w + j] = im[i][j] #np.arctan(h/w)/np.pi*180 测试左上角点是否旋转至水平 t_xy = rotate.rotate(t_xy, angle) #获取边界 for i in range(len(t_xy[0])): if t_xy[0][i] > max_w: max_w = t_xy[0][i] if t_xy[1][i] > max_h: max_h = t_xy[1][i] #矩阵转置 t_xy = np.transpose(t_xy) #新图像大小 new_h = int(max_h * 2 + 1) new_w = int(max_w * 2 + 1) if len(im.shape) == 3: new_im = np.zeros((new_h, new_w, 3)) else: new_im = np.zeros((new_h, new_w)) new_h = new_im.shape[0] new_w = new_im.shape[1] new_midx = (new_w - 1) / 2 new_midy = (new_h - 1) / 2 #获取网格点 xi = np.zeros((new_h * new_w, 2)) for i in range(new_im.shape[0]): for j in range(new_im.shape[1]): xi[i * new_w + j][0] = j - new_midx #i,j与x,y坐标的换算 xi[i * new_w + j][1] = new_midy - i #使用scipy函数griddata实现,t_xy代表新的点的坐标,values代表点的值,xi是网格点的坐标 new_im_values = scipy.interpolate.griddata(t_xy, values, xi) for i in range(new_im.shape[0]): for j in range(new_im.shape[1]): new_im[i][j] = new_im_values[i * new_w + j] return new_im.astype('uint8')
def main2(): print("Main Start") g1 = gr.Graph() g2 = gr.Graph() g1.createCircle(2) g2.createCircle(2) g3 = gr.multiply(g1, g2) g4 = gr.multiply(g1, g3) g = gr.multiply(g1, g3) print(len(g.V)) drawing.setID(g) # вставь граф physics.setConstans(g) while True: physics.physStep(g) physics.physStep(g) drawing.drawing(g) #вставь граф drawing.canvas.update() rotate.rotate(g, [1, 2, 3], 0.001) time.sleep(1/60)
def data_augmentation(images, x_slide=None, y_slide=None, z_rotation=0, y_rotation=0, x_rotation=0, blur_max_sigma=None, noise_max_sigma=None): assert (len(images.shape) > 2) data_type = images.dtype batch_size = images.shape[0] img_rows, img_cols = images.shape[1], images.shape[2] if len(images.shape) == 4: img_channels = images.shape[3] else: img_channels = 1 rst = np.copy(images) rst = rst.astype(float) #slide if x_slide > 0 or y_slide > 0: slide(rst, img_rows, img_cols, x_slide, y_slide) #rotate if x_rotation > 0 or y_rotation > 0 or z_rotation > 0: rotate(rst, x_rotation, y_rotation, z_rotation, img_rows, img_cols) #gaussian_blur if blur_max_sigma > 0: guassian_blur(rst, blur_max_sigma) #Add noise if noise_max_sigma > 0: gaussian_noise(rst, noise_max_sigma, img_rows, img_cols, img_channels) rst = rst.astype(data_type) return rst
def vector_rotate(objs_list): #rotate objects list from sensor to ego frame global egoveh # object containing ego parameters global new #current objects list time global old # previous object list time global time # time step global count1 #count for time step calculation #global count global old_objs #previous objects list #calculate time if count1 == 0: new = objs_list.header.stamp.to_sec() time = 0.1 count1 += 1 else: old = new new = objs_list.header.stamp.to_sec() time = float((new - old)) sens = Sens() for i, a in enumerate(objs_list.obj_list): objs_list.header.frame_id = "EGOframe" a.time = objs_list.header.stamp.to_sec() ## Change the sensor position/velocity/acc origin from sensor to ego [a.geometric.x, a.geometric.y] = rotate(a.geometric.x, a.geometric.y, sens.rot.yaw) [a.geometric.vx, a.geometric.vy] = rotate(a.geometric.vx, a.geometric.vy, sens.rot.yaw) [a.geometric.ax, a.geometric.ay] = rotate(a.geometric.ax, a.geometric.ay, sens.rot.yaw) a.geometric.x = a.geometric.x + sens.pos.x a.geometric.y = a.geometric.y + sens.pos.y a.geometric.yaw += sens.rot.yaw #confirm + or - return objs_list
def update(self, *args): if self.hp <= 0: self.all_sprites.add( Coin(self.rect.x / 50, self.rect.y / 50, self.hero)) self.kill() self.hero.kills += 1 return self.shooting(self.hero, self.rect.x, self.rect.y) x = self.hero.rect.x + self.hero.rect.w // 2 y = self.hero.rect.y + self.hero.rect.h // 2 rel_x, rel_y = x - self.rect.x, y - self.rect.y angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) self.image, self.rect = rotate(self.frame, self.rect, int(angle))
def update(self): """Перемещение игрока по полю""" if self.moving: self.cur_frame = (self.cur_frame + 1) % len(self.frames) self.image = self.frames[self.cur_frame] elif len(self.motions) == 0: self.cur_frame = 0 self.moving = False mouse_x, mouse_y = pygame.mouse.get_pos() rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) self.image, self.rect = rotate(self.frames[self.cur_frame], self.rect, int(angle)) for motion in self.motions: if motion == 119: self.rect.y -= self.step for tile in self.impassable_tiles_group: if pygame.sprite.collide_mask(self, tile): self.rect.y += self.step break elif motion == 115: self.rect.y += self.step for tile in self.impassable_tiles_group: if pygame.sprite.collide_mask(self, tile): self.rect.y -= self.step break elif motion == 97: self.rect.x -= self.step for tile in self.impassable_tiles_group: if pygame.sprite.collide_mask(self, tile): self.rect.x += self.step break elif motion == 100: self.rect.x += self.step for tile in self.impassable_tiles_group: if pygame.sprite.collide_mask(self, tile): self.rect.x -= self.step break clock.tick(10)
def create_ini(self, cent, output_path, grid_max=15.0, grid_step=0.1, num_of_events=1, one_shot_ini=False, align_for_oneshot=False): smin, smax = self.get_smin_smax(cent) call([ './trento', self.config['projectile'], self.config['target'], '%s' % num_of_events, '-o', output_path, '-x', '%s' % self.config['cross_section'], '--s-min', '%s' % smin, '--s-max', '%s' % smax, '--grid-max', '%s' % grid_max, '--grid-step', '%s' % grid_step ]) if one_shot_ini: ngrid = int(2 * grid_max / grid_step) sxy = np.zeros((ngrid, ngrid), dtype=np.float32) events = os.listdir(output_path) print(events) num_of_events = 0 for event in events: try: fname = os.path.join(output_path, event) dat = np.loadtxt(fname).reshape(ngrid, ngrid) opt = reader.get_comments(fname) sd_new = rotate(dat, opt['ixcm'], opt['iycm'], opt['phi_2'], ngrid, ngrid) sxy += np.fabs(sd_new) num_of_events += 1 except: print(fname, 'is not a trento event') np.savetxt(os.path.join(output_path, "one_shot_ini.dat"), sxy / num_of_events, header=cent)
def test_rotate_positive(): result = rotate('hello', 2) expected = 'llohe' assert result == expected
option2 = args['option2'] # Load image: input_image = Image.open(args["image"]) if option or option2: if option == "bright" or option2 == "bright": from bright import brightnesss # get brightness: brightness = args["factor"] #brightness function output = brightnesss(input_image, brightness) #save to output folder save(option, output) elif option == "rotate" or option2 == "rotate": from rotate import rotate angle = args["factor"] # angle in radian output = rotate(input_image, angle) save(option, output) elif option == "scale" or option2 == "scale": # nearest neighbor algorithm from upscale import upscale p1 = args["factor"] # pixel p2 = args["factor2"] new_size = (p1, p2) output = upscale(input_image, new_size) save(option, output) elif option == "crop" or option2 == "crop": # cropping from crop import crop p1 = args["factor"] # pos p2 = args["factor2"] pos = (p1, p2) #origin
import matplotlib.pyplot as plt import rotate import math xy = [[], []] n = 3 for i in range(n): for j in range(n): xy[0].append(i) for j in range(n): xy[1].append(j) xy1 = rotate.rotate(xy, -30) maxx = math.ceil(max(xy1[0])) maxy = math.ceil(max(xy1[1])) minx = math.floor(min(xy1[0])) miny = math.floor(min(xy1[1])) xy = [[], []] for i in range(minx - 1, maxx + 1): for j in range(miny - 1, maxy + 1): xy[0].append(i) for j in range(miny - 1, maxy + 1): xy[1].append(j) plt.plot(xy[0], xy[1], 'o', color='b') plt.plot(xy1[0], xy1[1], 'o', color='r') #mx=20 #plt.plot([-mx,mx],[-mx,mx],'o',color='w')
def __init__(self, lst_of_models, opp=False): self.num_aa = [x.num_aa for x in lst_of_models] self.schedule = {} self.grid = {} self.max_aa = max(self.num_aa) for i in range(4 * self.max_aa): for j in range(4 * self.max_aa): for k in range(4 * self.max_aa): self.grid[(i, j, k)] = (0, 0) # create aa for k in range(len(lst_of_models)): aa_lst = [x for x in lst_of_models[k].schedule] if opp: for i, aa in enumerate(aa_lst): x1, y1, z1 = lst_of_models[k].schedule[aa].pos_ca x2, y2, z2 = lst_of_models[k].schedule[aa].pos_side if i % 2 == 0: move = len(aa_lst) else: move = 0 piv = (len(aa_lst), len(aa_lst), len(aa_lst)) pt = (x1, y1, z1) x1, y1, z1 = rotate( piv, rotate(piv, rotate(piv, pt, (0, 1, -1)), (-1, 0, 1)), (-1, 1, 0)) pt = (x2, y2, z2) x2, y2, z2 = rotate( piv, rotate(piv, rotate(piv, pt, (0, 1, -1)), (-1, 0, 1)), (-1, 1, 0)) pt1 = (x1 + move, y1 + move, z1 + move) pt2 = (x2 + move, y2 + move, z2 + move) a = AminoAgent(pt1, pt2, self, i, aa) self.grid[pt1] = (i + 1, k) self.grid[pt2] = (i + 1, k) self.schedule[(i, k)] = a else: for i, aa in enumerate(aa_lst): x1, y1, z1 = lst_of_models[k].schedule[aa].pos_ca x2, y2, z2 = lst_of_models[k].schedule[aa].pos_side if i % 2 == 0: move = len(aa_lst) else: move = 0 piv = (len(aa_lst), len(aa_lst), len(aa_lst)) pt = (x1, y1, z1) x1, y1, z1 = rotate( piv, rotate(piv, rotate(piv, pt, (0, 1, -1)), (-1, 0, 1)), (-1, 1, 0)) pt = (x2, y2, z2) x2, y2, z2 = rotate( piv, rotate(piv, rotate(piv, pt, (0, 1, -1)), (-1, 0, 1)), (-1, 1, 0)) pt1 = (x1 + move, y1 + move, z1 + move) pt2 = (x2 + move, y2 + move, z2 + move) a = AminoAgent(pt1, pt2, self, i, aa) self.grid[pt1] = (i + 1, k) self.grid[pt2] = (i + 1, k) self.schedule[(i, k)] = a self.energies = [[1 / (x - 1) for i in range(x - 1)] for x in self.num_aa]
def addCoord(dm, plot = False): """ Adds coordinates to dm Arguments: dm --- A datamatrix instance. Keyword arguments: plot --- Boolean indicating whether or not to show some debug plots """ exp = dm["expId"][0] # HACK: # Only symmetrical objects: if exp != "004C": dm = dm.select("symm == 'asymm'") # Add col headers: # HACK: Only first 5 saccades (otherwise it becomes too slow, and the trials # with a lot of fixations are probably non-representative, e.g. just after # a break, anyway) #for sacc in range(1, int(max(dm["saccCount"])) + 1): for sacc in range(1, 6): dm = dm.addField("xRot%s" % sacc, default = -1000) dm = dm.addField("yRot%s" % sacc, default = -1000) dm = dm.addField("xFlipped%s" % sacc, default = -1000) dm = dm.addField("yFlipped%s" % sacc, default = -1000) dm = dm.addField("xNorm%s" % sacc, default = -1000) dm = dm.addField("yNorm%s" % sacc, default = -1000) dm = dm.addField("xNormOnCenter%s" % sacc, default = -1000) dm = dm.addField("yNormOnCenter%s" % sacc, default = -1000) # In the first experiment: add 'corrected' LPs: if dm["expId"][0] == "004A": dm = dm.addField("xNormCorr%s" % sacc, default = -1000) dm = dm.addField("wBoxScaled") dm = dm.addField("hBoxScaled") dm = dm.addField("xCogScaled") dm = dm.addField("xCogScaledDegr") dm = dm.addField("xCogNorm") dm = dm.addField("stimFile", dtype = str) count = 0 # Walk through trials: for i in dm.range(): # Get file info: aRot = dm["realAngle"][i] xStim = dm["xStim"][i] yStim = dm["yStim"][i] #xCog = dm["xCog"][i] vf = dm["visual_field"][i] flipCond = dm["flip"][i] # Log new info: # PNG name: # TODO: is this okay for 004A and 004B too?? stimFile = "%s_%s.png" % (dm["stim_type"][i], dm["stim_name"][i]) dm["stimFile"][i] = stimFile # Scaled cog: xCog = dm["xCog"][i] xCogScaled = xCog/3 dm["xCogScaled"][i] = xCogScaled # Size bounding box wBoxScaled, hBoxScaled = bbox.bbox(stimFile) dm["wBoxScaled"][i] = wBoxScaled dm["hBoxScaled"][i] = hBoxScaled # Scaled cog in degrees: xCogScaledDegr = dm["xCogScaled"][i]/constants.ratio dm["xCogScaledDegr"][i] = xCogScaledDegr # Cog normalized on object width: dm["xCogNorm"][i] = dm["xCogScaled"][i]/dm["wBoxScaled"][i] # Walk through fixations within trial: saccTot = int(dm["saccCount"][i]) for sacc in range(1,saccTot +1): # HACK: Are there really trials containing more than 10 saccades? # If so, do we want these saccades anyway? if sacc > 5: continue # Get raw coordinates: x = dm["sacc%s_ex" % sacc][i] y = dm["sacc%s_ey" % sacc][i] # Normalize such that origin = (0,0): xNormOnCenter, yNormOnCenter = centralOrigin.centralOrigin(x, y,plot=plot) # Rotate as if object was presented at -90 in UVF: xRot, yRot= rotate.rotate(xNormOnCenter,yNormOnCenter, \ aRot,plot=plot) # Normalize on orientation, as if handle was always to the right. xNormOnFlip, yNormOnFlip = flip.flip(xRot, \ yRot,flipCond, vf, plot=plot) # Normalize on object width: xNormOnWidth, yNormOnWidth = normOnWidth.normOnWidth(xNormOnFlip, yNormOnFlip, wBoxScaled, hBoxScaled, yStim) # Save new variables: dm["xRot%s" % sacc][i] = xRot dm["yRot%s" % sacc][i] = yRot dm["xNorm%s" % sacc][i] = xNormOnWidth dm["yNorm%s" % sacc][i] = yNormOnWidth dm["xNormOnCenter%s" % sacc][i] = xNormOnCenter dm["yNormOnCenter%s" % sacc][i] = yNormOnCenter dm["xFlipped%s" % sacc][i] = xNormOnFlip dm["yFlipped%s" % sacc][i] = yNormOnFlip # TODO: CHECK!!! if dm["expId"][i] == "004A": dm["xNormCorr%s" % sacc][i] = dm["xNorm%s" % sacc][i] - \ dm["xCogNorm"][i] return dm
elif pos[1] - PLAYER_LENGTH // 2 <= 0: pos = (pos[0], PLAYER_LENGTH // 2) move = DOWN rotation = 0 elif pos[1] + PLAYER_LENGTH // 2 >= WINDOW_HEIGHT: pos = (pos[0], WINDOW_HEIGHT - PLAYER_LENGTH // 2) move = UP rotation = 180 facing = move if facing[0] == 0 and facing[1] == 0: facing = UP rotation = 180 # triangle: tip, left & right shoulders offset = PLAYER_WIDTH // 2 tipRelative = rotate((0, offset), rotation) lsRelative = rotate((offset, -offset), rotation) rsRelative = rotate((-offset, -offset), rotation) tip = (pos[0] + tipRelative[0], pos[1] + tipRelative[1]) ls = (pos[0] + lsRelative[0], pos[1] + lsRelative[1]) rs = (pos[0] + rsRelative[0], pos[1] + rsRelative[1]) print("rot: " + str(rotation) + ", ls = " + str(lsRelative) + ", rs = " + str(rsRelative)) pygame.draw.polygon(surface, PLAYER_COLORS[color], (tip, rs, ls)) pygame.display.update() mainClock.tick(4)
def FTIR(lst, pad_factor=16, apdzr=None, apodize_method='Blackman-Harris-3', pcpoints=512, **kwargs): """ applies a FFT to the supplied interferogram factor is the power of 2 used to zero pad the interferogram apodize_method is the apodization window method to be used apdzr (if provided) is an instance of the apodizer class (this can avoid redefinition of the same method for multiple calls of FTIR) apodize_method defines the apodization method to be used if no apodizer instance is supplied pcpoints defines the number of points around the zpd that will be used for phase correction kwargs allows for the function to be called from another function, allowing that function to supply the keywords """ def extract_centerburst(interferogram, points=512): """ extracts the n number of points surrounding the centerburst if the script cannot find n points centered around the zpd, the number of points will be narrowed to keep the zpd centered """ zpd = np.where( interferogram == max(interferogram))[0][0] # find the zpd if zpd < points / 2: return interferogram[:zpd * 2] else: return interferogram[zpd - points / 2:zpd + points / 2] def Mertz_phase_correct(interferogram, ftresult): """ phase corrects the interferogram using the Mertz method the interferogram is expected to be rotated the ftresult is the output of the fft of the interferogram series of steps: - FFT the apodized, rotated interferogram - calculate the ratio of imaginary/real along the axis - take the arctan of that ratio (this is the power spectrum) - take the cosine and sine of the power spectrum - multiply the real part of the FT result by the cosine - multiply the imaginary part of the FT result by the sine - return the sum of the these as the phase corrected spectrum """ narrowed = extract_centerburst(interferogram, pcpoints) # extract centerburst narrowed = apdzr.apodize(narrowed, about='center') # apodize about the center #narrowed.resize(2**pad_factor) # zero pad rotated = rotate(narrowed) # rotate fftpc = np.fft.fft(rotated) # apply discrete FFT powspec = np.arctan(fftpc.imag / fftpc.real) # calculate the power spectrum powspec = np.interp( np.arange(len(ftresult)), np.linspace(0, len(ftresult), len(powspec)), powspec ) # apply a linear interpolation to make the array the appropriate size return (ftresult * np.exp(-np.complex(0, 1) * powspec) ).real # phase correct the supplied ftresult def pipramp(interferogram): """ multiplies the double-sided portion of the interferogram by a ramp to avoid wiggles the ramp goes from 0 at the beginning of the interferogram to 1 at 2 times the zpd location, and remain at one for the remainder of the pulse """ zpd = np.where( interferogram == max(interferogram))[0][0] # find the zpd y = np.linspace(-0.5, 0.5, zpd * 2) # generate the ramp y -= 0.5 # shift so that all values are negative y.resize(len(interferogram) ) # pad with zeros to the length of the interferogram y += 1. # shift y return interferogram * y try: np except NameError: # import numpy if not already defined import numpy as np try: rotate except NameError: # import rotate if not already defined from rotate import rotate if apdzr is None: # if the function has not been handed an apodizer instance, create one from _apodizer import apodizer apdzr = apodizer(apodize_method) ifg = lst - sum(lst) / len( lst) # shift the interferogram to be centered at zero #ifg = lst # do not apply the zeroing apdzd = apdzr.apodize(ifg, about='zpd') # apodize about the zpd apdzd = pipramp(apdzd) # ramp to remove wiggles apdzd.resize(2**pad_factor) # zero pad rtd = rotate(apdzd) # rotate ft = np.fft.fft(rtd) # fft pc = Mertz_phase_correct(ifg, ft) # phase correct return pc[:len(pc) / 2]
def test_small_rotate(): assert rotate("hello", 2) == "llohe" assert rotate("hello", -2) == "lohel"
def ASYM(cutimage, maskimage, ini_xcntr, ini_ycntr, pa, one_minus_eg_sq, r50, background, ext_rad, angle, flag_image, ABS_ZSUM): if flag_image == 0: maskimage = 'BMask.fits' # it is just for the testing code # otheriwse BackMask.fits co = np.cos(pa * np.pi / 180.0) si = np.sin(pa * np.pi / 180.0) Aabs = np.zeros(9) Aabs = Aabs.astype(np.float32) rot_sum = np.zeros(9) rot_sum = rot_sum.astype(np.float32) abs_zsum = np.zeros(9) abs_zsum = abs_zsum.astype(np.float32) sh_sum = np.zeros(9) sh_sum = sh_sum.astype(np.float32) absres_sum = np.zeros(9) absres_sum = absres_sum.astype(np.float32) f = pyfits.open(cutimage) z = f[0].data z = z - background f.close() fm = pyfits.open(maskimage) zm = fm[0].data fm.close() # Rotate the mask rzm = rotate(zm, 180.0, ini_xcntr, ini_ycntr) mask = zm + rzm # Adding rotated and original mask center_rad = 0.01 * r50 # 0.01 * r50 The centering correction has to # be done by calculating asymmetric parameters # at different points 0.1% of r50 away around #the center flag_center = 0 # flag_center=1 if the program finds the # exact center else center=0 nn = 0 # This nn is given here and the following loop run either # it finds the minimum asymmetry or n=20 while flag_center == 0: flag_out = 0 # x and y coordinates of different center points in 1-d array xcntr = np.reshape(np.array([[ini_xcntr] * 3, \ [ini_xcntr - center_rad] * 3, \ [ini_xcntr + center_rad] * 3]), (9, )) xcntr = xcntr.astype(np.float32) ycntr = np.array([ini_ycntr, ini_ycntr - center_rad, \ ini_ycntr + center_rad]*3) ycntr = ycntr.astype(np.float32) for iter in range(9): # The below is done in order to keep the # extraction radius inside the image. If the # extraction radius goes outside the image # then flag_out=1 CutImDa, cut_xcntr, cut_ycntr, SizeY, SizeX, ymin, \ ymax, xmin, xmax, flag_out = \ ImSec(z, xcntr[iter], ycntr[iter], ext_rad) if flag_image == 0: # flag_image will tell whether the input is \ # image (flag_image=1) or background flag_out = 0 x = np.reshape(np.arange(SizeX * SizeY), (SizeY, SizeX)) % SizeX x = x.astype(np.float32) y = np.reshape(np.arange(SizeX * SizeY), (SizeY, SizeX)) / SizeX y = y.astype(np.float32) tx = (x - cut_xcntr) * co + (y - cut_ycntr) * si ty = (cut_xcntr - x) * si + (y - cut_ycntr) * co R = np.sqrt(tx**2.0 + ty**2.0 / one_minus_eg_sq) # print xcntr[iter] , ycntr[iter] rz = rotate(CutImDa, 180.0, cut_xcntr, cut_ycntr) res = CutImDa - rz masksub = mask[ymin:ymax, xmin:xmax].copy() # If want to check the rotated image and cutout image # uncomment the following for myfile in ['Rotated.fits', 'CutImDa.fits']: if os.access(myfile, os.F_OK): os.remove(myfile) mrz = ma.masked_array(CutImDa, masksub) mrz = ma.filled(mrz, 0) mrz[R > 50] = 0 hdu = pyfits.PrimaryHDU(mrz) hdu.writeto('Rotated.fits') hdu = pyfits.PrimaryHDU(CutImDa) hdu.writeto('CutImDa.fits') # raw_input() # END sh_sum[iter] = ma.masked_array(CutImDa, masksub) \ [np.where(R <= ext_rad)].sum() rot_sum[iter] = ma.masked_array(rz, masksub) \ [np.where(R <= ext_rad)].sum() abs_zsum[iter] = abs(ma.masked_array(CutImDa, masksub) \ [np.where(R <= ext_rad)]).sum() absres_sum[iter] = abs(ma.masked_array(res, masksub) \ [np.where(R <= ext_rad)]).sum() if(flag_image): Aabs[iter] = absres_sum[iter] / (abs_zsum[iter]) else: Aabs[iter] = absres_sum[iter] / (ABS_ZSUM) Aabso = Aabs.min() index = Aabs.argmin() if(nn > 20): xcntr[index] = ini_xcntr ycntr[index] = ini_ycntr if(xcntr[index] == ini_xcntr and ycntr[index] == ini_ycntr): flag_center = 1 rz = rotate(CutImDa, 180.0, cut_xcntr, cut_ycntr) res = CutImDa - rz rot_sum = rot_sum[index] abs_zsum = abs_zsum[index] if flag_image == 0: abs_zsum = ABS_ZSUM sh_sum = sh_sum[index] absres_sum = absres_sum[index] if(flag_image): error_asym = np.sqrt( Aabso**2*( ((sh_sum + rot_sum + 4 * \ background * \ R[np.where(R <= np.floor(ext_rad))].size) \ / absres_sum**2.0) + ((sh_sum + 2.0 * background * \ R[np.where(R <= np.floor(ext_rad))].size) \ / abs_zsum**2) ) ) else: error_asym = np.sqrt( Aabso**2 * (((sh_sum+rot_sum + 2 * \ background * \ R[np.where(R <= np.floor(ext_rad))].size) \ / absres_sum**2.0) + ((sh_sum + 2.0 * background * \ R[np.where(R <= np.floor(ext_rad))].size) \ / abs_zsum**2) ) ) else: ini_xcntr = xcntr[index] ini_ycntr = ycntr[index] nn += 1 print Aabso, error_asym, ini_xcntr, ini_ycntr, nn, flag_out,\ abs_zsum, sh_sum, ext_rad return Aabso, error_asym, ini_xcntr, ini_ycntr, nn, flag_out,\ abs_zsum, sh_sum, ext_rad
def test_rotate_negative(): result = rotate('hello', -2) expected = 'lohel' assert result == expected
def main(path): print("Working on it, please have patience") src_dir = 'data2/' + path df = pd.read_csv('data2/val_csv.csv', sep=',') br = 0 for filename in glob.glob(os.path.join(src_dir, '*.jpg')): im = cv2.imread(filename) name = filename.replace(src_dir, '') img_name = name.replace('.jpg', '') img_name = img_name.replace('\\', '') preprocessed = preprocessing(im, img_name, df) create_mask_of_tag(preprocessed, img_name, df) br += 1 print(br) src_dir = 'data2/masked_val/small vehicle' dst_dir = 'data2/masked_rotated_h_val/' for filename in glob.glob(os.path.join(src_dir, '*.jpg')): im = cv2.imread(filename) name = filename.replace(src_dir, '') tag_name = name.replace('.jpg', '') tag_name = tag_name.replace('\\', '') rot = rotate(im, tag_name, df) rot_h = rotate_horizontal_and_resize(rot, (30, 75)) tag_id_new = int(tag_name) selection = df[df.tag_id == tag_id_new] for idx, row in selection.iterrows(): if str(row.general_class) == "small vehicle": add_dst = 'small vehicle/' if str(row.sub_class) == "sedan": cv2.imwrite( dst_dir + add_dst + 'sedan/' + str(row.tag_id) + '.jpg', rot_h) elif str(row.sub_class) == "hatchback": cv2.imwrite( dst_dir + add_dst + 'hatchback/' + str(row.tag_id) + '.jpg', rot_h) elif str(row.sub_class) == "minivan": cv2.imwrite( dst_dir + add_dst + 'minivan/' + str(row.tag_id) + '.jpg', rot_h) elif str(row.sub_class) == "van": cv2.imwrite( dst_dir + add_dst + 'van/' + str(row.tag_id) + '.jpg', rot_h) elif str(row.sub_class) == "jeep": cv2.imwrite( dst_dir + add_dst + 'jeep/' + str(row.tag_id) + '.jpg', rot_h) elif str(row.sub_class) == "pickup": cv2.imwrite( dst_dir + add_dst + 'pickup/' + str(row.tag_id) + '.jpg', rot_h) br += 1 print(br) # preparing data for predictions size = (30, 75) X_eval = list() y_eval = list() X_tag = list() # hatchback files = os.listdir('data2/masked_rotated_h_val/small vehicle/hatchback/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/hatchback/' + files[i], size)) y_eval.append(0) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # jeep files = os.listdir('data2/masked_rotated_h_val/small vehicle/jeep/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/jeep/' + files[i], size)) y_eval.append(1) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # minivan files = os.listdir('data2/masked_rotated_h_val/small vehicle/minivan/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/minivan/' + files[i], size)) y_eval.append(2) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # pickup files = os.listdir('data2/masked_rotated_h_val/small vehicle/pickup/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/pickup/' + files[i], size)) y_eval.append(3) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # sedan files = os.listdir('data2/masked_rotated_h_val/small vehicle/sedan/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/sedan/' + files[i], size)) y_eval.append(4) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # van files = os.listdir('data2/masked_rotated_h_val/small vehicle/van/') files.sort() for i in range(0, len(files)): X_eval.append( transform_image( 'data2/masked_rotated_h_val/small vehicle/van/' + files[i], size)) y_eval.append(5) tag = files[i].replace('.jpg', '') X_tag.append(int(tag)) # stacking the arrays X_eval = np.vstack(X_eval) labels_index = { 0: "hatchback", 1: "jeep", 2: "minivan", 3: "pickup", 4: "sedan", 5: "van" } # load the model cnn_classifier = tf.keras.models.load_model( 'data2/vehicle_classification_model_dropout.h5') cnn_pred = cnn_classifier.predict_classes(X_eval, batch_size=32) pretty_cm(cnn_pred, y_eval, labels_index) correctly_classified_indices, misclassified_indices = evaluation_indices( cnn_pred, y_eval) plt.figure(figsize=(36, 6)) shuffle(correctly_classified_indices) plt.show() for plot_index, good_index in enumerate(correctly_classified_indices[0:5]): plt.subplot(1, 5, plot_index + 1) plt.imshow(X_eval[good_index]) plt.title('Predicted: {}, Actual: {}'.format( labels_index[cnn_pred[good_index]], labels_index[y_eval[good_index]]), fontsize=5) plt.show() print(X_tag) print(list(cnn_pred)) print(y_eval) predicted_dict = dict(zip(X_tag, list(cnn_pred))) actual_dict = dict(zip(X_tag, y_eval)) print(len(X_tag)) print(len(list(cnn_pred))) print(len(y_eval)) df = pd.read_csv('data2/val_csv.csv', sep=',') path = 'data2/val' src_dir = path dst_dir = 'data2/labeled_predicted_val' for filename in glob.glob(os.path.join(src_dir, '*.jpg')): im = cv2.imread(filename) name = filename.replace(src_dir, '') img_name = name.replace('.jpg', '') img_name = img_name.replace('\\', '') labeled_img_p = label_vehicle(im.copy(), img_name, df, predicted_dict) cv2.imwrite(dst_dir + name, labeled_img_p) labeled_img_a = label_vehicle(im.copy(), img_name, df, actual_dict) cv2.imwrite('data2/labeled_actual_val' + name, labeled_img_a) report(y_eval, list(cnn_pred), labels_index) print("Done")
def test_bigger_rotation_of_positive_n(): string = 'bob and julian love pybites!' expected = 'love pybites!bob and julian ' assert rotate(string, 15) == expected
def test_small_rotate(): assert rotate('hello', 2) == 'llohe' assert rotate('hello', -2) == 'lohel'
def test_bigger_rotation_of_negative_n(): string = 'pybites loves julian and bob!' expected = 'julian and bob!pybites loves ' assert rotate(string, -15) == expected
def create_ini3D(self, cent, output_path, num_of_events=1, grid_max=12.0, grid_step=0.12, eta_max=9.9, eta_step=0.3, one_shot_ini=False, align_for_oneshot=False): output_path = os.path.abspath(output_path) centrality_file = os.path.join(__cwd__, self.config['centrality_file_b']) self.info_b = pd.read_csv(centrality_file) bmin, bmax = self.get_bmin_bmax(cent) #cwd1 = os.getcwd() #os.chdir("../../../3rdparty/trento3d-master/build/src/") call([ './trento3d', self.config['projectile'], self.config['target'], '%s' % num_of_events, '-o', output_path, '-x', '%s' % self.config['cross_section'], '--b-min', '%s' % bmin, '--b-max', '%s' % bmax, '--xy-max', '%s' % grid_max, '--xy-step', '%s' % grid_step, '--eta-max', '%s' % eta_max, '--eta-step', '%s' % eta_step, '--mean-coeff', self.config['mean_coeff'], '--std-coeff', self.config['std_coeff'], '--skew-coeff', self.config['skew_coeff'], '--skew-type', self.config['skew_type'], '--jacobian', self.config['jacobian'], '--fluctuation', self.config['fluctuation'], '--nucleon-width', self.config['nucleon_width'] ]) #os.chdir(cwd1) if one_shot_ini: ngridxy = int(2 * grid_max / grid_step) ngrideta = int(2 * eta_max / eta_step) + 1 sxyz = np.zeros((ngridxy, ngridxy, ngrideta), dtype=np.float32) events = os.listdir(output_path) print(events) num_of_events = 0 for event in events: #try: fname = os.path.join(output_path, event) dat = np.loadtxt(fname).reshape(ngridxy, ngridxy, ngrideta) opt = reader.get_comments(fname) sd_new = rotate(dat, opt['ixcm'], opt['iycm'], opt['phi_2'], ngridxy, ngridxy, ngrideta, is3D=True) sxyz += np.fabs(sd_new) num_of_events += 1 #except: # print(fname, 'is not a trento event') sxyz = sxyz.flatten() np.savetxt(os.path.join(output_path, "one_shot_ini.dat"), sxyz / num_of_events, header=cent)
def test_bigger_rotation_of_negative_n(): string = "pybites loves julian and bob!" expected = "julian and bob!pybites loves " assert rotate(string, -15) == expected
def data_process (ego,osi_objs_noego,header): # Import all sensor parameter from Sensor class <-- Parameter are changeable in Ros launch File sens = Sens() global count # Counter for iniciating yawrate calculation = 0 global counter # Counter for intitiating old osi data global osi_old # global ntime global otime global yawrate if counter == 0: osi_old = osi_objs_noego counter += 1 if count == 0: yawrate = 0 objs_list = ObjectsList() objs_list.header.stamp = header.stamp objs_list.header.frame_id = "Sensor" #Assign Sensor properties to topic objs_list.sensor_property.sensor_id = rospy.get_param("sensorID") objs_list.sensor_property.sensortype = rospy.get_param("sensortype") if rospy.get_param("sensortype") == 0: objs_list.sensor_property.posx_variance = float(rospy.get_param("rangerr"))/3 objs_list.sensor_property.posy_variance = float(rospy.get_param("rangerr"))/3 objs_list.sensor_property.trust_existance = float(rospy.get_param("trust_existance")) objs_list.sensor_property.trust_car = float(rospy.get_param("trust_car")) objs_list.sensor_property.trust_truck = float(rospy.get_param("trust_truck")) objs_list.sensor_property.trust_motorcycle = float(rospy.get_param("trust_motorcycle")) objs_list.sensor_property.trust_bicycle = float(rospy.get_param("trust_bicycle")) objs_list.sensor_property.trust_pedestrian = float(rospy.get_param("trust_pedestrian")) objs_list.sensor_property.trust_stationary = float(rospy.get_param("trust_stationary")) objs_list.sensor_property.trust_other = float(rospy.get_param("trust_other")) elif rospy.get_param("sensortype") != 5 : objs_list.sensor_property.posx_variance= float(rospy.get_param("posxerr"))/3 #print(objs_list.sensor_property.posx_variance) objs_list.sensor_property.posy_variance = float(rospy.get_param("posyerr"))/3 objs_list.sensor_property.trust_existance = float(rospy.get_param("trust_existance")) objs_list.sensor_property.trust_car = float(rospy.get_param("trust_car")) objs_list.sensor_property.trust_truck = float(rospy.get_param("trust_truck")) objs_list.sensor_property.trust_motorcycle = float(rospy.get_param("trust_motorcycle")) objs_list.sensor_property.trust_bicycle = float(rospy.get_param("trust_bicycle")) objs_list.sensor_property.trust_pedestrian = float(rospy.get_param("trust_pedestrian")) objs_list.sensor_property.trust_stationary = float(rospy.get_param("trust_stationary")) objs_list.sensor_property.trust_other = float(rospy.get_param("trust_other")) objs_list.sensor_property.velx_variance = float(rospy.get_param("velerr"))/3 objs_list.sensor_property.vely_variance = float(rospy.get_param("velerr"))/3 for i in range (len(osi_objs_noego)): # Rotate and Translate the object position from map to ego osi_objs_noego[i].position.x = osi_objs_noego[i].position.x - ego.position.x osi_objs_noego[i].position.y = osi_objs_noego[i].position.y - ego.position.y [osi_objs_noego[i].position.x, osi_objs_noego[i].position.y] = rotate(osi_objs_noego[i].position.x, osi_objs_noego[i].position.y, -ego.orientation.yaw) # Rotate and Translate the object position from ego to sensor osi_objs_noego[i].position.x = osi_objs_noego[i].position.x - sens.pos.x osi_objs_noego[i].position.y = osi_objs_noego[i].position.y - sens.pos.y [osi_objs_noego[i].position.x, osi_objs_noego[i].position.y] = rotate(osi_objs_noego[i].position.x,osi_objs_noego[i].position.y, -sens.rot.yaw) # Calculate the object orientation from map to sensor osi_objs_noego[i].orientation.yaw -= (ego.orientation.yaw + sens.rot.yaw) # Keep the angles are between -pi and pi if osi_objs_noego[i].orientation.yaw < -math.pi: osi_objs_noego[i].orientation.yaw += 2*math.pi elif osi_objs_noego[i].orientation.yaw > math.pi: osi_objs_noego[i].orientation.yaw -= 2*math.pi # changed to absolute , real sensor should add ego velocity and give overground velocity/objs of objects # Rotate and Translate the object velocity from map to sensor (Relative Velocity) [osi_objs_noego[i].velocity.x, osi_objs_noego[i].velocity.y] = rotate(osi_objs_noego[i].velocity.x, osi_objs_noego[i].velocity.y, -(ego.orientation.yaw + sens.rot.yaw)) osi_objs_noego[i].velocity.x = osi_objs_noego[i].velocity.x - ego.velocity.x osi_objs_noego[i].velocity.y = osi_objs_noego[i].velocity.y - ego.velocity.y # Transpose the object acceleration from map to sensor. [osi_objs_noego[i].acceleration.x, osi_objs_noego[i].acceleration.y] = rotate(osi_objs_noego[i].acceleration.x, osi_objs_noego[i].acceleration.y, -(ego.orientation.yaw + sens.rot.yaw)) osi_objs_noego[i].acceleration.x = osi_objs_noego[i].acceleration.x - ego.acceleration.x osi_objs_noego[i].acceleration.y = osi_objs_noego[i].acceleration.y - ego.acceleration.y # Calculate features [features,features_check] = calculate_features(osi_objs_noego[i],sens) # If one of the features is inside the field of view it calculates the error and fullfil the Aeberhard Object List if features_check == 1: # Just entities inside FOV ## Include statistical errors on osi_objs_noego[i] = include_sens_error (osi_objs_noego[i]) ## Initialize the Object list obj_list= ObjectList() ## fullfil object list obj_list.geometric.x = osi_objs_noego[i].position.x #relative obj_list.geometric.y = osi_objs_noego[i].position.y #relative obj_list.geometric.vx = osi_objs_noego[i].velocity.x #relative obj_list.geometric.vy = osi_objs_noego[i].velocity.y #relative obj_list.geometric.ax = osi_objs_noego[i].acceleration.x #relative obj_list.geometric.ay = osi_objs_noego[i].acceleration.y #relative obj_list.geometric.yaw = osi_objs_noego[i].orientation.yaw #- (ego.orientation.yaw +sens.rot.yaw) obj_list.obj_id=osi_objs_noego[i].id ## Necessary to include errors obj_list.dimension.length = osi_objs_noego[i].dimension.length obj_list.dimension.width = osi_objs_noego[i].dimension.width obj_list.dimension.length_variance = 0.2 obj_list.dimension.width_variance = 0.2 obj_list.features = features ## Necessary to include errors if classification[osi_objs_noego[i].type] == "car": obj_list.classification.car = 1 obj_list.prop_mov = 1 elif classification[osi_objs_noego[i].type] == "truck": obj_list.classification.truck = 1 obj_list.prop_mov = 1 elif classification[osi_objs_noego[i].type] == "motorcycle": obj_list.classification.motorcycle = 1 obj_list.prop_mov = 1 elif classification[osi_objs_noego[i].type] == "bicycle": obj_list.classification.bicycle = 1 elif classification[osi_objs_noego[i].type] == "pedestrian": obj_list.classification.pedestrian = 1 elif classification[osi_objs_noego[i].type] == "stacionary": obj_list.classification.stacionary = 1 elif classification[osi_objs_noego[i].type] == "other": obj_list.classification.other = 1 if count != 0: t = float(str(ntime)) - float(str(otime)) if t == 0 : t = 1/(rospy.get_param('freq')) #t = t / 1000000000.0 obj_list.geometric.yawrate = (osi_objs_noego[i].orientation.yaw - osi_old[i].orientation.yaw) / t else: obj_list.geometric.yawrate = 0 #obj_list.geometric.yaw -= egoyaw objs_list.obj_list.append(obj_list) count=1 # Publish the object list pub = rospy.Publisher("objs_list", ObjectsList, queue_size=10,latch=True) pub.publish(objs_list) osi_old = osi_objs_noego
import rotate from astropy.table import Table import numpy as np import matplotlib.pyplot as plt t = Table.read('testspec.fits',format='fits') t = t[(t['WAVE'] < 1550.0) & (t['WAVE'] > 1549.0)] print len(t) wl = np.array(t['WAVE']) flx = np.array(t['QMU1']/t['QMU2']) rotatedict = {"NRAD":100,"VROT":100.0} rot = rotate.rotate() out = rot.rotate(wl,flx,rotatedict) print out # plt.plot(wl,flx,'-r',alpha=0.5) # plt.plot(out['WAVE'],out['FLUX'],'-b') # plt.show(block=True)
def test_rotation_of_n_same_as_len_str(): string = expected = "julian and bob!" assert rotate(string, len(string)) == expected
src = cv2.imread(filename, cv2.IMREAD_COLOR) #Pre-processing """ blur = np.ones((src.shape[0],src.shape[1]), np.uint8) cv2.medianBlur(src, 3, src) """ cv2.imshow('preproced', src) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('preproced.png', src) #Mask make_mask('preproced.png') #Rotate rotate('mask.png') crop_img('rotated.png') #tesseract Output print "=====After Rotation Tesseract output======" message = pytesseract.image_to_string(Image.open('cropped.png')) print message cv2.waitKey(0) cv2.destroyAllWindows()
def test_bigger_rotation_of_positive_n(): string = "bob and julian love pybites!" expected = "love pybites!bob and julian " assert rotate(string, 15) == expected
print('mass center = ', ixmc, iymc) print('center_of_mass(ed) from python=', center_of_mass(ed)) plt.subplot(131) plt.imshow(ed, origin='lower') plt.subplot(132) #ed_shift = matrix.shift(ed, (-iymc+49.5, -ixmc+49.5)) # #ed_rot = matrix.rotate(ed_shift, phi_2 * 180. / np.pi, mode='constant', reshape=False) from rotate import rotate ed_rot = rotate(ed, ixmc, iymc, phi_2, nx=100, ny=100) from ecc3_from_smotthIni import eccn print('ecc2 after rotation is:', eccn(ed_rot, ixcm=49.5, iycm=49.5, n=2)) plt.imshow(ed_rot, origin='lower') plt.subplot(133) #ed_rot3 = matrix.rotate(ed_shift, phi_3 * 180. / np.pi, mode='constant', reshape=False) ed_rot3 = rotate(ed, ixmc, iymc, phi_3) print('ecc3 after rotation is:', eccn(ed_rot3, ixcm=49.5, iycm=49.5, n=3)) plt.imshow(ed_rot3, origin='lower')
import My_MaxEntropy import convolution_column import numpy as np import rail_location import time ####################################################################1. Read + canny image = cv2.imread('input_data/0179.jpg',0) #直接读为灰度图像 edges = cv2.Canny(image, 50, 150, apertureSize = 3) result = image.copy() ####################################################################2. Hough algorithm + Rotation k=hough.hough(edges,result) #img2 = transform.rotate(result,k-90)#归一化 (均值为0 方差为1) img_rotate = rotate.rotate(image,k-90) plt.subplot(111) plt.imshow(img_rotate ,cmap ='gray') plt.axis('off') plt.show() #######################3. HPCG algorithm W = rail_location.convolution(img_rotate) img_crop = img_rotate[:,W:(W+50)] h, w = img_crop.shape #######################4. LWLC algorithm img_crop = img_crop[250:(h-250), 4:(w-3)] img_nomali=convolution_column.convolution(img_crop) plt.subplot(111)
def main(): #Simulation start time t1 = time.clock() #Random generator engine from a time-based seed random.seed() #Set parameters num_timesteps = 1600000 timestep_inc = 0.2 arena_size = 1000 top_left = np.array([0.0, 0.0]) bottom_right = np.array([arena_size, arena_size]) sight_num = 166 #make even total_agents = 100 total_prey_agents = 75 total_pred_agents = total_agents - total_prey_agents max_turning_rate_prey = 3.0 max_turning_rate_pred = 2.0 zop_prey = 100.0 zop_pred = 150.0 speed_prey = 6.0 speed_pred = 9.0 color_prey = [255, 135, 71] color_pred = [255, 255, 255] length_prey = 5.0 length_pred = 10.0 angular_error_sd = 0.0 zop_max = zop_pred if zop_pred > zop_prey else zop_prey agents = [] #Simulation starts HERE #Set up agents for i in range(total_agents): set_direction = np.array([1.0, 0.0]) # need to be set to unit vectors set_direction = rotate(set_direction, random.random() * 360.0) set_r_centre = random_bounded_point(bottom_right, top_left) if i < total_prey_agents: agents.append( Individual(set_r_centre, set_direction, max_turning_rate_prey, speed_prey, zop_prey, angular_error_sd, 1, color_prey, length_prey, sight_num, i)) else: agents.append( Individual(set_r_centre, set_direction, max_turning_rate_pred, speed_pred, zop_pred, angular_error_sd, 2, color_pred, length_pred, sight_num, i)) for j in range(num_timesteps): #draw to screen if j % 1 == 0: graphics(arena_size, agents, zop_max) move_agents(arena_size, zop_max, agents, timestep_inc)
def ASYM(cutimage, maskimage, ini_xcntr, ini_ycntr, pa, one_minus_eg_sq, r50, background, extraction_radius, angle, flag_image, ABS_ZSUM): if flag_image == 0: maskimage = 'BackMask.fits' co = np.cos(pa * np.pi / 180.0) si = np.sin(pa * np.pi / 180.0) Aabs = np.zeros(9) Aabs = Aabs.astype(np.float32) rot_sum = np.zeros(9) rot_sum = rot_sum.astype(np.float32) abs_zsum = np.zeros(9) abs_zsum = abs_zsum.astype(np.float32) sh_sum = np.zeros(9) sh_sum = sh_sum.astype(np.float32) absres_sum = np.zeros(9) absres_sum = absres_sum.astype(np.float32) f = pyfits.open(os.path.join(c.datadir, cutimage)) z = f[0].data z = z - background f.close() fm = pyfits.open(os.path.join(c.outdir, maskimage)) zm = fm[0].data fm.close() # Rotate the mask rzm = rotate(zm, 180.0, ini_xcntr, ini_ycntr) mask = zm + rzm # Adding rotated and original mask center_rad = 0.01 * r50 # 0.01 * r50 The centering correction has to # be done by calculating asymmetric parameters # at different points 0.1% of r50 away around #the center flag_center = 0 # flag_center=1 if the program finds the # exact center else center=0 nn = 0 # This nn is given here and the following loop run either # it finds the minimum asymmetry or n=20 while flag_center == 0: flag_out = 0 # x and y coordinates of different center points in 1-d array xcntr = np.reshape(np.array([[ini_xcntr] * 3, \ [ini_xcntr - center_rad] * 3, \ [ini_xcntr + center_rad] * 3]), (9, )) xcntr = xcntr.astype(np.float32) ycntr = np.array([ini_ycntr, ini_ycntr - center_rad, \ ini_ycntr + center_rad]*3) ycntr = ycntr.astype(np.float32) for iter in range(9): # The below is done in order to keep the # extraction radius inside the image. If the # extraction radius goes outside the image # then flag_out=1 CutImDa, cut_xcntr, cut_ycntr, SizeY, SizeX, ymin, \ ymax, xmin, xmax, flag_out = \ ImSec(z, xcntr[iter], ycntr[iter], extraction_radius) if flag_image == 0: # flag_image will tell whether the input is \ # image (flag_image=1) or background flag_out = 0 x = np.reshape(np.arange(SizeX * SizeY), (SizeY, SizeX)) % SizeX x = x.astype(np.float32) y = np.reshape(np.arange(SizeX * SizeY), (SizeY, SizeX)) / SizeX y = y.astype(np.float32) tx = (x - cut_xcntr) * co + (y - cut_ycntr) * si ty = (cut_xcntr - x) * si + (y - cut_ycntr) * co R = np.sqrt(tx**2.0 + ty**2.0 / one_minus_eg_sq) # print xcntr[iter] , ycntr[iter] rz = rotate(CutImDa, 180.0, cut_xcntr, cut_ycntr) res = CutImDa - rz masksub = mask[ymin:ymax, xmin:xmax].copy() # If want to check the rotated image and cutout image # uncomment the following # for myfile in ['Rotated.fits', 'CutImDa.fits']: # if os.access(myfile, os.F_OK): # os.remove(myfile) # hdu = pyfits.PrimaryHDU(rz) # hdu.writeto('Rotated.fits') # hdu = pyfits.PrimaryHDU(CutImDa) # hdu.writeto('CutImDa.fits') # raw_input() # END sh_sum[iter] = ma.masked_array(CutImDa, masksub) \ [np.where(R <= extraction_radius)].sum() rot_sum[iter] = ma.masked_array(rz, masksub) \ [np.where(R <= extraction_radius)].sum() abs_zsum[iter] = abs(ma.masked_array(CutImDa, masksub) \ [np.where(R <= extraction_radius)]).sum() absres_sum[iter] = abs(ma.masked_array(res, masksub) \ [np.where(R <= extraction_radius)]).sum() if(flag_image): Aabs[iter] = absres_sum[iter] / (abs_zsum[iter]) else: Aabs[iter] = absres_sum[iter] / (ABS_ZSUM) Aabso = Aabs.min() index = Aabs.argmin() if(nn > 20): xcntr[index] = ini_xcntr ycntr[index] = ini_ycntr if(xcntr[index] == ini_xcntr and ycntr[index] == ini_ycntr): flag_center = 1 rz = rotate(CutImDa, 180.0, cut_xcntr, cut_ycntr) res = CutImDa - rz rot_sum = rot_sum[index] abs_zsum = abs_zsum[index] if flag_image == 0: abs_zsum = ABS_ZSUM sh_sum = sh_sum[index] absres_sum = absres_sum[index] if(flag_image): error_asym = np.sqrt( Aabso**2*( ((sh_sum + rot_sum + 4 * \ background * \ R[np.where(R <= np.floor(extraction_radius))].size) \ / absres_sum**2.0) + ((sh_sum + 2.0 * background * \ R[np.where(R <= np.floor(extraction_radius))].size) \ / abs_zsum**2) ) ) else: error_asym = np.sqrt( Aabso**2 * (((sh_sum+rot_sum + 2 * \ background * \ R[np.where(R <= np.floor(extraction_radius))].size) \ / absres_sum**2.0) + ((sh_sum + 2.0 * background * \ R[np.where(R <= np.floor(extraction_radius))].size) \ / abs_zsum**2) ) ) else: ini_xcntr = xcntr[index] ini_ycntr = ycntr[index] nn += 1 # print Aabso, error_asym, ini_xcntr, ini_ycntr, nn, flag_out,\ # abs_zsum, sh_sum, extraction_radius return Aabso, error_asym, ini_xcntr, ini_ycntr, nn, flag_out,\ abs_zsum, sh_sum, extraction_radius
def rotate_word(word,dic): for i in range(1,14): rotated=rotate(word,i) if rotated in dic: print word,i,rotated