def __init__(self, particles, rows, columns): self.map = Map(columns, rows) first_half = [ Particle(random.randint(1, columns // 2), random.randint(1, rows), 'g') for x in range(particles // 2) ] second_half = [ Particle(random.randint(columns // 2 + 1, columns), random.randint(1, rows), 'r') for x in range(particles // 2 + (1 if particles % 2 == 0 else 0)) ] self.particles = first_half + second_half
def populate(self, num_particle=50): """Populates the _field with randomly-positioned _particles. """ self._field.clear() particle_new = Particle(Position(max=self.size), Direction(), self._colours.get(State.INFECTED), self._field) self._particles.append(particle_new) for p in range(num_particle - 1): position = Position( max=self.size) # generate 0 <= random Position < size direction = Direction() color = self._colours.get(State.SUSCEPTIBLE) particle_new = Particle(position, direction, color, self._field) self._particles.append(particle_new)
def generate_particle(self): self.paint_gl = 0 self.start_time = time.clock() self.start_time_gl = time.clock() N_p = int(self.lineEdit_N.text()) del particle_system[:] particle_system.append( Particle(Coord(0, 0, 0), Speed(0, 0, 0), 1000, (0.1, 0.1, 0.8))) self.number = N_p if counts != 0: self.number = counts for i in range(1, self.number): crd = Coord(random.randint(-100, 100), random.randint(-100, 100), random.randint(-100, 100)) vel = Speed( random.randint(-10, 10) / 100000.0, random.randint(-10, 10) / 100000.0, random.randint(-10, 10) / 100000.0) mass = random.uniform(1, 500) rgb_col = [ random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0) ] particle_system.append(Particle(crd, vel, mass, rgb_col)) self.gl_widget_.update() if self.comboBox.currentIndex() == 1: # self.timer_1.timeout.connect(self.gl_widget_.verlet) # self.timer_1.start(10) self.gl_widget_.verlet() if self.comboBox.currentIndex() == 0: self.gl_widget_.verlet_scipy() if self.comboBox.currentIndex() == 2: print('index = 2') self.vrl_slv.verlet__scipy() if self.comboBox.currentIndex() == 3: print('index = 3') self.vrl_slv.verlet__() if self.comboBox.currentIndex() == 4: print('index = 4') self.vrl_slv.verlet_threading() if self.comboBox.currentIndex() == 5: print('index = 5') self.vrl_slv.verlet_cython() if self.comboBox.currentIndex() == 6: print('index = 5') self.vrl_slv.verlet_opencl() self.gl_widget_.update()
def __init__(self, span_size, cost_function, min_val=0, max_val=0.99999, population_size=16, inertia=1, c1=1.3, c2=1.3, max_iter=1000, local_search_alg=None, **kwargs): self.global_best_cost = 2 ** 64 self.global_best_position = np.array([0] * span_size) self.particles = [] for _ in range(0, population_size): self.particles.append(Particle(span_size, cost_function, inertia, c1, c2, min_val, max_val, local_search_alg)) if self.particles[-1].best_cost < self.global_best_cost: self.global_best_cost = self.particles[-1].best_cost self.global_best_position = self.particles[-1].best_position self.inertia = inertia self.c1 = c1 self.c2 = c2 self.max_iter = max_iter if 'callbacks' in kwargs.keys(): self.callbacks = kwargs['callbacks']
def create_population(population): pop = [] for particle in xrange(population): particle = Particle() particle.initialize() pop.append(particle) return pop
def run(self): for n in reversed(range(len(self.particles))): self.particles[n].display() self.particles[n].update() self.particles[n].keep_inside_window() if key_is_pressed: wind = Wind(mouse_x, mouse_y) wind_force = wind.wind_force(self.particles[n].location) self.particles[n].applyForce(wind_force) if self.particles[n].is_dead: self.particles.pop(n) print(f"Particle {n+1} from fountain {self.identifier} died ") if len(self.particles) >= 15: self.particles.pop(0) self.counter += 1 if self.counter % 10 == 0: self.particles.append( Particle( self.width, self.height, self.origin.x, self.origin.y, self.identifier, ) )
def initialize(obj, dim, algo): fitness = [] for i in range(0, no_particles): p = Particle() # Object for the Particle Class particles.append( p) # Add the particle object to the :code:`particles` list p._pos = np.random.randint( 2, size=dim) # create of particles and dimension p._velocity = np.random.uniform( -1, 1, size=dim) # create a velocity for all the particle p._fitness = obj.getAccuracy(obj.data_cleaning(p._pos), algo) # Fitness of the particle fitness.append( p._fitness ) # An array that stores all the fitness of each and every particle p._personalBest = p._pos # the personal best of the particle max_fitness_index = fitness.index( max(fitness)) # stores the index of particle with best fitness best_fitness_obj = particles[ max_fitness_index] # best fitness object in the swarm best_pos = particles[ max_fitness_index]._pos # stores the position of the best particle with max fitness best_fitness = particles[ max_fitness_index]._fitness # the best in the swarm fitness_overall.append( best_fitness) # add the current best fitness to fitness overall pos_overall.append( best_pos) # add the current best position to position overall return
def update(self): for n in reversed(range(len(self.particles))): self.particles[n].display() self.particles[n].update() self.particles[n].keep_inside_window() if self.particles[n].is_dead or self.particles[n].mass == 0: self.particles.pop(n) # print(f"Particle {n+1} from fountain {self.identifier} died ") if len(self.particles) >= 15: self.particles.pop(0) self.frame_counter += 1 if self.frame_counter % 10 == 0: print( f"there are {len(self.particles)} particles in fountain {self.identifier}." ) dice = random_uniform() if dice <= 0.4: self.particles.append(Particle(self.origin, self.identifier)) else: self.particles.append(SquareParticle(self.origin, self.identifier)) self.particle_counter += 1 if self.particle_counter >= 10: self.is_empty = True
def turn(self, rad): self.amom += rad Particle( 0, 255, 0, self.loc.copy(), PVector.fromAngle(self.dir + sign(rad) * HALF_PI + random(-QUARTER_PI, QUARTER_PI)).mult(0.3), 200, 1, 3)
def benchmark_memory(): particles = [ Particle(uniform(-1.0, 1.0), uniform(-1.0, 1.0), uniform(-1.0, 1.0)) for i in range(100000) ] simulator = ParticleSimulator(particles) simulator.evolve(0.001)
def __generateNMuscle(self): ''' Generate nMuscles connected muscle ''' nEx = 7 nEy = 4 nEz = 1 #7 for nM in range(self.nMuscles): for x in range(nEx): for y in range(nEy): for z in range(nEz): p_x = Const.xmax / 2.0 + float( x) * Const.r0 - nEx * Const.r0 / 2.0 - Const.r0 * ( nEx) / 2.0 + Const.r0 * (nEx + 0.4) * float(nM > 2) p_y = Const.ymax / 2.0 + y * Const.r0 - nEy * Const.r0 / 2.0 p_z = Const.zmax / 2.0 + z * Const.r0 - nEz * Const.r0 / 2.0 - ( nM <= 2) * (nM - 1) * (nEz * Const.r0) - float( nM > 2) * ( Const.r0 / 2 + (nM - 4) * Const.r0) * nEz - ( nM == 1) * Const.r0 / 2.5 - ( nM == 2) * Const.r0 * 2 / 2.5 + ( nM == 4) * Const.r0 / 2.5 particle = Particle(p_x, p_y, p_z, Const.elastic_particle) particle.setVelocity( Float4(0.0, 0.0, 0.0, Const.elastic_particle)) self.particles.append(particle)
def __generateLiquidCube1(self, numOfCreatedParticles): ''' This Method is generating cub of liquid coeff should be 0.2325 because need generate volume of liquid with density 1000, this important for modeling incompressible liquid. We generate liquid matter after elastic particles So liquid TODO: generate more detailed Comment ''' x = 15 * Const.r0 / 2 y = 3 * Const.r0 / 2 z = 3 * Const.r0 / 2 + (Const.zmax - Const.zmin) for x in self.__my_range(15 * Const.r0 / 2, (Const.xmax - Const.xmin) / 5 + 3 * Const.r0 / 2, Const.r0): for y in self.__my_range(3 * Const.r0 / 2, (Const.ymax - Const.ymin) - 3 * Const.r0 / 2, Const.r0): for z in self.__my_range( 3 * Const.r0 / 2 + (Const.zmax - Const.zmin), (Const.zmax - Const.zmin) * 7 / 10 - 3 * Const.r0 / 2, Const.r0): particle = Particle(x, y, z, Const.liquid_particle) self.particles.append(particle)
def add_particles(self, line): for square in self.squares: if square.get_row() == line: for row in range(2): for col in range(15): self.particles.append( Particle(self.pygame_screen, col, row, line, 5))
def __init__ (self, volume, particles, n, bindingSites): self.pList = [] self.n = n pId = 0 for i, particle in enumerate(particles): pType = i + 1 mass = particle[1] radius = particle[2] name = particle[3] diffusion = MassToDiffusion(radius) sites = {site: [bindingSites[i][site],-1] for site in bindingSites[i]} angles = SitesToAngles(sites) forceprefactor = MassToFactor(radius) #TESTCASES--------------------------- #seeds = [[[0.0,130.0,4.0], [30.0,125.0,4.0],[60.0,115.3,4.0], [90.0, 93.0, 4.0],[110.0,70.0,4.0],[120.0,50.0,4.0],[130.0,0.0,4.0]], [[2.0,0.0,4.0]]] #seeds = [[[0.0,0.0,0.0], [0.0, 9.0,00.0], [0.0, 18.0,00.0]]] #seeds = [[[0.0,0.0,0.0],[9.0,0.0,0.0]]] for _ in range(particle[0]): seed = RandomTripleUniform(volume) #seed = seeds[i][_] self.pList += [Particle(pId, pType, seed, mass, radius, name, diffusion, sites, angles, forceprefactor)] pId += 1
def __init__(self,func_fitness,x0,bounds,num_particles,maxiter): err_best_g=-1 # best error for group pos_best_g=[] # best position for group # establish the swarm swarm=[] for i in range(0,num_particles): swarm.append(Particle(x0)) # begin optimization loop i=0 while i < maxiter: #print i,err_best_g # cycle through particles in swarm and evaluate fitness for j in range(0,num_particles): swarm[j].evaluate(func_fitness) # determine if current particle is the best (globally) if swarm[j].err < err_best_g or err_best_g == -1: pos_best_g=list(swarm[j].position) err_best_g=float(swarm[j].err) # cycle through swarm and update velocities and position for j in range(0,num_particles): swarm[j].update_velocity_intertia(pos_best_g) #swarm[j].update_velocity_clerc(pos_best_g) swarm[j].update_position(bounds) i+=1 # print final results print('Best position: ', pos_best_g) print('Best error: ', err_best_g)
def __init__(self): rospy.init_node("propagation_test_node") self.tf_helper = TFHelper() self.base_link_pose = PoseStamped() self.base_link_pose.header.frame_id = "base_link" self.base_link_pose.header.stamp = rospy.Time(0) self.last_odom_pose = PoseStamped() self.last_odom_pose.header.frame_id = "odom" self.last_odom_pose.header.stamp = rospy.Time(0) self.particle_pose_pub = rospy.Publisher('/particle_pose_array', PoseArray, queue_size=10) self.odom_pose_pub = rospy.Publisher('/odom_pose', PoseArray, queue_size=10) self.pose_array = PoseArray() self.pose_array.header.stamp = rospy.Time(0) self.pose_array.header.frame_id = "odom" self.p = Particle(x=0, y=0, theta=180, weight=0) self.p_array = PoseArray() self.p_array.header.stamp = rospy.Time(0) self.p_array.header.frame_id = "map" self.is_first = True
def __init__(self): rospy.init_node('error_validation_node') # Initialize subscribers to sensors and motors rospy.Subscriber('/scan', LaserScan, self.read_sensor) # Initialize publishers for visualization self.error_markers_pub = rospy.Publisher('/error_markers', MarkerArray, queue_size=10) self.odom_pose_pub = rospy.Publisher('odom_particle_pose', Pose, queue_size=10) self.latest_scan_ranges = [] # pose_listener responds to selection of a new approximate robot # location (for instance using rviz) rospy.Subscriber("initialpose", PoseWithCovarianceStamped, self.update_initial_pose) # Class initializations self.map_model = MapModel() self.tf_helper = TFHelper() self.motion_model = MotionModel() self.sensor_model = SensorModel() """for static error validation""" self.static_particle = Particle(x=0, y=0, theta=0, weight=1) self.sample_ranges = np.ones(361) self.predicted_obstacle_x = 0.0 self.predicted_obstacle_y = 0.0
def __init__(self, w, a1, a2, dim, population_size, time_steps, search_range, points): # Here we use values that are (somewhat) known to be good # There are no "best" parameters (No Free Lunch), so try using different ones # There are several papers online which discuss various different tunings of a1 and a2 # for different types of problems self.w = w # Inertia self.a1 = a2 # Attraction to personal best self.a2 = a2 # Attraction to global best self.dim = dim self.swarm = [] for label in points: temp_swarm = [ Particle(dim, -search_range, search_range, points[label], label, points) for i in range(int(population_size / 2)) ] self.swarm += temp_swarm self.X = [p.position for p in self.swarm] self.Y = [p.label for p in self.swarm] print(self.X) print(self.Y) self.time_steps = time_steps # Initialising global best, you can wait until the end of the first time step # but creating a random initial best and fitness which is very high will mean you # do not have to write an if statement for the one off case self.best_swarm_pos = np.random.uniform(low=-500, high=500, size=dim) self.best_swarm_fitness = 1e100
def newObject(): """This function allows the user to add up to 3 new bodies to the system It uses a while loop to check an input is an integer between 0 and 4 and takes in initial conditions supplied and initialises the new object """ newObject1=0 newObject2=0 newObject3=0 newObjectNames = [newObject1, newObject2, newObject3] howManyNewBodies = int(input("Enter the number of bodies you wish to add to the system (0-3): ")) while howManyNewBodies > 3 or howManyNewBodies < 0 or not type(howManyNewBodies) is int: howManyNewBodies = int(input("""Input has to be an integer between "1" and "4"! Try again!Enter the number of bodies you wish to add to the system (0-3): """)) for i in range(0, howManyNewBodies): newObjectNames[i] = Particle( position= np.array([input("Enter x-component of initial position: "), input("Enter y-component of initial position: "), input("Enter z-component of initial position: ")], dtype=float), velocity= np.array([input("Enter x-component of initial velocity: "), input("Enter y-component of initial velocity: "), input("Enter z-component of initial velocity: ")], dtype=float), acceleration=np.array([0, 0, 0], dtype=float), name=input("What do you want to name this body: "), mass=float(input("Enter mass of the body: ")) ) bodies.append(newObjectNames[i])
def add_particles(self, n=1, **kargs): """ Add an amount n of particles with the past kargs """ margin = 10 for i in range(n): repeat = True while repeat: inside = False radius = kargs.get('radius', random.randint(10, 15)) pos = kargs.get('pos', (random.randint(radius+margin, self.width-radius-margin),\ random.randint(radius+margin, self.height-radius-margin))) color = kargs.get('color', random_color_vibrant()) speed = kargs.get('speed', random.randint(20, 100)) vel = vector2(0, 1).rotate(random.uniform(0, 360)) * speed new_particle = Particle(pos, radius, color) new_particle.vel = vel if 'pos' not in kargs: for particles in self.particles: if particles.inside(new_particle): inside = True break if inside == False: self.particles.append(new_particle) repeat = False
def LoadMembrane(): InitialState = pickle.load(open('Membranes/' + membrane_id, 'rb')) particles = [] springs = [] for i_p in range(0, len(InitialState['particles']['pos'])): p = Particle(i_p, InitialState['particles']['pos'][i_p], InitialState['particles']['mass'][i_p], InitialState['particles']['fixed'][i_p], InitialState['particles']['w_feed'][i_p], InitialState['particles']['w_in'][i_p]) particles.append(p) for i_s in range(0, len(InitialState['springs']['l0'])): s = Spring(InitialState['springs']['l0'][i_s], InitialState['springs']['p1'][i_s], InitialState['springs']['p2'][i_s], InitialState['springs']['k'][i_s], InitialState['springs']['d'][i_s]) springs.append(s) m = InitialState['mesh'] n = InitialState['nb_edge'] id = InitialState['id'] w = InitialState['washout_time'] dim = InitialState['net_dim'] M = MembraneSystem(particles, springs, m, n, dim) M.network_id = id M.washout_time = w return M
def test_Particle_constructor_should_set_basic_attributes(r, x, y, vx, vy): p = Particle(r, (x, y), (vx, vy)) assert p.r == r assert p.x == x assert p.y == y assert p.vx == vx assert p.vy == vy
def __init__(self, popSize, c1, c2): length = int(math.sqrt(popSize)) self.pop = numpy.empty([length, length], dtype=Particle) self.c1 = c1 self.c2 = c2 self.phi = c1 + c2 self.bestPerGen = [] # Stores value of best sol per generation self.bestSol = [0, 0] self.bestSolValue = 99999 self.averagePerGen = [] # Stores average fitness per generation self.iter = 0 for i in range(length): # init pop for j in range(length): tempX = random.random() * 10.0 - 5.0 tempY = random.random() * 10.0 - 5.0 initW = 0.792 self.pop[i][j] = Particle([tempX, tempY], [0, 0], initW) for i in range(length): # init neighbours for pop for j in range(length): self.setNeighbours(i, j, self.pop[i][j]) # Set neighbourhood best values for i in range(len(self.pop)): for j in range(len(self.pop)): self.pop[i][j].nbestUpdate()
def generateRandomParticle(self): x = np.random.uniform(MIN_X, MAX_X) z = np.random.uniform(MIN_Z, MAX_Z) angle = np.random.uniform(MIN_ANGLE, MAX_ANGLE) weight = 1.0 # print("x: %f, z: %f, angle: %f" % (x,z,angle)) return Particle(x, z, angle, weight)
def meta_pso(algorithm, ft, dimensions, bounds, m_stop_count, stop_prec, m_fitness, timeout): swarm = [] for i in range(m_parts): swarm.append(Particle(bounds)) res = {"params": [0] * dimensions, "fit": 0, "value": 100, "time": 100} for i in range(m_stop_count): tournament = [] for particle in swarm: particle.update_v(res["params"], m_cp, m_cs, m_cg) particle.update_pos(bounds) ftres = {"value": 0, "time": 0} # print("\na: {}, d_prec: {}".format(particle.pos[0], particle.pos[1])) lcount = 5 for j in range(lcount): tmpres = algorithm(ft, 2, [[-10, 10], [-10, 10]], round(particle.pos[1]), stop_prec, particle.pos[0], 0.1, 0.75, round(particle.pos[2]), m_fitness[0], timeout) ftres["value"] += tmpres["fvalue"] ftres["time"] += tmpres["time"] ftres["value"] /= lcount ftres["time"] /= lcount tournament.append([particle.pos, [ftres["value"], ftres["time"]]]) # adding result to tournament # fit = m_fitness([ftres["value"], ftres["time"]]) # # # print(ftres, fit) # # if fit > particle.best_fit: # particle.best = particle.pos # particle.best_fit = fit board, winner_i = best_tournament(tournament, m_fitness, 2) print(tournament[winner_i]) for j in range(m_parts): if board[j] > swarm[j].best_fit: swarm[j].best_fit = board[j] swarm[j].best = tournament[j][0] if swarm[j].best_fit > res["fit"]: res["params"] = swarm[j].best res["fit"] = swarm[j].best_fit res["value"] = tournament[j][1][0] res["time"] = tournament[j][1][1] note = "[{}] {}".format( datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"), res) print(note) log = open("log.txt", mode="a+") log.write(str(note) + "\n") log.close() return res
def createPopulation(self): population = [] max_coords = [] min_coords = [] max_velocities = [] min_velocities = [] for velocity in self.vel_range: min_velocities.append(velocity[0]) max_velocities.append(velocity[1]) for coord in self.search_space: min_coords.append(coord[0]) max_coords.append(coord[1]) for i in range(0, self.population_size): population.append( Particle(coord_max=max_coords, coord_min=min_coords, min_vel=min_velocities, max_vel=max_velocities, fitness_func=self.fitness_func)) for index, particle in enumerate(population): pos_before = index - 1 pos_after = (index + 1) % self.population_size particle.setNeighborhood( [population[pos_before], population[pos_after]]) self.population = population
def run(self): for n in reversed(range(len(self.particles))): self.particles[n].display() self.particles[n].update() self.particles[n].keep_inside_window() ground = SurfaceGravity() ground.display() gravity = ground.attract() self.particles[n].applyForce(gravity) if self.particles[n].is_dead: self.particles.pop(n) # print(f"Particle {n+1} from fountain {self.identifier} died ") if len(self.particles) >= 15: self.particles.pop(0) self.counter += 1 if self.counter % 10 == 0: # print(f"there are {len(self.particles)} particles.") dice = random_uniform() if dice <= 0.4: self.particles.append( Particle(self.origin.x, self.origin.y, self.identifier)) else: self.particles.append( SquareParticle(self.origin.x, self.origin.y, self.identifier))
def run(num_particles, box_width, box_height, temp, num_steps): fig, ax = plt.subplots() particle_array = [] for i in range(num_particles): random_x = np.random.uniform(0, box_width) random_y = np.random.uniform(0, box_height) ptcle = Particle(random_x, random_y) particle_array.append(ptcle) # Box with initial starting configuration box = Box(box_width, box_height, particle_array) points, = ax.plot(box.get_x_array(), 'o', c='red', markersize=5) ax.set_ylim(0, box_height) ax.set_xlim(0, box_width) ani = animation.FuncAnimation(fig, metropolis, frames=np.arange(0, num_steps), fargs=(box, temp, num_particles, points), interval=1) plt.grid() plt.title("Metropolis-Hastings Gas Simulation. %d particles at %d K" % (num_particles, temp)) plt.show()
def buildSwarm(self): #build sizeSwarm particles, by defualt they are initialized randomly for i in range(self.sizeSwarm): p = Particle(self.dimension, self.function, self.funcType) p.randomInit() self.particles += [p] #check for global best self.updateGlobalBest()
def create_particles(self): """ :return: Creates a list of particles and returns them """ particle_list = list() for i in range(self.no_of_particles): particle_list.append(Particle(self.my_prng, self.dimensions)) return particle_list