def test_right_is_frozen(self): """ Test to determine if is_frozen() correctly identifies a walking particle as frozen if the position one RIGHT from the current position is in stuck_list (is part of the cluster). Case: RIGHT [x+1, y] in stuck_list """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = -1, 0 particle.is_frozen() self.assertTrue(particle.frozen)
def addObject(newobject, object, velocity=None): newobject = scene.addObject(newobject, object) newobject["bonds"] = set() if newobject.name in ["Carbon", "Oxygen", "Nitrogen"]: newobject["doubles"] = set() newobject["triple"] = None if velocity != None: newobject.localLinearVelocity = velocity particle = Particle(newobject) return particle
def test_down_is_frozen(self): """ Test to determine if is_frozen() correctly identifies a walking particle as frozen if the position one DOWN from the current position is in stuck_list (is part of the cluster). Case: DOWN [x, y-1] in stuck_list """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = 0, 1 particle.is_frozen() self.assertTrue(particle.frozen)
def __init__(self, problem: TigerProblem, belief=[Particle().state for _ in range(100)], exploration=7, tier=1): self.problem = problem self.N = 0 # visitation count self.total = 0 self.V = 0 # score of state self.children = dict() self.tier = tier # 1 . Action 0 . Observation self.exploration = exploration
def _init_particles(self): for i in range(self.n_particles): particle = None particle = Particle(self.n_cluster, self.data) if particle.best_score < self.gbest_score: self.gbest_centroids = particle.centroids.copy() self.gbest_score = particle.best_score self.particles.append(particle) self.gbest_sse = min(particle.best_sse, self.gbest_sse) par = [] par.append(self.gbest_sse)
def gen_n_particles_robot(self, n): p = [] for i in range(n): x_coord = self.myrobot.x + Random.gauss(0, self.sense_noise * 3) y_coord = self.myrobot.y + Random.gauss(0, self.sense_noise * 3) yaw = self.myrobot.yaw + Random.gauss(0, self.yaw_noise) * math.pi if yaw < 0: yaw = 2 * math.pi + yaw if yaw > 2 * math.pi: yaw %= (2 * math.pi) p.append([Particle(x_coord, y_coord, yaw), 0]) return p
def take_damage(self, damage, origin=None): was_shield = False sa = min(damage, self.shield) if self.shield > 0: was_shield = True self.shield -= sa damage -= sa self.health -= damage if origin: delta = origin.pos - self.pos dn = helper.try_normalize(delta) hitpos = self.pos + dn * self.radius if was_shield: sound.play("shield") for i in range(10): ang = dn.as_polar()[1] ang *= 3.14159 / 180 rad = max(self.radius, 5) + 2 hp = self.pos + rad * helper.from_angle( ang + random.random() - 0.5) p = Particle([ PICO_GREEN, PICO_WHITE, PICO_BLUE, PICO_BLUE, PICO_BLUE, PICO_BLUE, PICO_DARKBLUE ], 1, hp, 0.65 + random.random() * 0.2, dn) self.scene.game_group.add(p) else: sound.play("hit") particles = 10 if self.radius > 6: particles = 4 e = Explosion(hitpos, [PICO_WHITE, PICO_YELLOW, PICO_RED], 0.2, 5, "log", 2) self.scene.game_group.add(e) for i in range(particles): p = Particle([ PICO_WHITE, PICO_YELLOW, PICO_YELLOW, PICO_RED, PICO_LIGHTGRAY ], 1, hitpos, 0.25, helper.random_angle() * 9) self.scene.game_group.add(p)
def __init__(self): self.initialized = False # make sure we don't perform updates before everything is setup rospy.init_node( 'pf') # tell roscore that we are creating a new node named "pf" self.base_frame = "base_link" # the frame of the robot base self.map_frame = "map" # the name of the map coordinate frame self.odom_frame = "odom" # the name of the odometry coordinate frame self.scan_topic = "scan" # the topic where we will get laser scans from self.n_particles = 300 # the number of particles to use self.d_thresh = 0.2 # the amount of linear movement before performing an update self.a_thresh = math.pi / 6 # the amount of angular movement before performing an update self.laser_max_distance = 2.0 # maximum penalty to assess in the likelihood field model # TODO: define additional constants if needed self.sd_xy_theta = (0.5, 0.5, math.pi / 10) # Setup pubs and subs # pose_listener responds to selection of a new approximate robot location (for instance using rviz) self.pose_listener = rospy.Subscriber("initialpose", PoseWithCovarianceStamped, self.update_initial_pose) # publish the current particle cloud. This enables viewing particles in rviz. self.particle_pub = rospy.Publisher("particlecloud", PoseArray, queue_size=10) # laser_subscriber listens for data from the lidar self.laser_subscriber = rospy.Subscriber(self.scan_topic, LaserScan, self.scan_received) # enable listening for and broadcasting coordinate transforms self.tf_listener = TransformListener() self.tf_broadcaster = TransformBroadcaster() self.particle_cloud = [] self.mean_particle = Particle() # Save the most probable particle here self.current_odom_xy_theta = [0, 0, 0] # request the map from the map server, the map should be of type nav_msgs/OccupancyGrid # TODONE: fill in the appropriate service call here. The resultant map should be assigned be passed # into the init method for OccupancyField rospy.wait_for_service('static_map') self.map = rospy.ServiceProxy('static_map', GetMap)().map # DONE: uncommented the occupancy field initialization after you can successfully fetch the map self.occupancy_field = OccupancyField(self.map) self.initialized = True
def test_take_step_right(self): """ Check: particle.x is increased by one after take_step() moves the particle RIGHT Case 2: Move RIGHT: [x+1, y] """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = 5, 5 particle.take_step(3) # Move particle RIGHT self.assertEqual( [6,5], [particle.x, particle.y] )
def test_take_step_left(self): """ Check: particle.x is decreased by one after take_step() moves the particle LEFT Case 2: Move LEFT: [x-1, y] """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = 5, 5 particle.take_step(2) # Move particle LEFT self.assertEqual( [4, 5], [particle.x, particle.y] )
def createParticles(self): particles = [] for j in reversed(range(0, self.yMax, ceil(self.supportRadius * 0.5))): for i in range(round(self.xMax / 2), self.xMax, ceil(self.supportRadius * 0.5)): if len(particles) >= self.numberOfParticles: break positionVector = np.array([i, self.yMax - j]) prevPositionVector = positionVector newParticle = Particle(positionVector) newParticle.prevPos = prevPositionVector particles.append(newParticle) self.particles = particles
def __init__(self, h, initial_particle_properties): ''' Constructor that initialised the system with the initial properties for all the particles in the system, and the kernel width. ''' self.h = h self.count = len(initial_particle_properties) self.particles = [] for particle_properties in initial_particle_properties: new_particle = Particle(particle_properties) self.particle.append(new_particle)
def test_data_association(self): robot = Particle(100, 100, 0, is_robot=True) landmark1 = Landmark(20, 20) landmark2 = Landmark(40, 60) landmark_fake2 = Landmark(45, 60) landmark3 = Landmark(20, 110) robot.landmarks = [landmark1, landmark_fake2, landmark3] obs = robot.sense([landmark2], 1) o = obs[0] prob, idx, ass_obs, ass_jacobian, ass_adjcov = robot.find_data_association( o) self.assertEqual(idx, 1)
def test_take_step_down(self): """ Check: particle.y is decreased by one after take_step() moves the particle DOWN Case 2: Move DOWN: [x, y-1] """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = 5, 5 particle.take_step(1) # Move particle DOWN self.assertEqual( [5, 4], [particle.x, particle.y] )
def select_new_particle_population(particles): number_particles = len(particles) weights = [particle.weight for particle in particles] population_selection = select_population_from_weights(weights) return [ Particle( particles[i].latitude, particles[i].longitude, particles[i].velocity, particles[i].heading, 1 / number_particles, ) for i in population_selection ]
def onHit(self, amount): self.hp -= amount self.hitCount = 10 self.slime_hurt.reset() diffX = self.x - self.world.player.x HIT_AMOUNT = 15 self.x_vel += HIT_AMOUNT if diffX > 0 else -HIT_AMOUNT audio.onSlimeHit() for i in range(0, 10): particle = Particle(self.world, self.x + self.width / 2, self.y + self.height / 2, (99, 199, 77)) self.world.addEntity(particle) self.world.camera.shake(5)
def instantiateMolecule(particles, color=MOLECULE_COLOR, position=None, velocity=None): if position == None: g_x = randint(0, GRID_X) g_y = randint(0, GRID_Y) else: g_x = int(position.x) g_y = int(position.y) if velocity == None: v_x = uniform(-1, 1) v_y = uniform(-1, 1) velocity = pygame.Vector2(v_x, v_y) if GRID[g_x][g_y]: p_x = g_x * MOLECULE_RADIUS * 2 + MOLECULE_RADIUS p_y = g_y * MOLECULE_RADIUS * 2 + MOLECULE_RADIUS GRID[g_x][g_y] = False position = pygame.Vector2(p_x, p_y) particles.append( Particle(position, velocity, MOLECULE_RADIUS, MOLECULE_MASS, color)) return else: for i in range(len(GRID)): for j in range(len(GRID[i])): if GRID[i][j]: p_x = i * MOLECULE_RADIUS * 2 + MOLECULE_RADIUS p_y = j * MOLECULE_RADIUS * 2 + MOLECULE_RADIUS GRID[i][j] = False position = pygame.Vector2(p_x, p_y) particles.append( Particle(position, velocity, MOLECULE_RADIUS, MOLECULE_MASS, color)) return print('The grid is full, too many molecules instantiated.')
def particleSpawnerClicks(self, event, ls: list): if self.mouseDownPos.x < self.size[0] - 200: self.dragging = True elif self.withinRect(pygame.Rect((self.size[0] - 95, 420), (80, 40))): self.uIParticleSpawn = False self.uILandingOpen = True self.virtualParticle = Particle(0, Vector(0, 0)) elif self.withinRect(pygame.Rect((self.size[0] - 190, 220), (175, 35))): self.massTextBoxEditable = True elif self.withinRect(pygame.Rect((self.size[0] - 190, 265), (175, 40))): self.positionTextBoxEditable = True elif self.withinRect(pygame.Rect((self.size[0] - 190, 320), (175, 35))): self.velocityTextBoxEditable = True elif self.withinRect(pygame.Rect((self.size[0] - 190, 365), (175, 35))): self.momentumTextBoxEditable = True elif self.withinRect(pygame.Rect((self.size[0] - 190, 420), (90, 40))): ls.append(self.virtualParticle) self.virtualParticle = Particle(0, Vector(0, 0))
def SpawnParticle(position, colour, life=2, magnitude=1, size=5, angle=None, spread=math.pi / 4, GRAV=0.25, velocity=None, outline=True): particles.append( Particle(position, colour, life, magnitude, size, angle, spread, GRAV, velocity, outline))
def SolvePso(self,fn="NONE"): self.InitilizeSwarm() #the best fit is a particle GlobalFit = Particle(self.d) GlobalFit.bestFit = 10000 #set the best fit to a high number #f = open(fn,'w') for i in range(self.epoch): self.UpdateVelocity(self.d,self.w,self.c1,self.c2,GlobalFit) GlobalFit = self.GetBestFit(GlobalFit) #Only used for creating the test file # f.write(str(GlobalFit.bestFit)+"\n") return GlobalFit.bestFit
def main(): ### CONFIG screen_w = 500 screen_h = 500 border_on = True num_walls = 6 num_rays = 180 ### END CONFIG pg.init() screen = pg.display.set_mode((screen_w, screen_h)) running = True pg.event.set_allowed([pg.QUIT, pg.KEYDOWN, pg.KEYUP]) p = Particle() boundaries = [] rays = [] if border_on: boundaries.append(Boundary(screen, (0, 0), (screen_w, 0))) boundaries.append(Boundary(screen, (screen_w, 0), (screen_w, screen_h))) boundaries.append(Boundary(screen, (screen_w, screen_h), (0, screen_h))) boundaries.append(Boundary(screen, (0, screen_h), (0, 0))) for i in range(num_walls): boundaries.append( Boundary(screen, (randint(0, screen_w), randint(0, screen_h)), (randint(0, screen_w), randint(0, screen_h)))) for i in range(num_rays): rays.append(Ray(p, i * 360 / num_rays)) while running: for event in pg.event.get(): if event.type == pg.QUIT: running = False screen.fill((0, 0, 0)) for b in boundaries: b.update(screen) p.update(screen) for r in rays: r.update(screen, p, boundaries) pg.display.update() pg.time.wait(75)
def make_univer(n_particles=int(10e6)): max_v = 1 min_v = -1 particles = [ Particle(r=Vector2d(random.uniform(-box_size // 2, box_size // 2), random.uniform(-box_size // 2, box_size // 2)), v=Vector2d(random.uniform(min_v, max_v), random.uniform(min_v, max_v))) ] # global box_size i = 1 while True: # if i % (n_particles//100) == 0: # print('box:', i // (n_particles//100) + 1) tmp_par = Particle(r=Vector2d( random.uniform(-box_size // 2, box_size // 2), random.uniform(-box_size // 2, box_size // 2)), v=Vector2d(random.uniform(min_v, max_v), random.uniform(min_v, max_v))) flag = 1 # for particle1 in particles: # tmp_e = particle1.r - tmp_par.r # if abs(tmp_e) == 0: # continue # tmp_f = forces.base_force(particle1, tmp_par) # if (tmp_f.x*tmp_e.x + tmp_f.y*tmp_e.y) < 0: # flag = 0 if flag == 1: particles.append(tmp_par) i += 1 if i >= n_particles: break # print(i) return particles
def read(read_path, mode=None): particles = [] with open(read_path, 'r') as inputfile: s_tmp = inputfile.read() for el in s_tmp.split('\n')[2:]: if el != '': if mode is None: rx, ry, rz, r, g, b = el.split() else: с, rx, ry, rz, c = el.split() particles.append( Particle(r=Vector3d(float(rx), float(ry), float(rz)), name=len(particles))) return particles
def start_population(self): population_list = [] for i in range(self.population): x = random.uniform(-512, 512) y = random.uniform(-512, 512) particle = Particle(x, y, self.x_speed, self.y_speed) fitness = particle.run_fitness() particle.set_fitness(fitness) population_list.append(particle) return population_list
def initParticle(self): self.particleArray = [] x = -0.625 #Creating the boundary element rho = 1.0 p = 1.0 u = 0 delx = 0.0015625 h = 2 * 0.006250 mass = delx for i in range(400): self.particleArray.append(Particle(x, rho, u, p, mass, h)) x = x + delx x = 0 delx = 0.00625 p = 0.1 mass = 0.00156250 rho = 0.25 for i in range(100): x = x + delx self.particleArray.append(Particle(x, rho, u, p, mass, h)) self.sP = 80 self.eP = 480
def create_particle(states, input_symbols, output_symbols, codec): row_size = len(input_symbols) * len(states) column_size = len(output_symbols) * len(states) pos = np.eye(row_size, column_size, dtype=bool) for row in pos: np.random.shuffle(row) # REVIEW: Whether initializing vel=0 works well vel = np.zeros((row_size, column_size)) particle = Particle(pos, vel) particle.mealymachine = create_mealymachine(states, \ input_symbols, output_symbols, pos, codec) return particle
def particle_burst(self, time: float, pos: Vec3, normal: Vec3, count: int, team: int): color = (50, 180, 255) if team == 0 else (255, 168, 50) self.particles.extend([ Particle( int(4 + 4 * random.random()), pos, 600 * (normal + 0.7 * Vec3.random()), Vec3(z=-500), 0.02, color if random.random() < 0.55 else (255, 255, 255), # Some chance for white instead time + 0.3 + 0.8 * random.random()) for _ in range(count) ])
def make_particles(self, n_dims, n_particles, **kwargs): self.particles = [] pos = np.random.random((n_particles, n_dims)) spd = self.speedscale * (np.random.random((n_particles, n_dims)) - 0.5) if "value_ranges" in kwargs: assert kwargs["value_ranges"].shape == (n_dims, 2) kwargs["value_ranges"] = np.asarray(kwargs["value_ranges"]) pos = pos * (kwargs["value_ranges"][:, 1] - kwargs["value_ranges"] [:, 0]) + kwargs["value_ranges"][:, 0] else: kwargs["value_ranges"] = None for i in range(n_particles): self.particles.append( Particle(pos[i], spd[i], self.fitness, **kwargs))
def createInitialParticles(): global particle_count, robotGuess particle_count = int(sys.argv[2]) for p in range(0, particle_count): positionTuple = findRandomPosition() i = positionTuple[0] j = positionTuple[1] theta = positionTuple[2] #add particle to particle_list particle = Particle(i, j, theta, 0) particle.set_noise(0.05, 0.05, 5.0) particle_list.append(particle) robotGuess = meanLocation(particle_list)
def test_take_step_up(self): """ Check: particle.y is increased by one after take_step() moves the particle UP Case 1: Move UP: [x, y+1] """ particle = Particle(axis_length=10, stuck_list=[[0, 0],]) particle.x, particle.y = 5, 5 np.random.seed(0) particle.take_step(0) # Move particle UP self.assertEqual( [5, 6], [particle.x, particle.y] )